text
stringlengths 184
4.48M
|
---|
<ion-view view-title="New Group">
<ion-content>
<form name="signinForm" novalidate="" ng-submit="signIn(signinForm)">
<ion-list class="padding">
<div class="list">
<label class="item item-avatar" ng-click="selectPicture()">
<img ng-src="{{imageSrc}}">
<h2>Group Photo</h2>
<p>Select a photo</p>
</label>
</div>
<div class="list">
<h5>  Give your group a name</h5>
<label class="item item-input" ng-class="{ 'has-error-lr' : signinForm.groupName.$invalid && signinForm.$submitted, 'valid-lr' : signinForm.groupName.$valid && signinForm.$submitted}">
<input ng-model='user.groupName' name="groupName" type="text" placeholder="Eg. Sunday Brunch" required>
</label>
</div>
<div class="list">
<h5>  Pick your plan</h5>
<label class="item item-input item-select" ng-class="{ 'has-error-lr' : signinForm.plan.$invalid && signinForm.$submitted, 'valid-lr' : signinForm.plan.$valid && signinForm.$submitted}">
<div class="input-label">
<p>Click to select a plan</p>
</div>
<select ng-model='user.plan' name="plan" required>
<option>weekly</option>
<option>biweekly</option>
<option>monthly</option>
</select>
</label>
</div>
<div class="list">
<h5>  Who should the pool amount go to?</h5>
<div class="button-bar padding" style="padding-left: 50px; padding-right: 50px">
<a grouped-radio="'Singular'" ng-model="user.circleType">Just Me</a>
<a grouped-radio="'Rotational'" ng-model="user.circleType">Everyone</a>
</div>
<br>
<div ng-if="user.circleType=='Singular' && user.plan!=null" style="padding-left: 20px; padding-right: 20px">
<p style="background-color: #d5eef7; padding-left: 20px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px">Alright! You'll be the admin for this group. The pooled amount will be credited to <b>you</b> {{user.plan}}.</p>
</div>
<div ng-if="user.circleType=='Rotational' && user.plan!=null" style="padding-left: 20px; padding-right: 20px">
<p style="background-color: #d5eef7; padding-left: 20px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px">The pooled amount will be credited to <b>everyone</b> in the group on a rotational basis {{user.plan}}.</p>
</div>
</div>
<div class="list">
<h5>  Set your payment amount</h5>
<label class="item item-input" ng-class="{ 'has-error-lr' : signinForm.amount.$invalid && signinForm.$submitted, 'valid-lr' : signinForm.amount.$valid && signinForm.$submitted}">
<input ng-model='user.amount' name="amount" type="tel" placeholder="$ 50" required>
</label>
</div>
<div class="list">
<h5>  Say something to your buddies</h5>
<label class="item item-input" ng-class="{ 'has-error-lr' : signinForm.groupMessage.$invalid && signinForm.$submitted, 'valid-lr' : signinForm.groupMessage.$valid && signinForm.$submitted}">
<textarea ng-model='user.groupMessage' name="groupMessage" placeholder="Brunch was fun last sunday we should do this more often. Join away!" required></textarea>
</label>
</div>
</ion-list>
<div class="form-errors" ng-show="signinForm.$error && signinForm.$submitted" ng-messages="signinForm.$error" ng-messages-include="templates/form-errors.html">
</div>
<div class="list" ng-if="data.selectedContacts.length!=0">
<h5>  Selected Contacts</h5>
</div>
<ion-list>
<!-- Picking contacts -->
<div class="padding" ng-if="data.selectedContacts.length==0">
<button class="button button-block button-dark" ng-click="pickContact()">Pick Your Buddies</button>
</div>
<div class="list">
<a class="item" ng-repeat="contact in data.selectedContacts">
<div class="row">
<div class="col col-90">
<h2>{{contact.name}}</h2>
<p ng-if="contact.email">{{contact.emailType}} : {{contact.email}}</p>
<p>{{contact.phoneType}} : {{contact.phone}}</p>
</div>
<div class="col">
<i class="icon ion-close-circled melon-icon " ng-click="contactDelete($index)"></i>
</div>
</div>
</a>
</div>
<div class="padding" ng-if="data.selectedContacts.length!=0">
<button class="button button-block button-dark" ng-click="pickContact()">Add More Buddies</button>
</div>
<!-- Picking contacts ends here -->
<div ng-if="user.circleType=='Singular' && user.plan!=null && user.amount!=null && data.selectedContacts.length!=0" style="padding-left: 20px; padding-right: 20px">
<p style="background-color: #d5eef7; padding-left: 20px; padding-right: 20px; padding-top: 20px; padding-bottom: 20px"><b>Here's your group summary:</b> WalletBuddies will debit <b>${{user.amount}}</b> from everyone <b>{{user.plan}}</b> and the pooled amount of <b>${{user.amount*(data.selectedContacts.length+1)}}</b> will be credited to <b>you</b>.</p>
</div>
<div ng-if="user.circleType=='Rotational' && user.plan!=null && user.amount!=null && data.selectedContacts.length!=0" style="padding-left: 20px; padding-right: 20px">
<p style="background-color: #d5eef7; padding-left: 20px; padding-right: 20px; padding-top: 20px; padding-bottom: 20px"><b>Here's your group summary:</b> WalletBuddies will debit <b>${{user.amount}}</b> from everyone <b>{{user.plan}}</b> and the pooled amount of <b>${{user.amount*(data.selectedContacts.length+1)}}</b> will be credited to <b>everyone</b> in the group on a rotational basis.</p>
</div>
<div class="list padding" ng-if="data.selectedContacts.length!=0">
<button class="button button-block button-balanced" ng-click="addGroup(user)">Invite</button>
</div>
</ion-list>
</form>
</ion-content>
</ion-view>
<script id="contacts-modal.html" type="text/ng-template">
<ion-modal-view>
<ion-header-bar class="bar bar-header bar-balanced">
<h1 class="title">Pick your buddies</h1>
<div class="button button-clear" ng-click="modal.hide()">Done</div>
</ion-header-bar>
<div class="bar bar-subheader bar-light item-input-inset">
<label class="item-input-wrapper">
<i class="icon ion-ios7-search placeholder-icon"></i>
<input type="search" placeholder="Search Contacts" ng-model="search.name.formatted" ng-change="scrollTop()">
</label>
</div>
<ion-content class="has-subheader">
<ion-list>
<div ng-repeat="contact in contacts | filter:search" ng-init="parentIndex=$index" collection-item-height="itemheight(contact.phoneNumbers.length)" collection-item-width="'100%'" style="width:100%">
<ion-item>
<ion-checkbox ng-repeat="phoneNumber in contact.phoneNumbers" style="border:none;" ng-model="phoneNumber.selected" ng-init="actIndex=$index" ng-click="phoneSelect(contact, phoneNumber)">
<div>
<h5>{{contact.name.formatted}}</h5></div>
<div>
<p style="font-size: smaller">{{phoneNumber.type}} {{phoneNumber.value}}</p>
</div>
</ion-checkbox>
</ion-item>
</div>
</ion-list>
</ion-content>
</ion-modal-view>
</script>
|
import { useTranslation } from 'react-i18next';
import React, { useState } from 'react';
import { BaseButtonsForm } from '@app/components/common/forms/BaseButtonsForm/BaseButtonsForm';
import { Option, Select } from '@app/components/common/selects/Select/Select';
import { Button } from '@app/components/common/buttons/Button/Button';
import { notificationController } from '@app/controllers/notificationController';
import { Input } from 'antd';
const formItemLayout = {
labelCol: { span: 24 },
wrapperCol: { span: 24 },
};
export const AdminCourseForm: React.FC = () => {
const [isFieldsChanged, setFieldsChanged] = useState(false);
const [isLoading, setLoading] = useState(false);
const { t } = useTranslation();
const onFinish = async (values = {}) => {
setLoading(true);
setTimeout(() => {
setLoading(false);
setFieldsChanged(false);
notificationController.success({ message: t('common.success') });
console.log(values);
}, 1000);
};
return (
<BaseButtonsForm
{...formItemLayout}
isFieldsChanged={isFieldsChanged}
onFieldsChange={() => setFieldsChanged(true)}
name="validateForm"
footer={
<BaseButtonsForm.Item>
<Button type="primary" htmlType="submit" loading={isLoading}>
{t('iot.forms.add-course.submit-btn')}
</Button>
</BaseButtonsForm.Item>
}
onFinish={onFinish}
>
<BaseButtonsForm.Item
name="select-multiple-groups"
label={t('iot.forms.add-course.group-select-title')}
rules={[{ required: true, message: t('forms.validationFormLabels.colorError'), type: 'array' }]}
>
<Select mode="multiple" placeholder={t('iot.forms.add-course.group-select-placeholder')}>
<Option value={'ИТ-31'}>{'ИТ-31'}</Option>
<Option value={'ЗИ-21'}>{'ЗИ-21'}</Option>
</Select>
</BaseButtonsForm.Item>
<BaseButtonsForm.Item
name="select-multiple-teachers"
label={t('iot.forms.add-course.teacher-select-title')}
rules={[{ required: true, message: t('forms.validationFormLabels.colorError'), type: 'array' }]}
>
<Select mode="multiple" placeholder={t('iot.forms.add-course.teacher-select-placeholder')}>
<Option value={'Петров А.С.'}>{'Петров А.С.'}</Option>
<Option value={'Назаров А.В.'}>{'Назаров А.В.'}</Option>
</Select>
</BaseButtonsForm.Item>
<BaseButtonsForm.Item
name="name"
label={t('iot.forms.add-course.name')}
rules={[{ required: true, message: t('forms.validationFormLabels.colorError'), type: 'array' }]}
>
<Input />
</BaseButtonsForm.Item>
<BaseButtonsForm.Item
name="description"
label={t('iot.forms.add-course.description')}
rules={[{ required: true, message: t('forms.validationFormLabels.colorError'), type: 'array' }]}
>
<Input.TextArea rows={4} />
</BaseButtonsForm.Item>
</BaseButtonsForm>
);
};
|
import { isBefore, subDays } from 'date-fns';
import React from 'react';
import { useTranslation } from 'next-i18next';
import { CardGrid } from 'src/components/layout/Card';
import DynamicList, {
DynamicListColumn,
} from 'src/components/layout/List/List';
import { Ws } from 'src/components/Typo/Typo';
import { useLocalizedActiveCoinValueFormatter } from 'src/hooks/useDisplayReward';
import {
useActiveCoin,
useActiveCoinTicker,
useCounterTicker,
} from 'src/rdx/localSettings/localSettings.hooks';
import { useReduxState } from 'src/rdx/useReduxState';
import { ApiMinerReward } from 'src/types/Miner.types';
import { useLocalizedCurrencyFormatter } from 'src/utils/si.utils';
const getIndexPastInterval = (index: number) => {
switch (index) {
case 0:
return 'rewards.past_earnings.yesterday';
case 1:
return 'rewards.past_earnings.last_week';
case 2:
return 'rewards.past_earnings.last_month';
default:
return 'Unknown';
}
};
const getIndexInterval = (index: number) => {
switch (index) {
case 0:
return 'rewards.forecasted_earnings.daily';
case 1:
return 'rewards.forecasted_earnings.weekly';
case 2:
return 'rewards.forecasted_earnings.monthly';
default:
return 'Unknown';
}
};
export const MinerRewardStatsSection: React.FC<{
rewards: ApiMinerReward[];
counterPrice: number;
}> = ({ rewards, counterPrice = 0 }) => {
// const dailyRewardPerGhState = useAsyncState('dailyRewGh', 0);
const coinTicker = useActiveCoinTicker();
const counterTicker = useCounterTicker();
const activeCoin = useActiveCoin();
const activeCoinFormatter = useLocalizedActiveCoinValueFormatter();
const { t } = useTranslation('dashboard');
const currencyFormatter = useLocalizedCurrencyFormatter();
const minerStatsState = useReduxState('minerStats');
const summary: [number, number, number] = React.useMemo(() => {
const dailySum = rewards[0] ? rewards[0].totalRewards : 0;
const weeklySum = rewards
.filter((item) =>
isBefore(subDays(new Date(), 7), new Date(item.timestamp * 1000))
)
.reduce((res, next) => {
return res + next.totalRewards;
}, 0);
const monthlySum = rewards.reduce((res, next) => {
return res + next.totalRewards;
}, 0);
return [dailySum, weeklySum, monthlySum];
}, [rewards]);
const pastData = React.useMemo(() => {
return summary.map((item) => ({
coinValue: item ? activeCoinFormatter(item) : '-',
counterValue: item
? currencyFormatter(
(item / Math.pow(10, activeCoin?.decimalPlaces || 3)) * counterPrice
)
: '-',
}));
}, [
summary,
activeCoin,
counterPrice,
activeCoinFormatter,
currencyFormatter,
]);
const minerHeaderStats = useReduxState('minerHeaderStats');
const futureData = React.useMemo(() => {
const daily =
minerHeaderStats.data?.dailyRewardsPerGh &&
minerStatsState.data?.averageEffectiveHashrate
? (minerStatsState.data?.averageEffectiveHashrate / 1000000000) *
minerHeaderStats.data?.dailyRewardsPerGh
: 0;
return [1, 7, 30.5].map((item) => ({
coinValue: daily ? activeCoinFormatter(daily * item) : '-',
counterValue: daily
? currencyFormatter(
((item * daily) /
Math.pow(10, activeCoin?.decimalPlaces || 1000000000)) *
counterPrice
)
: '-',
}));
}, [
minerHeaderStats.data?.dailyRewardsPerGh,
activeCoin,
minerStatsState.data?.averageEffectiveHashrate,
counterPrice,
activeCoinFormatter,
currencyFormatter,
]);
const earningsCols: DynamicListColumn<{
coinValue: React.ReactNode;
counterValue: React.ReactNode;
}>[] = [
{
title: coinTicker,
alignRight: true,
Component: ({ data }) => {
return <Ws>{data.coinValue}</Ws>;
},
},
{
title: counterTicker,
alignRight: true,
Component: ({ data }) => {
return <Ws>{data.counterValue}</Ws>;
},
},
];
return (
<CardGrid>
<div>
<h2>{t('rewards.past_earnings.title')}</h2>
<DynamicList
data={pastData}
columns={[
{
title: '',
Component: ({ index }) => {
return <strong>{t(getIndexPastInterval(index))}</strong>;
},
},
...earningsCols,
]}
/>
</div>
<div>
<h2>{t('rewards.forecasted_earnings.title')}</h2>
<DynamicList
data={futureData}
columns={[
{
title: '',
Component: ({ index }) => {
return <strong>{t(getIndexInterval(index))}</strong>;
},
},
...earningsCols,
]}
/>
</div>
</CardGrid>
);
};
|
# This is used when in two sets, one is a subset of the other i.e. one set contains all the elements of the other.
# The set which its elements is contained in the other set is called the subset.It is represented using the symbol <=
# The set that contains all the elements of the other set is called the subset. It is represented using the symbol >=
# Subset and superset are more like booleans, except no figure return except true or false
# use the value variable since you are printing out booleans
set1 = set([1,2,3,4])
set2 = set([2,3])
value = set2.issubset(set1)
print(value)
value = set1.issuperset(set2)
print(value)
print()
fruit_hamper1 = {'watermelon', 'pineapple', 'pawpaw', 'mango', 'cashew', 'orange'}
fruit_hamper2 = {'mango', 'orange'}
new_fruit_hamper = fruit_hamper1.issuperset(fruit_hamper2)
new_fruit_hamper2 = fruit_hamper2.issubset(fruit_hamper1)
print(new_fruit_hamper)
print(new_fruit_hamper2)
print()
# To represent using the subset symbol <= and the superset symbol >=
set1 = set([1,2,3,4])
set2 = set([2,3])
value = set2<=(set1)
print(value)
value = set1>=(set2)
print(value)
print()
fruit_hamper1 = {'watermelon', 'pineapple', 'pawpaw', 'mango', 'cashew', 'orange'}
fruit_hamper2 = {'mango', 'orange'}
new_fruit_hamper = fruit_hamper1>=(fruit_hamper2)
new_fruit_hamper2 = fruit_hamper2<=(fruit_hamper1)
print(new_fruit_hamper)
print(new_fruit_hamper2)
|
#!/usr/bin/python3
"""class student
"""
class Student:
"""student class """
def __init__(self, first_name, last_name, age):
"""method __int__
"""
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
"""get the dictionary representation of the student
if attr is a list of strings
"""
if (type(attrs) == list and
all(type(ele) == str for ele in attrs)):
return {k: getattr(self, k) for k in attrs if hasattr(self, k)}
return self.__dict__
|
#ifndef USER_HPP
#define USER_HPP "USER_HPP"
#include <iostream>
#include <string>
#include <random>
#include <math.h>
#include <vector>
#include "Hotel.hpp"
#include "Reserve.hpp"
#include "InitialData.hpp"
class User
{
public:
User(const std::string& _email, const std::string& _userName, const std::string& _password);
bool checkEmailSimilarity(const std::string& _email);
bool checkUserNameSimilarity(const std::string& _userName);
bool checkPasswordSimilarity(const std::string& _password);
void increaseMoney(const double& amount);
WalletRecord getWalletRecord(const int& count);
bool checkIfHasEnoughMoney(const double& amount);
void addReserve(Reserve reserve);
int getReserveIdBase();
Reserves& getReserves();
void deleteReserve(const int& reserveId);
std::string getUserName();
void addRating(const Rating rating);
void editUserManualWeights(const Weights& _manualWeights);
Weights getWeights();
Weights getManualWeights();
private:
void estimatePersonalWeight();
void setPersonalWeightsRandomly();
std::vector<double> calculateErrorFuncDifferential();
double calculateErrorFuncPartial(const Rating& rating, const std::string& partialOn);
double calculateErrorFunc(const Rating& rating, const Weights& _weights);
void clampWeights();
void clampWeight(double& weight);
std::string email;
std::string userName;
std::string password;
double money;
WalletRecord walletRecord;
Reserves reserves;
int reserveIdBase;
Ratings userRatings;
Weights weights;
};
#endif
|
from typing import Any, Dict, List
import numpy as np
import onnx
from numpy.typing import NDArray
from onnx import TensorProto
from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info
from onnx.numpy_helper import from_array
from util import Base
info = make_tensor_value_info
def test_hard_swish_00() -> None:
"""
opset version >= 14
"""
class HardSwishTester(Base):
def __init__(self, inputs: Dict[str, NDArray[Any]], outputs: List[str]):
super().__init__(inputs, outputs)
def create_onnx(self) -> onnx.ModelProto:
node = make_node("HardSwish", inputs=["v0"], outputs=["v1"])
inputs = [info("v0", TensorProto.FLOAT, (1, 3, 4, 5))]
outputs = [info("v1", TensorProto.FLOAT, (1, 3, 4, 5))]
graph = make_graph([node], "add_graph", inputs, outputs)
model = make_model(graph)
return model
outputs = ["v1"]
v0 = np.random.rand(1, 3, 4, 5).astype(np.float32) * 12.0 - 6.0
HardSwishTester({"v0": v0}, outputs).run()
|
---
title: Passing the parameters to SOLIDWORKS Macro using the SWBasic macro
caption: Via SWBasic Macro
description: Workaround of passing the parameters to the SOLIDWORKS macro via replacing the text in the SWBasic macro
labels: [argument, swb]
---
[SWBasic (*.swb)宏](/solidworks-api/getting-started/macros/types#swbasic-macros.swb)是仍然在SOLIDWORKS应用程序中支持的一种传统宏类型。
这种宏类型的一个好处是它以纯文本形式保存。这使得第三方应用程序能够动态创建宏。特别是可以使用这种技术来模拟将参数传递给SOLIDWORKS宏。
例如,可以创建以下模板宏:
**template.swb**
{% code-snippet { file-name: Macro.swb, lang: vba } %}
其中*{{Argument1}}*是一个占位符,由外部应用程序或脚本填充参数值:
~~~ cs jagged-bottom
static void Main(string[] args)
{
var macroPath = args[0];
var param = args[1];
var templateMacro = File.ReadAllText(macroPath);
var macro = templateMacro.Replace("{{Argument1}}", param);
var tempMacroPath = Path.Combine(Path.GetTempPath(), Path.GetFileName(macroPath));
File.WriteAllText(tempMacroPath, macro);
~~~
生成的文件可以像普通的[SOLIDWORKS宏](/solidworks-api/application/frame/run-macros-group/)一样运行。
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->decimal('price');
$table->string('slug');
$table->string('photo');
$table->foreignId('giver_id')->nullable()->constrained('givers');
$table->boolean('available')->default(true);
$table->integer('paid')->default(0);
$table->string('mercado_pago_url')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('products');
}
};
|
<?php
use App\Http\Controllers\Api\Auth\AuthController;
use App\Http\Controllers\Api\BilletsController;
use App\Http\Controllers\Api\CarsController;
use App\Http\Controllers\Api\CategoriesController;
use App\Http\Controllers\Api\ConvoisController;
use App\Http\Controllers\Api\HorairesController;
use App\Http\Controllers\Api\PaysController;
use App\Http\Controllers\Api\VillesController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// Route d'authentification
// Route::post('auth/login', [AuthController::class, 'authenticate']);
// Route::post('auth/register', [AuthController::class, 'register']);
Route::group(['middleware' => 'api'], function() {
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/profile', [AuthController::class, 'profile']);
});
// Route des catégories de cars
Route::get('/categories', [CategoriesController::class, 'index']);
Route::post('/categories/create', [CategoriesController::class, 'store']);
Route::put('/categories/update/{id}', [CategoriesController::class, 'update']);
Route::delete('/categories/delete/{id}', [CategoriesController::class, 'destroy']);
Route::get('/categories/search', [CategoriesController::class, 'search']);
// Route des villes
Route::get('/villes', [VillesController::class, 'index']);
Route::post('/villes/create', [VillesController::class, 'store']);
Route::put('/villes/update/{id}', [VillesController::class, 'update']);
Route::delete('/villes/delete/{id}', [VillesController::class, 'destroy']);
Route::get('/villes/search', [VillesController::class, 'search']);
// Route des pays
Route::get('/pays', [PaysController::class, 'index']);
Route::post('/pays/create', [PaysController::class, 'store']);
Route::put('/pays/update/{id}', [PaysController::class, 'update']);
Route::delete('/pays/delete/{id}', [PaysController::class, 'destroy']);
Route::get('/pays/search', [PaysController::class, 'search']);
// Route des horaires
Route::get('/horaires', [HorairesController::class, 'index']);
Route::post('/horaires/create', [HorairesController::class, 'store']);
Route::put('/horaires/update/{id}', [HorairesController::class, 'update']);
Route::delete('/horaires/delete/{id}', [HorairesController::class, 'destroy']);
Route::get('/horaires/search', [HorairesController::class, 'search']);
// Route des cars
Route::get('/cars', [CarsController::class, 'index']);
Route::post('/cars/create', [CarsController::class, 'store']);
Route::put('/cars/update/{id}', [CarsController::class, 'update']);
Route::delete('/cars/delete/{id}', [CarsController::class, 'destroy']);
Route::get('/cars/search', [CarsController::class, 'search']);
// Route des convois
Route::get('/convois', [ConvoisController::class, 'index']);
Route::post('/convois/create', [ConvoisController::class, 'store']);
Route::get('/convois/detail/{id}', [ConvoisController::class, 'show']);
Route::put('/convois/update/{id}', [ConvoisController::class, 'update']);
Route::delete('/convois/delete/{id}', [ConvoisController::class, 'destroy']);
Route::get('/convois/search', [ConvoisController::class, 'search']);
// Route des billets
Route::get('/billets', [BilletsController::class, 'index']);
Route::post('/billets/create', [BilletsController::class, 'store']);
Route::get('/billets/detail/{id}', [BilletsController::class, 'show']);
Route::put('/billets/update/{id}', [BilletsController::class, 'update']);
Route::delete('/billets/delete/{id}', [BilletsController::class, 'destroy']);
Route::get('/billets/search', [BilletsController::class, 'search']);
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
|
import {
ConflictException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import {
UserCreateDto,
UserFindAllQueryParamsDto,
UserUpdateDto,
UserUpdateRoleDto,
} from './dto';
import { PrismaService } from 'src/modules/prisma/prisma.service';
import { UserEntity } from './user.entity';
import { extractObjectPart } from 'src/utils/extract-object-part';
import { Prisma } from '@prisma/client';
import OrderEnum from 'src/dto/order';
@Injectable()
export class UserService {
constructor(private readonly prisma: PrismaService) {}
async findAll({ search, openTicketCount }: UserFindAllQueryParamsDto) {
const sqlQuery = `%${search}%`;
const users = await this.prisma.$queryRaw`
SELECT
"User"."id",
"firstName",
"lastName",
"username",
"phone",
"Role"."name" AS "role",
COUNT(DISTINCT "DeveloperTickets"."id") AS "totalTicketCount",
COUNT(DISTINCT CASE WHEN "DeveloperTickets"."status" = 'task_done' THEN "DeveloperTickets"."id" END) AS "doneTicketCount",
COUNT(DISTINCT CASE WHEN "DeveloperTickets"."status" <> 'task_done' THEN "DeveloperTickets"."id" END) AS "openTicketCount"
FROM
"User"
LEFT JOIN
"Ticket" AS "OperatorTickets"
ON
"User"."id" = "OperatorTickets"."operatorId"
LEFT JOIN
"Ticket" AS "DeveloperTickets"
ON
"User"."id" = "DeveloperTickets"."developerId"
LEFT JOIN
"Role"
ON
"User"."roleId" = "Role"."id"
WHERE
"User"."firstName" ILIKE ${sqlQuery} OR "User"."lastName" ILIKE ${sqlQuery} OR "User"."username" ILIKE ${sqlQuery}
GROUP BY
"User"."id",
"User"."firstName",
"User"."lastName",
"User"."username",
"User"."phone",
"Role"."name"
${Prisma.sql`
ORDER BY
${
!openTicketCount ? Prisma.sql`LOWER("User"."firstName")` : Prisma.empty
}
${
openTicketCount
? openTicketCount === OrderEnum.ASC
? Prisma.sql`"openTicketCount" ASC`
: Prisma.sql`"openTicketCount" DESC`
: Prisma.empty
}`}
`;
return {
status: 'success',
data: JSON.parse(
JSON.stringify(users, (key: string, value) =>
typeof value === 'bigint' ? value.toString() : value,
),
),
};
}
async findOptions() {
const users = await this.prisma.user.findMany({
where: {
orgId: null,
},
select: { id: true, firstName: true, lastName: true },
});
return {
status: 'success',
data: users,
};
}
async findOne(id: number) {
const user = await this.prisma.user.findUnique({
where: { id },
include: {
role: true,
},
});
if (!user) {
throw new NotFoundException(`User with the id ${id} not found`);
}
return {
data: {
...extractObjectPart<UserEntity>({
type: 'exclude',
obj: user,
keys: ['hash', 'orgId'],
}),
clientId: user.orgId,
},
status: 'success',
};
}
async findMe(user: UserEntity) {
const dbUser = await this.prisma.user.findUnique({
where: { id: user.id },
include: {
role: {
include: {
permissions: true,
},
},
},
});
if (!dbUser) {
throw new NotFoundException(`User with the id ${user.id} not found`);
}
const client =
typeof dbUser.orgId === 'number'
? await this.prisma.client.findFirst({
where: { id: dbUser.orgId },
})
: {};
const {
role: { permissions, ...roleRest },
...rest
} = dbUser;
return {
status: 'success',
data: {
...rest,
role: roleRest,
permissions,
client,
},
};
}
async create(dto: UserCreateDto) {
const isAlreadyExists = await this.checkUserAlreadyExists(dto.username);
if (isAlreadyExists) {
throw new ConflictException({
status: 'error',
data: null,
message: 'User already exists',
});
}
// Create a hash
const hash = await bcrypt.hash(dto.password, 10);
// Save the user in db
const newUser = await this.prisma.user.create({
data: {
username: dto.username,
hash,
firstName: dto.firstName,
lastName: dto.lastName,
roleId: dto.roleId,
phone: dto.phone,
orgId: dto.clientId,
},
select: {
username: true,
firstName: true,
lastName: true,
role: {
select: {
name: true,
},
},
},
});
return {
status: 'success',
data: newUser,
};
}
async update({ id, ...rest }: UserUpdateDto) {
const updatedUser = await this.prisma.user.update({
where: { id },
data: rest,
});
return {
status: 'success',
data: updatedUser,
};
}
async deleteUser(id: number) {
await this.prisma.user.delete({ where: { id } });
return {
status: 'success',
data: null,
};
}
async updateRole(id: number, dto: UserUpdateRoleDto) {
const updatedUser = await this.prisma.user.update({
where: { id },
data: {
roleId: dto.roleId,
},
});
return {
status: 'success',
data: updatedUser,
};
}
async checkUserAlreadyExists(username: string) {
return await this.prisma.user.findUnique({ where: { username } });
}
}
|
import { useEffect, useState } from 'react'
import useSWR from 'swr'
import { useCoinsShortData } from '@/hooks'
import { CoinsATHsType, CoinsWithATHType, CoinFullDataType, ResponseType } from '@/types'
import { fetcher } from '@/utils'
export const useCoinsFullData = (offset: number, limit: number) => {
const [coinKeys, setCoinKeys] = useState<string[]>([])
const [fullCoinsData, setFullCoinsData] = useState<CoinFullDataType[]>([])
const [coinsCount, setCoinsCount] = useState<number>()
const { coinsShortData, isLoading } = useCoinsShortData(offset, limit)
const { data: coinsDataWithATH, error: coinsDataWithATHError } = useSWR<
ResponseType<CoinsWithATHType[]>
>(
coinKeys?.length
? `${process.env.NEXT_PUBLIC_BASE_URL_TEST}/v0/coins/?keys=${coinKeys.join()}`
: undefined,
fetcher
)
useEffect(() => {
if (coinsShortData) {
setCoinKeys(coinsShortData?.data?.map(coin => coin.slug))
setCoinsCount(coinsShortData?.meta?.count)
}
}, [coinsShortData])
useEffect(() => {
const coinsATHPrices = coinsDataWithATH?.data.reduce((acc, coin) => {
acc[coin.key] = coin.athPrice.USD
return acc
}, {} as CoinsATHsType)
if (coinsShortData && coinsATHPrices) {
const fullData = coinsShortData.data.map(coin => ({
...coin,
ath: coinsATHPrices[coin.slug],
}))
setFullCoinsData(fullData)
}
}, [coinsShortData, coinsDataWithATH])
return { fullCoinsData, isLoading, coinsCount, coinsDataWithATHError }
}
|
/*
* Copyright (C) 2008 Thomas Klapiscak (t.g.klapiscak@durham.ac.uk)
*
* This file is part of JASDL.
*
* JASDL is free software: you can redistribute it and/or modify
* it under the terms of the Lesser GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JASDL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the Lesser GNU General Public License
* along with JASDL. If not, see <http://www.gnu.org/licenses/>.
*
*/
package jasdl.ia;
import jasdl.asSemantics.JASDLAgent;
import jasdl.bridge.seliteral.SELiteral;
import jason.asSemantics.DefaultInternalAction;
import jason.asSemantics.TransitionSystem;
import jason.asSemantics.Unifier;
import jason.asSyntax.Literal;
import jason.asSyntax.StringTermImpl;
import jason.asSyntax.Term;
import java.util.logging.Logger;
import org.semanticweb.owl.model.OWLAxiom;
import org.semanticweb.owl.model.OWLClass;
import org.semanticweb.owl.model.OWLDescription;
import org.semanticweb.owl.model.OWLObject;
import bebops.common.IndividualAxiomToDescriptionConverter;
/**
* @author Tom Klapiscak
*
* Produces a rendering in Manchester OWL syntax (in JASDL's Namespace prefix form) of the assertion made by any valid SE-Literal.
*
* For example: jasdl.ia.get_class_definition(bread(hovis)[o(c)], Rendering), unifies Rendering with "c:bread and {c:hovis}".
*
* Usage: jasdl.ia.get_class_definition(Assertion, Rendering), where Assertion is any valid SE-Literal.
*
*/
public class get_class_definition extends DefaultInternalAction {
private Logger logger = Logger.getLogger("jasdl." + get_class_definition.class.getName());
@Override
public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
try {
if (!args[0].isLiteral()) {
throw new Exception(get_class_definition.class.getName() + "'s first argument must be a literal");
}
Literal l = (Literal) args[0];
JASDLAgent agent = (JASDLAgent) ts.getAg();
SELiteral sl = agent.getSELiteralFactory().construct(l);
String expression = "";
if (sl.getLiteral().isGround()) {
IndividualAxiomToDescriptionConverter conv = new IndividualAxiomToDescriptionConverter(agent.getOWLDataFactory(), agent.getReasoner());
//for(OWLAxiom axiom : ){
OWLAxiom axiom = agent.getSELiteralToAxiomConverter().create(sl);
agent.getLogger().finest("Rendering axiom " + axiom);
OWLDescription desc = conv.performDirectConversion(axiom);
expression += agent.getJom().getManchesterNsPrefixOWLObjectRenderer().render(desc);
//}
} else {
// TODO: Extract to SELiteral class (e.g. getDescription)?
OWLObject o = sl.toOWLObject();
if (o instanceof OWLClass) {
expression += agent.getJom().getManchesterNsPrefixOWLObjectRenderer().render((OWLClass) o);
} else {
throw new Exception("Not yet implemented for properties");
}
}
expression = expression.replace("\n", " ");
return un.unifies(args[1], new StringTermImpl(expression));
} catch (Exception e) {
logger.warning("Error in internal action '" + get_class_definition.class.getName() + "'! Reason:");
e.printStackTrace();
return false;
}
}
}
|
Higher-Order Functions
Functions as Data
JavaScript functions behave like any other data type in the language; we can assign functions to variables, and we can reassign them to new variables.
Below, we have an annoyingly long function name that hurts the readability of any code in which it’s used. Note: If the below function’s syntax feels unfamiliar, revisit the arrow functions exercise to refresh your knowledge on ES6 arrow notation.
const announceThatIAmDoingImportantWork = () => {
console.log("I’m doing very important work!");
};
Let’s pretend this function does important work and needs to be called repeatedly. To rename this function without sacrificing the source code, we can re-assign the function to a variable with a suitably short name:
const busy = announceThatIAmDoingImportantWork;
busy(); // This function call barely takes any space!
busy is a variable that holds a reference to our original function. If we could look up the address in memory of busy and the address in memory of announceThatIAmDoingImportantWork they would point to the same place. Our new busy() function can be invoked with parentheses as if that was the name we originally gave our function.
Notice how we assign announceThatIAmDoingImportantWork without parentheses as the value to the busy variable. We want to assign the value of the function itself, not the value it returns when invoked.
In JavaScript, functions are first class objects. This means that, like other objects you’ve encountered, JavaScript functions can have properties and methods.
Since functions are a type of object, they have properties such as .length and .name, and methods such as .toString(). You can see more about the methods and properties of functions in the documentation.
Functions are special because we can invoke them, but we can still treat them like any other type of data. Let’s get some practice doing that!
Ex.
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
for(let i = 1; i <= 1000000; i++) {
if ( (2 + 2) != 4) {
console.log('Something has gone very wrong :( ');
}
}
}
// Write your code below
const isTwoPlusTwo = checkThatTwoPlusTwoEqualsFourAMillionTimes
isTwoPlusTwo()
console.log(isTwoPlusTwo.name);
Functions as Parameters
As you know, a parameter is a placeholder for the data that gets passed into a function. Since functions can behave like any other type of data in JavaScript, it might not surprise you to learn that functions can accept other functions as parameters. A higher-order function is a function that either accepts functions as parameters, returns a function, or both! We call functions that get passed in as parameters callback functions. Callback functions get invoked during the execution of the higher-order function.
When we invoke a higher-order function, and pass another function in as an argument, we don’t invoke the argument function. Invoking it would evaluate to passing in the return value of that function call. With callback functions, we pass in the function itself by typing the function name without the parentheses:
const higherOrderFunc = param => {
param();
return `I just invoked ${param.name} as a callback function!`
}
const anotherFunc = () => {
return 'I\'m being invoked by the higher-order function!';
}
higherOrderFunc(anotherFunc);
We wrote a higher-order function higherOrderFunc that accepts a single parameter, param. Inside the body, param gets invoked using parentheses. And finally, a string is returned, telling us the name of the callback function that was passed in.
Below the higher-order function, we have another function aptly named anotherFunc. This function aspires to be called inside the higher-order function.
Lastly, we invoke higherOrderFunc(), passing in anotherFunc as its argument, thus fulfilling its dreams of being called by the higher-order function.
higherOrderFunc(() => {
for (let i = 0; i <= 10; i++){
console.log(i);
}
});
In this example, we invoked higherOrderFunc() with an anonymous function (a function without a name) that counts to 10. Anonymous functions can be arguments too!
Let’s get some practice writing higher-order functions.
Ex.
const addTwo = num => {
return num + 2;
}
const checkConsistentOutput = (func, val) => {
let checkA = val + 2;
let checkB = func(val);
if (checkA === checkB) {
return func(val);
} else {
return "inconsistent results";
}
}
console.log(checkConsistentOutput(addTwo, 2));
Summary
By thinking about functions as data, and learning about higher-order functions, you’ve taken important steps in learning to write clean, modular code that takes advantage of JavaScript’s flexibility.
Abstraction allows us to write complicated code in a way that’s easy to reuse, debug, and understand for human readers.
We can work with functions the same way we work with any other type of data, including reassigning them to new variables.
JavaScript functions are first-class objects, so they have properties and methods like any other object.
Functions can be passed into other functions as parameters.
A higher-order function is a function that either accepts functions as parameters, returns a function, or both.
The built-in JavaScript array methods that help us iterate are called iteration methods, at times referred to as iterators. Iterators are methods called on arrays to manipulate elements and return values.
The .forEach() Method
The first iteration method that we’re going to learn is .forEach(). Aptly named, .forEach() will execute the same code for each element of an array.
Diagram outlining the parts of an array iterator including the array identifier, the section that is the iterator, and the callback function
The code above will log a nicely formatted list of the groceries to the console. Let’s explore the syntax of invoking .forEach().
groceries.forEach() calls the forEach method on the groceries array.
.forEach() takes an argument of callback function. Remember, a callback function is a function passed as an argument into another function.
.forEach() loops through the array and executes the callback function for each element. During each execution, the current element is passed as an argument to the callback function.
The return value for .forEach() will always be undefined.
Another way to pass a callback for .forEach() is to use arrow function syntax.
groceries.forEach(groceryItem => console.log(groceryItem));
We can also define a function beforehand to be used as the callback function.
function printGrocery(element){
console.log(element);
}
groceries.forEach(printGrocery);
The above example uses a function declaration but you can also use a function expression or arrow function as well.
All three code snippets do the same thing. In each array iteration method, we can use any of the three examples to supply a callback function as an argument to the iterator. It’s good to be aware of the different ways to pass in callback functions as arguments in iterators because developers have different stylistic preferences.
Ex2
const fruits = ['mango', 'papaya', 'pineapple', 'apple'];
// Iterate over fruits below
fruits.forEach(fruitItem => console.log("I want to eat a " + fruitItem));
The .map() Method
The second iterator we’re going to cover is .map(). When .map() is called on an array, it takes an argument of a callback function and returns a new array! Take a look at an example of calling .map():
const numbers = [1, 2, 3, 4, 5];
const bigNumbers = numbers.map(number => {
return number * 10;
});
.map() works in a similar manner to .forEach()— the major difference is that .map() returns a new array.
In the example above:
numbers is an array of numbers.
bigNumbers will store the return value of calling .map() on numbers.
numbers.map will iterate through each element in the numbers array and pass the element into the callback function.
return number * 10 is the code we wish to execute upon each element in the array. This will save each value from the numbers array, multiplied by 10, to a new array.
If we take a look at numbers and bigNumbers:
console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]
Notice that the elements in numbers were not altered and bigNumbers is a new array.
The .filter() Method
Another useful iterator method is .filter(). Like .map(), .filter() returns a new array. However, .filter() returns an array of elements after filtering out certain elements from the original array. The callback function for the .filter() method should return true or false depending on the element that is passed to it. The elements that cause the callback function to return true are added to the new array. Take a look at the following example:
const words = ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
const shortWords = words.filter(word => {
return word.length < 6;
});
words is an array that contains string elements.
const shortWords = declares a new variable that will store the returned array from invoking .filter().
The callback function is an arrow function that has a single parameter, word. Each element in the words array will be passed to this function as an argument.
word.length < 6; is the condition in the callback function. Any word from the words array that has fewer than 6 characters will be added to the shortWords array.
Let’s also check the values of words and shortWords:
console.log(words); // Output: ['chair', 'music', 'pillow', 'brick', 'pen', 'door'];
console.log(shortWords); // Output: ['chair', 'music', 'brick', 'pen', 'door']
Observe how words was not mutated, i.e. changed, and shortWords is a new array.
Ex.
const randomNumbers = [375, 200, 3.14, 7, 13, 852];
// Call .filter() on randomNumbers below
const smallNumbers = randomNumbers.filter(number => {
if (number < 250) {
return true;
}
})
const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];
// Call .filter() on favoriteWords below
const longFavoriteWords = favoriteWords.filter(word => {
return word.length > 7;
})
The .findIndex() Method
We sometimes want to find the location of an element in an array. That’s where the .findIndex() method comes in! Calling .findIndex() on an array will return the index of the first element that evaluates to true in the callback function.
const jumbledNums = [123, 25, 78, 5, 9];
const lessThanTen = jumbledNums.findIndex(num => {
return num < 10;
});
jumbledNums is an array that contains elements that are numbers.
const lessThanTen = declares a new variable that stores the returned index number from invoking .findIndex().
The callback function is an arrow function that has a single parameter, num. Each element in the jumbledNums array will be passed to this function as an argument.
num < 10; is the condition that elements are checked against. .findIndex() will return the index of the first element which evaluates to true for that condition.
Let’s take a look at what lessThanTen evaluates to:
console.log(lessThanTen); // Output: 3
If we check what element has index of 3:
console.log(jumbledNums[3]); // Output: 5
Great, the element in index 3 is the number 5. This makes sense since 5 is the first element that is less than 10.
If there isn’t a single element in the array that satisfies the condition in the callback, then .findIndex() will return -1.
const greaterThan1000 = jumbledNums.findIndex(num => {
return num > 1000;
});
console.log(greaterThan1000); // Output: -1
Ex.
//finds animal and animal that starts with s
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];
const foundAnimal = animals.findIndex(animal => {
return animal === 'elephant';
});
const startsWithS = animals.findIndex(animal => {
return animal[0] === 's' ? true : false;
});
The .reduce() Method
Another widely used iteration method is .reduce(). The .reduce() method returns a single value after iterating through the elements of an array, thereby reducing the array. Take a look at the example below:
const numbers = [1, 2, 4, 10];
const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
})
console.log(summedNums) // Output: 17
Here are the values of accumulator and currentValue as we iterate through the numbers array:
Iteration accumulator currentValue return value
First 1 2 3
Second 3 4 7
Third 7 10 17
Now let’s go over the use of .reduce() from the example above:
numbers is an array that contains numbers.
summedNums is a variable that stores the returned value of invoking .reduce() on numbers.
numbers.reduce() calls the .reduce() method on the numbers array and takes in a callback function as argument.
The callback function has two parameters, accumulator and currentValue. The value of accumulator starts off as the value of the first element in the array and the currentValue starts as the second element. To see the value of accumulator and currentValue change, review the chart above.
As .reduce() iterates through the array, the return value of the callback function becomes the accumulator value for the next iteration, currentValue takes on the value of the current element in the looping process.
The .reduce() method can also take an optional second parameter to set an initial value for accumulator (remember, the first argument is the callback function!). For instance:
const numbers = [1, 2, 4, 10];
const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 100) // <- Second argument for .reduce()
console.log(summedNums); // Output: 117
Here’s an updated chart that accounts for the second argument of 100:
Iteration # accumulator currentValue return value
First 100 1 101
Second 101 2 103
Third 103 4 107
Fourth 107 10 117
This is an example of it
const newNumbers = [1, 3, 5, 7];
const newSum = newNumbers.reduce((accumulator, currentValue) => {
console.log('The value of accumulator: ', accumulator);
console.log('The value of currentValue: ', currentValue);
return accumulator + currentValue;
}, 10);
console.log(newSum);
The documentation for each method contains several sections:
A short definition.
A block with the correct syntax for using the method.
A list of parameters the method accepts or requires.
The return value of the function.
An extended description.
Examples of the method’s use.
Other additional information.
In the instructions below, there are some errors in the code. Use the documentation for a given method to determine the error or fill in a blank to make the code run correctly.
Ex od some iterator
const words = ['unique', 'uncanny', 'pique', 'oxymoron', 'guise'];
// Something is missing in the method call below
console.log(words.some(word => {
return word.length < 6;
}));
// Use filter to create a new array
const interestingWords = words.filter((word) => {return word.length > 5});
// Make sure to uncomment the code below and fix the incorrect code before running it
console.log(interestingWords.every((word) => {return word.length > 5}));
Ex2
const cities = ['Orlando', 'Dubai', 'Edinburgh', 'Chennai', 'Accra', 'Denver', 'Eskisehir', 'Medellin', 'Yokohama'];
const nums = [1, 50, 75, 200, 350, 525, 1000];
// Choose a method that will return undefined
cities.forEach(city => console.log('Have you visited ' + city + '?'));
// Choose a method that will return a new array
const longCities = cities.filter(city => city.length > 7);
// Choose a method that will return a single value
const word = cities.reduce((acc, currVal) => {
return acc + currVal[0]
}, "C");
console.log(word)
// Choose a method that will return a new array
const smallerNums = nums.map(num => num - 5);
// Choose a method that will return a boolean value
nums.every(num => num < 0);
// OR nums.some(num => num < 0);
projects
//secret message project
const animals = ['Hen', 'elephant', 'llama', 'leopard', 'ostrich', 'Whale', 'octopus', 'rabbit', 'lion', 'dog'];
// Create the secretMessage array below
const secretMessage = animals.map(animals => {
return animals[0];
})
//it logs hello world very cool!!! uses .join
console.log(secretMessage.join(''));
//numbers thing
const bigNumbers = [100, 200, 300, 400, 500];
// Create the smallNumbers array below
const smallNumbers = bigNumbers.map(bigNumbers => {
return bigNumbers / 100;
})
resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods
|
/*
* Author: PabstMirror
* Adds a key to a unit that will open a vehicle
* Note: has global effects for Unit (will add items to remote unit)
*
* Arguments:
* 0: Unit <OBJECT>
* 1: Vehicle <OBJECT>
* 2: custom key (true: custom key (magazine) - false: side key (item)) <BOOL>
*
* Return Value:
* None
*
* Example:
* [ACE_player, car, true] call ACE_VehicleLock_fnc_addKeyForVehicle
*
* Public: Yes
*/
#include "script_component.hpp"
if (!params [["_unit", objNull, [objNull]], ["_veh", objNull, [objNull]], ["_useCustom", false, [false]]]) exitWith {
ERROR("Input wrong type");
};
TRACE_3("params",_unit,_veh,_useCustom);
if (isNull _unit) exitWith {ERROR("null unit");};
if (isNull _veh) exitWith {ERROR("null vehicle");};
if (_useCustom) then {
private _previousMags = magazinesDetail _unit;
_unit addMagazine ["ACE_key_customKeyMagazine", 1]; //addMagazine array has global effects
private _newMags = (magazinesDetail _unit) - _previousMags;
if ((count _newMags) == 0) exitWith {ERROR("failed to add magazine (inventory full?)");};
private _keyMagazine = _newMags select 0;
TRACE_2("setting up key on server",_veh,_keyMagazine);
//Have the server run add the key to the vehicle's key array:
[QGVAR(setupCustomKey), [_veh, _keyMagazine]] call CBA_fnc_serverEvent;
} else {
private _keyName = [_veh] call FUNC(getVehicleSideKey);
_unit addItem _keyName; //addItem has global effects
};
|
import { useEffect, useState } from "react";
import OfferCard from "./OfferCard";
import Aos from "aos";
import "aos/dist/aos.css";
const SpecialOffer = () => {
const [offers, setOffer] = useState([]);
useEffect(() => {
Aos.init({ duration: 3000 });
}, []);
useEffect(() => {
fetch("https://toy-car-world-server.vercel.app/alltoys")
.then((res) => res.json())
.then((data) => {
setOffer(data);
});
}, []);
const sliceOffers = offers.slice(1, 7);
return (
<div data-aos="fade-up">
<h1 className="text-3xl font-bold text-center text-red-400 mt-36 mb-24">
Special Offer
</h1>
<p
className="text-gray-500 md:px-44 lg:px-44 ms-4 mb-24"
data-aos="fade-left">
Toy cars are miniature replicas of real vehicles, designed for children
is play and enjoyment. They are typically made of plastic or die-cast
metal and come in various shapes, sizes, and colors. Toy cars often
feature details such as moving wheels, opening doors, and realistic
designs to enhance the imaginative play experience.
</p>
<div
className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-12"
data-aos="fade-right">
{sliceOffers.map((offer) => (
<OfferCard key={offer._id} offer={offer}></OfferCard>
))}
</div>
</div>
);
};
export default SpecialOffer;
|
import styled from "styled-components";
import { ApiComponent } from "../Components/ApiComponent";
import { ReadMoreButton, RecipeButton } from "../Components/Button";
import { Carousel } from "../Components/Carousel";
import { HowCard } from "../Components/HowCard";
import { OrderButton } from "../Components/OrderButton";
import { PromotionAd } from "../Components/PromotionAd";
import { RecipeCard, RecipeCardProps } from "../Components/RecipeCard";
import { ReviewCards } from "../Components/Review";
import { TextBlock } from "../Components/TextBlock";
export function Home() {
const recipe1: RecipeCardProps = {
title: "BLOMKÅLSPURÉ",
image: "Images/recipe9.jpg",
description: "Krämig blomkålspuré serverad med mandarin och körsbärstomat",
};
const recipe2: RecipeCardProps = {
title: "KRÄMIG MOROTSSOPPA",
image: "Images/recipe6.jpg",
description:
"Rustik och färgglad morotssoppa, en perfekt värmande soppa när det är lite kyligare ute",
};
const recipe3: RecipeCardProps = {
title: "KLASSISKA UNGSBAKADE ROTFRUKTER",
image: "Images/recipe7.jpg",
description:
"Potatisen, palsternackan och morötterna smakar ljuvligt gott av smakhöjare som salt, citron och färsk rosmarin",
};
const recipe4: RecipeCardProps = {
title: "GRÖN ÄRTPURÉ MED GRANATÄPPLE",
image: "Images/recipe8.jpg",
description:
"Knalligt grön ärtpuré med granatäpple. God som både birätt eller som pålägg",
};
return (
<div>
<PromotionAd
text="Begränsat erbjudande! Gratis frakt och 20% rabatt om du beställer innan
24:00"
onClose={() => console.log("Ad closed")}
/>
<StyledMain>
<Carousel
height={55}
images={[
"Images/food_10.jpg",
"Images/food_7.jpg",
"Images/food_2.jpg",
]}
titles={[
"Vi gör vegetarisk matlagning enkelt och inspirerande!",
"Enkla, goda och miljövänliga recept!",
"Varje grön dag är en bra dag! Börja din idag!",
]}
buttonText={["Våra Kassar", "Så funkar det!"]}
gradientColor={"tbc"}
/>
<StyledCardDiv>
<HowCard
numberProps="1"
imgSrc="Images/order1.jpg"
h2Props="Du beställer"
text="Beställ enkelt på vår hemsida."
altProps="Person beställer på laptop"
/>
<HowCard
numberProps="2"
imgSrc="Images/deliver1.jpg"
h2Props="Vi levererar"
text="Våra leveranser är klimatkompenserade och vi levererar bara den mängd som behövs för att minska matsvinn!"
altProps="Lastbil kör över bro"
/>
<HowCard
numberProps="3"
imgSrc="Images/cooking_3.jpg"
h2Props="Ni äter god mat"
text="Följ våra recept och njut av god vegetarisk mat anpassad efter din familj."
altProps="Ett par lagar mat"
/>
</StyledCardDiv>
<StyledButton>
<ReadMoreButton text="Läs mer" />
</StyledButton>
<StyledRecipeCardsWrapper>
<StyledSloganWrapper>
<StyledSloganHeading>
Mat som gör både dig och planeten glad
</StyledSloganHeading>
<StyledSloganHeadingSmall>
Måltider som ingår i våra kassar
</StyledSloganHeadingSmall>
</StyledSloganWrapper>
<StyledRecipeCardsContainer>
<RecipeCard {...recipe1} />
<RecipeCard {...recipe2} />
<RecipeCard {...recipe3} />
<RecipeCard {...recipe4} />
</StyledRecipeCardsContainer>
<StyledButton>
<RecipeButton text="Läs mer" />
</StyledButton>
</StyledRecipeCardsWrapper>
</StyledMain>
<TextBlock
title="Nr 1 Vegetariska matkassar online*"
description="*Enligt vegetariska föreningens egna säkra källor som provar alla 2 olika alternativ på markaden just nu i Sverige, samt våra helt riktiga kunder som recenserat oss"
backgroundColor="#FF8A48"
textColor="#082512"
></TextBlock>
<ReviewCards></ReviewCards>
<ApiComponent></ApiComponent>
<>
<OrderButton text="Beställ" />
</>
</div>
);
}
const StyledMain = styled.main`
margin: 0;
background-color: #fff8ea;
`;
const H = styled.h1`
margin: 0;
`;
const StyledCardDiv = styled.div`
width: 100%;
display: grid;
gap: 0.5rem;
grid-template-columns: repeat(3, 1fr);
@media (max-width: 768px) {
grid-template-columns: 1fr;
margin-left: 0.1rem;
margin-right: 0.1rem;
}
`;
// Recipe container + slogan styling
const StyledSloganWrapper = styled.div`
padding: 50px;
`;
const StyledSloganHeading = styled.p`
color: #f37d39;
text-align: center;
font-size: 30px;
font-family: "Titillium Web", sans-serif;
font-weight: bold;
`;
const StyledSloganHeadingSmall = styled.p`
color: #608f60;
text-align: center;
font-size: 25px;
font-family: "Titillium Web", sans-serif;
`;
const StyledButton = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin-top: 30px;
`;
// Recipe cards styling
const StyledRecipeCardsWrapper = styled.div`
background-color: #fff8ea;
padding-bottom: 50px;
`;
export const StyledRecipeCardsContainer = styled.div`
display: flex;
flex-wrap: wrap;
justify-content: space-between;
@media (max-width: 850px) {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-left: 0;
margin-right: 0;
}
@media (min-width: 851px) and (max-width: 1000px) {
display: flex;
justify-content: space-between;
margin-left: 100px;
margin-right: 100px;
}
`;
|
import { Object3D, Scene3D, Engine3D, CameraUtil, HoverCameraController, View3D, AtmosphericComponent, DirectLight, KelvinUtil, MeshRenderer, LitMaterial, SphereGeometry, Color, SkyRenderer } from '@orillusion/core'
import dat from 'dat.gui'
class Sample_ClearCoat {
lightObj3D: Object3D
scene: Scene3D
async run() {
Engine3D.setting.shadow.shadowBound = 300
await Engine3D.init()
this.scene = new Scene3D()
let camera = CameraUtil.createCamera3DObject(this.scene)
camera.perspective(60, Engine3D.aspect, 1, 5000.0)
camera.object3D.addComponent(HoverCameraController).setCamera(-25, -5, 300)
let view = new View3D()
view.scene = this.scene
view.camera = camera
Engine3D.startRenderView(view)
await this.initScene()
}
async initScene() {
/******** sky *******/
{
let sky = this.scene.getOrAddComponent(SkyRenderer)
sky.map = await Engine3D.res.loadHDRTextureCube('https://cdn.orillusion.com//hdri/sunset.hdr')
this.scene.envMap = sky.map
}
/******** light *******/
{
this.lightObj3D = new Object3D()
this.lightObj3D.rotationX = 124
this.lightObj3D.rotationY = 327
this.lightObj3D.rotationZ = 265.38
let directLight = this.lightObj3D.addComponent(DirectLight)
directLight.lightColor = KelvinUtil.color_temperature_to_rgb(5355)
directLight.castShadow = true
directLight.intensity = 43
let gui = new dat.GUI()
let DirLight = gui.addFolder('DirectLight')
DirLight.add(directLight, 'enable')
DirLight.add(directLight.transform, 'rotationX', 0.0, 360.0, 0.01)
DirLight.add(directLight.transform, 'rotationY', 0.0, 360.0, 0.01)
DirLight.add(directLight.transform, 'rotationZ', 0.0, 360.0, 0.01)
DirLight.addColor({
lightColor: [directLight.lightColor.r, directLight.lightColor.g, directLight.lightColor.b, 1].map((v,i)=> i == 3 ? v : Math.floor(v*255))
}, 'lightColor').onChange(v=>{
directLight.lightColor = new Color(v[0]/255, v[1]/255, v[2]/255, v[3])
})
DirLight.add(directLight, 'intensity', 0.0, 160.0, 0.01)
DirLight.add(directLight, 'indirect', 0.0, 10.0, 0.01)
DirLight.add(directLight, 'castShadow')
DirLight.open()
this.scene.addChild(this.lightObj3D)
}
{
let clearCoatRoughnessTex = await Engine3D.res.loadTexture('https://cdn.orillusion.com/PBR/ClearCoatTest/T_Imperfections_Wipe_Mask.PNG')
let space = 50
let geo = new SphereGeometry(15, 35, 35)
for (let i = 0; i < 10; i++) {
var obj = new Object3D()
let mr = obj.addComponent(MeshRenderer)
mr.geometry = geo
let mat = new LitMaterial()
mat.baseColor = new Color(1.0, 0.0, 0.0)
mat.metallic = 0
mat.roughness = 1
mat.clearCoatRoughnessMap = clearCoatRoughnessTex
// mat.clearcoatFactor = i / 10;
mat.clearcoatColor = new Color(0.0, 0.0, 0.0)
mat.clearcoatWeight = 0.65
mat.clearcoatFactor = 1
mat.clearcoatRoughnessFactor = i / 10
mr.material = mat
this.scene.addChild(obj)
obj.x = space * i - space * 10 * 0.5
}
}
}
}
new Sample_ClearCoat().run()
|
using Amazon.Lambda.TestUtilities;
using Amazon.Runtime.SharedInterfaces;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
using LatestFilingsEventPublisher.UnitTests;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Moq;
using Moq.Protected;
using System.Net;
using System.Xml.Serialization;
using Xunit;
namespace LatestFilingsEventPublisher.Tests;
public class FunctionTests
{
/// <summary>
/// Tests that the required <see cref="Function"/> services are registered in the DI container.
/// </summary>
[Fact]
public void Function_DependencyInjection_RequiredServicesAreFound()
{
// Arrange
ServiceCollection serviceCollection = new();
// Act
var function = new Function(serviceCollection);
// Assert
Assert.NotNull(function.ServiceProvider);
Assert.NotNull(function.ServiceProvider.GetService(typeof(ILogger<Function>)));
Assert.NotNull(function.ServiceProvider.GetService(typeof(IHttpClientFactory)));
Assert.NotNull(function.ServiceProvider.GetService(typeof(IAmazonSimpleNotificationService)));
Assert.NotNull(function.ServiceProvider.GetService(typeof(XmlSerializer)));
}
/// <summary>
/// Tests the function handler publishes the expected number of events when the feed data is valid.
/// </summary>
[Theory]
[InlineData(TestFeedData.FeedWithNoEntries, 0)]
[InlineData(TestFeedData.FeedWithTwoEntries, 2)]
public async void FunctionHandler_ValidFeedData_PublishesExpectedNumberOfEvents(string testFeedData, int expectedPublishedEventsCount)
{
// Arrange
var loggerMock = new Mock<ILogger<Function>>();
// Setup the HTTP client to return a Feed with the test Theory entries.
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
var mockResponse = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(testFeedData)
};
mockHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(m => m.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(mockResponse);
var httpClient = new HttpClient(mockHandler.Object);
var httpClientFactoryMock = new Mock<IHttpClientFactory>();
httpClientFactoryMock
.Setup(_ => _.CreateClient(It.IsAny<string>()))
.Returns(httpClient);
var snsConfigMock = new Mock<AmazonSimpleNotificationServiceConfig>();
var snsMock = new Mock<IAmazonSimpleNotificationService>();
snsMock.Setup(sns => sns.PublishAsync(It.IsAny<PublishRequest>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(new PublishResponse { HttpStatusCode = HttpStatusCode.OK });
ServiceCollection serviceCollection = new();
serviceCollection.AddSingleton(loggerMock.Object);
serviceCollection.AddSingleton(httpClientFactoryMock.Object);
serviceCollection.AddSingleton(snsConfigMock.Object);
serviceCollection.AddSingleton(snsMock.Object);
// Don't mock the XML serializer, use the real one.
var context = new TestLambdaContext();
var function = new Function(serviceCollection);
// Act
var exception = await Record.ExceptionAsync(async () =>
{
await function.FunctionHandler(context);
});
// Assert
Assert.Null(exception);
Assert.True(snsMock.Invocations.Count == expectedPublishedEventsCount);
}
}
|
# سرطان الشرج: العوامل، الأعراض، طرق العلاج
__شارك __غرد
الحكة والنزيف في فتحة الشرج يشتبه عادة بانه بسبب البواسير. ولكن في بعض الحالات
قد تشير هذه الأعراض إلى سرطان الشرج. السبب الرئيسي لسرطان الشرج هو فيروس الورم
الحليمي البشري الذي يسبب أيضا سرطان عنق الرحم!
**سرطان الشرج** هو ورم خبيث نادر الحدوث يظهر عند فتحة الشرج. عوامل المرض مختلفة وتشمل الإيدز (HIV)، فيروس الورم الحليمي البشري والتدخين. تشمل العلاجات عادة العلاج الكيميائي والإشعاعي ويمكن دمج العلاجات الطبية التكميلية مثل الوخز بالإبر، والتي سنفصلها لاحقا.
حوالي نصف حالات **سرطان الشرج** يتم تشخيصها قبل انتشار الورم خارج المنطقة، في
حين ان حوالي الثلث يتم تشخيصهم بعد أن يكون السرطان قد انتشر إلى الغدد
الليمفاوية. ويتم تشخيص 10٪ من المرضى بعد أن يكون السرطان قد انتشر إلى أعضاء
بعيدة. كلما تم الكشف عن سرطان الشرج في وقت مبكر، كلما كانت فرص نجاح علاجه
أفضل.
نسبة البقاء على قيد الحياة لدى النساء بعد خمس سنوات من تشخيص سرطان الشرج هي
71٪، في حين أنها تبلغ لدى الرجال 60٪. عندما يتم تشخيص السرطان في مرحلة مبكرة
من المرض فإن نسبة البقاء على قيد الحياة بعد خمس سنوات هي 82٪. إذا تم تشخيص
السرطان بعد انتشاره إلى الغدد الليمفاوية، فإن نسبة البقاء على قيد الحياة بعد
خمس سنوات تنخفض الى 60٪. في حال تم تشخيص السرطان بعد انتشاره إلى أعضاء أخرى،
فواحد فقط من كل خمسة مرضى يعيشون أكثر من خمسة أعوام.
## من يصاب بسرطان الشرج؟
عادة ما يتم تشخيص **سرطان الشرج** لدى الأشخاص الذين تتراوح أعمارهم بين 50 و-
80 عام وتكون نسبته أكثر بقليل لدى النساء. فقبل سن ال 50، يكون سرطان الشرج أكثر
شيوعا لدى الرجال.
التلوث في منطقة الشرج الناجم عن فيروس الورم الحليمي البشري- HPV هو السبب
الرئيسي لحدوث سرطان الشرج. وترتبط 85٪ من حالات سرطان الشرج بالتلوثات المستمرة
بالفيروس الذي ينتقل عن طريق الاتصال الجنسي. ينتشر الفيروس من شخص لاخر خلال
ملامسة الجلد للجلد عندما يكون احدهم مصاب بالفيروس. يمكن أن تحدث الإصابة بفيروس
HPV خلال ولوج المهبل، ولوج الشرج، وكذلك خلال ممارسة الجنس عن طريق الفم.
التلوث الناجم عن فيروس الورم الحليمي البشري شائع وفي معظم الحالات يكون الجسم
قادرا على تنقية نفسه من الفيروس. في بعض الحالات فان التلوث لا يختفي ويصبح
مزمنا. التلوث المزمن يمكن أن يؤدي إلى أنواع معينة من السرطان مثل سرطان عنق
الرحم وسرطان الشرج. لقاح ال- HPV صرح بالأصل للوقاية من سرطان عنق الرحم، وتمت
الموافقة عليه مؤخرا أيضا للوقاية من سرطان الشرج.
عوامل الخطر الأخرى لسرطان الشرج، بالإضافة إلى عامل السن (فوق ال- 50) هي:
ممارسة الجنس مع الكثير من الشركاء، ممارسة الجنس عن طريق الشرج، ضعف الجهاز
المناعي، الاحمرار والألم مستمر في هذه المنطقة والتدخين. بعض الأورام التي تتطور
في منطقة الشرج ليست سرطانية، لكن يمكن أن تتطور لتصبح كذلك مع مرور الوقت. وقد
أظهرت الدراسات الحديثة أن الرجال الذين خضعوا للختان ، يكون خطر إصابتهم بفيروس
HPV وتطوير سرطان الشرج أقل من الرجال الذين لم يخضعوا لعملية الختان.
أيضا الأشخاص الذين تم تشخيص فيروس نقص المناعة البشرية (HIV) المسبب لمرض
الايدز، يكونون أكثر عرضة للإصابة بسرطان الشرج. يقلل العلاج الدوائي لل- HIV من
مخاطر العديد من الأمراض المرتبطة بالإيدز، ولكنه لا يقلل من نسبة الإصابة بسرطان
الشرج.
## ما هي أعراض سرطان الشرج؟
في حالات معينة، لا تظهر أعراض مرتبطة بسرطان الشرج، ولكن لدى نصف المرضى يحدث
النزيف الذي يشكل العلامة الأولى للمرض. الحكة الشرجية يمكن أيضا أن تكون من
أعراض سرطان الشرج، لذلك يعتقد الكثيرون خطأ أنهم مصابون بالبواسير.
### علامات وأعراض سرطان الشرج الأخرى:
* ألم أو ضغط في منطقة الشرج
* افرازات غير طبيعية من فتحة الشرج
* ورم في منطقة فتحة الشرج
* تغيير في عمل الأمعاء
### كيف يتم تشخيص سرطان الشرج؟
يمكن الكشف عن سرطان الشرج أثناء الفحص الرقمي الروتيني لمنطقة الشرج أو أثناء
إجراء عملية قصيرة مثل استئصال البواسير. السرطان قد يكتشف بإجراءات غازية أكثر
مثل التنظير، تنظير القولون أو فحص الموجات فوق الصوتية للمستقيم. إذا كان هناك
اشتباه بوجود السرطان، فيتم اجراء خزعة وفحصها من قبل الطبيب المختص.
### كيف يتم علاج سرطان الشرج؟
تشمل العلاجات التقليدية لسرطان الشرج الجراحة، العلاج الكيميائي والإشعاعي.
العلاج يكون عادة مدمج ويشمل اثنتين أو أكثر من استراتيجيات العلاج. العلاج
الكيميائي مع العلاج الإشعاعي هو الدمج الأكثر شيوعا للعلاج الأولي للمرض.
### الطب البديل يخفف من التعامل مع العلاجات
لا تقدم أساليب الطب التكميلي كعلاج للسرطان، لكنها تستخدم للتخفيف من الام
المريض. بعض الأمثلة على هذه الأساليب التي يتم إضافتها إلى العلاج الطبي
التقليدي هي الوخز بالإبر الصينية لتخفيف الالام، التأمل للحد من التوتر أو شاي
النعناع لتخفيف الشعور بالغثيان.
من قبل ويب طب - الاثنين ، 16 فبراير 2015
آخر تعديل - الأربعاء ، 25 فبراير 2015
__شارك __غرد
|
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
phone_number = forms.CharField(label=_("phone number"), max_length=20, required=False)
class Meta(UserCreationForm.Meta):
model = CustomUser
fields = ("email", "username", "phone_number")
class CustomUserChangeForm(UserChangeForm):
phone_number = forms.CharField(label=_("phone number"), max_length=20, required=False)
class Meta(UserChangeForm.Meta):
model = CustomUser
fields = ("email", "phone_number")
|
package leetcode.editor.cn;
//给你一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。
//
//
//
// 示例 1:
//
//
//输入:points = [[1,1],[2,2],[3,3]]
//输出:3
//
//
// 示例 2:
//
//
//输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
//输出:4
//
//
//
//
// 提示:
//
//
// 1 <= points.length <= 300
// points[i].length == 2
// -10⁴ <= xi, yi <= 10⁴
// points 中的所有点 互不相同
//
// 👍 418 👎 0
import java.util.HashMap;
/**
* 直线上最多的点数
*
* @author IronSid
* @version 1.0
* @since 2022-06-29 22:49:44
*/
public class MaxPointsOnALineSolution {
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int maxPoints(int[][] points) {
int n = points.length;
if (n == 1) return 1;
int max = 2;
for (int i = 0; i < n; i++) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int j = i + 1; j < n; j++) {
int[] simplest = simplify(points[i][1] - points[j][1], points[i][0] - points[j][0]);
int key = (simplest[0] << 16) | simplest[1];
int cnt = map.getOrDefault(key, 0) + 1;
map.put(key, cnt);
max = Math.max(max, cnt + 1);
}
}
return max;
}
// 简化分数 a / b
int[] simplify(int a, int b) {
if (a == 0) return new int[]{0, 1};
if (b == 0) return new int[]{1, 0};
boolean negative = a > 0 != b > 0;
if (a < 0) a = -a;
if (b < 0) b = -b;
int gcd = gcd(a, b);
a /= gcd;
b /= gcd;
// 规定分母必须为正
return new int[]{negative ? -a : a, b};
}
int gcd(int a, int b) {
while (b != 0) {
int t = a;
a = b;
b = t % b;
}
return a;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
|
<!--DataBinding sencillo para contenido de datos:
Para crear un databinding dencillo, basta con usar dentro del contenido html la variable entre los carácteres especiales, de esta
manera se mostrarán los datos que estén implementados en la lógica dentro de esa variable y cambiará dinámicamente en la vista
-->
<div class="container">
<div class="row">
<div class="col-xs-12">
<h3>Ejemplo de DataBinding sencillo {{serverId +" "+ serverStatus}} is {{serverStatus}}!</h3>
</div>
</div>
</div>
<div class="text-white ">Separador</div>
<!--DataBinding de un atributo
*forrma1
[nombre del atributo]="nombreVariable o código"
-->
<div class="container">
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary" [style.display]="nuevoServer">Botonazo</button>
</div>
</div>
</div>
<div class="text-white ">Separador</div>
<!--DataBinding de un evento
*forrma1
(nombre del evento, click,mouseEnter...) ="nombreMétodo o código"
-->
<div class="container">
<div class="row">
<div class="col-xs-12">
<button class="btn btn-primary" (click)="boton1click()">Botonazo</button>
</div>
</div>
</div>
<div class="text-white ">Separador</div>
<!--DataBinding doble:
Para crear un databinding doble se usa ngModel (para usarlo debe estar incluido en app.module.ts como:
"import { FormsModule } from '@angular/forms';"
Y declarado dentro de los imports
"FormsModule"
[(ngModel)]="nombre variable"-->
<div class="container">
<div class="row">
<div class="col-xs-12">
<h3>Ejemplo de DataBinding doble</h3>
<input type="text" class="form-control" [(ngModel)]="serverResume" placeHolder="hola">
<p>{{serverResume}}</p>
</div>
</div>
</div>
|
/*
* Copyright (c) 2018.
*
* Anthony Ngure
*
* Email : anthonyngure25@gmail.com
*/
package ke.co.toshngure.basecode.database;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import java.util.List;
/**
* Created by Anthony Ngure on 8/26/2016.
* Email : anthonyngure25@gmail.com.
* Company : Laysan Incorporation
*/
public abstract class BaseLoader<T> extends AsyncTaskLoader<List<T>> {
private static final String TAG = BaseLoader.class.getSimpleName();
private List<T> mData;
public BaseLoader(Context context) {
super(context);
}
@Override
public List<T> loadInBackground() {
return onLoad();
}
public abstract List<T> onLoad();
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
//super.onStartLoading();
}
@Override
protected void onStopLoading() {
super.onStopLoading();
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
onStopLoading();
if (mData != null) {
releaseResources(mData);
}
}
@Override
public void onCanceled(List<T> data) {
super.onCanceled(data);
releaseResources(mData);
}
@Override
public void deliverResult(List<T> data) {
if (isReset()) {
releaseResources(data);
return;
}
List<T> oldData = mData;
mData = data;
if (isStarted()) {
super.deliverResult(data);
}
if ((oldData != null) && (oldData != data)) {
releaseResources(oldData);
}
}
private void releaseResources(List<T> data) {
}
public interface DataLoaderCallBacks<T> {
List<T> loadData();
}
}
|
package com.dwtedx.income.filter;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;
import com.alibaba.fastjson.JSON;
import com.dwtedx.income.model.common.ResultInfo;
import com.dwtedx.income.utility.CommonUtility;
import com.dwtedx.income.utility.ICConsants;
import com.dwtedx.income.utility.MD5Util;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RequestVerifySingFilter extends OncePerRequestFilter {
private static Logger logger = Logger.getLogger(RequestVerifySingFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
try {
String contentType = request.getHeader("content-type");
if (CommonUtility.isEmpty(contentType)) {
contentType = request.getHeader("Content-type");
}
if (CommonUtility.isEmpty(contentType)) {
contentType = request.getHeader("Content-Type");
}
if (!CommonUtility.isEmpty(contentType) && "application/json".equals(contentType)) {
// 防止流读取一次后就没有了, 所以需要将流继续写出去
ServletRequest requestWrapper = new JsonReaderRequestWrapper(request);
String json = JsonHttpHelper.getBodyString(requestWrapper);
logger.info("request:" + json);
// 准备工作 传入vo请参照第一篇里面的实体。此处不再重新贴上代码 浪费大家时间
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(json);// 这里的JsonNode和XML里面的Node很像
json = node.get("body").toString();// 获取voName
node = node.get("head");// 获取voName
String sing = node.get("sign").textValue();// 获取voName
// MD5
String md5Str = json + ";jFX024sn0gk08m8J630PJq7D787sWNnIQYLdwtedx199117??";
md5Str = md5Str.replaceAll("/", "");
md5Str = md5Str.replaceAll("\\\\", "");
md5Str = MD5Util.stringToMD5(md5Str);
// String strVal32 = MD5Util.getStringRandom(32);
// 暂时放过一切请求
// filterChain.doFilter(request, response);
if (md5Str.equals(sing)) {
filterChain.doFilter(requestWrapper, response);
} else {
ResultInfo resultInfo = new ResultInfo();
resultInfo.getHead().setMessage("非法请求,肉机走开。");
resultInfo.getHead().setErrorCode(ICConsants.ERRORCODE_10001);
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
// Boolean.TRUE);
// String json = mapper.writeValueAsString(resultInfo);
String jsonOut = JSON.toJSONString(resultInfo);
response.setStatus(500);
OutputStream outputStream = response.getOutputStream();// 获取OutputStream输出流
response.setHeader("content-type", "text/html;charset=UTF-8");// 通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
byte[] dataByteArr = jsonOut.getBytes("UTF-8");// 将字符转换成字节数组,指定以UTF-8编码进行转换
outputStream.write(dataByteArr);// 使用OutputStream流向客户端输出字节数组
}
} else {
filterChain.doFilter(request, response);
}
} catch (Exception e) {
try {
ResultInfo resultInfo = new ResultInfo();
resultInfo.getHead().setMessage(e.getMessage());
resultInfo.getHead().setErrorCode(ICConsants.ERRORCODE_10001);
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
// Boolean.TRUE);
// String json = mapper.writeValueAsString(resultInfo);
String jsonOut = JSON.toJSONString(resultInfo);
response.setStatus(500);
OutputStream outputStream = response.getOutputStream();// 获取OutputStream输出流
response.setHeader("content-type", "text/html;charset=UTF-8");// 通过设置响应头控制浏览器以UTF-8的编码显示数据,如果不加这句话,那么浏览器显示的将是乱码
byte[] dataByteArr = jsonOut.getBytes("UTF-8");// 将字符转换成字节数组,指定以UTF-8编码进行转换
outputStream.write(dataByteArr);// 使用OutputStream流向客户端输出字节数组
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
|
/// This is where I plan to keep all the math, including vector operations I guess
pub mod math {
use std::f32::consts::PI;
use rlbot_lib::rlbot::{Rotator, Vector3};
pub fn vec_new(x: f32, y: f32, z: f32) -> Vector3 {
Vector3 { x, y, z }
}
pub fn vec2_new(x: f32, y: f32) -> Vector3 {
Vector3 { x, y, z: 0. }
}
pub fn clamp(n: f32, lower_limit: f32, upper_limit: f32) -> f32 {
if n > upper_limit {
upper_limit
} else if n < lower_limit {
lower_limit
} else {
n
}
}
pub fn abs_clamp(n: f32, limit: f32) -> f32 {
if n.abs() > limit {
return limit * n.signum();
}
n
}
// don't ask me why this works. I don't know
pub fn rotate(
axis: &nalgebra::Unit<
nalgebra::Matrix<
f32,
nalgebra::Const<3>,
nalgebra::Const<1>,
nalgebra::ArrayStorage<f32, 3, 1>,
>,
>,
rotr: nalgebra::Rotation<f32, 3>,
rotp: nalgebra::Rotation<f32, 3>,
roty: nalgebra::Rotation<f32, 3>,
) -> nalgebra::Vector3<f32> {
let axis = rotr.inverse_transform_unit_vector(&axis);
let axis = rotp.inverse_transform_unit_vector(&axis);
let axis = roty.inverse_transform_unit_vector(&axis);
*axis
}
pub fn forward_vec(rotator: &Rotator) -> Vector3 {
let rotr = nalgebra::Rotation::from_euler_angles(0., rotator.roll, 0.);
let rotp = nalgebra::Rotation::from_euler_angles(-rotator.pitch, 0., 0.);
let roty = nalgebra::Rotation::from_euler_angles(0., 0., -rotator.yaw + PI / 2.);
Vector3::from_nalg(rotate(&nalgebra::Vector3::y_axis(), rotr, rotp, roty))
}
pub fn up_vec(rotator: &Rotator) -> Vector3 {
let rotr = nalgebra::Rotation::from_euler_angles(0., rotator.roll, 0.);
let rotp = nalgebra::Rotation::from_euler_angles(-rotator.pitch, 0., 0.);
let roty = nalgebra::Rotation::from_euler_angles(0., 0., -rotator.yaw + PI / 2.);
Vector3::from_nalg(rotate(&nalgebra::Vector3::z_axis(), rotr, rotp, roty))
}
pub fn left_vec(rotator: &Rotator) -> Vector3 {
let rotr = nalgebra::Rotation::from_euler_angles(0., rotator.roll, 0.);
let rotp = nalgebra::Rotation::from_euler_angles(-rotator.pitch, 0., 0.);
let roty = nalgebra::Rotation::from_euler_angles(0., 0., -rotator.yaw + PI / 2.);
Vector3::from_nalg(rotate(&nalgebra::Vector3::x_axis(), rotr, rotp, roty))
}
pub fn dir_vecs(rotator: &Rotator) -> Vec<Vector3> {
let rotr = nalgebra::Rotation::from_euler_angles(0., rotator.roll, 0.);
let rotp = nalgebra::Rotation::from_euler_angles(-rotator.pitch, 0., 0.);
let roty = nalgebra::Rotation::from_euler_angles(0., 0., -rotator.yaw + PI / 2.);
let forward = rotate(&nalgebra::Vector3::y_axis(), rotr, rotp, roty);
let left = rotate(&nalgebra::Vector3::x_axis(), rotr, rotp, roty);
let up = rotate(&nalgebra::Vector3::z_axis(), rotr, rotp, roty);
vec![
Vector3 {
x: forward.x,
y: forward.y,
z: forward.z,
},
Vector3 {
x: up.x,
y: up.y,
z: up.z,
},
Vector3 {
x: left.x,
y: left.y,
z: left.z,
},
]
}
pub trait Vec3 {
fn dot(&self, v: &Vector3) -> f32;
fn cross(&self, v: &Vector3) -> Vector3;
fn dist(&self, v: &Vector3) -> f32;
fn ground_dist(&self, v: &Vector3) -> f32;
fn ground(&self) -> Vector3;
fn sub(&self, v: &Vector3) -> Vector3;
fn add(&self, v: &Vector3) -> Vector3;
fn scale(&self, s: f32) -> Vector3;
fn normalize(&self) -> Vector3;
fn norm(&self) -> f32;
fn angle_between(&self, v: &Vector3) -> f32;
fn direction(&self, v: &Vector3) -> Vector3;
fn x(&self) -> f32;
fn y(&self) -> f32;
fn z(&self) -> f32;
fn to_nalg(&self) -> nalgebra::Vector3<f32>;
fn from_nalg(v: nalgebra::Vector3<f32>) -> Vector3;
fn up() -> Vector3;
}
pub trait Rot3 {
fn to_nalg(&self) -> nalgebra::Rotation3<f32>;
}
impl Vec3 for Vector3 {
/// Calculate the dot product of two vectors
fn dot(&self, v: &Vector3) -> f32 {
self.x * v.x + self.y * v.y + self.z * v.z
}
fn cross(&self, v: &Vector3) -> Vector3 {
Vector3 {
x: self.y * v.z - self.z * v.y,
y: self.z * v.x - self.x * v.z,
z: self.x * v.y - self.y * v.x,
}
}
/// Calculate the distance from this vector to another
fn dist(&self, v: &Vector3) -> f32 {
((self.x - v.x).powi(2) + (self.y - v.y).powi(2) + (self.z - v.z).powi(2)).sqrt()
}
/// Zero the z component of the vector
fn ground(&self) -> Vector3 {
Vector3 { z: 0., x: self.x, y: self.y }
}
/// Operator overloading on a trait is a royal pain in the ass. Thanks rust
fn sub(&self, v: &Vector3) -> Vector3 {
Vector3 {
x: self.x - v.x,
y: self.y - v.y,
z: self.z - v.z,
}
}
fn add(&self, v: &Vector3) -> Vector3 {
Vector3 {
x: self.x + v.x,
y: self.y + v.y,
z: self.z + v.z,
}
}
fn scale(&self, s: f32) -> Vector3 {
Vector3 {
x: self.x * s,
y: self.y * s,
z: self.z * s,
}
}
/// direction vector of length 1
fn normalize(&self) -> Vector3 {
let sum = self.x + self.y + self.z;
Vector3 {
x: self.x / sum,
y: self.y / sum,
z: self.z / sum,
}
}
/// length of the vector
fn norm(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2) + self.z.powi(2)).sqrt()
}
// kinda a hack to enable operator overloading
fn x(&self) -> f32 {
self.x
}
fn z(&self) -> f32 {
self.z
}
fn y(&self) -> f32 {
self.y
}
fn from_nalg(v: nalgebra::Vector3<f32>) -> Vector3 {
Vector3 {
x: v.x,
y: v.y,
z: v.z,
}
}
fn to_nalg(&self) -> nalgebra::Vector3<f32> {
nalgebra::Vector3::new(self.x, self.y, self.z)
}
fn up() -> Vector3 {
Vector3 {
x: 0.,
y: 0.,
z: 1.,
}
}
fn angle_between(&self, v: &Vector3) -> f32 {
(self.dot(v) / (self.norm() * v.norm())).acos()
}
fn direction(&self, target: &Vector3) -> Vector3 {
target.sub(self).normalize()
}
fn ground_dist(&self, v: &Vector3) -> f32 {
self.ground().dist(&v.ground())
}
}
impl Rot3 for Rotator {
fn to_nalg(&self) -> nalgebra::Rotation3<f32> {
nalgebra::Rotation3::from_euler_angles(self.roll, self.pitch, self.yaw)
}
}
}
|
const express = require('express')
const app = express()
const port = process.env.PORT || 3000;
const cors = require("cors")
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
app.use(express.json());
app.use(cors());
// msmasumbillah0000
// DHYBDqxrFYqLhYZc
const uri = "mongodb+srv://msmasumbillah0000:DHYBDqxrFYqLhYZc@cluster0.pf0bweu.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0";
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
const userCollection = client.db("usersDB").collection("users");
app.get("/users", async (req, res) => {
const quary = client.db("usersDB").collection("users");
const cursor = quary.find();
const result = await cursor.toArray();
res.send(result);
})
app.get("/users/:id", async (req, res) => {
const id = req.params.id;
const quary = { _id: new ObjectId(id) };
const result = await userCollection.findOne(quary);
res.send(result)
})
app.post("/users", async (req, res) => {
const user = req.body;
const result = await userCollection.insertOne(user);
res.send(result)
console.log(user)
})
app.put("/users/:id", async (req, res) => {
const id = req.params.id;
const user = req.body;
const quary = { _id: new ObjectId(id) };
const options = { upsert: true };
const updatedUser = {
$set: {
name: user.name,
email: user.email
}
}
const result = await userCollection.updateOne(quary, updatedUser, options);
res.send(result)
// console.log(user);
})
app.delete("/users/:usersId", async (req, res) => {
const quary = { _id: new ObjectId(req.params.usersId) };
const result = await userCollection.deleteOne(quary);
res.send(result)
})
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
|
import UIKit
import CoreData
// MARK: - CoreDataManager
struct CoreDataManager {
enum Categories: String, CaseIterable {
case characters = "Characters"
case episodes = "Episodes"
case stores = "Next Door Stores"
case trucks = "Pest Control Trucks"
case credits = "End Credits"
case burgers = "Burgers Of The Day"
}
static var favoritesDictionary: [Categories: [Any]] = [.characters: [],
.episodes: [],
.stores: [],
.trucks: [],
.credits: [],
.burgers: []
]
// swiftlint:disable force_cast
static let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// swiftlint:enable force_cast
// MARK: - Data Manipulation Methods
static func saveFavorites() {
do {
try context.save()
} catch {
print("\(String.contextSavingError) \(error)")
}
}
static func deleteItem(withKey key: Categories, at index: Int) {
guard let itemToDelete = (favoritesDictionary[key]?[index]) as? NSManagedObject else { return }
context.delete(itemToDelete)
favoritesDictionary[key]?.remove(at: index)
saveFavorites()
}
static func loadAll() {
loadFavorites(with: CDBurger.fetchRequest())
loadFavorites(with: CDCredits.fetchRequest())
loadFavorites(with: CDTruck.fetchRequest())
loadFavorites(with: CDStore.fetchRequest())
loadFavorites(with: CDEpisode.fetchRequest())
loadFavorites(with: CDCharacter.fetchRequest())
}
// swiftlint:disable:next cyclomatic_complexity
static func loadFavorites(with request: NSFetchRequest<NSFetchRequestResult>) {
switch request.entityName {
case K.CoreDataEntitiesNames.cdCharacter:
do {
favoritesDictionary[.characters] = try context.fetch(request)
} catch {
print("\(String.contextDataFetchingError) \(error)")
}
case K.CoreDataEntitiesNames.cdEpisode:
do {
favoritesDictionary[.episodes] = try context.fetch(request)
} catch {
print("\(String.contextDataFetchingError) \(error)")
}
case K.CoreDataEntitiesNames.cdStore:
do {
favoritesDictionary[.stores] = try context.fetch(request)
} catch {
print("\(String.contextDataFetchingError) \(error)")
}
case K.CoreDataEntitiesNames.cdTruck:
do {
favoritesDictionary[.trucks] = try context.fetch(request)
} catch {
print("\(String.contextDataFetchingError) \(error)")
}
case K.CoreDataEntitiesNames.cdCredits:
do {
favoritesDictionary[.credits] = try context.fetch(request)
} catch {
print("\(String.contextDataFetchingError) \(error)")
}
case K.CoreDataEntitiesNames.cdBurger:
do {
favoritesDictionary[.burgers] = try context.fetch(request)
} catch {
print("\(String.contextDataFetchingError) \(error)")
}
default:
return
}
}
}
// MARK: - String fileprivate extension
fileprivate extension String {
static let contextSavingError = "Error saving context:"
static let contextDataFetchingError = "Error fetching data from context:"
}
|
import type { RouteRecordRaw, RouteLocation } from 'vue-router'
import { constRoutes, asyncRoutes } from '@/router/routes'
import { router } from '@/router'
// 检查路由所需权限
function hasPermission(
userPermissions: string[],
route: RouteRecordRaw
): boolean {
if (route.meta && route.meta.permissions)
return userPermissions.some((permission) =>
route.meta?.permissions?.includes(permission)
)
return true
}
// 根据权限过滤动态路由
function filterAsyncRoutes(
asyncRoutes: RouteRecordRaw[],
userPermissions: string[]
): RouteRecordRaw[] {
const filteredRoutes: RouteRecordRaw[] = []
asyncRoutes.forEach((asyncRoute) => {
const clonedRoute: RouteRecordRaw = { ...asyncRoute }
if (hasPermission(userPermissions, clonedRoute)) {
if (clonedRoute.children) {
clonedRoute.children = filterAsyncRoutes(
clonedRoute.children,
userPermissions
)
}
filteredRoutes.push(clonedRoute)
}
})
return filteredRoutes
}
// 筛选出用作导航菜单的路由
function filterMenuRoutes(accessRoutes: RouteRecordRaw[]): RouteLocation[] {
return accessRoutes.flatMap((accessRoute) => {
if (accessRoute.name && accessRoute.meta?.isNavMenu) {
return [router.resolve(accessRoute)]
} else if (accessRoute.children) {
return filterMenuRoutes(accessRoute.children)
}
return []
})
}
export default defineStore('dynamicRoute', () => {
const accessRoutes = shallowRef<RouteRecordRaw[]>(constRoutes)
const isGeneratedRoutes = ref<boolean>(false) // flag,标识是否已经生成动态路由
const menuRoutes = computed(() => filterMenuRoutes(accessRoutes.value))
function generatedRoutes(userPermissions: string[]) {
const filteredRoutes = filterAsyncRoutes(asyncRoutes, userPermissions)
accessRoutes.value = accessRoutes.value.concat(filteredRoutes)
return filteredRoutes
}
function setFlag4GenRoutes(flag: boolean) {
isGeneratedRoutes.value = flag
}
function resetAccessRoutes() {
accessRoutes.value = constRoutes
}
return {
accessRoutes,
isGeneratedRoutes,
menuRoutes,
generatedRoutes,
setFlag4GenRoutes,
resetAccessRoutes,
}
})
|
import React, { useState, useEffect } from 'react';
import { db, auth } from '../firebase-config';
import SendMessage from './SendMessage';
import {
collection,
query,
limit,
orderBy,
onSnapshot,
} from 'firebase/firestore';
import { Link } from 'react-router-dom';
function Chat() {
const [messages, setMessages] = useState([]);
const { userID } = auth.currentUser;
useEffect(() => {
const q = query(
collection(db, 'messages'),
orderBy('createdAt'),
limit(50)
);
const data = onSnapshot(q, (QuerySnapshot) => {
let messages = [];
QuerySnapshot.forEach((doc) => {
messages.push({ ...doc.data(), id: doc.id });
});
setMessages(messages);
});
return () => data();
}, []);
return (
<div className="flex flex-col h-screen bg-gray-100">
<div className="flex justify-between items-center p-4 bg-blue-500 text-white">
<div>Kura</div>
{/* link to go to profile */}
<div className="flex gap-3">
<Link to="/profile">
<img
src={auth.currentUser.photoURL}
alt="User"
className="w-8 h-8 rounded-full border-2 border-white"
/>
</Link>
<button
onClick={() => auth.signOut()}
className="p-2 bg-red-500 rounded"
>
Sign Out
</button>
</div>
</div>
<div className="flex-1 overflow-y-auto p-4">
{messages &&
messages.map((message) => (
<div
key={message.id}
className={`flex mb-4 ${
userID === auth.currentUser.uid
? 'justify-end'
: 'justify-start'
}`}
>
<div
className={`msg ${
userID === auth.currentUser.uid ? 'sent' : 'received'
}`}
>
<img
src={message.photoURL}
alt="User"
className="w-8 h-8 rounded-full mr-2"
/>
<p>{message.text}</p>
</div>
</div>
))}
</div>
<SendMessage />
</div>
);
}
export default Chat;
|
<?php
namespace App\Entity;
use App\Repository\MethodeCaptureRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: MethodeCaptureRepository::class)]
class MethodeCapture
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 50)]
private ?string $nomMethode = null;
/**
* @var Collection<int, Capture>
*/
#[ORM\OneToMany(targetEntity: Capture::class, mappedBy: 'methodeCapture')]
private Collection $captures;
public function __construct()
{
$this->captures = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getNomMethode(): ?string
{
return $this->nomMethode;
}
public function setNomMethode(string $nomMethode): static
{
$this->nomMethode = $nomMethode;
return $this;
}
/**
* @return Collection<int, Capture>
*/
public function getCaptures(): Collection
{
return $this->captures;
}
public function addCapture(Capture $capture): static
{
if (!$this->captures->contains($capture)) {
$this->captures->add($capture);
$capture->setMethodeCapture($this);
}
return $this;
}
public function removeCapture(Capture $capture): static
{
if ($this->captures->removeElement($capture)) {
// set the owning side to null (unless already changed)
if ($capture->getMethodeCapture() === $this) {
$capture->setMethodeCapture(null);
}
}
return $this;
}
public function __toString()
{
return $this->nomMethode;
}
}
|
import 'package:flutter/material.dart';
import 'package:flutter_cubit_appp/pages/nav_pages/bar_item_page.dart';
import 'package:flutter_cubit_appp/pages/nav_pages/home_page.dart';
import 'package:flutter_cubit_appp/pages/nav_pages/my_page.dart';
import 'package:flutter_cubit_appp/pages/nav_pages/search_page.dart';
class MainPage extends StatefulWidget {
const MainPage({Key? key}) : super(key: key);
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
List pages = [
HomePage(),
BarItemPage(),
SearchPage(),
MyPage(),
];
int currentIndex = 0;
void onTap(int index) {
setState(() {
currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: pages[currentIndex],
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.black54,
unselectedItemColor: Colors.grey.withOpacity(0.5),
showSelectedLabels: false,
showUnselectedLabels: false,
backgroundColor: Colors.white,
currentIndex: currentIndex,
elevation: 0,
onTap: onTap,
items: [
BottomNavigationBarItem(icon: Icon(Icons.apps), label: "Home"),
BottomNavigationBarItem(
icon: Icon(Icons.bar_chart_sharp), label: "Bar"),
BottomNavigationBarItem(icon: Icon(Icons.search), label: "Search"),
BottomNavigationBarItem(icon: Icon(Icons.person), label: "My"),
],
),
);
}
}
|
package main
import (
"fmt"
"log"
"strings"
"github.com/mariogarzac/Advent/utils"
)
type Point struct {
x int
y int
}
var valid = map[Point]map[string]map[string]bool {
{0, 1} : {
// - J 7
"S" : {"-": true, "J": true, "7": true},
"-" : {"-": true, "J": true, "7": true},
"L" : {"-": true, "J": true, "7": true},
"F" : {"-": true, "J": true, "7": true},
},
{0,-1} : {
// - F L
"S" : {"-": true, "F": true, "L": true},
"-" : {"-": true, "F": true, "L": true},
"J" : {"-": true, "F": true, "L": true},
"7" : {"-": true, "F": true, "L": true},
},
{-1,0} : {
// | F 7
"S" : {"|": true, "F": true, "7": true},
"|" : {"|": true, "F": true, "7": true},
"L" : {"|": true, "F": true, "7": true},
"J" : {"|": true, "F": true, "7": true},
},
{1, 0} : {
// | L J
"S" : {"|": true, "L": true, "J": true,},
"|" : {"|": true, "L": true, "J": true,},
"7" : {"|": true, "L": true, "J": true,},
"F" : {"|": true, "L": true, "J": true,},
},
}
var directions = []Point {
{0, 1}, {0, -1}, {-1, 0}, {1, 0},
}
func main() {
file, err := utils.ReadWholeFile("input.txt")
if err != nil {
log.Fatal(err)
}
var pipes[][]string
var row, col int
row, col, pipes = parseTubes(string(file))
fmt.Println(part1(row, col, pipes))
}
func part1(row, col int, pipes [][]string) int {
begin := getPossiblePaths(row, col, pipes)
paths := [][]Point{}
for _, b := range begin {
visited := make(map[Point]bool)
path := []Point{}
traverseMaze(b.x, b.y, pipes, visited, &path)
paths = append(paths, path)
}
return findCommonPosition(paths)
}
func replaceS(){
}
func traverseMaze(row, col int, pipes [][]string, visited map[Point]bool, path *[]Point) {
visited[Point{row, col}] = true
*path = append(*path, Point{row,col})
possiblePaths := getPossiblePaths(row, col, pipes)
for _, nextPoint := range possiblePaths {
if !visited[nextPoint] {
traverseMaze(nextPoint.x, nextPoint.y, pipes, visited, path)
}
}
}
func findCommonPosition(paths [][]Point) int {
found := 0
for i := 1; i < len(paths); i++ {
for j:= 0; j < len(paths[i]); j++ {
if paths[i - 1][j] == paths[i][j] {
found = j + 1
continue
}
}
}
return found
}
func getPossiblePaths(row, col int, pipes[][]string) []Point {
start := []Point{}
for _, p := range directions {
nRow := row + p.x
nCol := col + p.y
if nRow < 0 || nRow > len(pipes) - 1 || nCol < 0 || nCol > len(pipes) - 1 {
continue
}
if pipes[nRow][nCol] == "." {
continue
}
next := pipes[nRow][nCol]
curr := pipes[row][col]
if exists := valid[p][curr][next]; exists{
start = append(start, Point{nRow,nCol})
}
}
return start
}
func parseTubes(tubes string) (int, int, [][]string) {
splitPipes := strings.Split(tubes, "\n")
var pipes [][]string
var row, col int
row = 0
col = -1
for _,sp := range splitPipes {
if sp == "" {
continue
}
split := strings.Split(sp, "")
if col == -1 {
col = strings.Index(sp, "S")
row += 1
}
pipes = append(pipes, split)
}
return row - 1, col, pipes
}
|
import express from 'express';
const router = express.Router();
router.post('/create-checkout-session', async (req, res) => {
const { products } = req.body;
try {
let lineItems;
if (Array.isArray(products) && products.length > 0) {
lineItems = products.map(item => ({
price_data: {
currency: 'inr',
product_data: {
name: item.productDetails.name,
},
unit_amount: item.productDetails.price * 100,
},
quantity: item.quantity,
}));
}
if (!lineItems || lineItems.length === 0) {
console.error('No line items provided');
res.status(400).json({ error: 'No line items provided' });
return;
}
const session = await req.stripe.checkout.sessions.create({
payment_method_types: ["card"],
line_items: lineItems,
mode: 'payment',
success_url: `http://localhost:5173/customer/payment`,
cancel_url: `http://localhost:5173/customer/`,
});
res.json({ id: session.id });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
export default router;
|
<?php
/*
* This file is part of the MODX Revolution package.
*
* Copyright (c) MODX, LLC
*
* For complete copyright and license information, see the COPYRIGHT and LICENSE
* files found in the top-level directory of this distribution.
*
*/
namespace MODX\Revolution\Tests\Controllers\Context;
use MODX\Revolution\MODxControllerTestCase;
/**
* Tests related to the Update Context controller
*
* @package modx-test
* @subpackage modx
* @group Controllers
* @group Context
* @group ContextControllers
* @group ContextUpdateController
*/
class ContextUpdateControllerTest extends MODxControllerTestCase {
/** @var \ContextUpdateManagerController $controller */
public $controller;
public $controllerName = 'ContextUpdateManagerController';
public $controllerPath = 'context/update';
/**
* Setup fixtures before each test.
*
* @before
*/
public function setUpFixtures() {
parent::setUpFixtures();
$this->controller->setProperty('key','web');
}
/**
* @return void
*/
public function testInitialize() {
$this->controller->initialize();
$this->assertNotEmpty($this->controller->context);
}
/**
* @return void
*/
public function testLoadCustomCssJs() {
$this->controller->loadCustomCssJs();
$this->assertNotEmpty($this->controller->head['js']);
}
/**
* @return void
*/
public function testGetTemplateFile() {
$templateFile = $this->controller->getTemplateFile();
$this->assertEmpty($templateFile);
}
/**
* @depends testInitialize
*/
public function testGetPageTitle() {
$this->controller->initialize();
$pageTitle = $this->controller->getPageTitle();
$this->assertNotEmpty($pageTitle);
}
/**
* @depends testInitialize
*/
public function testProcess() {
$this->controller->initialize();
$this->controller->process();
$this->assertNotEmpty($this->controller->getPlaceholder('_ctx'));
}
}
|
import torch
import time
from .meters import AverageMeter, ProgressMeter
from .accuracy import Accuracy
def Validate(val_loader, model, criterion, args, epoch, prefix=''):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(val_loader),
[batch_time, losses, top1, top5],
prefix="Epoch: [{}] Test: ".format(epoch))
# switch to evaluate mode
model.eval()
with torch.no_grad():
for i, (images, target) in enumerate(val_loader):
if args.gpu is not None:
images = images.cuda(args.gpu, non_blocking=True)
target = target.cuda(args.gpu, non_blocking=True)
# compute output
output = model(images)
loss = criterion(output, target)
# measure accuracy and record loss
acc1, acc5 = Accuracy(output, target, topk=(1, 5))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# measure elapsed time
#epoch_time.update((time.time() - end)*len(val_loader))
#end = time.time()
progress.display(i, prefix=prefix)
return top1.avg
|
import clsx from 'clsx';
import style from './styles.scss';
const Card = ({
imgSrc,
imgAlt,
children,
disabled = false,
sideContent,
skeleton = false,
dataTestId,
size = 's',
...otherProps
}) =>
skeleton ? (
<div size={size} />
) : (
<div
className={clsx(
style.card,
disabled && style.cardDisabled,
style[`card--size-${size}`]
)}
{...(dataTestId && { 'data-testid': dataTestId })}
{...otherProps}
>
<div className={style.imageContainer}>
<span
src={imgSrc}
alt={imgAlt}
{...(dataTestId && { 'data-testid': `${dataTestId}-img` })}
/>
</div>
<div className={style.contentContainer}>{children}</div>
{sideContent && <div className={style.sideContainer}>{sideContent}</div>}
</div>
);
export default Card;
|
import {ChangeDetectionStrategy, Component, Inject, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'bundle-spec-modal',
templateUrl: './bundle-modal.component.html',
styleUrls: ['../../styles/root.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class BundleModalComponent implements OnInit {
constructor(private builder: FormBuilder,
public dialogRef: MatDialogRef<BundleModalComponent>,
@Inject(MAT_DIALOG_DATA) public data: any) {
this.bundle = this.data.bundle;
}
get endTime() {
return this.form.get('endTime');
}
get startTime() {
return this.form.get('startTime');
}
bundle: any;
form: FormGroup;
private static addMonthsToTime(start, nMonths) {
const end = new Date(start);
const month = end.getMonth() + nMonths;
end.setMonth(month);
return end;
}
ngOnInit(): void {
const bundle = Object.assign({}, this.bundle);
if (!bundle.startTime) {
bundle.startTime = new Date();
bundle.endTime = BundleModalComponent.addMonthsToTime(bundle.startTime, bundle.option.number);
}
this.buildForm(bundle);
}
private buildForm(bundle) {
this.form = new FormGroup({
startTime: new FormControl(new Date(bundle.startTime), Validators.required),
endTime: new FormControl(new Date(bundle.endTime), Validators.required),
});
}
submit() {
const bundle = this.getBundle();
this.dialogRef.close(bundle);
}
private getBundle() {
this.bundle.startTime = this.startTime.value;
this.bundle.endTime = this.endTime.value;
return this.bundle;
}
}
|
"use client";
import { Skeleton } from "@/app/components";
import Link from "next/link";
import { usePathname } from "next/navigation";
import React, { FC } from "react";
import classnames from "classnames";
import { useSession } from "next-auth/react";
import {
Avatar,
Badge,
Box,
Button,
Container,
DropdownMenu,
Flex,
HoverCard,
Separator,
Text,
} from "@radix-ui/themes";
import { PersonIcon } from "@radix-ui/react-icons";
import Image from "next/image";
type NavBarProps = {
count: number;
userId: string;
};
const NavBar: FC<NavBarProps> = ({ count, userId }) => {
const { status } = useSession();
const hideHoverCard =
count === 0 || status === "unauthenticated" || status === "loading";
return (
<nav className="px-5 py-3 bg-neutral-800">
<Container>
<Flex justify="between">
<Flex align="center" gap="3">
<Link href="/">
<Image src="/logo.png" alt="Logo" width={60} height={60} />
</Link>
<NavLinks />
</Flex>
<Flex align="center" justify="between" gap="4">
{hideHoverCard ? null : (
<HoverCard.Root>
<HoverCard.Trigger>
<Badge variant="solid" radius="full" color="red">
{count}
</Badge>
</HoverCard.Trigger>
<HoverCard.Content>
Open issue(s) on your name: {count}
</HoverCard.Content>
</HoverCard.Root>
)}
<AuthStatus userId={userId} count={count} />
</Flex>
</Flex>
</Container>
</nav>
);
};
const NavLinks = () => {
const currentPath = usePathname();
const links = [
{ label: "Dashboard", href: "/" },
{ label: "Issues", href: "/issues/list" },
];
return (
<ul className="flex space-x-3">
{links.map((link, i) => (
<Flex align="center" gap="3" key={i}>
<li key={link.href}>
<Link
className={classnames({
"nav-link": true,
"!text-pink-400": link.href === currentPath,
"font-bold": link.href === currentPath,
})}
href={link.href}
>
{link.label}
</Link>
</li>
<Separator orientation="vertical" />
</Flex>
))}
</ul>
);
};
type AuthStatus = {
userId: string;
count: number;
};
const AuthStatus: FC<AuthStatus> = ({ userId, count }) => {
const { status, data: session } = useSession();
if (status === "loading") return <Skeleton width="3rem" />;
if (status === "unauthenticated")
return (
<Link className="hover:cursor-pointer nav-link" href="/api/auth/signin">
<Button className="hover:cursor-pointer">
<PersonIcon />
Log in
</Button>
</Link>
);
return (
<Box>
<DropdownMenu.Root>
<DropdownMenu.Trigger>
<Avatar
src={session!.user!.image!}
fallback="?"
size="2"
radius="full"
className="cursor-pointer hover:border-2 border-gray-300 transition-all"
referrerPolicy="no-referrer"
/>
</DropdownMenu.Trigger>
<DropdownMenu.Content>
<DropdownMenu.Label>
<Text size="2">{session!.user!.email}</Text>
</DropdownMenu.Label>
<Link href={`/issues/list?assignedToUserId=${userId}`}>
<DropdownMenu.Item>
<Flex justify="between" width="100%">
<Text>My issues</Text>
{count >= 1 && (
<Badge variant="solid" radius="full" color="red">
{count}
</Badge>
)}
</Flex>
</DropdownMenu.Item>
</Link>
<DropdownMenu.Separator />
<DropdownMenu.Item>
<Link href="/api/auth/signout">Log out</Link>
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
</Box>
);
};
export default NavBar;
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:immerse/src/features/authentication/screens/login/login.dart';
import 'package:immerse/src/features/authentication/screens/success_screen/success_screen.dart';
import '../../../../utils/constants/sizes.dart';
class VerifyEmailScreen extends StatelessWidget {
const VerifyEmailScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false, // Add this line to remove the default back arrow
actions: [
IconButton(onPressed: () => Get.offAll(() => const LoginScreen()), icon: const Icon(CupertinoIcons.clear))
],
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.only(
left: TSizes.defaultSpacing,
right: TSizes.defaultSpacing,
),
child: Column(
children: [
Text(
"Verify your email",
style: Theme.of(context).textTheme.headlineSmall,
),
const SizedBox(height: 16),
Text(
"We have sent an email to your email address. Please verify your email to continue.",
style: Theme.of(context).textTheme.bodyMedium,
textAlign: TextAlign.center,
),
const SizedBox(height: 26),
ElevatedButton(
onPressed: () => Get.to(() => SuccessScreen(
title: "Email verified",
message: "Your email has been verified successfully.",
onPressed: () => Get.to(() => const LoginScreen()),
)),
child: const Text("Continue"),
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {},
child: const Text("Resend email"),
),
],
),
),
),
);
}
}
|
<template>
<div class="main-content" v-loading="loading_choose_guide">
<!-- 选择orderItem -->
<div class="choose-order-item">
<div class="title">选择订单子场次</div>
<div class="order-item-grid">
<div
v-for="(item, idx) in order_items_for_choose"
class="order-item"
:class="{
active: item.checked,
}"
@click="() => onChooseOrderItem(item)"
>
<div class="session">场次-{{ idx + 1 }}</div>
<div class="time-desc">{{ getOrderItemTimeFrame(item) }}</div>
</div>
</div>
</div>
<div v-if="choose_order_item">
<div class="title">空闲管理员</div>
<div class="guide-grid">
<PopoverButton
:pop-content="`确认选择该引导员?`"
:on-confirm="
() => onConfirmPick(choose_order_item?.id!, item.id!)
"
v-for="(item, idx) in guide_list"
:key="idx"
>
<div
class="guide"
:class="{
active: choose_guide?.id === item.id,
}"
>
{{ item.name }}
</div>
</PopoverButton>
<PopoverButton
:pop-content="`确认重置解说员设置?`"
:on-confirm="
() => resetGuideData(choose_order_item?.id!)
"
>
<div class="guide reset">重置解说员</div>
</PopoverButton>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import PopoverButton from "@/components/button/popoverButton.vue";
import { useOrderStoreForSetup } from "@/store";
import { getGuideList } from "@/utils/api/guide";
import { assignGuide, removeGuide } from "@/utils/api/order/";
import { getOrderItemTimeFrame } from "@/utils/fn/index";
import { ElMessage } from "element-plus";
import { storeToRefs } from "pinia";
import { onMounted, ref } from "vue";
interface IOrderItemForChoose extends IOrderItem {
checked: boolean;
}
// -------------------- P R O P S --------------------
const choose_guide = ref<IGuide>();
const orderStore = useOrderStoreForSetup();
const { edit_order_data } = storeToRefs(orderStore);
const guide_list = ref<IGuide[]>();
// 选择的订单子场次列表
const order_items_for_choose = ref<IOrderItemForChoose[]>([]);
// 选择的订单子场次
const choose_order_item = ref<IOrderItemForChoose>();
// loading for choose guide
const loading_choose_guide = ref(false);
// ------------------- C I R C L E -------------------
onMounted(async () => {
console.log("choose_guide edit_order_data:", edit_order_data.value);
guide_list.value = (await getGuideList()).data;
order_items_for_choose.value = edit_order_data.value.orderItems!.map(
(item) => {
return {
...item,
checked: false,
};
}
);
console.log(guide_list.value);
// await reflushChooseGuide();
console.log(choose_guide.value);
});
// ----------------- F U N C T I O N -----------------
// 选择订单子场次
const onChooseOrderItem = (item: IOrderItemForChoose) => {
choose_guide.value = item.guide;
if (item.checked) {
choose_order_item.value = undefined;
item.checked = false;
return;
}
order_items_for_choose.value.forEach((item) => {
item.checked = false;
});
item.checked = true;
choose_order_item.value = item;
if (item.guide) {
choose_guide.value = item.guide;
}
};
//为订单 配置 引导员
const onConfirmPick = (order_item_id: number, guide_id: number) => {
loading_choose_guide.value = true;
assignGuide(order_item_id, guide_id)
.then(async (res) => {
console.log(res);
if (res.status === 201) {
syncGuideData(order_item_id, guide_id);
}
// await reflushChooseGuide();
ElMessage.success("指定成功");
})
.catch((err) => {
console.log(err);
})
.finally(() => {
loading_choose_guide.value = false;
});
};
// 同步解说员数据
const syncGuideData = (order_item_id: number, guide_id: number | undefined) => {
choose_guide.value = guide_list.value!.find((item) => item.id === guide_id);
order_items_for_choose.value.find((item) => {
if (item.id === order_item_id) {
item.guide = choose_guide.value;
return true;
}
return false;
});
edit_order_data.value.orderItems = order_items_for_choose.value;
};
//重置解说员
const resetGuideData = (order_item_id: number) => {
removeGuide(order_item_id)
.then(async (res) => {
console.log(res);
if (res.status === 201) {
syncGuideData(order_item_id, undefined);
}
// await reflushChooseGuide();
ElMessage.success("成功重置解说员");
})
.catch((err) => {
console.log(err);
});
};
</script>
<style lang="scss" scoped>
.main-content {
width: 400px;
.title {
font-size: 15px;
margin-bottom: 10px;
color: #000000;
padding-bottom: 10px;
}
.order-item-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: var(--common-padding);
// border: 1px solid red;
padding-bottom: var(--common-padding);
.order-item {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--common-padding);
padding-block: var(--common-padding);
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
transition: var(--common-transition);
user-select: none;
&:hover {
transform: scale(1.1);
}
&.active {
background-color: var(--button-primary-bg-color);
color: #fff;
}
.time-desc {
font-size: 11px;
}
}
}
.guide-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: var(--common-padding);
.guide {
user-select: none;
box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
aspect-ratio: 1.5;
display: flex;
justify-content: center;
align-items: center;
transition: var(--common-transition);
color: #555;
cursor: pointer;
&.active {
background-color: var(--button-primary-bg-color);
color: #fff;
}
&:hover {
transform: scale(1.1);
}
&.reset {
font-size: 13px;
}
}
}
}
</style>
|
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm"
import { ApiProperty } from '@nestjs/swagger'
import { Product } from "src/products/entities/product.entity"
@Entity('users')
export class User {
@ApiProperty({
example: '439c9809-1e8b-471d-bb98-943d1d93e5f8',
description: 'User ID',
uniqueItems: true,
})
@PrimaryGeneratedColumn('uuid')
id: string
@ApiProperty({
example: 'mocking@gmail.com',
description: 'User email',
uniqueItems: true,
})
@Column('text', {
unique: true,
})
email: string
@Column('text', {
select: false
})
password: string
@ApiProperty({
example: 'Roy Jhones',
description: 'User name',
})
@Column('text')
fullName: string
@ApiProperty({
example: ['user'],
description: 'User roles',
})
@Column('text', {
array: true,
default: [ 'user' ],
})
roles: string[]
@ApiProperty({
example: true,
description: 'User active',
})
@Column('boolean', { default: true })
isActive: boolean
@OneToMany(
() => Product,
(product) => product.user,
)
product: Product[]
}
|
//
// LoginScreenObject.swift
// MdEditorUITests
//
// Created by Alexey Turulin on 1/18/24.
// Copyright © 2024 repakuku. All rights reserved.
//
import XCTest
final class LoginScreenObject: BaseScreenObject {
// MARK: - Private properties
private lazy var textFieldLogin = app.textFields[AccessibilityIdentifier.LoginScene.textFieldLogin.description]
private lazy var textFieldPass = app.secureTextFields[AccessibilityIdentifier.LoginScene.textFieldPass.description]
private lazy var loginButton = app.buttons[AccessibilityIdentifier.LoginScene.buttonLogin.description]
// MARK: - ScreenObject Methods
@discardableResult
func isLoginScreen() -> Self {
checkTitle(contains: L10n.Login.title)
assert(textFieldLogin, [.exists])
assert(textFieldPass, [.exists])
assert(loginButton, [.exists])
return self
}
@discardableResult
func set(login: String) -> Self {
assert(textFieldLogin, [.exists])
textFieldLogin.tap()
textFieldLogin.typeText(login)
return self
}
@discardableResult
func set(password: String) -> Self {
assert(textFieldPass, [.exists])
textFieldPass.tap()
textFieldPass.typeText(password)
return self
}
@discardableResult
func login() -> Self {
assert(loginButton, [.exists])
loginButton.tap()
return self
}
}
|
import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, Col, Row, Table } from 'reactstrap';
import { Translate, TextFormat } from 'react-jhipster';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IRootState } from 'app/shared/reducers';
import { getEntities } from './user-setting.reducer';
import { IUserSetting } from 'app/shared/model/user-setting.model';
import { APP_DATE_FORMAT, APP_LOCAL_DATE_FORMAT } from 'app/config/constants';
export interface IUserSettingProps extends StateProps, DispatchProps, RouteComponentProps<{ url: string }> {}
export const UserSetting = (props: IUserSettingProps) => {
useEffect(() => {
props.getEntities();
}, []);
const handleSyncList = () => {
props.getEntities();
};
const { userSettingList, match, loading } = props;
return (
<div>
<h2 id="user-setting-heading" data-cy="UserSettingHeading">
User Settings
<div className="d-flex justify-content-end">
<Button className="mr-2" color="info" onClick={handleSyncList} disabled={loading}>
<FontAwesomeIcon icon="sync" spin={loading} /> Refresh List
</Button>
<Link to={`${match.url}/new`} className="btn btn-primary jh-create-entity" id="jh-create-entity" data-cy="entityCreateButton">
<FontAwesomeIcon icon="plus" />
Create new User Setting
</Link>
</div>
</h2>
<div className="table-responsive">
{userSettingList && userSettingList.length > 0 ? (
<Table responsive>
<thead>
<tr>
<th>ID</th>
<th>Receive Email</th>
<th>Private Profile</th>
<th>Phone Number</th>
<th>Created Date</th>
<th>Updated Date</th>
<th>User</th>
<th />
</tr>
</thead>
<tbody>
{userSettingList.map((userSetting, i) => (
<tr key={`entity-${i}`} data-cy="entityTable">
<td>
<Button tag={Link} to={`${match.url}/${userSetting.id}`} color="link" size="sm">
{userSetting.id}
</Button>
</td>
<td>{userSetting.id}</td>
<td>{userSetting.receiveEmail ? 'true' : 'false'}</td>
<td>{userSetting.privateProfile ? 'true' : 'false'}</td>
<td>{userSetting.phoneNumber}</td>
<td>
{userSetting.createdDate ? <TextFormat type="date" value={userSetting.createdDate} format={APP_DATE_FORMAT} /> : null}
</td>
<td>
{userSetting.updatedDate ? <TextFormat type="date" value={userSetting.updatedDate} format={APP_DATE_FORMAT} /> : null}
</td>
<td>{userSetting.user ? userSetting.user.id : ''}</td>
<td className="text-right">
<div className="btn-group flex-btn-group-container">
<Button tag={Link} to={`${match.url}/${userSetting.id}`} color="info" size="sm" data-cy="entityDetailsButton">
<FontAwesomeIcon icon="eye" /> <span className="d-none d-md-inline">View</span>
</Button>
<Button tag={Link} to={`${match.url}/${userSetting.id}/edit`} color="primary" size="sm" data-cy="entityEditButton">
<FontAwesomeIcon icon="pencil-alt" /> <span className="d-none d-md-inline">Edit</span>
</Button>
<Button tag={Link} to={`${match.url}/${userSetting.id}/delete`} color="danger" size="sm" data-cy="entityDeleteButton">
<FontAwesomeIcon icon="trash" /> <span className="d-none d-md-inline">Delete</span>
</Button>
</div>
</td>
</tr>
))}
</tbody>
</Table>
) : (
!loading && <div className="alert alert-warning">No User Settings found</div>
)}
</div>
</div>
);
};
const mapStateToProps = ({ userSetting }: IRootState) => ({
userSettingList: userSetting.entities,
loading: userSetting.loading,
});
const mapDispatchToProps = {
getEntities,
};
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(mapStateToProps, mapDispatchToProps)(UserSetting);
|
/*! \file IHost.h
\author Michael Olsen
\date 24/Jan/2005
\date 24/Jan/2005
*/
/*! \brief Host callback interface
*/
class IHost
{
public:
static IHost* IHost::Create(kspiCCallbackDispatcherFunc pCallback, void* hHost);
//! The plug-in calls this to notify autumation update (changes caused by user interaction)
virtual void KSPI_CALL OnAutomationUpdate(IPlugIn* pCaller, tint32 iParameterIndex, tint32 iValue) = 0;
//! The plug-in calls this to ask about the BPM. It should not be called from inside processing or MIDI receival
/*!
return tfloat: Current BPM, or 0 if unknown
*/
virtual tfloat32 KSPI_CALL GetCurrentBPM() = 0;
//! The host type determines what format the host wrapper is.
enum EType {
//! Stand-alone, i.e. application.
HostTypeStandAlone = 0,
//! VST
HostTypeVST,
//! RTAS
HostTypeRTAS,
//! AS
HostTypeAS,
//! TDM
HostTypeTDM,
//! AU
HostTypeAU,
//! Not used. Present to force enum to 32-bit
HostTypeForce = 0xffffffff
};
//! The plug-in calls this to ask about the host type
/*!
return EType: Format of host wrapper
*/
virtual EType KSPI_CALL GetType() = 0;
//! Tells the host to switch to a specific window
virtual void KSPI_CALL ActivateWindow(tint32 iIndex) = 0;
//! Tells the host to hide to a specific window
virtual void KSPI_CALL HideWindow(tint32 iIndex) = 0;
//! Asks the host whether a specific window is visible
virtual tint32 KSPI_CALL IsWindowVisible(tint32 iIndex) = 0;
//! Tells the host that the (buffer-drawing) window needs to be redrawn within given rectangle
virtual void KSPI_CALL RedrawWindow(IGUI* pCaller, tint32 iX, tint32 iY, tint32 iCX, tint32 iCY) = 0;
//! Asks the host if a given window should have a custom toolbar, of if one is already supplied by the host
virtual tint32 KSPI_CALL DoesWindowHaveToolbar(tint32 iIndex) = 0;
};
class CHost : public virtual IHost
{
public:
CHost(void* pCallback, void* hHost);
~CHost();
virtual void Destroy();
//! IHost override
virtual void KSPI_CALL OnAutomationUpdate(IPlugIn* pCaller, tint32 iParameterIndex, tint32 iValue);
//! IHost override
virtual tfloat32 KSPI_CALL GetCurrentBPM();
//! IHost override
virtual EType KSPI_CALL GetType();
//! IHost override
virtual void KSPI_CALL ActivateWindow(tint32 iIndex);
//! IHost override
virtual void KSPI_CALL HideWindow(tint32 iIndex);
//! IHost override
virtual tint32 KSPI_CALL IsWindowVisible(tint32 iIndex);
//! IHost override
virtual void KSPI_CALL RedrawWindow(IGUI* pCaller, tint32 iX, tint32 iY, tint32 iCX, tint32 iCY);
//! IHost override
virtual tint32 KSPI_CALL DoesWindowHaveToolbar(tint32 iIndex);
protected:
kspiCCallbackDispatcherFunc mpCallback;
void* mhHost;
};
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.sidecar.restore;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.cassandra.sidecar.exceptions.RestoreJobFatalException;
import org.jetbrains.annotations.NotNull;
import software.amazon.awssdk.utils.ImmutableMap;
/**
* Schema for the manifest file in slice
* It is essentially the mapping from SSTable identifier (String) to the ManifestEntry.
*/
public class RestoreSliceManifest extends HashMap<String, RestoreSliceManifest.ManifestEntry>
{
public static final String MANIFEST_FILE_NAME = "manifest.json";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Logger LOGGER = LoggerFactory.getLogger(RestoreSliceManifest.class);
public static RestoreSliceManifest read(File file) throws RestoreJobFatalException
{
if (!file.exists())
{
throw new RestoreJobFatalException("Manifest file does not exist. file: " + file);
}
try
{
return MAPPER.readValue(file, RestoreSliceManifest.class);
}
catch (IOException e)
{
LOGGER.error("Failed to read restore slice manifest. file={}", file, e);
throw new RestoreJobFatalException("Unable to read manifest", e);
}
}
/**
* Merge all checksums of all the SSTable components included in the manifest
* @return map of file name to checksum; it never returns null
*/
public @NotNull Map<String, String> mergeAllChecksums()
{
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
values().forEach(entry -> entry.componentsChecksum()
.forEach(builder::put));
return builder.build();
}
/**
* Manifest entry that contains the checksum of each component in the SSTable and the token range
*/
public static class ManifestEntry
{
private final Map<String, String> componentsChecksum;
private final BigInteger startToken;
private final BigInteger endToken;
@JsonCreator
public ManifestEntry(@JsonProperty("components_checksum") Map<String, String> componentsChecksum,
@JsonProperty("start_token") BigInteger startToken,
@JsonProperty("end_token") BigInteger endToken)
{
this.componentsChecksum = componentsChecksum;
this.startToken = startToken;
this.endToken = endToken;
}
@JsonProperty("components_checksum")
public Map<String, String> componentsChecksum()
{
return componentsChecksum;
}
@JsonProperty("start_token")
public BigInteger startToken()
{
return startToken;
}
@JsonProperty("end_token")
public BigInteger endToken()
{
return endToken;
}
}
}
|
import classNames from 'classnames/bind';
import PropTypes from 'prop-types';
import React, { useContext } from 'react';
import FeaturedPost from 'components/shared/featured-post';
import Heading from 'components/shared/heading';
import Pagination from 'components/shared/pagination';
import MainContext from 'context/main';
import PodcastCard from '../podcast-card';
import styles from './blog-posts-list.module.scss';
import Item from './item';
const cx = classNames.bind(styles);
const BlogPostsList = ({ pageTitle, featuredPost, posts, rootPath }) => {
const { pageCount, currentPage } = useContext(MainContext);
return (
<section className={cx('wrapper')}>
<div className={cx('container', 'inner')}>
<Heading className={cx('title')} tag="h1" size="xl">
{pageTitle}
</Heading>
<FeaturedPost {...featuredPost} />
{posts.map((post, index) => {
const { tags } = post;
const hasPodcastTag = Boolean(tags?.nodes.find((tag) => tag?.name === 'podcast'));
const { podcast } = post.acf;
return (
<div className={cx('item')} key={index}>
{hasPodcastTag && podcast ? <PodcastCard {...podcast} /> : <Item {...post} />}
</div>
);
})}
<Pagination pageCount={pageCount} currentPage={currentPage} rootPath={rootPath} />
</div>
</section>
);
};
BlogPostsList.propTypes = {
pageTitle: PropTypes.string.isRequired,
featuredPost: PropTypes.shape({}).isRequired,
posts: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
rootPath: PropTypes.string.isRequired,
};
export default BlogPostsList;
|
import type { Metadata } from 'next';
import { dark } from '@clerk/themes';
import { Inter } from 'next/font/google';
import './globals.css';
import { ClerkProvider } from '@clerk/nextjs';
import { ThemeProvider } from '@/components/theme-provider';
import { Toaster } from 'sonner';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'StreamHub',
description:
'Experience the next level of live streaming with StreamHub, your go-to web application for immersive and interactive content. Explore a diverse range of channels, connect with creators, and engage in real-time with a vibrant community. Elevate your streaming experience with StreamHub - where entertainment meets innovation.',
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<ClerkProvider appearance={{ baseTheme: dark }}>
<html lang="en">
<body className={inter.className}>
<ThemeProvider
attribute="class"
forcedTheme="dark"
storageKey="streamhub-theme"
>
<Toaster theme="light" position="bottom-center" />
{children}
</ThemeProvider>
</body>
</html>
</ClerkProvider>
);
}
|
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router";
import { useEffect, useState } from "react";
import { setCurrentUser } from "../reducer";
import { Link } from "react-router-dom";
import * as fClient from "../Follows/followClient";
import * as client from "../client"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBeer } from '@fortawesome/free-solid-svg-icons';
import axios from "axios";
export const BASE_API = process.env.REACT_APP_API_BASE;
axios.defaults.withCredentials = true;
export default function PublicProfile() {
const { profileId } = useParams();
const { currentUser } = useSelector((state) => state.userReducer);
const navigate = useNavigate();
const dispatch = useDispatch();
const [user, setUser] = useState({});
const [follows, setFollows] = useState([]);
const [foNumber, setFoNumber] = useState(0);
const [ferNumber, setFerNumber] = useState(0);
const [beers, setBeers] = useState([]);
const [isSelf, setIsSelf] = useState(false);
const [profile, setProfile] = useState({ _id: "", description: "", favs: [] });
const [favoriteBeers, setFavoriteBeers] = useState([]);
const [beerBrew, setbeerBrew] = useState([]);
const [filter, setFilter] = useState('');
const handleFilterChange = (e) => {
setFilter(e.target.value.toLowerCase());
}
const updateUser = async () => {
try {
const user = await client.updateUser(profile._id, profile);
dispatch(setCurrentUser(user));
alert('Profile successfully updated.');
} catch (err) {
console.log(err.response.data.message)
}
};
const fetchProfile = async () => {
try {
const cur = await client.findUserById(profileId);
setUser(cur);
const follows = await fClient.followsNumber(profileId);
const followers = await fClient.followersNumber(profileId);
setFoNumber(follows)
setFerNumber(followers)
const account = await client.profile();
const u = await client.findUserById(account._id);
dispatch(setCurrentUser(u));
setProfile(u)
if (u) {
const fos = await fClient.findFollowsOfAUser(u._id);
setFollows(fos);
if (u._id === profileId) {
setIsSelf(true);
}
}
} catch (err) {
navigate("/User/Profile")
}
}
const fetchFollows = async () => {
try {
if (currentUser) {
const fos = await fClient.findFollowsOfAUser(currentUser._id);
setFollows(fos);
}
const follows = await fClient.followsNumber(profileId);
const followers = await fClient.followersNumber(profileId);
setFoNumber(follows)
setFerNumber(followers)
} catch (err) {
navigate("/User/Profile")
}
}
const following = () => {
if (!currentUser || !follows) return false;
return follows.some(fo => fo.follows?._id === profileId);
}
const followUser = async () => {
console.log(profile.favs)
if (!currentUser) {
alert("Sign in to follow user")
navigate("/User/Signin")
return;
}
if (user && user.role === "ADMIN") {
alert("Cannot follow admin")
navigate("/User/Profile")
return;
}
if (currentUser._id === profileId) {
alert("This is your profile, cannot follow.")
return;
}
const status = await fClient.followsUser(profileId);
fetchFollows();
}
const unfollowUser = async () => {
if (!currentUser) {
alert("Sign in first")
navigate("/User/Signin")
return;
}
const status = await fClient.unfollowsUser(profileId);
fetchFollows();
}
const fetchBeers = async () => {
const beersUrl = `${BASE_API}/api/beers`;
const beersResponse = await fetch(beersUrl);
const beersData = await beersResponse.json();
setBeers(beersData);
const cur = await client.findUserById(profileId);
if (cur && cur.favs && beersData) {
const favs = cur.favs.map(fav => {
const beer = beersData.find(beer => beer._id === fav._id);
return beer ? beer.name : 'Unknown Beer';
});
setFavoriteBeers(favs);
}
};
useEffect(() => {
fetchProfile();
fetchBeers();
}, [profileId]);
const isNewUser = (registerDate) => {
const registrationDate = new Date(registerDate);
const now = new Date();
const diffTime = Math.abs(now - registrationDate);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays <= 10;
};
const isVeteranUser = (registerDate) => {
const registrationDate = new Date(registerDate);
const now = new Date();
const diffTime = Math.abs(now - registrationDate);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
return diffDays > 10;
};
const handleSelectChange = (e) => {
const selectedOptions = Array.from(e.target.selectedOptions).map(option => ({_id: option.value}));
setProfile(prevProfile => ({
...prevProfile,
favs: selectedOptions
}));
};
return (
<div className="container-fluid">
<div className="card">
<div className="card-header">
<h3>Welcome To...</h3>
{currentUser &&
<div className="d-flex justify-content-end align-items-center">
<Link to={`/User/Profile/${profileId}/follows`} className="badge bg-success-subtle text-dark p-2 fs-6 me-2 text-decoration-none">
Followers
<span className="badge bg-light text-dark ms-1">{ferNumber}</span>
</Link>
<Link to={`/User/Profile/${profileId}/follows`} className="badge bg-secondary p-2 fs-6 text-decoration-none">
Follows
<span className="badge bg-light text-dark ms-1">{foNumber}</span>
</Link>
</div>
}
</div>
<div className="card-body">
<div className="d-flex align-items-center">
<h3 className="me-2">{user.username}'s Profile</h3>
{isNewUser(user.registerDate) && (
<span className="badge bg-info text-white" title="This user is still new">
New User
</span>
)}
{isVeteranUser(user.registerDate) && (
<span className="badge bg-primary-subtle text-dark ms-2" title="This user is a veteran member of the community">
Veteran User
</span>
)}
</div>
{following() && currentUser && (currentUser._id !== user._id) ? (
<button onClick={unfollowUser} className="btn bg-danger-subtle form-control">
Unfollow
</button>
):(
<button onClick={followUser} className="btn bg-warning-subtle form-control">
Follow
</button>
)}
{isSelf ? (
<>
<h4 className="mt-4">Update Your description</h4>
<button className="badge bg-success-subtle text-dark mt-3 mb-2 float-end"
onClick={updateUser}> Update Description to Display</button>
<textarea
className="form-control"
value={profile.description}
onChange = {(e) => setProfile({ ...profile, description: e.target.value })}
placeholder="Describe yourself here..."
/>
</>
) : (
<div className="card mt-3">
<div className="card-body bg-dark-subtle fw-bold">
<p className="card-text ">{user.description || "User has nothing to show here"}</p>
</div>
</div>
)}
{isSelf ? <div className="profile-container">
<button className="badge bg-success-subtle text-dark mt-3 mb-2 float-end"
onClick={updateUser}> Update Your Fav Beer To Display</button>
<h4 className="mt-4">Multi Select Your Favorite Beers</h4>
<input
type="text"
value={filter}
onChange={handleFilterChange}
placeholder="Search beers..."
className="form-control mb-2"
/>
<select multiple className="form-control" size="5" style={{ overflowY: 'scroll' }}
onChange = {(e) => {handleSelectChange(e)}} >
{beers
.filter(beer => beer.name.toLowerCase().startsWith(filter))
.map((beer) => (
<option key={beer._id} value={beer._id} selected={profile.favs.some(fav => fav._id === beer._id)}>
{beer.name}
</option>
))}
</select>
</div> :
<div className="accordion mt-3" id="accordionExample">
<div className="accordion-item">
<h2 className="accordion-header" id="headingOne">
<button className="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
My Favorite Beers
</button>
</h2>
<div id="collapseOne" className="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample">
<div className="accordion-body">
<ul>
{favoriteBeers.length > 0 ? favoriteBeers.map((beer, index) => (
<li key={index}>
<FontAwesomeIcon icon={faBeer} className="me-2" />
{beer}
</li>
)) : <p>User has no favorite beers</p>}
</ul>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
)
}
|
from django.db import models
from django.utils.text import slugify
class OchaDashboard(models.Model):
name = models.CharField(max_length=200)
slug = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
content = models.TextField(null=True, blank=True)
thumbnail = models.ImageField(null=True, blank=True, upload_to='external_dashboard_thumbnails')
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-updated', '-created']
constraints = [
models.UniqueConstraint(fields=['slug'], name='unique_slug')
]
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
return super().save(*args, **kwargs)
def __str__(self):
return self.name
|
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import './App.css';
import Home from './pages/home/home';
import Sobre from './pages/sobre/sobre';
import Produtos from './pages/produtos/produtos';
import Politica from './pages/politica/politica';
import Faq from './pages/faq/faq';
import FaleConosco from './pages/faleconosco/faleconosco';
import Cadastro from './pages/cadastro/cadastro';
import Login from './pages/login/login';
import Curso from './pages/curso/curso';
//Rotas Protegidas necessarias login:
import Dashboard from './pages/dashboard/dashboard';
import Painel from './components/painel/painel';
import Agenda from './components/agenda/agenda';
import Cursos from './components/cursos/cursos';
import Configuracoes from './components/configuracoes/configuracoes';
//Configurações:
import Assinatura from './components/configuracoes/assinatura/assinatura';
import Contato from './components/configuracoes/contato/contato';
import MeusDados from './components/configuracoes/meusdados/meusdados';
import Politicas from './components/configuracoes/politicas/politicas';
import ProtectedRoute from './ProtectedRoute';
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route path="/" exact element={<Home />} ></Route>
<Route path="/sobre" element={<Sobre />} ></Route>
<Route path="/produtos" element={<Produtos />} ></Route>
<Route path="/politica" element={<Politica />} ></Route>
<Route path="/faq" element={<Faq />} ></Route>
<Route path="/faleconosco" element={<FaleConosco />} ></Route>
<Route path="/cadastro" element={<Cadastro />} ></Route>
<Route path="/login" element={<Login />} ></Route>
<Route path="/curso" element={<Curso />} ></Route>
<Route path='/dashboard' element={
<ProtectedRoute><Dashboard /></ProtectedRoute>
} />
</Routes>
</Router>
<ToastContainer />
</div>
);
}
export default App;
|
import faiss
import numpy as np
import pandas as pd
from app.scrape import get_wikipedia_text, get_embeddings
class RAGSearcher:
def __init__(self, urls: list[str]) -> None:
self.text_corpus, self.faiss_db = self.create_vector_from_text(urls)
def create_vector_from_text(self, urls: list[str] | str):
# get text from all urls one by one
text_corpus = []
for url in urls:
text_corpus.extend(get_wikipedia_text(url))
text_embeddings = get_embeddings(text_corpus)
faiss_db = self.init_new_vector_database(text_embeddings, len(text_embeddings[0]),
len(text_embeddings) // 50) # can be changed later
return text_corpus, faiss_db
# TODO in the future: add a way to maybe save db's by conversation by person maybe?
# would need better CRUD for this
def init_new_vector_database(self, embeddings: pd.Series, dims: int, nlist):
quantizer = faiss.IndexFlatL2(dims)
index = faiss.IndexIVFFlat(quantizer, dims, nlist)
# make it into a gpu index
index.train(np.array(embeddings))
index.add(np.array(embeddings))
return index
def search_faiss(self, query: str, k:int= 3):
q_embed = np.array(get_embeddings([query])) # get embeddings from the model
_dist, indices = self.faiss_db.search(q_embed, k)
return [self.text_corpus[int(i)] for i in indices[0]]
if __name__ == "__main__":
main = RAGSearcher(['https://en.wikipedia.org/wiki/Luke_Skywalker'])
print(main.search_faiss("Why is Luke Skywalker Famous?"))
|
import { Atom, PrimitiveAtom, useAtom, useAtomValue } from "jotai"
import PrefItem, { PrefItemProps } from "./Item"
import { Input } from "../ui/input"
import { Button } from "../ui/button"
import { ReactNode, Suspense } from "react"
import clsx from "clsx"
import { dialog } from "@tauri-apps/api"
import { Skeleton } from "../ui/skeleton"
interface DialogFilter {
name: string
extensions: string[]
}
type PrefProgramProps = {
valueAtom: PrimitiveAtom<string>
versionAtom: Atom<string | null>
versionFallback: string
dialogFilter?: DialogFilter[]
children?: ReactNode
} & {
[Property in keyof PrefItemProps as Exclude<Property, "children" | "msg">]: PrefItemProps[Property]
}
function Msg({ atom, fallback }: { atom: Atom<string | null>; fallback: string }) {
const value = useAtomValue(atom)
return (
<span
className={clsx("text-xs", {
"text-red-500": value == null,
})}
>
{value ?? fallback}
</span>
)
}
export default function PrefProgram(props: PrefProgramProps) {
const [path, setPath] = useAtom(props.valueAtom)
async function choosePath() {
let userChooseFile = await dialog.open({
multiple: false,
filters: props.dialogFilter,
})
if (userChooseFile == null) return null
let file = userChooseFile as string
setPath(file)
}
return (
<div>
<PrefItem leading={props.leading} className="gap-1">
<Input
defaultValue={path}
onBlur={(e) => setPath(e.target.value)}
onKeyDown={(e) => {
if (e.key == "Enter") setPath((e.target as any).value)
}}
/>
<Button variant="outline" onClick={choosePath}>...</Button>
{props.children}
</PrefItem>
<Suspense fallback={<Skeleton className="h-3 w-full my-2"/>}>
<Msg atom={props.versionAtom} fallback={props.versionFallback} />
</Suspense>
</div>
)
}
|
package com.wmy.community.service.impl;
import com.wmy.community.service.LikeService;
import com.wmy.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;
/**
* @Description:
* @Author: 三水
* @Date: 2022/2/24 14:58
*/
@Service
public class LikeServiceImpl implements LikeService {
@Autowired
private RedisTemplate redisTemplate;
@Override
public void like(int userId, int entityType, int entityId, int entityUserId) {
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
//实体获得赞
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
//被赞的用户赞增加
String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
//判断是否已经点赞
Boolean isMember = operations.opsForSet().isMember(entityLikeKey, userId);
//事务启动
operations.multi();
if(isMember){
operations.opsForSet().remove(entityLikeKey,userId);
operations.opsForValue().decrement(userLikeKey);
}else{
operations.opsForSet().add(entityLikeKey,userId);
operations.opsForValue().increment(userLikeKey);
}
//事务提交
return operations.exec();
}
});
}
@Override
public long findEntityLikeCount(int entityType, int entityId) {
String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
Long size = redisTemplate.opsForSet().size(entityLikeKey);
return size;
}
}
|
/* Cabeçalho */
.menu {
/* Definir o flexbox */
display: flex;
/* Espaçamento no eixo principal */
justify-content: space-evenly;
/* Espaçamento no eixo secundário */
align-items: center;
/* Quebrar para a próxima linha quando não houver mais espaço */
flex-wrap: wrap;
/* Aplicar espaçamento apenas entre os items - Aplica apenas dos lados */
column-gap: 33px;
}
/* Categorias */
.categorias__lista {
/* Declarar como flexbox e por padrão ele fica como coluna*/
display: flex;
/* Alterar a disposição para coluna */
flex-direction: column;
/* Incluir espaçamento entre linhas row */
row-gap: .5rem;
}
/* Destaques */
.destaques {
display: flex;
align-items: center;
column-gap: 10px;
}
.destaques__barra {
/* Flex-grow é utilizado para expandir o elemento de acordo com o espaço disponível */
flex-grow: 1;
}
/* Eventos */
.eventos__lista {
display: flex;
flex-wrap: wrap;
column-gap: 1.5rem;
row-gap: 1rem;
justify-content: center;
}
.eventos__item {
flex-grow: 1;
max-width: 400px;
}
/* Agenda */
.agenda__lista {
display: flex;
flex-wrap: wrap;
row-gap: 1rem;
column-gap: 1.5rem;
justify-content: center;
}
.agenda__item {
flex-grow: 1;
}
/* Rodapé */
.rodape {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.rodape__logo {
align-self: end;
}
/* Aplicando os estilos para a tela de tablet */
@media (min-width: 720px) {
/* Cabeçalho */
.menu {
column-gap: 75px;
}
/* Categorias */
.categorias__lista {
flex-wrap: wrap;
column-gap: 1.5rem;
row-gap: 1rem;
}
/* Eventos */
.eventos__lista {
justify-content: end;
}
/* Agenda */
.agenda__lista {
justify-content: end;
}
}
/* Aplicando os estilos para a tela de desktop */
@media (min-width: 1440px) {
/* Cabeçalho */
.menu {
column-gap: 105px;
/* Impedir a quebra de linha */
flex-wrap: nowrap;
}
/* Ordenando individualmente (pelo filho) cada item do flexbox */
.menu__item:nth-child(1) {
order: 1;
}
.menu__item:nth-child(2) {
order: 3;
}
.menu__item:nth-child(3) {
order: 4;
}
.menu__item:nth-child(4) {
order: 5;
}
.menu__item:nth-child(5) {
order: 2;
}
}
|
.TH include_server 1 "9 June 2008"
.SH "NAME"
include_server.py \- conservative approximation of include dependencies for C/C++
.SH "SYNOPSIS"
.B include_server
--port
.I INCLUDE_SERVER_PORT [OPTIONS]
.SH "DESCRIPTION"
.P
include_server.py starts an include server process. This process answers
queries from
\fBdistcc\fR(1)
clients about what files to include in C/C++ compilations. The include_server.py
command itself terminates as soon as the include server has been spawned.
.PP
The INCLUDE_SERVER_PORT argument is the name of a socket used for all
communication between distcc clients and the include server. The \fBpump\fR(1)
command is responsible for creating the socket location, for passing it to this
script, and for passing it to all distcc clients via the environment variable
named INCLUDE_SERVER_PORT.
.PP
The protocol used by the include server uses distcc's RPC implementation. Each
distcc request consists of (1) the current directory and (2) the list of
arguments of the compilation command.
.PP
If the include server is able to process the request, then it answers the distcc
client by sending a list of filepaths. The filepaths are those of the
compressed source and header files found to be necessary for compilation through
include analysis. The list also comprises symbolic links and even dummy files
needed for the compilation server to construct an accurate replica of the parts of
the filesystem needed for compilation. In this way, a needed header file like
/path/foo.h is compressed, renamed, and stored in a temporary location, such as
/dev/shm/tmpiAvfGv.include_server-9368-1/path/foo.h.lzo. The distcc client will
pass these files on to a compilation server, where they will be uncompressed and
mounted temporarily.
.PP
If the include server is not able to process the request, then it returns the
empty list to the distcc client.
.PP
There are two kinds of failures that relate to the include server. The include
server may fail to compute the includes or fail in other ways, see section
\fBINCLUDE SERVER SYMPTOMS\fR. Also, the compilation on the remove server may
fail due to inadequacy of the calculated include closure, but then succeed when
locally retried, see section \fBDISTCC DISCREPANCY SYMPTOMS\fR.
.SH "OPTION SUMMARY"
The following options are understood by include_server.py.
.TP
.B -dPAT, --debug_pattern=PAT
Bit vector for turning on warnings and debugging
1 = warnings
2 = trace some functions
other powers of two: see include_server/basics.py.
.TP
.B -e, --email
Send email to 'distcc-pump-errors' or if defined, the value of environment
variable DISTCC_EMAILLOG_WHOM_TO_BLAME, when include server gets in trouble.
The default is to not send email.
.TP
.B --email_bound NUMBER
Maximal number of emails to send (in addition to a final email). Default: 3.
.TP
.B --no-email
Do not send email. This is the default.
.TP
.B --path_observation_re=RE
Issue warning message whenever a filename is resolved to a realpath that is
matched by RE, which is a regular expression in Python syntax. This is useful
for finding out where files included actually come from. Use RE="" to find them
all. Note: warnings must be enabled with at least -d1.
.TP
.B --pid_file FILEPATH
The pid of the include server is written to file FILEPATH. This allows a script
such a \fBpump\fR to tear down the include server.
.TP
.B -s, --statistics
Print information to stdout about include analysis.
.TP
.B --stat_reset_triggers=LIST
Flush stat caches when the timestamp of any filepath in LIST changes or the
filepath comes in or out of existence. LIST is a colon separated string of
filepaths, possibly containing simple globs (as allowed by Python's glob
module). Print a warning whenever such a change happens (if warnings are
enabled). This option allows limited exceptions to distcc_pump's normal
assumption that source files are not modified during the build.
.TP
.B -t, --time
Print elapsed, user, and system time to stderr.
.TP
.B --unsafe_absolute_includes
Do preprocessing on the compilation server even if includes of absolute
filepaths are encountered. Normally the include-server will fall back on local
preprocessing if it detects any absolute includes. Thus, this flag is useful
for preventing such fallbacks when the absolute includes are a false alarm,
either because the absolute include is discarded during preprocessing or because
the absolutely included file exists on the compilation servers.
.IP
More precisely, with --unsafe_absolute_includes absolute includes are ignored
for the purposes of gathering the include closure. Using this option may lead
to incorrect results because (1) the header may actually be included on the
compilation server and it may not be the same as on the client, (2) the include
directives of the header are not further analyzed.
.IP
The option is useful for compiling code that has such hardcoded absolute
locations of header files inside conditional directives (e.g. "#ifdef") that
render the includes irrelevant. More precisely, these includes must be
eliminated during preprocessing for the actual configuration. Then the question
of existence of the header file is moot and the remote compilation is sound.
This is often the case if such includes are meant for unusual configurations
different from the actual configuration.
.TP
.B --no_force_dirs
Do not force the creation of all directories used
in an include path. May improve performance for
some cases, but will break builds which use
include structures like "<foo/../file.h>" without
including other files in foo/.
.TP
.B -v, --verify
Verify that files in CPP closure are contained in
closure calculated by include processor.
.TP
.B -w, --write_include_closure
Write a .d_approx file which lists all the included files calculated by the
include server; with -x, additionally write the included files as calculated by
CPP to a .d_exact file.
.TP
.B -x, --exact_analysis
Use CPP instead, do not omit system headers files.
.SH "INCLUDE SERVER SYMPTOMS AND ISSUES"
The most likely messages and warnings to come from the include processor are
listed below.
.PP
.TP
.B "Preprocessing locally. Include server not covering: Couldn't determine default system include directories"
To determine the default system header directories, the include server runs the
compiler once for each language needed during its session. This message
indicates that the compiler specified to distcc is not present on the client.
.PP
.TP
.B Preprocessing locally. Include server not covering: Bailing out because include server spent more than ...s user time handling request
In uncommon situations, the include server fails to analyze very complicated
macro expressions. The distcc client will use plain distcc mode.
.PP
.TP
.B Warning: Filepath must be relative but isn't
The include server does not accept absolute filepaths, such as
/usr/include/stdio.h, in include directives, because there is no guarantee that
this header on the compilation server machine will be the same as that on the
client. The include server gives up analyzing the include closure. The distcc
client cannot use pump-mode.
.IP
To overcome this problem in a not always reliable way, set the environment
variable INCLUDE_SERVER_ARGS='--unsafe_absolute_includes' when invoking the pump
script to pass the --unsafe_absolute_includes option to the include server.
.PP
.TP
.B Warning: Absolute filepath ... was IGNORED
The --unsafe_absolute_includes is in use. This situation happens under the same
circumstances as when "Filepath must be relative but isn't" is issued, but in
this case the include will provide an answer to the distcc client.
.PP
.TP
.B Warning: Path '/PATH/FILE' changed/came into existence/no longer exists
These warnings are issued when using stat reset triggers. Because /PATH/FILE
changed, the include server clears its caches; the new version of the file (or
the lack of it) renders the include analysis invalid. This message can usually
be ignored; it does signify a somewhat precarious use of files by the build
system. It is recommended to fix the build system so that files are not
rewritten.
.PP
.TP
.B Warning: For translation unit ..., lookup of file ... resolved to ... whose realpath is ...
This warning occurs with --path_observation_re when a new realpath matching
a source or header file is observed.
.SH "DISTCC DISCREPANCY SYMPTOMS"
The interactions between the build system, distcc, and the include server is
somewhat complex. When a distcc commands receives a failing compilation from the
remote server it retries the compilation locally. This section discusses the
causes of discrepancies between remote and local compilation. These are flagged
by the demotion message:
.PP
.B __________Warning: ... pump-mode compilation(s) failed on server,
.B but succeeded locally.
.br
.B __________Distcc-pump was demoted to plain mode.
.B See the Distcc Discrepancy Symptoms section in the include_server(1) man
.B page.
.PP
The pump script issues this message at the end of the build. This means that for
at least one distcc invocation a local compilation succeeded after the remote
compilation failed. Each distcc invocation for which such a discrepancy occurred
in turn also issues a message such as:
.PP
.B Warning: remote compilation of '...' failed,
.B retried locally and got a different result.
.PP
The demotion makes subsequent distcc invocations use plain distcc mode. Thus
preprocessing will take place on the local machine for the remainder of the
build. This technique prevents very slow builds where all compilations end up
on the local machine after failing remotely.
.PP
Of course, if the local compilations fails after the remote failures, then the
distcc invocation exits with the non-zero status of the local compilation. The
error messages printed are also those of the local compilation.
.PP
The fallback behavior for distcc-pump mode to local compilation can be disabled
by setting the environment variable DISTCC_FALLBACK to 0, which makes the distcc
command fail as soon as the remote compilation has failed. This setting is very
useful for debugging why the remote compilation went wrong, because now the
output from the server will be printed.
.PP
Next we discuss the possible causes of discrepancies.
.PP
.TP
.B The user changed a source or header file during the build.
This yields inconsistent results of course.
.PP
.TP
.B A source or header file changed during the build.
The build system rewrites a file. For Linux kernel 2.6, this happens
for 'include/linux/compile.h' and 'include/asm/asm-offsets.h'. This condition is
fixed by letting the include server know that it must reset its caches when a
stat of any of the files changes. Practically, this is done by gathering the
files in a colon-separated list and then setting the INCLUDE_SERVER_ARGS
environment variable when invoking the pump script, so that it passes
the
.B --stat_reset_triggers
option; for example,
INCLUDE_SERVER_ARGS="--stat_reset_triggers=include/linux/compile.h:include/asm/asm-offsets.h"
.PP
.TP
.B A header file is potentially included, but does not exist, and is then later included.
This occurs when some header foo.h includes another header file trick.h, but the
trick.h file has not yet been generated and the inclusion is actually ignored
because of preprocessing directives. The include server will probe for the
existence of trick.h, because it overapproximates all possible ways directives
actually evaluate. The file trick.h is determined not to exist. If it is later
generated, and then really included, then the include server will falsely
believe that the file still does not exist. The solution to this problem is to
make the build system generate trick.h before the first time any header file
is included that makes a syntactic reference to trick.h
.PP
.TP
.B The include server was started with \fB--unsafe_absolute_includes\fR.
This is a problem if there are header files locally that do not exist remotely
and that are actually used. Such includes are often protected by conditional
directives that evaluate so that are actually used on only specific and often
uncommon platforms. If you are not compiling for such a platform, then it may be
correct to use \fB--unsafe_absolute_include\fR.
.PP
.TP
.B The include server has calculated the wrong includes.
We do not know of such a situation.
.SH "EXIT CODES"
The exit code of include_server.py is usually 0. That the include server has
been started properly is communicated through the existence of the pid_file.
.SH "ENVIRONMENT VARIABLES"
.B DISTCC_EMAILLOG_WHOM_TO_BLAME
The email address to use for include server automated emails. The default
is 'distcc-pump-errors' (which is an email address that probably will not
exist in your domain).
.PP
Additionally, the invocation of the compiler may use additional environment
variables.
.SH "BUGS"
If you think you have found a distcc bug, please see the file
.I reporting-bugs.txt
in the documentation directory for information on how to report it.
.PP
In distcc-pump mode, the include server is unable to handle certain very
complicated computed includes as found in parts of the Boost library. The
include server will time out and distcc will revert to plain mode.
.PP
Other known bugs may be documented on
.I http://code.google.com/p/distcc/
.SH "AUTHOR"
The include server was written by Nils Klarlund, with assistance from Fergus
Henderson, Manos Renieris, and Craig Silverstein. Please report bugs to
<distcc@lists.samba.org>.
.SH "LICENCE"
You are free to use distcc. distcc (including this manual) may be
copied, modified or distributed only under the terms of the GNU
General Public Licence version 2 or later. distcc comes with
absolutely no warrany. A copy of the GPL is included in the file
COPYING.
.SH "SEE ALSO"
\fBdistcc\fR(1), \fBdistccd\fR(1), \fBinclude_server\fR(1), and \fBgcc\fR(1).
http://code.google.com/p/distcc/ https://ccache.dev/
|
package com.print.controller;
import com.print.models.request.TempUpdateRequest;
import com.print.models.response.TemplateAllResponse;
import com.print.persistence.entity.TemplateTable;
import com.print.service.TemplateService;
import org.apache.coyote.Response;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin("*")
@RequestMapping("/template")
public class TemplateController {
private final TemplateService templateService;
public TemplateController(TemplateService templateService) {
this.templateService = templateService;
}
@GetMapping
private ResponseEntity<TemplateAllResponse> getAllTemplateInfo() {
return ResponseEntity.ok(templateService.getAllTemplateInfo());
}
@DeleteMapping("/{templateId}")
private ResponseEntity<String> deleteTemplateId(@PathVariable("templateId") Long templateId) {
return ResponseEntity.ok(templateService.deleteTemplateId(templateId));
}
@GetMapping("/all")
private ResponseEntity<List<TemplateTable>> getAllTemplate() {
return ResponseEntity.ok(templateService.getAllTemplate());
}
@PostMapping("/update")
private ResponseEntity<TemplateTable> updateTemplate(@RequestBody TempUpdateRequest tempUpdateRequest) {
return ResponseEntity.ok(templateService.updateTemplate(tempUpdateRequest));
}
}
|
# TP1 Cryptographie appliquée : TLS/SSL PKI
#### Antoine DEPOISIER & Jules FINCK
## Question 1
- Il faut choisir 2 grands nombres, p et q
- Calculer n = p * x
- Calculer z = (p - 1) * (q - 1)
- Trouver un nombre e tel que e et z soient premiers entre eux
- Trouver d tel que (e * d) mod z = 1
- e et n sont la clé publique
- d et n sont la clé privée
## Question 2
Pour chiffrer le message, on fait C = M<sup>e</sup>mod n
Pour déchiffrer ce message, c'est l'inverse M = C<sup>d</sup>mod n
## Question 3
- Pour qui le certificat a été signé, c'est-à-dire le sujet, dans un certificat TLS, un nom de domaine
- La signature du certificat
- Le CA du certificat, c'est à dire l'entité pouvant créer un certificat valide pour les navigateurs
- La clé publique du nom de domaine
## Question 4
- Le site `alice.com` envoie le certificat au navigateur
- Le navigateur récupère dans le certificat de `root-ca` contenu dans l'OS
- Le navigateur vérifie si le hash de `ca-1` est le même que la signature décryptée du certificat de `root-ca`
- Le navigateur vérifie si le certificat `ca-1` a l'autorité nécessaire pour délivrer des certificats
- Le navigateur vérifie si le hash du dernier certificat est le même que la signature décryptée de `ca-1`
- Le navigateur va vérifier si la date de couverture du certificat est toujours valide
- Le navigateur va vérifier si le nom de domaine délivrant le certificat est bel et bien un sujet alternatif dans le certificat
- Le navigateur récupère la clé publique du site `alice.com` et envoie un message random généré au site, étant encrypté par la clé publique
- Le serveur d'`alice.com` décrypte le message random
<div style="page-break-after: always;"></div>
## Question 5
Création d'une clé avec une taille 512 bits
```shell
openssl genrsa -out rsa_keys.pem 512
```
La taille des deux nombres premiers choisis est de 33 octets, soit 264 bits.
La longueur du n, c'est celle du modulus est de 65 octets, soit 520 bits.
Le publicExponant est utilisé lors du chiffrement ou du déchiffrement d'un message par l'utilisateur possédant la clé publique. Cette clé peut être connue de tous. Le privateExponant permet d'effectuer les mêmes calculs, mais est utilisé par la personne possédant la clé privée. Elle est seulement connue d'une personne en général.
Le publicExponant est facile à deviner pour un pirate, c'est presque tout le temps le même.
## Question 6
Il n'y a pas d'intérêt à chiffrer une clé publique, étant donné qu'elle est connue de tous, même si elle est chiffrée, on peut la deviner.
Il est néanmoins intéressant de chiffrer une clé privée pour la protéger contre les accès non autorisés.
## Question 7
L'encodage utilisé est en base64. Ça facilite la transmission de données binaires.
## Question 8
Dans la clé publique, on retrouve bien les éléments attendus, tels que le modulo, n, et l'exposant e, étant 65537.
C'est intéressant quand on veut la partager, pour la partager uniquement elle, et non la clé privée en même temps.
## Question 9
Si l'on veut envoyer un message de manière confidentielle, il faut chiffrer ce message avec la clé publique, parce que seulement l'émetteur de la clé publique pourra déchiffrer ce message. Alors que dans le cas inverse, si l'on chiffre une donnée avec la clé privée, tout le monde pourra déchiffrer ce message.
<div style="page-break-after: always;"></div>
## Question 10
Cette commande permet d'encrypter un message contenu dans un TXT
```shell
openssl pkeyutl -encrypt -in clair.txt -out cipher.bin -pubin -inkey pub.finck.pem
```
- -in clair.txt => fichier input contenant la clé
- -out cipher.bin => fichier output qui va contenir le message chiffré
- -pubin => pour spécifier que l'on utilise une clé publique
- -inkey pub.finck.pem => fichier de la clé utilisée
## Question 11
Ils sont différents, c'est normal parce qu'il y a une part d'aléatoire pour éviter de récupérer des pattern qui permettraient de bypass la sécurité.
```shell
openssl pkeyutl -decrypt -inkey rsa_keys.pem -in cipher.finck.bin -out message.txt
```
si on veut utiliser la passphrase :
```shell
openssl pkeyutl -decrypt -inkey rsa_keys_cyphered.pem -in cipher.finck.bin -out message.txt
```
## Question 12
L'option `-showcerts` permet d'afficher les certificats hébergés par le serveur.
3 Certificats ont été renvoyés par le serveur.
<div style="page-break-after: always;"></div>
## Question 13
x509 est une norme définie dans les RFC, pour les certificats à clé publique. C'est un algorithme pour la validation du chemin de certification.
Le sujet du certificat est :
```
Subject: C = FR, ST = Auvergne-Rh\C3\B4ne-Alpes, O = Universit\C3\A9 Grenoble Alpes, CN = *.univ-grenoble-alpes.fr
```
- C => Country, pour le pays
- ST => la région, ou l'état, ou le canton
- O => l'organisation
- CN => configuration name, c'est le nom de domaine pouvant utiliser ce certificat
L'organisme ayant délivré le certificat est Sectigo Limited
## Question 14
Le `s` signifie subject, c'est-à-dire l'entité utilisant le certificat, et `i` signifie l'issuer, c'est-à-dire l'entité délivrant un certificat.
## Question 15
Le certificat possède la clé publique de la clé RSA. L'algorithme utilisé pour signer ce certificat est `sha256WithRSAEncryption`.
Voici le sujet du certificat :
```
Subject: C = FR, ST = Auvergne-Rh\C3\B4ne-Alpes, O = Universit\C3\A9 Grenoble Alpes, CN = *.univ-grenoble-alpes.fr
```
L'attribut sujet comporte le pays, la région et le nom de l'organisation demandant un certificat. Il comporte également le nom de domaine pouvant utiliser ce certificat.
L'attribut qui comporte les autres noms de machine pouvant utilise ce certificat est `Subject Alternative Name`, et les machines pouvant l'utiliser sont `*.univ-grenoble-alpes.fr` et `univ-grenoble-alpes.fr`, donc le nom de domaine et tous ses sous domaine.
Le certificat est valide du `May 8 00:00:00 2023` au ` May 7 23:59:59 2024`, autrement dit pendant un an.
Le fichier `crl` est la liste des certificats révoquée par l'entité ayant certifié des certificats.
<div style="page-break-after: always;"></div>
On peut voir son contenu en utilisant la commande
```shell
openssl crl -in crlfile.crl -inform DER -text -noout
```
## Question 16
Le certificat de l'université a été signé parSectigo Limited.
Pour créer cette signature, `Sectigo Limited` a utilisé la formule suivante : E<sub>KPrivSectigo</sub>(sha256(infoCertifif))
## Question 17
Le sujet de ce certificat est `Sectigo Limited`, ou plus en détail :
```
Subject: C = GB, ST = Greater Manchester, L = Salford, O = Sectigo Limited, CN = Sectigo RSA Organization Validation Secure Server CA
```
La taille de la clé publique du certificat est de 2048 bits.
La CA ayant signé ce certificat est `The USERTRUST Network`, ou plus en détails :
```
Issuer: C = US, ST = New Jersey, L = Jersey City, O = The USERTRUST Network, CN = USERTrust RSA Certification Authority
```
## Question 18
Pour le certificat de l'université, il n'y a rien à vérifier, il ne certifie aucun certificat.
Pour le certificat `Sectigo Limited`, on voit bien qu'il possède les mêmes informations que la CA ayant certifié l'université. Il possède le même nom que le certificat CA de l'université.
Pour le certificat `The USERTRUST Network`, on voit bien qu'il possède les mêmes informations que la CA ayant certifié `Sectigo Limited`. Il possède le même nom que le certificat CA de `Sectigo Limited`.
Le certificat permettant de valider ce certificat est celui qui est en dernier, c'est le certificat racine, il est généralement stocké dans l'OS, ou bien dans le navigateur.
<div style="page-break-after: always;"></div>
## Question 19
On voit que le subject et l'issuer sont les mêmes parce que ce certificat a été auto-signé par ` Comodo CA Limited`.
E<sub>KPrivComodo</sub>(sha384(infoCertifif))
Ce sont des `Trusted Root Certificates` ou bien en français des certificats racine de confiance. Ces certificats sont autorisés dans notre OS à certifier des entités.
Quand on vérifie dans le navigateur, on obtient les mêmes informations que celles, dites dans les questions précédentes.
## Question 20
La taille de la clé publique est de 4096 bits.
Le certificat est valide du `Oct 10 15:49:41 2023` au `Oct 5 15:49:41 2043`
On peut voir que c'est un certificat auto-signé parce que le subject et l'issuer sont la même entité.
```
X509v3 Key Usage: Digital Signature, Certificate Sign, CRL Sign
```
Ce certificat peut être utilisé pour effectuer des signatures digitales, des signatures de certificats, et également des signatures de fichier crl, ceux qui permettent de définir une liste de révocations.
La clé privée : `private_key = $dir/private/ca.key.pem`
Pour la lire, on utilise la commande
```shell
openssl rsa -in private/ca.key.pem -noout -text
```
## Question 21
Dans le paramètre dir, j'ai mis le paramètre `/home/etudiant/ca`
La clé privée devra être dans le dossier `private` sous le nom de `intermediate.key.pem`
Le certificat devra être dans le dossier `certs` sous le nom de `intermediate.cert.pem`
<div style="page-break-after: always;"></div>
## Question 22
Voici la commande permettant de créer la clé :
```shell
openssl genrsa -aes128 -out private/intermediate.key.pem 3072
```
```shell
openssl req -config openssl.cnf -new -sha256 -key private/intermediate.key.pem -out csr/intermediate.csr.pem -subj "/C=FR/ST=Savoie/L=Chambery/O=TP Sécurité/CN=RA depoisier"
```
## Question 23
On peut la qualifier de bizarre parce que l'algorithme utilisé n'est pas `aes128` mais `sha256`. La signature du demandeur empêche une entité de demander un faux certificat de la clé publique de quelqu'un d'autre.
```shell
openssl ca -config openssl.cnf -extensions v3_intermediate_ca -days 3650 -notext -md sha256 -in csr/depoisier.csr.pem -out certs/depoisier.cert.pem
```
```shell
openssl x509 -in depoisier.cert.pem -noout -text
```
```shell
sudo openssl req -new -key /etc/pki/tls/private/serveur_http.pem -out serveur_http.csr.pem -subj "/C=FR/ST=Rhone/L=Lyon/O=Canut depoisier inc/CN=www.depoisier.fr" -addext "subjectAltName = DNS:www.depoisier.fr, DNS:dev.depoisier.fr, DNS:*.depoisier.fr"
```
```shell
openssl ca -config openssl.cnf -extensions server_cert -days 375 -notext -md sha256 -in csr/serveur_http.csr.pem -out certs/serveur_http.cert.pem
```
<div style="page-break-after: always;"></div>
```conf
events {}
http {
server {
listen 443 ssl;
server_name www.depoisier.fr;
ssl_certificate /etc/nginx/ssl/serveur_http.cert.pem;
ssl_certificate_key /etc/nginx/ssl/serveur_http.pem;
location / {
proxy_pass http://web1;
}
location /admin/ {
proxy_pass http://web2/;
}
}
}
```
## Question 24
La 3ᵉ solution est la plus pertinente parce que le certificat root expose moins sa clé privée que les certificats intermédiaires. C'est-à-dire, que si un certificat intermédiaire doit changer sa clé privée parce qu'elle a été volée, il faudra modifier les certificats de confiances de notre machine.
Étant donné que le certificat racine expose moins sa clé, on risque de ne jamais avoir besoin de le changer des certificats de confiances.
De plus, les certificats de serveur ont des dates de validités, ce qui demanderait d'update les certificats à chaque fois qu'ils sont expirés.
Petit ajout : après avoir rencontré un problème pour notre certificat mal généré, nous sommes bien contents d'avoir donné confiance au certificat root, et non celui du serveur.
Pour ajouter un CA de confiance, on ajoute le certificat dans le dossier `/etc/pki/ca-trust/source/anchors/` et on effectue la commande `update-ca-trust`
## Question 25
Nous avons ajouté cette information :
```
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 www.depoisier.fr
```
<div style="page-break-after: always;"></div>
## Question 26
[Voici le lien du repo GitHub](https://github.com/copsfuraxx/info001Secu) : https://github.com/copsfuraxx/info001Secu
Pour tester l'application, il faut ajouter dans les host de son serveur, les différents host différent comme alias de `127.0.0.1` :
- `www.depoisier.fr`
- `dev.depoisier.fr`
- `test.depoisier.fr`
Il faut ensuite ajouter dans son ca-bundle, le fichier `certificates/rout-ca-lorne.pem` contenu dans le projet.
Pour ajouter un CA de confiance, on ajoute le certificat dans le dossier `/etc/pki/ca-trust/source/anchors/` et on effectue la commande `update-ca-trust`
Maintenant, vous pouvez lancer le serveur en effectuant la commande
```
python3 server.py
```
Et le client avec la commande
```
python3 client.py
```
Le client demande un serveur, vous pouvez utiliser les trois serveurs ajoutés en alias de localhost.
Quand le client a envoyé son message au serveur, le serveur se ferme.
## Question 27
Le navigateur nous affiche deux erreurs, la première `ERR_CERT_AUTHORITY_INVALID` nous indique que l'autorité ayant délivré le certificat n'est pas de confiance.
La seconde erreur, `SSL_ERROR_BAD_CERT_DOMAIN`, nous indique que le nom du serveur n'est pas celui indiqué dans le certificat.
La première erreur a pu être corrigée en ajoutant dans le magasin de certificat de Firefox le certificat root-ca-lorne.
## Question 28
C'est pour avoir une sécurité renforcée, étant donné que la CA expose moins sa clé privée.
Il y a plus de détails à la réponse de cette question dans la question 24.
|
// Copyright A.T. Chamillard. All Rights Reserved.
#pragma once
#include "MutualFund.h"
/**
* An employer-sponsored account
*/
class EmployerSponsoredAccount :
public MutualFund
{
public:
/**
* Constructor
* @param Deposit initial deposit
*/
EmployerSponsoredAccount(float Deposit);
/**
* Adds money to the account, adding employer match
* @param Amount amount to add
*/
virtual void AddMoney(float Amount) override;
/**
* Provides balance with account type caption
* @return balance with caption
*/
virtual std::string GetString() override;
};
|
package com.example.jpabook.dto;
import com.example.jpabook.api.OrderApiController;
import com.example.jpabook.domain.Address;
import com.example.jpabook.domain.Order;
import com.example.jpabook.domain.OrderStatus;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Data
public class OrderDto {
private Long orderId;
private String name;
private LocalDateTime orderDate;
private OrderStatus orderStatus;
private Address address;
private List<OrderItemDto> orderItems;
public OrderDto(Order order) {
orderId = order.getId();
name = order.getMember().getName();
orderDate = order.getOrderDate();
orderStatus = order.getStatus();
address = order.getDelivery().getAddress();
order.getOrderItems().stream().forEach(o -> o.getItem().getName());
orderItems = order.getOrderItems().stream().map(orderItem -> new OrderItemDto(orderItem)).collect(toList());
}
}
|
# Fingerprint-Ridge-Counting
Project Name: Finding the number of ridges from a fingerprint.
<br>
Project Type: A graduation project in an image processing course.
<br>
Code for fingerprint ridge counting using image processing: identifies optimal regions, enhances images, counts ridges via diagonal analysis for accurate results.
<br>
Introduction to the project:
<br>
This code is used to count the number of ridges in an image using the identification and isolation of the most suitable rectangular region in terms of brightness and density in the image. To achieve this, I apply different image processing techniques as a deferment to clean the image and emphasize the desired parts (gray, blur, Gaussian blur, threshold, mask, Kernel, clahe, skeleton, and dilate).
Then I repeat the rectangular areas within the picture to find the one that is more appropriate. After identifying the brightest rectangle, I cut the original image into this area and apply additional image processing techniques to isolate and improve the parts and ridges, and epic of the image within this area.
Then when everything is ready, I begin to tell the number of ridges in the picture that the diagonal is cut with them, and every time it is cut I count one and I do it in both diagonals from left to right and to right of Lest and then at the end I choose the highest substrate that comes out of the two diagonals and he will be the number of ridges in the picture.
<br>
Description of the project in stages:
<br>
This code receives images in the PNG format from an input_images directory and performs several image processing operations on them (gray, blur, Gaussian blur, threshold, mask, Kernel, clahe, skeleton, and dilate) to find the most suitable rectangular area to perform a ridges count and finally save the images with a direction on the rectangle location and also the number of ridges in the library called output_images.
<br>
The steps for processing the image in code:
<br>
1- Loading the image using OpenCV.
<br>
2- Converts the image to grayscale.
<br>
3– Apply Gaussian blur to the image.
<br>
4 - Apply Otsu's thresholding to the blurry image to create a binary mask.
<br>
5- Turn the mask over so that the front is white and the background is black.
<br>
6– Perform some morphological actions to clear the mask.
<br>
7- Create a mask image by applying the mask to the original image.
<br>
8—Apply a histogram comparison (CLAHE) to the masked image.
<br>
9 – Create an embedded version of the image using the skeletonize function from the skimage package.
<br>
10 – Looking for the most suitable rectangular area in the picture.
<br>
11 - Draw a rectangle around the most appropriate area.
<br>
12 - Crop the most suitable rectangular area and perform additional image processing on it.
<br>
13 - Count the number of black pixels in the left and right diagonal of the cutting area.
<br>
14- Select the maximum number of assets counted and take it.
<br>
15- Draw a rectangle with a diagonal on the original image that shows the best place with the number of ridges.
<br>
Description of the project in general:
<br>
The code uses cv2, os, numpy, and skimming libraries.
<br>
The code reads pictures from the input_images library, processes a picture to find the most appropriate rectangular area in the picture, draws a rectangle around it, and extracts it as a new image.
It loads the image from the given directory using the OpenCV Imread function. It checks to see if the image is loaded successfully, converts the image to grayscale, and applies Gaussian Blur.
<br>
He then applies thresholding to the image to obtain a binary mask of the object and cleans the mask using morphological actions. Then, he applies the mask to the original image to get a picture with a mask. Then apply histogram equalization to a picture in grayscale and then apply Gaussian Blur to slide the picture.
Then, perform skeletonization on the image to get a skeletonized image. Then, it sets the rectangular area size to look for the most appropriate area in the picture. It then repeats any possible rectangular area and follows the most appropriate area.
<br>
It draws a rectangle around the best area and displays the original image with the area described by the rectangle. It also extracts the area as a separate image and applies image processing operations such as histogram equalization, Gaussian Blu, and thresholding to this image to identify the black pixels that are cut with the diagonals on the left and right of the image. It counts the number of black pixels in the left and right diagonal and prints the count.
<br>
And finally, he saves the pictures in a library called Output_images, highlighting each moderate rectangle with the number of ridges.
|
import os
from datetime import datetime
from functools import partial
import click
import torch
from ray import tune
from ray.tune import CLIReporter
from ray.tune.schedulers import ASHAScheduler
from data import load_estimator_data
from models.ankle_estimator import LSTMEstimator
def try_train(config, target):
train_set, val_set, _ = load_estimator_data(config['batch_size'], target=target)
model = LSTMEstimator(input_dim=config['input_dim'],
output_dim=config['output_dim'],
feature_dim=config['feature_dim'],
hidden_dim=config['hidden_dim'],
n_lstm_layers=config['n_lstm_layers'],
pre_layers=[config['n_pre_nodes']] * config['n_pre_layers'],
post_layers=[config['n_post_nodes']] * config['n_post_layers'],
p_drop=config['p_drop'],
layer_norm=config['layer_norm'],
lr=config['lr'],
device='cuda')
for epoch in range(1000):
""" Training """
train_loss = model.train_model(epoch, train_set)
""" Validation """
val_loss = model.train_model(epoch, val_set, evaluation=True)
""" Temporally save a model"""
trial_dir = tune.get_trial_dir()
path = os.path.join(trial_dir, "model.pt")
torch.save(model.state_dict(), path)
tune.report(train_loss=train_loss, val_loss=val_loss)
@click.command()
@click.option('--target', default='Ankle')
def main(target):
target = target[0].upper() + target[1:]
config = {
'input_dim': 8,
'output_dim': 1,
'batch_size': tune.choice([32, 64, 128]),
'feature_dim': tune.choice([5, 10, 15, 20, 25]),
'hidden_dim': tune.choice([16, 32, 64, 128, 256]),
'n_lstm_layers': tune.choice([1, 2, 3]),
'n_pre_nodes': tune.choice([32, 64, 128]),
'n_pre_layers': tune.choice([0, 1, 2]),
'n_post_nodes': tune.choice([32, 64, 128]),
'n_post_layers': tune.choice([0, 1, 2]),
'p_drop': tune.choice([0.0, 0.1, 0.3, 0.5, 0.8]),
'layer_norm': tune.choice([False, True]),
'lr': tune.loguniform(1e-4, 1e-2)
}
scheduler = ASHAScheduler(
metric="val_loss",
mode="min",
max_t=1000,
grace_period=20,
reduction_factor=2)
reporter = CLIReporter(metric_columns=["train_loss", "val_loss", "training_iteration"])
result = tune.run(
partial(try_train, target=target),
name='R' + target + 'FromEmgLSTM' + '_' + datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),
resources_per_trial={"cpu": os.cpu_count() // 8, "gpu": 0.11},
config=config,
num_samples=500,
scheduler=scheduler,
progress_reporter=reporter,
checkpoint_at_end=True,
)
best_trial = result.get_best_trial("val_loss", "min", "last")
print(f"Best trial config: {best_trial.config}")
print(f"Best trial final validation loss: {best_trial.last_result['val_loss']:.4f}")
best_config = best_trial.config
_, _, test_set = load_estimator_data(best_config['batch_size'], device='cpu', target=target)
best_logdir = result.get_best_logdir(metric='val_loss', mode='min')
model = LSTMEstimator.load_from_config(best_config,
os.path.join(best_logdir, "model.pt"),
map_location='cpu')
model.eval()
test_loss = model.train_model(-1, test_set)
print(f"Best trial test set loss: {test_loss:.4f}")
if __name__ == '__main__':
main()
|
import { Project } from "@/Data/data";
import Chips from "@/components/Chips";
import HText from "@/components/HText";
import ProjectCard from "@/components/ProjectCard";
import { useState } from "react";
import { projectData } from "@/Data/data";
import { motion } from "framer-motion";
type ProfileProps = {
projectItemData: Project[];
filterProjectItem: (category: string) => void;
setProjectItem: React.Dispatch<React.SetStateAction<Project[]>>;
setSelectedPage: React.Dispatch<React.SetStateAction<string>>;
};
const Portfolio = ({
projectItemData,
filterProjectItem,
setProjectItem,
setSelectedPage,
}: ProfileProps) => {
const [selectedChip, setSelectedChip] = useState("All");
const handleChipClick = (chipTitle: string) => {
setSelectedChip(chipTitle);
if (chipTitle === "All") setProjectItem(projectData);
else filterProjectItem(chipTitle);
};
return (
<section id="Projects">
<motion.div
className="mt-4 py-4 w-4/5 mx-auto"
onViewportEnter={() => setSelectedPage("projects")}
>
<HText header="Portfolio" subHeader="My Diverse Range of Work" />
{/* Chips Area */}
<div className="flex items-center justify-center">
<Chips
title="All"
active={selectedChip === "All"}
onClick={() => handleChipClick("All")}
/>
<Chips
title="Web"
active={selectedChip === "Web"}
onClick={() => handleChipClick("Web")}
/>
<Chips
title="Machine Learning"
active={selectedChip === "Machine Learning"}
onClick={() => handleChipClick("Machine Learning")}
/>
</div>
{/* Chips Area end*/}
{/* Project Card Area */}
<div className="grid ms:grid-cols-3 xm:grid-cols-2 grid-cols-1 mt-4 gap-4">
{projectItemData.map((value, index) => (
<ProjectCard
key={index}
id={value.id}
title={value.title}
projectImg={value.projectImg}
demoLink={value.demoLink}
codeLink={value.codeLink}
details={value.details}
category={value.category}
/>
))}
</div>
</motion.div>
</section>
);
};
export default Portfolio;
|
import { Link } from "react-router-dom";
import React, { useState, useEffect } from "react";
import SearchBar from "./SearchBar";
import Header from "./Header";
import axios from "axios";
import autoprefixer from "autoprefixer";
const styleLink = document.createElement("link");
export default function ArtzSuchen() {
const [searchValue, setSearchValue] = useState("");
const [doctors, setDoctors] = useState([]);
useEffect(() => {
const getAllDoctors = async () => {
try {
const response = await axios.get(
`${import.meta.env.VITE_APP_DR_TIME}/doctors/`
);
setDoctors(response.data);
} catch (error) {
console.error(error);
}
};
getAllDoctors();
}, []);
return (
<>
<div className=" flex items-center flex-col ">
<div className="mt-10 mb-5">
<h1 className="text-5xl text-purple-700 flex justify-center">
Arzt suchen
</h1>
</div>
<SearchBar
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
<div className="mt-5 docList flex justify-center ">
<ul className="">
{doctors.map((doctor, index) => (
<Link to={`/doctors/${doctor._id}`} key={index}>
<li className="flex items-center space-x-4 mt-8 hover:bg-gradient-to-r from-blue-450 via-blue-400 to-blue-450">
<div className="w-22 h-22">
<img
className="w-20 h-20 ml-2 rounded-full shadow-lg object-cover"
src={doctor.profilePhoto}
alt="Image Silhouette"
/>
</div>
<div className=" flex flex-col ">
<p className="text-3xl text-purple-700 font-bold ">
{doctor.title}
{doctor.name}
</p>
<p className="bg-gradient-to-r from-blue-600 via-blue-700 to-blue-600 rounded-full w-52 h-10 text-2xl text-white flex justify-center items-center">
{doctor.specialization}
</p>
</div>
</li>
</Link>
))}
{/* {data.filter(item => item.name.toLowerCase().includes(searchValue.toLowerCase())).map((item, index) => (
<li key={index} className='flex items-center space-x-4 mt-5 cursor-pointer'>
<div className="w-20 h-20"><img src={silhouetteProfil} alt="Image Silhouette" /></div>
<p>{item.name}</p>
</li>
))} */}
</ul>
</div>
</div>
</>
);
}
|
/*
* Copyright [2020-2030] [https://www.stylefeng.cn]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Guns采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
*
* 1.请不要删除和修改根目录下的LICENSE文件。
* 2.请不要删除和修改Guns源码头部的版权声明。
* 3.请保留源码和相关描述文件的项目出处,作者声明等。
* 4.分发源码时候,请注明软件出处 https://gitee.com/stylefeng/guns
* 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/stylefeng/guns
* 6.若您的项目无法满足以上几点,可申请商业授权
*/
package cn.stylefeng.roses.kernel.sys.api.enums.org;
import lombok.Getter;
/**
* 组织审批类型:1-负责人,2-部长,3-体系负责人,4-部门助理,5-资产助理(专员),6-考勤专员,7-HRBP,8-门禁员,9-办公账号员,10-转岗须知员
*
* @author fengshuonan
* @since 2024-02-25 15:04
*/
@Getter
public enum OrgApproverTypeEnum {
/**
* 负责人
*/
FZR(1, "负责人"),
/**
* 部长
*/
BZ(2, "部长"),
/**
* 体系负责人
*/
TXFZR(3, "体系负责人"),
/**
* 部门助理
*/
BMZL(4, "部门助理"),
/**
* 资产助理(专员)
*/
ZCZL(5, "资产助理(专员)"),
/**
* 考勤专员
*/
KQZY(6, "考勤专员"),
/**
* HRBP
*/
HRBP(7, "HRBP"),
/**
* 门禁员
*/
MJY(8, "门禁员"),
/**
* 办公账号员
*/
BGZHY(9, "办公账号员"),
/**
* 转岗须知员
*/
ZGXZY(10, "转岗须知员");
private final Integer code;
private final String message;
OrgApproverTypeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
/**
* code转化为enum
*
* @author fengshuonan
* @since 2024-02-18 16:11
*/
public static OrgApproverTypeEnum toEnum(Integer code) {
for (OrgApproverTypeEnum orgTypeEnum : OrgApproverTypeEnum.values()) {
if (orgTypeEnum.getCode().equals(code)) {
return orgTypeEnum;
}
}
return null;
}
/**
* 获取code对应的message
*
* @author fengshuonan
* @since 2024-02-18 16:11
*/
public static String getCodeMessage(Integer code) {
OrgApproverTypeEnum orgTypeEnum = toEnum(code);
if (orgTypeEnum != null) {
return orgTypeEnum.getMessage();
} else {
return "";
}
}
}
|
import Head from 'next/head';
import { useEffect, useState } from 'react'
import { AiFillEdit, AiFillCloseCircle, AiOutlineArrowLeft, AiOutlineArrowRight, AiOutlineSearch, AiOutlineLoading3Quarters } from 'react-icons/ai'
import { IoIosPersonAdd } from 'react-icons/io'
import { toast } from 'react-toastify';
import { convertReadableDate, convertActiveDate } from '../helpers/date';
import { HiRefresh } from 'react-icons/hi'
import { useRouter } from 'next/router';
import Link from 'next/link';
// user interface
export interface User {
username: string
id: number // user id in database
name?: string
email?: string
phone: string
role?: string
credit?: number
bonus?: number
winnings?: number // total winnings of user bets. admin only
losses?: number // total losses of user bets. admin only
pnl?: number // total profit and loss of user bets, i.e winnings + losses. admin only
deposits?: number // total deposits of user. admin only
withdrawals?: number // total withdrawals of user. admin only
exposure?: number // total exposure. Will be mostly saved in negative value, i.e the total amount of money user can lose on all bets.
exposureTime?: Date // last exposure time. Required by provider: Fawk Poker
exposureLimit?: number // Exposure limit. How much exposure is allowed.
wagering?: number // total wagering/rolling amount of user on all bets.stake. resets on every deposit.
newPassword?: string // for setting new password while editing or adding user. Not for fetching user data from API as password field is encrypted and not returned.
ip?: string
user_agent?: string
is_active?: boolean
is_verified?: boolean
is_deleted?: boolean
is_banned?: boolean
createdAt?: string
updatedAt?: string
lastActive?: string
access?: { // access permissions for admin panel
dashboard?: boolean,
users?: boolean,
games?: boolean,
team?: boolean,
offers?: boolean,
deposits?: boolean,
withdrawals?: boolean,
bankAccounts?: boolean,
transactions?: boolean,
settings?: boolean,
reports?: boolean,
}
transactions?: Transaction[]
}
// transaction type
export interface Transaction {
id?: number
createdAt?: string
updatedAt?: string
user_id: number
type: string
amount: number
game_data: any
status: string
remark: string
reference: string
timestamp: string
}
export default function Users() {
const [users, setUsers] = useState<User[]>([])
const [page, setPage] = useState(1)
const [hasNextPage, setHasNextPage] = useState(false)
const [search, setSearch] = useState('')
const [showUserModal, setShowUserModal] = useState(false)
const [showTransactionModal, setShowTransactionModal] = useState(false)
const [loading, setLoading] = useState(true)
const router = useRouter();
const emptyUser: User = {
username: '',
id: 0,
name: '',
email: '',
phone: '',
credit: 0,
newPassword: '',
is_verified: false,
is_banned: false,
is_deleted: false,
bonus: 0,
exposure: 0,
exposureLimit: -200000, // default 2 lakhs exposure limit
}
const [modalUser, setModalUser] = useState<User>(emptyUser)
// Call API to fetch users
const fetchUsers = async () => {
setLoading(true);
const limit = 20;
const skip = page > 1 ? (page - 1) * 20 : 0;
const options = {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
};
const response = await fetch(`/api/team/users?limit=${limit}&skip=${skip}&search=${search}&user=${router.query.user || 0}`, options);
if (response.status === 200) {
const data = await response.json();
if (!response.ok) {
const error = (data && data.message) || response.status;
return Promise.reject(error);
}
setUsers(data);
setHasNextPage(data && data.length === limit);
setLoading(false);
} else {
toast.error(await response.text());
}
}
useEffect(() => {
fetchUsers()
}, [page, search, router.query.user])
// Call API to add user
const addUser = async (user: User) => {
// if user password or phone is empty, return
if (!user.newPassword || !user.phone) {
toast.error('Please enter phone number and password');
return;
}
// if password not empty and less than 8 characters, return
if (user.newPassword && user.newPassword.length < 8) {
toast.error('Password must be at least 8 characters');
return;
}
const body = {
name: user.name,
email: user.email,
phoneNumber: user.phone,
newPassword: user.newPassword,
is_verified: user.is_verified,
is_banned: user.is_banned,
role: user.role,
credit: user.credit,
bonus: user.bonus,
exposure: user.exposure,
exposureLimit: user.exposureLimit
}
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
};
const response = await fetch('/api/team/users/', options)
if (response.status === 200) {
// add user to state
const updatedUsers = [user, ...users]
setUsers(updatedUsers)
// close modal
setShowUserModal(false)
toast.success('User added successfully!');
router.reload();
} else {
toast.error(await response.text());
}
}
// Call API update user
const updateUser = async (user: User) => {
// if user password or phone is empty, return
if (!user.phone) {
toast.error('User must have a phone number');
return;
}
// if password not empty and less than 8 characters, return
if (user.newPassword && user.newPassword.length < 8) {
toast.error('Password must be at least 8 characters');
return;
}
const body = {
name: user.name,
email: user.email,
phoneNumber: user.phone,
newPassword: user.newPassword,
is_verified: user.is_verified,
is_banned: user.is_banned,
role: user.role,
credit: user.credit,
bonus: user.bonus,
exposure: user.exposure,
exposureLimit: user.exposureLimit
}
const options = {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
};
const response = await fetch(`/api/team/users/${user.id}/`, options);
if (response.status === 200) {
setShowUserModal(false)
toast.success('User updated successfully!');
// update user in state
const updatedUsers = users.map(u => u.id === user.id ? user : u);
setUsers(updatedUsers)
} else {
toast.error(await response.text());
}
}
// Call API to delete user
const deleteUser = async (id: number) => {
// confirm deleteion
const confirm = window.confirm('Are you sure you want to delete this user? All data related to this user like bets, deposits, bank accounts etc will also be deleted.')
if (!confirm) return
const response = await fetch(`/api/team/users/${id}/`, { method: 'DELETE' });
if (response.status === 200) {
// delete user from state
const updatedUsers = users.filter(u => u.id !== id);
setUsers(updatedUsers);
toast.success('User deleted successfully!');
} else {
toast.error(await response.text());
}
}
return (
<>
<Head>
<title>Users | Spade365</title>
<meta name="description" content="Users | Spade365" />
</Head>
<div className="flex flex-col justify-start items-center min-h-[800px] w-full container mx-auto overflow-hidden">
<div className="flex flex-col md:flex-row justify-between w-full items-center mb-8 md:mb-4">
<h1 className="text-center md:text-left text-4xl lg:text-5xl my-6 w-1/2">
{!router.query.user ? `Users` : `User ID: ${router.query.user}`}
<button className="bg-white text-black p-1 text-2xl cursor-pointer rounded ml-4" title="Refresh" onClick={() => {
fetchUsers()
toast.success('Users refreshed successfully!')
}} >
<HiRefresh />
</button>
</h1>
{/* search and add user button */}
<div className="flex flex-row justify-center md:justify-start items-center w-full md:w-1/2">
{/* search inpout with search icon */}
<div className="md:ml-auto flex flex-row justify-start items-center w-full bg-gray rounded-md border max-w-xs">
<button className="p-2 h-full rounded-md">
<AiOutlineSearch className='text-2xl' />
</button>
<input
type="search"
className="w-full p-2 focus:outline-none focus:ring-0 border-none bg-transparent"
placeholder="Search"
autoComplete="new-search"
value={search}
onChange={(e) => {
setPage(1) // reset page to 1 when search is changed
setSearch(e.target.value)
}
}
/>
</div>
{/* button to add user */}
<button
className="ml-4 p-2 bg-white text-black rounded-md flex flex-row justify-center items-center"
title='Add User'
onClick={() => {
setModalUser(emptyUser)
setShowUserModal(true)
}}
>
<IoIosPersonAdd className='text-2xl' />
<span className='ml-1 hidden lg:inline-block'>Add User</span>
</button>
</div>
</div>
<div className='overflow-x-scroll scrollbar-hide w-full'>
{/* table with users, user, amount, date, status, action */}
<table className="table-auto w-full text-left break-words">
<thead className="bg-primary text-white">
<tr>
<th className="border border-white/20 px-4 py-2 text-center">ID</th>
<th className="border border-white/20 px-4 py-2 text-center">Phone</th>
<th className="border border-white/20 px-4 py-2 text-center">Name</th>
<th className="border border-white/20 px-4 py-2 text-center">Username</th>
<th className="border border-white/20 px-4 py-2 text-center">Email</th>
<th className="border border-white/20 px-4 py-2">Deposits</th>
<th className="border border-white/20 px-4 py-2">Withdrawals</th>
{/* <th className="border border-white/20 px-4 py-2 text-center">Bonus</th> */}
<th className="border border-white/20 px-4 py-2 text-center">Balance</th>
<th className="border border-white/20 px-4 py-2 text-center">P/L</th>
{/* <th className="border border-white/20 px-4 py-2 text-center">Exposure</th> */}
{/* <th className="border border-white/20 px-4 py-2 text-center">Exp. Limit</th> */}
<th className="border border-white/20 px-4 py-2 text-center">Status</th>
<th className="border border-white/20 px-4 py-2 text-center">IP</th>
<th className="border border-white/20 px-4 py-2 text-center">Last Active</th>
<th className="border border-white/20 px-4 py-2 text-center">Date Joined</th>
<th className="border border-white/20 px-4 py-2 text-center">Action</th>
</tr>
</thead>
<tbody>
{/* map through users and display them */}
{users.map((user) => (
<tr key={user.id} className={`h-[120px] odd:bg-transparent even:bg-primary/10 ${user.is_banned || user.is_deleted ? 'text-red-500' : ''}`}>
<td className="border border-white/20 px-4 py-2 font-semibold">
{user.id}
</td>
<td className={`border border-white/20 px-4 py-2 text-left`}>
{user.phone}
</td>
<td className={`border border-white/20 px-4 py-2 text-left`}>
{user.name}
</td>
<td className={`border border-white/20 px-4 py-2 text-left`}>
{user.username}
</td>
<td className={`border border-white/20 px-4 py-2 text-left`}>
{user.email}
</td>
<td className="border border-white/20 px-4 py-2">
{user.deposits}
</td>
<td className="border border-white/20 px-4 py-2">
{user.withdrawals}
</td>
{/* <td className="border border-white/20 px-4 py-2">
{user.bonus}
</td> */}
<td className={`border border-white/20 px-4 py-2 ${user.credit && user.credit > 0 ? 'text-green-400' : 'text-red-400'}`}>
<span className='mr-1'>₹</span>{user.credit}
</td>
<td className="border border-white/20 px-4 py-2 text-left min-w-[250px]">
<div className="flex flex-col justify-start items-start h-full">
<span>Wagering: {user.wagering}</span>
<span>Win: {user.winnings}</span>
<span>Loss: {user.losses}</span>
<span>Total: {user.pnl}</span>
</div>
</td>
{/* <td className="border border-white/20 px-4 py-2">
{user.exposure}
</td> */}
{/* <td className="border border-white/20 px-4 py-2">
{user.exposureLimit}
</td> */}
<td className="border border-white/20 px-4 py-2 min-w-[80px]">
<div className='grid grid-cols-1 gap-2 text-center justify-center items-center'>
{user.is_banned ? ( // if user is banned
<span className="bg-red-500 text-white px-2 py-1 rounded-md" title='Banned'>
{'B'}{<span className='hidden 3xl:inline'>anned</span>}
</span>
) : ( // if user is not banned
<span className="bg-green-500 text-white px-2 py-1 rounded-md" title='Active'>
{'A'}{<span className='hidden 3xl:inline'>ctive</span>}
</span>
)}
{/* {user.is_verified ? ( // if user is verified
<span className="bg-green-500 text-white px-2 py-1 rounded-md" title='Verified'>
{'V'}{<span className='hidden 3xl:inline'>erified</span>}
</span>
) : ( // if user is not verified
<span className="bg-red-500 text-white px-2 py-1 rounded-md" title='Not Verified'>
{'N'}{<span className='hidden 3xl:inline'>ot Verified</span>}
</span>
)} */}
</div>
</td>
<td className="border border-white/20 px-4 py-2">
<div className="flex flex-col max-w-xs">
<span>{user.ip && <Link href={`https://ipinfo.io/${user.ip}`} target='_blank' rel="noreferrer" className='font-semibold hover:underline'>{user.ip}</Link>}</span>
<span className='text-xs'>{user.user_agent || ""}</span>
</div>
</td>
<td className="border border-white/20 px-4 py-2" title={user.lastActive}>
{user.lastActive && convertActiveDate(user.lastActive as string)}
</td>
<td className="border border-white/20 px-4 py-2" title={user.createdAt}>
{user.createdAt && convertReadableDate(user.createdAt as string)}
</td>
<td className="border border-white/20 px-4 py-2 min-w-[200px]">
<div className='grid grid-cols-1 gap-2'>
{/* view transactions, open transaction modal */}
<Link href={`/transactions?user=${user.id}`} passHref>
<button title='View Transactions' type="button" className="bg-green-600 hover:bg-green-800 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1 w-full">
Transactions
</button>
</Link>
{/* View bets, direct to bets page with ?user= */}
<Link href={`/reports/betlist?user=${user.id}`} passHref>
<button title='View Bets' type="button" className="bg-teal-600 hover:bg-teal-800 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1 w-full">
Bets
</button>
</Link>
{/* View Deposits */}
<Link href={`/deposits?user=${user.id}&type=deposit`} passHref>
<button title='View Deposits' type="button" className="bg-purple-600 hover:bg-purple-800 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1 w-full">
Deposits
</button>
</Link>
{/* View Withdrawals */}
<Link href={`/withdrawals?user=${user.id}`} passHref>
<button title='View Withdrawals' type="button" className="bg-yellow-600 hover:bg-yellow-800 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1 w-full">
Withdrawals
</button>
</Link>
{/* Edit button */}
<button
title='Edit User'
type="button"
onClick={() => {
setModalUser(user)
setShowUserModal(true)
}}
className="bg-blue-600 hover:bg-blue-800 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1">
Edit
</button>
{/* Delete Button */}
<button title='Delete User' type="button" onClick={() => deleteUser(user.id)} className="bg-red-600 hover:bg-red-800 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1">
DELETE
</button>
{/* <button
title='View Transactions'
type="button"
onClick={() => {
setModalUser(user)
setShowTransactionModal(true)
}}
className="bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-2 px-2 rounded text-center flex flex-row justify-center items-center col-span-1 w-full">
Transactions
</button> */}
</div>
</td>
</tr>
))}
</tbody>
<tfoot>
<tr>
{/* <td colSpan={8} className="border border-white/20 px-4 py-2 text-center">
<span className='text-sm text-white/60'>Showing {users.length} of {total} users</span>
</td> */}
{/* loading spinner if loading is true */}
{loading && (
<td colSpan={18} className="border border-white/20 px-4 py-8 text-center">
<div className="flex flex-row justify-center items-center text-white">
<AiOutlineLoading3Quarters className='animate-spin text-3xl mr-2' />
</div>
</td>
)}
</tr>
</tfoot>
</table>
</div>
{/* pagination */}
{(page > 1 || hasNextPage) && (
<div className="flex flex-row justify-center items-center my-12">
{page > 1 && (
<button className="bg-primary hover:bg-neutral/80 text-white font-bold py-2 px-4 rounded-l text-center flex flex-row items-center justify-center" onClick={() => setPage(page - 1)}>
<AiOutlineArrowLeft className='mr-2' />{'Previous'}
</button>
)}
{hasNextPage && (
<button className="bg-primary hover:bg-neutral/80 text-white font-bold py-2 px-4 rounded-r text-center border-l-2 border-white/20 flex flex-row items-center justify-center" onClick={() => setPage(page + 1)}>
{'Next'}<AiOutlineArrowRight className='ml-2' />
</button>
)}
</div>
)}
{/* Add/Edit User Modal */}
<div className={`fixed top-0 backdrop-blur left-0 w-full h-full bg-black/50 z-50 flex flex-col justify-center items-center ${showUserModal ? 'visible' : 'invisible'}`}>
<div className="bg-slate-900/95 w-[95vw] max-w-[1200px] rounded-md overflow-y-scroll scrollbar-hide flex flex-col justify-start items-start p-4">
<h2 className="text-2xl my-4">
{modalUser.id == 0 ? 'Add User' : 'Edit User'}
</h2>
<div className="flex flex-col justify-start items-start w-full ">
<div className='grid grid-cols-2 gap-4 w-full'>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 font-semibold flex flex-col">
Phone*
<small className='font-light'>10 Digit phone number of user. Without +91 (Required)</small>
</label>
<input type="text" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.phone} onChange={(e) => setModalUser({ ...modalUser, phone: e.target.value })} />
</div>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">
Name
<small className='font-light'>Name of user (if any)</small>
</label>
<input type="text" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.name} onChange={(e) => setModalUser({ ...modalUser, name: e.target.value })} />
</div>
</div>
<div className='grid grid-cols-2 gap-4 w-full'>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">
Email
<small className='font-light'>Email of user (if any)</small>
</label>
<input type="text" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.email} onChange={(e) => setModalUser({ ...modalUser, email: e.target.value })} />
</div>
<div className='w-full'>
{/* New password */}
<label className={`text-sm text-white/80 mb-2 font-semibold flex flex-col ${modalUser.id == 0 ? 'font-semibold' : ''}`}>New Password{modalUser.id == 0 ? '*' : ''}
<small className='font-light'>Changing this will update the password for user.</small>
</label>
<input type="password" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.newPassword} onChange={(e) => setModalUser({ ...modalUser, newPassword: e.target.value })} />
</div>
</div>
<div className='grid grid-cols-2 gap-4 w-full'>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">Credits/Balance (₹)
<small className='font-light'>Credits/Wallet Balance of user. Changing this will update the user balance.</small>
</label>
<input type="number" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" min={0} value={modalUser.credit} onChange={(e) => setModalUser({ ...modalUser, credit: parseInt(e.target.value) })} />
</div>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">Bonus (₹)
<small className='font-light'>Bonus claimed by user. Changing this will update the user bonus.</small>
</label>
<input type="number" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" min={0} value={modalUser.bonus} onChange={(e) => setModalUser({ ...modalUser, bonus: parseInt(e.target.value) })} />
</div>
{/* <div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">Is User Verified?</label>
<select className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.is_verified ? 1 : 0} onChange={(e) => setModalUser({ ...modalUser, is_verified: parseInt(e.target.value) == 1 ? true : false })}>
<option value={0}>No</option>
<option value={1}>Yes</option>
</select>
</div> */}
</div>
<div className='grid grid-cols-2 gap-4 w-full'>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">Exposure (₹)
<small className='font-light'>How much exposure the user currently has for all his bets</small>
</label>
<input type="number" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.exposure} onChange={(e) => setModalUser({ ...modalUser, exposure: parseInt(e.target.value) })} />
</div>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">Exposure Limit (₹)
<small className='font-light'>Max Exposure user is allowed to have</small>
</label>
<input type="number" className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" min={0} value={modalUser.exposureLimit} onChange={(e) => setModalUser({ ...modalUser, exposureLimit: parseInt(e.target.value) })} />
</div>
</div>
<div className='grid grid-cols-2 gap-4 w-full'>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">
Deleted?
<small className='font-light'>Is user deleted from logging in? If yes, user won't be allowed to login or signup.</small>
</label>
<select className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.is_deleted ? 1 : 0} onChange={(e) => setModalUser({ ...modalUser, is_deleted: parseInt(e.target.value) == 1 ? true : false })}>
<option value={0}>No</option>
<option value={1}>Yes</option>
</select>
</div>
<div className='w-full'>
<label className="text-sm text-white/80 mb-2 flex flex-col">
Banned?
<small className='font-light'>Is user banned from logging in? If yes, user won't be allowed to login or signup.</small>
</label>
<select className="bg-slate-900/80 text-white/80 w-full rounded-md px-4 py-2 mb-4" value={modalUser.is_banned ? 1 : 0} onChange={(e) => setModalUser({ ...modalUser, is_banned: parseInt(e.target.value) == 1 ? true : false })}>
<option value={0}>No</option>
<option value={1}>Yes</option>
</select>
</div>
</div>
<div className="flex flex-row justify-end items-center w-full mt-4">
<button className="bg-white text-black px-4 py-2 text-base rounded-md mr-4" onClick={() => setShowUserModal(false)}>
Cancel
</button>
<button className="bg-secondary text-black px-4 py-2 text-base rounded-md" onClick={() => {
if (modalUser.id == 0) {
addUser(modalUser)
} else {
updateUser(modalUser)
}
}}>
{modalUser.id == 0 ? 'Add User' : 'Update User'}
</button>
</div>
</div>
</div>
</div>
{/* Transactions Modal */}
<div className={`fixed top-0 backdrop-blur left-0 w-full h-full bg-black/50 z-50 flex flex-col justify-center items-center ${showTransactionModal ? 'visible' : 'invisible'}`}>
<div className="bg-slate-900/95 w-[95vw] max-w-[1400px] rounded-md overflow-y-scroll scrollbar-hide flex flex-col justify-start items-start p-4">
<h2 className="text-2xl my-4">
{`Transactions for User: ${modalUser.id}`}
</h2>
<div className="flex flex-col justify-start items-start w-full ">
<table className="table-auto w-full text-left break-words overflow-scroll scrollbar-hide min-h-[500px] max-h-[600px]">
<thead className="bg-primary text-white">
<tr>
<th className="border border-white/20 px-4 py-2">ID</th>
<th className="border border-white/20 px-4 py-2">Type</th>
<th className="border border-white/20 px-4 py-2">Amount</th>
<th className="border border-white/20 px-4 py-2">Status</th>
<th className="border border-white/20 px-4 py-2">Remark</th>
<th className="border border-white/20 px-4 py-2">Date</th>
</tr>
</thead>
<tbody>
{modalUser?.transactions?.map((transaction, index) => (
<tr key={index} className="text-left">
<td className="border border-white/20 px-4 py-2">{transaction.id}</td>
<td className={`border border-white/20 px-4 py-2 font-medium ${transaction.type == "credit" ? 'text-green-500' : transaction.type == "debit" ? 'text-red-500' : 'text-white'}`}>{transaction.type}</td>
<td className="border border-white/20 px-4 py-2">{transaction.amount}</td>
<td className="border border-white/20 px-4 py-2">{transaction.status}</td>
<td className="border border-white/20 px-4 py-2">{transaction.remark}</td>
<td className="border border-white/20 px-4 py-2">{convertReadableDate(transaction.createdAt as string)}</td>
</tr>
))}
</tbody>
</table>
<div className="flex flex-row justify-end items-center w-full mt-4">
<button className="bg-white text-black px-4 py-2 text-base rounded-md mr-4" onClick={() => setShowTransactionModal(false)}>
Close
</button>
</div>
</div>
</div>
</div>
</div>
</>
)
}
|
// String Replace
@function str-replace($string, $search, $replace: "") {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
// Font Face
@mixin font-face($name, $path, $weight: null, $style: null, $exts: eot woff2 woff ttf svg) {
$src: null;
$extmods: (
eot: "?",
svg: "#" + str-replace($name, " ", "_")
);
$formats: (
otf: "opentype",
ttf: "truetype"
);
@each $ext in $exts {
$extmod: if(map-has-key($extmods, $ext), $ext + map-get($extmods, $ext), $ext);
$format: if(map-has-key($formats, $ext), map-get($formats, $ext), $ext);
$src: append($src, url(quote($path + "." + $extmod)) format(quote($format)), comma);
}
@font-face {
font-family: quote($name);
font-style: $style;
font-weight: $weight;
src: $src;
}
}
// @include font-face("latin-modern-mono", "~@/assets/Latin-Modern-Mono/latinmodernmono_10regular_macroman/lmmono10-regular-webfont", normal, normal, eot woff ttf svg);
// @include font-face("pt-sans", "~@/assets/PT-Sans/ptsans_regular_macroman/PTS55F-webfont", normal, normal, eot woff ttf svg);
// @include font-face("pt-sans", "~@/assets/PT-Sans/ptsans_bold_macroman/PTS75F-webfont", 700, normal, eot woff ttf svg);
// @include font-face("pt-sans", "~@/assets/PT-Sans/ptsans_italic_macroman/PTS56F-webfont", normal, italic, eot woff ttf svg);
|
import { MongoClient } from 'mongodb';
import * as constants from '../config/constants';
import { createUserFixture } from './collections/users';
import { Users } from './userStates';
export default async function injectInitialData() {
const connection = await MongoClient.connect(constants.URL_MONGODB);
const usersFixtures = [createUserFixture(Users.user1), createUserFixture(Users.user2), createUserFixture(Users.user3)];
await Promise.all(
usersFixtures.map((user) =>
connection.db().collection('users').updateOne({ username: user.username }, { $set: user }, { upsert: true }),
),
);
await connection
.db()
.collection('users')
.updateOne(
{ username: Users.admin.data.username },
{ $addToSet: { 'services.resume.loginTokens': { when: Users.admin.data.loginExpire, hashedToken: Users.admin.data.hashedToken } } },
);
await Promise.all(
[
{
_id: 'API_Enable_Rate_Limiter_Dev',
value: false,
},
{
_id: 'Show_Setup_Wizard',
value: 'completed',
},
{
_id: 'Country',
value: 'brazil',
},
{
_id: 'Organization_Type',
value: 'community',
},
{
_id: 'Industry',
value: 'aerospaceDefense',
},
{
_id: 'Size',
value: 0,
},
{
_id: 'Organization_Name',
value: 'any_name',
},
{
_id: 'API_Enable_Rate_Limiter_Dev',
value: false,
},
{
_id: 'SAML_Custom_Default_provider',
value: 'test-sp',
},
{
_id: 'SAML_Custom_Default_issuer',
value: 'http://localhost:3000/_saml/metadata/test-sp',
},
{
_id: 'SAML_Custom_Default_entry_point',
value: 'http://localhost:8080/simplesaml/saml2/idp/SSOService.php',
},
{
_id: 'SAML_Custom_Default_idp_slo_redirect_url',
value: 'http://localhost:8080/simplesaml/saml2/idp/SingleLogoutService.php',
},
{
_id: 'Accounts_OAuth_Google',
value: false,
},
].map((setting) =>
connection
.db()
.collection('rocketchat_settings')
.updateOne({ _id: setting._id }, { $set: { value: setting.value } }),
),
);
return { usersFixtures };
}
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 14:06:14 2023
@author: lb945465
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def process_iaq_file(file_path, environment):
# Create an empty DataFrame to store the merged data
merged_df = pd.DataFrame()
# Read each worksheet in the Excel file and merge them into a single DataFrame
excel_file = pd.ExcelFile(file_path)
for sheet_name in excel_file.sheet_names:
df = excel_file.parse(sheet_name)
# Check if the sheet contains the necessary columns
if 'DateTime' not in df.columns:
# If 'DateTime' column doesn't exist, combine 'Date' and 'Time' columns into one
if 'Date' in df.columns and 'Time' in df.columns:
df['DateTime'] = pd.to_datetime(df['Date'].astype(str) + ' ' + df['Time'].astype(str))
df.drop(['Date', 'Time'], axis=1, inplace=True)
else:
# Handle the case where neither 'DateTime' nor 'Date' and 'Time' columns exist
continue
# Set the DateTime column as the index
df.set_index('DateTime', inplace=True)
# Append the DataFrame to the merged DataFrame if it's not empty
if not df.empty:
merged_df = pd.concat([merged_df, df])
# Optionally, sort the merged DataFrame by DateTime
merged_df.sort_index(inplace=True)
# Filter the merged DataFrame to include only columns ending with "_BC"
BC_columns = merged_df.filter(like='_BC')
# Add the "Site" column to the filtered DataFrame
BC_columns['Site'] = merged_df['Site']
# Remove the "_BC" suffix from column names
BC = BC_columns.rename(columns=lambda x: x.rstrip('_BC'))
# Check if "_BrC" columns exist in the DataFrame before processing
if '_BrC' in merged_df.columns:
# Filter the merged DataFrame to include only columns ending with "_BrC"
BrC_columns = merged_df.filter(like='_BrC')
# Add the "Site" column to the filtered DataFrame
BrC_columns['Site'] = merged_df['Site']
# Remove the "_BrC" suffix from column names
BrC = BrC_columns.rename(columns=lambda x: x.rstrip('_BrC'))
else:
BrC = None
# Add the "Dataset" column to identify the environment
BC['Dataset'] = environment
if BrC is not None:
BrC['Dataset'] = environment
return BC, BrC
# Define file paths for indoor and outdoor data
indoor_file_path = r'C:\Users\LB945465\OneDrive - University at Albany - SUNY\State University of New York\Extra\Extra work\IAQ\IAQ_Indoor.xlsx'
outdoor_file_path = r'C:\Users\LB945465\OneDrive - University at Albany - SUNY\State University of New York\Extra\Extra work\IAQ\IAQ_Outdoor.xlsx' # Replace with the outdoor file path
# Process indoor and outdoor data
indoor_BC, indoor_BrC = process_iaq_file(indoor_file_path, 'Indoor')
outdoor_BC, outdoor_BrC = process_iaq_file(outdoor_file_path, 'Outdoor')
# Print the first few rows of the resulting DataFrames
print("Indoor BC:")
if indoor_BC is not None:
print(indoor_BC.head())
else:
print("No BC data for Indoor")
print("Indoor BrC:")
if indoor_BrC is not None:
print(indoor_BrC.head())
else:
print("No BrC data for Indoor")
print("Outdoor BC:")
if outdoor_BC is not None:
print(outdoor_BC.head())
else:
print("No BrC data for Outdoor")
print("Outdoor BrC:")
if outdoor_BrC is not None:
print(outdoor_BrC.head())
else:
print("No BrC data for Outdoor")
# Merge indoor and outdoor BC DataFrames
all_BC = pd.concat([indoor_BC, outdoor_BC])
#all_BrC = pd.concat([indoor_BrC, outdoor_BrC])
# Drop rows with all NaN values
all_BC.dropna(how='all', inplace=True)
# Reset the index to convert it into a regular column
all_BC.reset_index(inplace=True)
# Define a function to replace outliers with NaNs based on IQR
def replace_outliers_with_nan_iqr(column):
Q1 = column.quantile(0.25)
Q3 = column.quantile(0.75)
IQR = Q3 - Q1
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
column[(column < lower_bound) | (column > upper_bound)] = pd.NA
# Select columns for outlier processing
columns_to_process = all_BC.columns.difference(['DateTime', 'Site', 'Dataset'])
# Apply the function to selected columns one by one
for column_name in columns_to_process:
replace_outliers_with_nan_iqr(all_BC[column_name])
# Melt the DataFrame while keeping 'Site' and 'Dataset' columns
melted_BC = pd.melt(all_BC, id_vars=['DateTime', 'Site', 'Dataset'], var_name='Variable', value_name='Value')
# Replace values less than or equal to 0 with NaN in the melted_BC DataFrame
melted_BC['Value'] = melted_BC['Value'].where(melted_BC['Value'] > 0, other=float('nan'))
# Create the catplot with the desired figure size
plot = sns.catplot(
data=melted_BC, x="Variable", y="Value", hue="Dataset",
kind="violin", bw_adjust=.5, cut=0, split=True,
inner="quartiles",
height=5, # Set the figure height
aspect=2, # Set the aspect ratio to control the width
)
# Create the figure and set the figure size
plt.figure(figsize=(12, 4))
# Define the color palette for the legend and violin plots
palette = {'Indoor': 'blue', 'Outdoor': 'orange'}
# Create the violin plots and specify the hue and palette
g=sns.violinplot(data=melted_BC,
x='Variable',
y='Value',
hue='Dataset',
split=True,
inner=None,
palette=palette,
)
# Create the box plots without legend
sns.boxplot(data=melted_BC,
x='Variable',
y='Value',
hue='Dataset',
color='white',
width=0.3,
boxprops={'zorder': 2},
showfliers=False,
)
# Set the x-label and y-label
plt.xlabel("")
plt.ylabel("BC concentration (μg/m${^3}$)")
handles, labels = g.get_legend_handles_labels()
g.legend(handles[:2], labels[:2], title='Set')
plt.tight_layout()
plt.show()
# Assuming you have the indoor_BC and outdoor_BC dataframes
dataframes = [indoor_BC, outdoor_BC]
# List to store the resulting dataframes
daily_mean_dfs = []
for df in dataframes:
# Reset the index and drop 'Dataset' column
df.drop(columns=['Dataset'], inplace=True)
df.reset_index(inplace=True)
# Melt the dataframe while keeping 'DateTime' and 'Site' columns
melted_df = pd.melt(df, id_vars=['DateTime', 'Site'], var_name='Variable', value_name='Value')
melted_df.set_index('DateTime', inplace=True)
# Group the melted dataframe by 'Site' and resample to daily frequency, calculating the mean
daily_mean_df = melted_df.groupby('Variable').resample('D').mean()
# Append the resulting dataframe to the list
daily_mean_dfs.append(daily_mean_df)
# Unpack the list into separate dataframes for indoor and outdoor
daily_mean_indoor, daily_mean_outdoor = daily_mean_dfs
# Print the resulting dataframes
print("Daily Mean Indoor:")
print(daily_mean_indoor)
print("Daily Mean Outdoor:")
print(daily_mean_outdoor)
# Assuming you have daily_mean_outdoor and daily_mean_indoor dataframes
# Create an empty dictionary to store the correlation results by Site
correlation_results = {}
# Get the unique Site values
unique_sites = daily_mean_outdoor.index.get_level_values('Variable').unique()
# Loop through each unique Site
for site in unique_sites:
# Extract the data for the current Site
outdoor_data = daily_mean_outdoor.loc[daily_mean_outdoor.index.get_level_values('Variable') == site]
indoor_data = daily_mean_indoor.loc[daily_mean_indoor.index.get_level_values('Variable') == site]
# Calculate the Spearman correlation between outdoor and indoor data for the current Site
spearman_corr = outdoor_data.corrwith(indoor_data, method='spearman')
# Store the correlation results in the dictionary
correlation_results[site] = spearman_corr
# Create a DataFrame from the correlation results
correlation_df = pd.DataFrame(correlation_results)
# Print the resulting correlation DataFrame
print(correlation_df)
# Assuming you have the correlation_df DataFrame
# Create a heatmap
plt.figure(figsize=(10, 3), dpi=300) # Adjust the figure size as needed
sns.heatmap(correlation_df, annot=True, cmap='coolwarm', linewidths=0.5, vmin=0, vmax=1)
# Set the plot title and labels
plt.title('Spearman Correlation Heatmap', fontweight="bold")
plt.xlabel('')
plt.ylabel('r${_s}$', fontweight="bold")
# Show the heatmap
plt.show()
|
/**
* jQuery EasyUI 1.4
*
* Copyright (c) 2009-2014 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL license: http://www.gnu.org/licenses/gpl.txt
* To use it on other terms please contact us at info@jeasyui.com
*
*/
/**
* calendar - jQuery EasyUI
*
*/
(function($){
function setSize(target, param){
var opts = $.data(target, 'calendar').options;
var t = $(target);
if (param){
$.extend(opts, {
width: param.width,
height: param.height
});
}
t._size(opts, t.parent());
t.find('.calendar-body')._outerHeight(t.height() - t.find('.calendar-header')._outerHeight());
if (t.find('.calendar-menu').is(':visible')){
showSelectMenus(target);
}
}
function init(target){
$(target).addClass('calendar').html(
'<div class="calendar-header">' +
'<div class="calendar-prevmonth"></div>' +
'<div class="calendar-nextmonth"></div>' +
'<div class="calendar-prevyear"></div>' +
'<div class="calendar-nextyear"></div>' +
'<div class="calendar-title">' +
'<span>Aprial 2010</span>' +
'</div>' +
'</div>' +
'<div class="calendar-body">' +
'<div class="calendar-menu">' +
'<div class="calendar-menu-year-inner">' +
'<span class="calendar-menu-prev"></span>' +
'<span><input class="calendar-menu-year" type="text"></input></span>' +
'<span class="calendar-menu-next"></span>' +
'</div>' +
'<div class="calendar-menu-month-inner">' +
'</div>' +
'</div>' +
'</div>'
);
$(target).find('.calendar-title span').hover(
function(){$(this).addClass('calendar-menu-hover');},
function(){$(this).removeClass('calendar-menu-hover');}
).click(function(){
var menu = $(target).find('.calendar-menu');
if (menu.is(':visible')){
menu.hide();
} else {
showSelectMenus(target);
}
});
$('.calendar-prevmonth,.calendar-nextmonth,.calendar-prevyear,.calendar-nextyear', target).hover(
function(){$(this).addClass('calendar-nav-hover');},
function(){$(this).removeClass('calendar-nav-hover');}
);
$(target).find('.calendar-nextmonth').click(function(){
showMonth(target, 1);
});
$(target).find('.calendar-prevmonth').click(function(){
showMonth(target, -1);
});
$(target).find('.calendar-nextyear').click(function(){
showYear(target, 1);
});
$(target).find('.calendar-prevyear').click(function(){
showYear(target, -1);
});
$(target).bind('_resize', function(e,force){
if ($(this).hasClass('easyui-fluid') || force){
setSize(target);
}
return false;
});
}
/**
* show the calendar corresponding to the current month.
*/
function showMonth(target, delta){
var opts = $.data(target, 'calendar').options;
opts.month += delta;
if (opts.month > 12){
opts.year++;
opts.month = 1;
} else if (opts.month < 1){
opts.year--;
opts.month = 12;
}
show(target);
var menu = $(target).find('.calendar-menu-month-inner');
menu.find('td.calendar-selected').removeClass('calendar-selected');
menu.find('td:eq(' + (opts.month-1) + ')').addClass('calendar-selected');
}
/**
* show the calendar corresponding to the current year.
*/
function showYear(target, delta){
var opts = $.data(target, 'calendar').options;
opts.year += delta;
show(target);
var menu = $(target).find('.calendar-menu-year');
menu.val(opts.year);
}
/**
* show the select menu that can change year or month, if the menu is not be created then create it.
*/
function showSelectMenus(target){
var opts = $.data(target, 'calendar').options;
$(target).find('.calendar-menu').show();
if ($(target).find('.calendar-menu-month-inner').is(':empty')){
$(target).find('.calendar-menu-month-inner').empty();
var t = $('<table class="calendar-mtable"></table>').appendTo($(target).find('.calendar-menu-month-inner'));
var idx = 0;
for(var i=0; i<3; i++){
var tr = $('<tr></tr>').appendTo(t);
for(var j=0; j<4; j++){
$('<td class="calendar-menu-month"></td>').html(opts.months[idx++]).attr('abbr',idx).appendTo(tr);
}
}
$(target).find('.calendar-menu-prev,.calendar-menu-next').hover(
function(){$(this).addClass('calendar-menu-hover');},
function(){$(this).removeClass('calendar-menu-hover');}
);
$(target).find('.calendar-menu-next').click(function(){
var y = $(target).find('.calendar-menu-year');
if (!isNaN(y.val())){
y.val(parseInt(y.val()) + 1);
setDate();
}
});
$(target).find('.calendar-menu-prev').click(function(){
var y = $(target).find('.calendar-menu-year');
if (!isNaN(y.val())){
y.val(parseInt(y.val() - 1));
setDate();
}
});
$(target).find('.calendar-menu-year').keypress(function(e){
if (e.keyCode == 13){
setDate(true);
}
});
$(target).find('.calendar-menu-month').hover(
function(){$(this).addClass('calendar-menu-hover');},
function(){$(this).removeClass('calendar-menu-hover');}
).click(function(){
var menu = $(target).find('.calendar-menu');
menu.find('.calendar-selected').removeClass('calendar-selected');
$(this).addClass('calendar-selected');
setDate(true);
});
}
function setDate(hideMenu){
var menu = $(target).find('.calendar-menu');
var year = menu.find('.calendar-menu-year').val();
var month = menu.find('.calendar-selected').attr('abbr');
if (!isNaN(year)){
opts.year = parseInt(year);
opts.month = parseInt(month);
show(target);
}
if (hideMenu){menu.hide()}
}
var body = $(target).find('.calendar-body');
var sele = $(target).find('.calendar-menu');
var seleYear = sele.find('.calendar-menu-year-inner');
var seleMonth = sele.find('.calendar-menu-month-inner');
seleYear.find('input').val(opts.year).focus();
seleMonth.find('td.calendar-selected').removeClass('calendar-selected');
seleMonth.find('td:eq('+(opts.month-1)+')').addClass('calendar-selected');
sele._outerWidth(body._outerWidth());
sele._outerHeight(body._outerHeight());
seleMonth._outerHeight(sele.height() - seleYear._outerHeight());
}
/**
* get weeks data.
*/
function getWeeks(target, year, month){
var opts = $.data(target, 'calendar').options;
var dates = [];
var lastDay = new Date(year, month, 0).getDate();
for(var i=1; i<=lastDay; i++) dates.push([year,month,i]);
// group date by week
var weeks = [], week = [];
// var memoDay = 0;
var memoDay = -1;
while(dates.length > 0){
var date = dates.shift();
week.push(date);
var day = new Date(date[0],date[1]-1,date[2]).getDay();
if (memoDay == day){
day = 0;
} else if (day == (opts.firstDay==0 ? 7 : opts.firstDay) - 1){
weeks.push(week);
week = [];
}
memoDay = day;
}
if (week.length){
weeks.push(week);
}
var firstWeek = weeks[0];
if (firstWeek.length < 7){
while(firstWeek.length < 7){
var firstDate = firstWeek[0];
var date = new Date(firstDate[0],firstDate[1]-1,firstDate[2]-1)
firstWeek.unshift([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
} else {
var firstDate = firstWeek[0];
var week = [];
for(var i=1; i<=7; i++){
var date = new Date(firstDate[0], firstDate[1]-1, firstDate[2]-i);
week.unshift([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
weeks.unshift(week);
}
var lastWeek = weeks[weeks.length-1];
while(lastWeek.length < 7){
var lastDate = lastWeek[lastWeek.length-1];
var date = new Date(lastDate[0], lastDate[1]-1, lastDate[2]+1);
lastWeek.push([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
if (weeks.length < 6){
var lastDate = lastWeek[lastWeek.length-1];
var week = [];
for(var i=1; i<=7; i++){
var date = new Date(lastDate[0], lastDate[1]-1, lastDate[2]+i);
week.push([date.getFullYear(), date.getMonth()+1, date.getDate()]);
}
weeks.push(week);
}
return weeks;
}
/**
* show the calendar day.
*/
function show(target){
var opts = $.data(target, 'calendar').options;
if (opts.current && !opts.validator.call(target, opts.current)){
opts.current = null;
}
var now = new Date();
var todayInfo = now.getFullYear()+','+(now.getMonth()+1)+','+now.getDate();
var currentInfo = opts.current ? (opts.current.getFullYear()+','+(opts.current.getMonth()+1)+','+opts.current.getDate()) : '';
// calulate the saturday and sunday index
var saIndex = 6 - opts.firstDay;
var suIndex = saIndex + 1;
if (saIndex >= 7) saIndex -= 7;
if (suIndex >= 7) suIndex -= 7;
$(target).find('.calendar-title span').html(opts.months[opts.month-1] + ' ' + opts.year);
var body = $(target).find('div.calendar-body');
body.children('table').remove();
var data = ['<table class="calendar-dtable" cellspacing="0" cellpadding="0" border="0">'];
data.push('<thead><tr>');
for(var i=opts.firstDay; i<opts.weeks.length; i++){
data.push('<th>'+opts.weeks[i]+'</th>');
}
for(var i=0; i<opts.firstDay; i++){
data.push('<th>'+opts.weeks[i]+'</th>');
}
data.push('</tr></thead>');
data.push('<tbody>');
var weeks = getWeeks(target, opts.year, opts.month);
for(var i=0; i<weeks.length; i++){
var week = weeks[i];
var cls = '';
if (i == 0){cls = 'calendar-first';}
else if (i == weeks.length - 1){cls = 'calendar-last';}
data.push('<tr class="' + cls + '">');
for(var j=0; j<week.length; j++){
var day = week[j];
var s = day[0]+','+day[1]+','+day[2];
var dvalue = new Date(day[0], parseInt(day[1])-1, day[2]);
var d = opts.formatter.call(target, dvalue);
var css = opts.styler.call(target, dvalue);
var classValue = '';
var styleValue = '';
if (typeof css == 'string'){
styleValue = css;
} else if (css){
classValue = css['class'] || '';
styleValue = css['style'] || '';
}
var cls = 'calendar-day';
if (!(opts.year == day[0] && opts.month == day[1])){
cls += ' calendar-other-month';
}
if (s == todayInfo){cls += ' calendar-today';}
if (s == currentInfo){cls += ' calendar-selected';}
if (j == saIndex){cls += ' calendar-saturday';}
else if (j == suIndex){cls += ' calendar-sunday';}
if (j == 0){cls += ' calendar-first';}
else if (j == week.length-1){cls += ' calendar-last';}
cls += ' ' + classValue;
if (!opts.validator.call(target, dvalue)){
cls += ' calendar-disabled';
}
data.push('<td class="' + cls + '" abbr="' + s + '" style="' + styleValue + '">' + d + '</td>');
}
data.push('</tr>');
}
data.push('</tbody>');
data.push('</table>');
body.append(data.join(''));
var t = body.children('table.calendar-dtable').prependTo(body);
t.find('td.calendar-day:not(.calendar-disabled)').hover(
function(){$(this).addClass('calendar-hover');},
function(){$(this).removeClass('calendar-hover');}
).click(function(){
var oldValue = opts.current;
t.find('.calendar-selected').removeClass('calendar-selected');
$(this).addClass('calendar-selected');
var parts = $(this).attr('abbr').split(',');
opts.current = new Date(parts[0], parseInt(parts[1])-1, parts[2]);
opts.onSelect.call(target, opts.current);
if (!oldValue || oldValue.getTime() != opts.current.getTime()){
opts.onChange.call(target, opts.current, oldValue);
}
});
}
$.fn.calendar = function(options, param){
if (typeof options == 'string'){
return $.fn.calendar.methods[options](this, param);
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'calendar');
if (state){
$.extend(state.options, options);
} else {
state = $.data(this, 'calendar', {
options:$.extend({}, $.fn.calendar.defaults, $.fn.calendar.parseOptions(this), options)
});
init(this);
}
if (state.options.border == false){
$(this).addClass('calendar-noborder');
}
setSize(this);
show(this);
$(this).find('div.calendar-menu').hide(); // hide the calendar menu
});
};
$.fn.calendar.methods = {
options: function(jq){
return $.data(jq[0], 'calendar').options;
},
resize: function(jq, param){
return jq.each(function(){
setSize(this, param);
});
},
moveTo: function(jq, date){
return jq.each(function(){
var opts = $(this).calendar('options');
if (opts.validator.call(this, date)){
var oldValue = opts.current;
$(this).calendar({
year: date.getFullYear(),
month: date.getMonth()+1,
current: date
});
if (!oldValue || oldValue.getTime() != date.getTime()){
opts.onChange.call(this, opts.current, oldValue);
}
}
});
}
};
$.fn.calendar.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.parser.parseOptions(target, [
{firstDay:'number',fit:'boolean',border:'boolean'}
]));
};
$.fn.calendar.defaults = {
width:180,
height:180,
fit:false,
border:true,
firstDay:0,
weeks:['S','M','T','W','T','F','S'],
months:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
year:new Date().getFullYear(),
month:new Date().getMonth()+1,
current:(function(){
var d = new Date();
return new Date(d.getFullYear(), d.getMonth(), d.getDate());
})(),
formatter:function(date){return date.getDate()},
styler:function(date){return ''},
validator:function(date){return true},
onSelect: function(date){},
onChange: function(newDate, oldDate){}
};
})(jQuery);
|
import { UsersComponent } from './components/users/users.component';
import { PostByUserComponent } from './pages/postsByUser/postByUser.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { UserComponent } from './components/users/user/user.component';
import { FeedComponent } from './pages/feed/feed.component';
import { PostById } from './pages/postById/post.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'user', component: UserComponent },
{ path: 'feed/:userId', component: FeedComponent },
{ path: 'posts/userId/:id', component: PostByUserComponent },
{ path: 'posts/:postId', component: PostById },
{ path: 'users/:id', component: UserComponent },
{ path: 'users', component: UsersComponent },
{ path: '**', redirectTo: 'home', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
function New-AzDevOpsBuildFolder {
<#
.SYNOPSIS
Creates new Azure DevOps Folder.
.DESCRIPTION
Creates new Folder in Azure Devops Pipeline.
.EXAMPLE
New-AzDevOpsBuildFolder -Name 'ProjectName' -Path 'FolderPath'
.EXAMPLE
New-AzDevOpsBuildFolder -Name 'ProjectName' -Path 'FolderPath' -Description 'Description'
.NOTES
PAT Permission Scope: vso.build_execute
Description: Grants the ability to access build artifacts, including build results, definitions, and requests,
and the ability to queue a build, update build properties, and the ability to receive notifications about build events via service hooks.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Project,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Path,
[string]$Description
)
end {
try {
$script:body = @{
path = $Path
description = $Description
} | ConvertTo-Json
$script:folderPath = $Path
$script:projectName = $Project
$script:function = $MyInvocation.MyCommand.Name
[AzureDevOpsBuildFolder]::Create()
}
catch {
throw $_
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="cav" width="600" height="200">
当前浏览器不支持canvas,请下载最新浏览器
<a href="https://www.google.cn/chrome/">下载Chrome</a>
</canvas>
<div>
<p>在输入框中输入miterlimit值,点击查看效果</p>
miterlimit<input type="text" id="ipt" /> <button id="btn">重绘</button>
</div>
<script>
// 1.找到canvas对象
var cav = document.getElementById("cav");
// 2.获取画布的 2D 渲染上下文
var ctx2D = cav.getContext("2d");
if (!ctx2D.getContext)
cav.innerText = "当前浏览器不支持canvas,请下载最新浏览器";
document.getElementById('btn').addEventListener('click', () => {
// 清空画布
ctx2D.clearRect(0, 0, 150, 150);
var iptValue = document.getElementById("ipt").value;
if (iptValue.match(/\d+(\.\d+)?/)) {
ctx2D.miterLimit = parseFloat(iptValue || 10); // 设置miterLimit值
renderLine()
} else
console.log('Value must be a positive number');
})
function renderLine() {
// 绘制参考线
ctx2D.strokeStyle = "#09f";
ctx2D.lineWidth = 2;
ctx2D.strokeRect(5, 50, 160, 50);
ctx2D.strokeStyle='rgb(0, 145, 255)'
ctx2D.lineWidth = 5
var path2D = new Path2D()
path2D.moveTo(0, 100);
for (let i = 0; i < 24; i++) {
var dy = i % 2 == 0 ? 25 : -25; // 如果整除则lineto点位,向下+25,向上-25
path2D.lineTo(Math.pow(i, 1.5), 75 + dy);
}
ctx2D.stroke(path2D)
}
renderLine()
</script>
</body>
</html>
|
<script setup>
import { onMounted } from 'vue';
import useSkills from '../../composables/skill';
const { skill, getSkill, updateSkill, errors } = useSkills();
const props = defineProps({
id: {
required: true,
type: String
}
})
onMounted(() => getSkill(props.id));
</script>
<template>
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
<div class="card">
<div class="card-header">
<h4>Edit Skill</h4>
</div>
<div class="card-body">
<form @submit.prevent="updateSkill($route.params.id)" method="POST">
<div class="mb-3">
<label for="name">Name</label>
<input type="text" v-model="skill.name" :class="{'is-invalid':errors.name}" id="name"
class="form-control" placeholder="Name">
<div v-if="errors.name" class="text-danger">
{{ errors.name[0] }}
</div>
</div>
<div class="mb-3">
<label for="slug">Slug</label>
<input type="text" v-model="skill.slug" :class="{'is-invalid':errors.slug}" id="slug"
class="form-control" placeholder="Slug">
<div v-if="errors.slug" class="text-danger">
{{ errors.slug[0] }}
</div>
</div>
<button type="submit" class="btn btn-sm btn-info text-light">Update</button>
</form>
</div>
</div>
</div>
</div>
</div>
</template>
|
import { IConfigService } from "./config.service.interface";
import { config, parse, DotenvConfigOutput, DotenvParseOutput } from 'dotenv';
import { injectable, inject } from "inversify";
import { TYPES } from "../types";
import { ILogger } from "../logger/logger.interface";
@injectable()
export class ConfigService implements IConfigService {
private config: DotenvParseOutput;
constructor(
@inject(TYPES.ILogger) private logger: ILogger
) {
const result: DotenvConfigOutput = config();
if (result.error) {
this.logger.error(`Cannot read .env file: ${result.error.message}`);
} else {
this.logger.log('[ConfigService] config from .env uploaded successful');
this.config = result.parsed as DotenvParseOutput;
}
}
get<T extends string | number>(key: string): T {
return this.config[key] as T;
};
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=x, initial-scale=1.0" />
<title>Omnifood Hero Section</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Rubik:wght@400;500;600;700&display=swap"
rel="stylesheet"
/>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-family: "Rubik", sans-serif;
color: #444;
}
.container {
margin: 0 auto;
width: 1200px;
}
.header-container {
width: 1200px;
position: absolute;
bottom: 50%;
right: 50%;
transform: translate(50%, 50%);
}
.header-container-inner {
width: 50%;
color: white;
}
header {
color: white;
height: 100vh;
background-image: linear-gradient(
rgba(34, 34, 34, 0.6),
rgba(34, 34, 34, 0.6)
),
url(hero.jpg);
background-size: cover;
}
nav {
padding-top: 32px;
font-size: 20px;
font-weight: 700;
display: flex;
justify-content: space-between;
/* background-color: green; */
/* background-image: linear-gradient(to right, red, blue); */
}
h1 {
font-size: 52px;
margin-bottom: 32px;
line-height: 1.05;
/* color: inherit; */
}
/* h1 + p {
color: inherit;
} */
p {
font-size: 20px;
line-height: 1.6;
margin-bottom: 48px;
}
.btn {
font-size: 20px;
font-weight: 600;
text-decoration: none;
background-color: #e67e22;
color: white;
border-radius: 8px;
display: inline-block;
padding: 16px 32px;
}
h2 {
font-size: 44px;
margin-bottom: 48px;
}
section {
padding: 96px 0;
background-color: #f7f7f7;
}
</style>
</head>
<body>
<header>
<nav class="container">
<div>LOGO</div>
<div>NAVIGATION</div>
</nav>
<div class="header-container">
<div class="header-container-inner">
<h1>A healthy meal delivered to your door, every single day</h1>
<p>
The smart 365-days-per-year food subscription that will make you eat
healthy again. Tailored to your personal tastes and nutritional
needs.
</p>
<a href="#" class="btn">Start Eating Well</a>
</div>
</div>
</header>
<section class="container">
<div>
<h2>Some random heading</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa, ad
consequuntur aperiam delectus iste cumque molestias repellendus?
Temporibus itaque beatae, quis reiciendis, quo dolores molestias
voluptatum porro molestiae dignissimos vero! Lorem ipsum dolor sit
amet consectetur adipisicing elit. Cumque unde voluptas enim. Natus
neque pariatur fugit quia reiciendis. Ut natus voluptatibus sapiente
autem reprehenderit voluptas aliquam! Aperiam quaerat soluta qui?
</p>
</div>
</section>
</body>
</html>
|
/**
******************************************************************************
* @file USART/USART_TwoBoards/DataExchangeInterrupt/stm32f0xx_it.c
* @author MCD Application Team
* @version V1.6.0
* @date 13-October-2021
* @brief Main Interrupt Service Routines.
* This file provides template for all exceptions handler and
* peripherals interrupt service routine.
******************************************************************************
* @attention
*
* Copyright (c) 2014 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_it.h"
/** @addtogroup STM32F0xx_StdPeriph_Examples
* @{
*/
/** @addtogroup USART_DataExchangeInterrupt
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
extern uint8_t TxBuffer[];
extern uint8_t RxBuffer[];
extern uint8_t CmdBuffer[];
extern uint8_t AckBuffer[];
extern __IO uint8_t RxIndex;
extern __IO uint8_t TxIndex;
extern __IO uint8_t UsartTransactionType;
extern __IO uint8_t UsartMode;
__IO uint8_t Counter = 0x00;
extern __IO uint32_t TimeOut;
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/******************************************************************************/
/* Cortex-M0 Processor Exceptions Handlers */
/******************************************************************************/
/**
* @brief This function handles NMI exception.
* @param None
* @retval None
*/
void NMI_Handler(void)
{
}
/**
* @brief This function handles Hard Fault exception.
* @param None
* @retval None
*/
void HardFault_Handler(void)
{
/* Go to infinite loop when Hard Fault exception occurs */
while (1)
{
}
}
/**
* @brief This function handles SVCall exception.
* @param None
* @retval None
*/
void SVC_Handler(void)
{
}
/**
* @brief This function handles PendSVC exception.
* @param None
* @retval None
*/
void PendSV_Handler(void)
{
}
/**
* @brief This function handles SysTick Handler.
* @param None
* @retval None
*/
void SysTick_Handler(void)
{
/* Decrement the timeout value */
if (TimeOut != 0x0)
{
TimeOut--;
}
if (Counter < 10)
{
Counter++;
}
else
{
Counter = 0x00;
STM_EVAL_LEDToggle(LED1);
}
}
/******************************************************************************/
/* STM32F0xx Peripherals Interrupt Handlers */
/******************************************************************************/
/**
* @brief This function handles USART interrupt request.
* @param None
* @retval None
*/
void USARTx_IRQHandler(void)
{
/* USART in mode Transmitter -------------------------------------------------*/
if (USART_GetITStatus(USARTx, USART_IT_TXE) == SET)
{ /* When Joystick Pressed send the command then send the data */
if (UsartMode == USART_MODE_TRANSMITTER)
{ /* Send the command */
if (UsartTransactionType == USART_TRANSACTIONTYPE_CMD)
{
USART_SendData(USARTx, CmdBuffer[TxIndex++]);
if (TxIndex == 0x02)
{
/* Disable the USARTx transmit data register empty interrupt */
USART_ITConfig(USARTx, USART_IT_TXE, DISABLE);
}
}
/* Send the data */
else
{
USART_SendData(USARTx, TxBuffer[TxIndex++]);
if (TxIndex == GetVar_NbrOfData())
{
/* Disable the USARTx transmit data register empty interrupt */
USART_ITConfig(USARTx, USART_IT_TXE, DISABLE);
}
}
}
/*If Data Received send the ACK*/
else
{
USART_SendData(USARTx, AckBuffer[TxIndex++]);
if (TxIndex == 0x02)
{
/* Disable the USARTx transmit data register empty interrupt */
USART_ITConfig(USARTx, USART_IT_TXE, DISABLE);
}
}
}
/* USART in mode Receiver --------------------------------------------------*/
if (USART_GetITStatus(USARTx, USART_IT_RXNE) == SET)
{
if (UsartMode == USART_MODE_TRANSMITTER)
{
AckBuffer[RxIndex++] = USART_ReceiveData(USARTx);
}
else
{
/* Receive the command */
if (UsartTransactionType == USART_TRANSACTIONTYPE_CMD)
{
CmdBuffer[RxIndex++] = USART_ReceiveData(USARTx);
}
/* Receive the USART data */
else
{
RxBuffer[RxIndex++] = USART_ReceiveData(USARTx);
}
}
}
}
/******************************************************************************/
/* STM32F0xx Peripherals Interrupt Handlers */
/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */
/* available peripheral interrupt handler's name please refer to the startup */
/* file (startup_stm32f0xx.s). */
/******************************************************************************/
/**
* @brief This function handles PPP interrupt request.
* @param None
* @retval None
*/
/*void PPP_IRQHandler(void)
{
}*/
/**
* @}
*/
/**
* @}
*/
|
-- The Airline Database is loaded in Postgres SQL. The Schema Of this Database is Bookings.
Questions:
/*1. Represent the “book_date” column in “yyyy-mmm-dd” format using Bookings table
Expected output: book_ref, book_date (in “yyyy-mmm-dd” format) , total amount */
Select book_ref,
to_char(book_date :: date, 'yyyy-mon-dd') as book_date ,
total_amount
from bookings.Bookings;
/*2. Get the following columns in the exact same sequence.
Expected columns in the output: ticket_no, boarding_no, seat_number, passenger_id, passenger_name.*/
SELECT
tfl.ticket_no,
bpas.boarding_no,
bpas.seat_no,
tfl.passenger_id,
tfl.passenger_name
FROM bookings.tickets tfl
LEFT JOIN bookings.boarding_passes Bpas
on tfl.ticket_no = bpas.ticket_no
/*Write a query to find the seat number which is least allocated among all the seats?*/
SELECT
seat_no
FROM bookings.boarding_passes
GROUP BY seat_no
HAVING count(boarding_no) =1
/* In the database, identify the month wise highest paying passenger name and passenger id
Expected output: Month_name(“mmm-yy” format), passenger_id, passenger_name and total amount*/
SELECT
Month_data,
passenger_id,
passenger_name,
total_amount
FROM
(
SELECT
Total_amount, passenger_id,
passenger_name,
to_char(book_date,'Mon-YY')as Month_data,
DENSE_RANK() OVER (PARTITION BY to_char(book_date,'Mon-YY') ORDER BY total_amount DESC) AS Rank_1
FROM bookings.bookings
Join bookings.Tickets
ON bookings.book_ref = tickets.book_ref)
AS MAX_PAYING_CUSTOMER
WHERE Rank_1 = 1
ORDER BY 1 ASC, 4 DESC
/*In the database, identify the month wise least paying passenger name and passenger id?
Expected output: Month_name(“mmm-yy” format), passenger_id, passenger_name and total amount*/
SELECT
Month_data,
passenger_id,
passenger_name,
total_amount FROM
(
SELECT
Total_amount, passenger_id,
passenger_name,
to_char(book_date,'MON-YY')as Month_data,
DENSE_RANK() OVER (PARTITION BY to_char(book_date,'MON-YY') ORDER BY total_amount asc) AS Rank_1
FROM Bookings.bookings
Join Bookings.Tickets
ON bookings.book_ref = tickets.book_ref) MIN_PAYING_CUSTOMER
WHERE Rank_1 = 1
ORDER BY 1 ASC, 4 DESC;
/*Identify the travel details of non stop journeys or return journeys (having more than 1 flight).
Expected Output: Passenger_id, passenger_name, ticket_number and flight count*/
SELECT
TFL.ticket_no,
Passenger_id,
passenger_name,
count(FL.flight_id) as Flight_journeys
FROM Bookings.FLIGHTS FL
JOIN Bookings.TICKET_FLIGHTS TFL
ON FL.FLIGHT_ID = TFL.FLIGHT_ID
JOIN Bookings.TICKETS TK
on TK.ticket_no = TFL.ticket_no
group by 1,2,3
having count(FL.flight_id) > 1
ORDER BY 4 DESC;
/*How many tickets are there without boarding passes?
Expected Output: just one number is required*/
SELECT count (tkt)
AS Number_of_passengers_without_boarding_ticket
FROM
(
SELECT tickets.ticket_no AS tkt,
boarding_passes.boarding_no
FROM bookings.Tickets
LEFT JOIN bookings.boarding_passes
ON Tickets.ticket_no = boarding_passes.ticket_no
WHERE boarding_passes.boarding_no IS NULL) AS TICKET_DETAILS
/*Identify details of the longest flight (using flights table)?
Expected Output: Flight number, departure airport, arrival airport, aircraft code and durations*/
With Time_details as
(SELECT
Flight_no,
departure_airport,
arrival_airport,
aircraft_code,
cast(scheduled_arrival as Time) - cast(scheduled_departure as Time) as duration
FROM FLIGHTS
),
ranking as
(
Select
flight_no,
departure_airport,
arrival_airport,
aircraft_code,
duration,
dense_rank() over(order by duration desc) as rank_1
from Time_details)
SELECT
flight_no,
departure_airport,
arrival_airport,
aircraft_code,
concat(duration,' ','Hour') as Duration_of_flight
FROM ranking
WHERE rank_1 = 1
/*Identify details of all the morning flights (morning means between 6AM to 11 AM, using flights table)?
Expected output: flight_id, flight_number, scheduled_departure, scheduled_arrival and timings*/
Answer:
SELECT
flight_id,
flight_no,
scheduled_arrival,
scheduled_departure,
CAST(scheduled_departure as time) AS time_of_departure
FROM FLIGHTS
GROUP BY 1,2,3,4
HAVING CAST(scheduled_departure as time) BETWEEN '05:00:00' AND '11:00:00'
ORDER BY 5
/*Identify the earliest morning flight available from every airport.
Expected output: flight_id, flight_number, scheduled_departure, scheduled_arrival, departure airport and timings*/
SELECT
flight_id,
flight_no,
scheduled_arrival,
scheduled_departure,
time_of_departure
FROM
(
SELECT
flight_id,
flight_no,
scheduled_arrival,
scheduled_departure,
CAST(scheduled_departure as time) AS time_of_departure,
DENSE_RANK () OVER(PARTITION BY departure_airport order by CAST(scheduled_departure as time) asc ) AS RANK_1
FROM FLIGHTS
JOIN AIRPORTS
ON FLIGHTS.departure_airport = AIRPORTS.AIRPORT_CODE
GROUP BY 1,2,3,4
HAVING CAST(scheduled_departure as time) BETWEEN '05:00:00' AND '11:00:00'
ORDER BY 5 ) AS EARLIEST_FLIGHT
WHERE RANK_1 = 1
|
#' add_columns
#'
#' Function adds new columns to the existing magpie object.
#'
#' @param x MAgPIE object which should be extended.
#' @param dim The (sub)dimension to be filled either identified via
#' name or dimension code (see \code{\link{dimCode}} for more information)
#' @param addnm The new elements that should be added to the (sub)dimension
#' @param fill fill value of length 1 for the newly added columns (NA by default)
#' @return The extended MAgPIE object
#' @author Jan Philipp Dietrich, Benjamin Bodirsky
#' @seealso \code{\link{add_dimension}},\code{\link{dimCode}}
#' @examples
#' a <- maxample("animal")
#' a2 <- add_columns(a, addnm = c("horse", "magpie"), dim = "species", fill = 42)
#' getItems(a2, dim = 3)
#' getItems(a2, dim = 3, split = TRUE)
#' head(a2[, , "magpie"])
#' @export
add_columns <- function(x, addnm = "new", dim = 3.1, fill = NA) { #nolint
if (length(dim) != 1) stop("dim must be a single (sub)dimension!")
if (length(fill) != 1) stop("fill value must be of length 1")
if (!dimExists(dim, x)) stop("dim \"", dim, "\" does not exist")
x <- clean_magpie(x, what = "sets")
if (length(addnm) == 0) return(x)
dim <- dimCode(dim, x)
add <- add_dimension(dimSums(x, dim = dim), dim = dim, nm = addnm)
add[, , ] <- fill
getSets(add) <- getSets(x)
return(mbind(x, add))
}
|
import { DOCUMENT } from '@angular/common';
import { Component, Inject, Renderer2 } from '@angular/core';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { CategoryData, CategoryReq } from 'src/app/commons/dto/category';
import { CategoryService } from 'src/app/services/category.service';
import { ImageService } from 'src/app/services/image.service';
@Component({
selector: 'app-category-add',
templateUrl: './category-add.component.html',
styleUrls: ['./category-add.component.css']
})
export class CategoryAddComponent {
categoryListData!: CategoryData[];
categoryReq: CategoryReq = {
categoryParentId: -1,
name: "",
imageId: ""
};
file: File | null = null;
categoryId!: number;
categoryData: CategoryData = new CategoryData();
module: string = 'CREATE';
constructor(
private _renderer2: Renderer2,
@Inject(DOCUMENT) private _document: Document,
private router: Router,
private categoryService: CategoryService,
public toastrService: ToastrService,
private imageService: ImageService
) { }
public ngOnInit() {
this.getAllCategory();
const currentUrl = this.router.url;
if (currentUrl != '/category/new') {
this.module = "UPDATE";
const urlSplit = currentUrl.split("/");
this.categoryId = Number(urlSplit[urlSplit.length - 1]);
this.getCategoryById();
}
this.generateJquery()
}
getAllCategory() {
this.categoryService.getAllCategory().subscribe(data => {
this.categoryListData = data.data;
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
}
getCategoryById() {
this.categoryService.getCategoriesById(this.categoryId).subscribe(data => {
this.categoryData = data.data;
this.categoryReq.name = this.categoryData.name;
this.categoryReq.categoryParentId = this.categoryData.categoryParent.id;
if (this.categoryData.image != null)
this.categoryReq.imageId = this.categoryData.image.id;
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
}
handleFileInput(eventTarget: any) {
this.file = eventTarget.files.item(0);
}
onCreate() {
if (this.file == null || this.categoryReq.name.trim() == "")
this.toastrService.error("Vui lòng nhập đầy đủ thông tin")
else {
this.imageService.uploadFile([this.file]).subscribe(data => {
this.categoryReq.imageId = data.data[0];
this.categoryService.createNewCategory(this.categoryReq).subscribe(data => {
this.toastrService.success("Thêm mới thành công")
this.router.navigate(['/category'])
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
}
console.log(this.file);
console.log(this.categoryReq)
}
onUpdate() {
if (this.categoryReq.name.trim() == "")
this.toastrService.error("Vui lòng nhập đầy đủ thông tin")
else if (this.file != null) {
this.imageService.uploadFile([this.file]).subscribe(data => {
this.categoryReq.imageId = data.data[0];
this.categoryService.updateCategory(this.categoryId, this.categoryReq).subscribe(data => {
this.toastrService.success("Cập nhật thành công")
this.router.navigate(['/category'])
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
} else {
this.categoryService.updateCategory(this.categoryId, this.categoryReq).subscribe(data => {
this.toastrService.success("Cập nhật thành công")
this.router.navigate(['/category'])
}, error => {
this.toastrService.error('Có lỗi xảy ra vui lòng thử lại sau')
})
}
console.log(this.file);
console.log(this.categoryReq)
}
generateJquery() {
let script = this._renderer2.createElement('script');
script.text = `
$(function () {
bsCustomFileInput.init();
//Initialize Select2 Elements
$('.select2').select2()
//Initialize Select2 Elements
$('.select2bs4').select2({
theme: 'bootstrap4'
})
});
`;
this._renderer2.appendChild(this._document.body, script);
}
}
|
//1. Обробка відправлення форми form.login-form повинна відбуватися відповідно до події submit.
//2. Під час відправлення форми сторінка не повинна перезавантажуватися.
//3. Якщо у формі є незаповнені поля, виводь alert з попередженням про те, що всі поля повинні бути заповнені.
//4. Якщо користувач заповнив усі поля і відправив форму, збери значення полів в об'єкт, де ім'я поля буде ім'ям властивості, а значення поля - значенням властивості. Для доступу до елементів форми використовуй властивість elements.
//5. Виведи об'єкт із введеними даними в консоль і очисти значення полів форми методом reset.
const loginForm = document.querySelector(".login-form");
loginForm.addEventListener("submit", onFormSubmit);
function onFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const email = form.elements.email.value;
const password = form.elements.password.value;
if (email === "" || password === "") {
return alert("Не введено ел. пошту або пароль");
}
// логуємо об'єкт в консоль
console.log(addUserData({ email, password }));
form.reset();
}
//функція створює об'єкт, який містить введену пошту та пароль
function addUserData({ email, password }) {
const userData = {
email,
password,
};
return userData;
}
|
package com.example.eindopdrachtyarnicornback.Service;
import com.example.eindopdrachtyarnicornback.DTO.ProductDto;
import com.example.eindopdrachtyarnicornback.Exceptions.IdNotFoundException;
import com.example.eindopdrachtyarnicornback.Models.FileDocument;
import com.example.eindopdrachtyarnicornback.Models.Product;
import com.example.eindopdrachtyarnicornback.Repository.DocFileRepository;
import com.example.eindopdrachtyarnicornback.Repository.ProductRepository;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class ProductService {
private final ProductRepository productRepository;
private final DocFileRepository docFileRepository;
public ProductService(ProductRepository productRepository, DocFileRepository docFileRepository) {
this.productRepository = productRepository;
this.docFileRepository = docFileRepository;
}
public List<ProductDto> getAllProducts() {
List<Product> products = productRepository.findAll();
List<ProductDto> productDtos = new ArrayList<>();
for (Product p : products) {
ProductDto pdto = new ProductDto();
productToProductDTO(p, pdto);
productDtos.add(pdto);
}
return productDtos;
}
@Transactional
public List<ProductDto> getProductsByCategory(String category) {
List<Product> products = productRepository.findByCategory(category);
List<ProductDto> productDtos = new ArrayList<>();
for (Product p : products) {
ProductDto pdto = new ProductDto();
productToProductDTO(p, pdto);
productDtos.add(pdto);
}
return productDtos;
}
private void productToProductDTO(Product p, ProductDto pdto) {
pdto.setName(p.getName());
pdto.setBrand(p.getBrand());
pdto.setColor(p.getColor());
pdto.setLength(p.getLength());
pdto.setBlend(p.getBlend());
pdto.setNeedleSize(p.getNeedleSize());
pdto.setGauge(p.getGauge());
pdto.setDescription(p.getDescription());
pdto.setCategory(p.getCategory());
pdto.setId(p.getId());
if (p.getFileDocument() != null) {
pdto.setDocFile(p.getFileDocument().getDocFile());
pdto.setFileUrl(p.getFileDocument().getFileName());
}
}
private void productDTOToProduct(ProductDto productDTO, Product product) {
product.setName(productDTO.getName());
product.setBrand(productDTO.getBrand());
product.setColor(productDTO.getColor());
product.setLength(productDTO.getLength());
product.setGauge(productDTO.getGauge());
product.setBlend(productDTO.getBlend());
product.setNeedleSize(productDTO.getNeedleSize());
product.setDescription(productDTO.getDescription());
product.setCategory(productDTO.getCategory());
// // Create and set FileDocument
// FileDocument fileDocument = new FileDocument();
// fileDocument.setFileName(productDTO.getFileUrl());
//// fileDocument.setDocFile(productDTO.getFileUrl().getBytes());
// fileDocument.setId(productDTO.getId());
//
//
// product.setFileDocument(fileDocument);
}
public ProductDto getProduct(Long id) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
Product p = product.get();
ProductDto pdto = new ProductDto();
productToProductDTO(p, pdto);
// Set the file URL in the ProductDto (assuming you have a method to get the file URL)
pdto.setFileUrl(getFileUrlForProduct(p.getId()));
return (pdto);
} else {
throw new IdNotFoundException("Product not found with id: " + id);
}
}
public String getFileUrlForProduct(Long productId) {
Product product = productRepository.findById(productId)
.orElseThrow(() -> new IdNotFoundException("Product not found with id: " + productId));
return getFileUrlFromDocument(product.getFileDocument());
}
private String getFileUrlFromDocument(FileDocument fileDocument) {
// Implement logic to get the file URL from FileDocument
// For example, you can concatenate the base URL with the file name
if (fileDocument == null) return null;
return "baseURL/" + fileDocument.getFileName();
}
public ProductDto createProduct(ProductDto productDTO) {
Product product = new Product();
productDTOToProduct(productDTO, product);
Product savedProduct = productRepository.save(product);
ProductDto savedProductDto = new ProductDto();
productToProductDTO(savedProduct, savedProductDto);
// Set the file URL in the created ProductDto
savedProductDto.setFileUrl(getFileUrlForProduct(savedProduct.getId()));
return savedProductDto;
}
public String deleteProduct(@RequestBody Long id) {
if (productRepository.existsById(id)) {
productRepository.deleteById(id);
} else {
throw new IdNotFoundException("Product not found with id: " + id);
}
return "Product deleted";
}
public ProductDto updateProduct(Long id, ProductDto productDTO) {
Optional<Product> product = productRepository.findById(id);
if (product.isPresent()) {
Product p = product.get();
p.setId(id);
productDTOToProduct(productDTO, p);
Product savedProduct = productRepository.save(p);
ProductDto savedProductDto = new ProductDto();
productToProductDTO(savedProduct, savedProductDto);
// Set the file URL in the updated ProductDto
savedProductDto.setFileUrl(getFileUrlForProduct(savedProduct.getId()));
return savedProductDto;
} else {
throw new IdNotFoundException("Product not found with id: " + id);
}
}
}
|
/*
* Copyright (C) 2013 Invenzzia Group <http://www.invenzzia.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.invenzzia.opentrans.lightweight.ui.tabs.world.modes;
import com.google.common.base.Preconditions;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.invenzzia.helium.exception.CommandExecutionException;
import org.invenzzia.opentrans.lightweight.annotations.InModelThread;
import org.invenzzia.opentrans.lightweight.model.navigator.VehicleNavigatorModel;
import org.invenzzia.opentrans.lightweight.ui.IDialogBuilder;
import org.invenzzia.opentrans.lightweight.ui.navigator.NavigatorController;
import org.invenzzia.opentrans.lightweight.ui.tabs.world.AbstractEditMode;
import org.invenzzia.opentrans.lightweight.ui.tabs.world.IEditModeAPI;
import org.invenzzia.opentrans.lightweight.ui.tabs.world.PopupBuilder;
import org.invenzzia.opentrans.lightweight.ui.tabs.world.popups.CenterAction;
import org.invenzzia.opentrans.lightweight.ui.tabs.world.popups.RemoveVehicleAction;
import org.invenzzia.opentrans.lightweight.ui.tabs.world.popups.ReorientVehicleAction;
import org.invenzzia.opentrans.visitons.Project;
import org.invenzzia.opentrans.visitons.data.Vehicle;
import org.invenzzia.opentrans.visitons.data.Vehicle.VehicleRecord;
import org.invenzzia.opentrans.visitons.editing.network.MoveVehicleCmd;
import org.invenzzia.opentrans.visitons.editing.network.PlaceVehicleCmd;
import org.invenzzia.opentrans.visitons.editing.operations.RemoveVehicleCmd;
import org.invenzzia.opentrans.visitons.events.VehicleRemovedEvent;
import org.invenzzia.opentrans.visitons.network.NetworkConst;
import org.invenzzia.opentrans.visitons.network.Track;
import org.invenzzia.opentrans.visitons.network.TrackRecord;
import org.invenzzia.opentrans.visitons.network.World;
import org.invenzzia.opentrans.visitons.render.scene.HoveredItemSnapshot;
import org.invenzzia.opentrans.visitons.render.scene.SelectedTrackObjectSnapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This mode allows placing vehicles on the tracks.
*
* @author Tomasz Jędrzejewski
*/
public class VehicleMode extends AbstractEditMode {
private final Logger logger = LoggerFactory.getLogger(StopMode.class);
private static final String DEFAULT_STATUS_TEXT = "Select a vehicle from the navigator and click on a track to place it. Click on an existing vehicle to select it.";
private static final String PLATFORM_SELECTED_STATUS_TEXT = "Click on a track to move the selected vehicle. Right-click anywhere to cancel the selection.";
private static final String SELECT_FROM_NAVIGATOR = "Please select a vehicle from the navigator first!";
@Inject
private NavigatorController navigatorController;
@Inject
private IDialogBuilder dialogBuilder;
@Inject
private EventBus eventBus;
@Inject
private Provider<CenterAction> centerAction;
@Inject
private ReorientVehicleAction reorientVehicleAction;
@Inject
private RemoveVehicleAction removeVehicleAction;
/**
* The API for edit modes.
*/
private IEditModeAPI api;
/**
* For the purpose of vehicle moving, we must remember a selected vehicle.
*/
private VehicleRecord selectedVehicle;
@Override
protected void handleCommandExecutionError(CommandExecutionException exception) {
logger.error("Exception occurred while saving the network unit of work.", exception);
}
@Override
public void modeEnabled(IEditModeAPI api) {
logger.info("VehicleMode enabled.");
this.api = api;
this.navigatorController.setModel(new VehicleNavigatorModel());
this.api.setStatusMessage(DEFAULT_STATUS_TEXT);
this.eventBus.register(this);
this.api.setPopup(PopupBuilder.create()
.action(this.centerAction)
.sep()
.action(this.reorientVehicleAction)
.action(this.removeVehicleAction)
);
}
@Override
public void modeDisabled() {
this.navigatorController.setModel(null);
this.eventBus.unregister(this);
logger.info("VehicleMode disabled.");
}
@InModelThread(asynchronous = false)
public TrackRecord getTrackRecord(World world, long id) {
Track track = world.findTrack(id);
return new TrackRecord(track);
}
@InModelThread(asynchronous = false)
public VehicleRecord getVehicleRecord(Project project, long id) {
Vehicle vehicle = project.getVehicleManager().findById(id);
VehicleRecord record = new VehicleRecord();
record.importData(vehicle, project);
return record;
}
@Override
public void leftActionPerformed(double worldX, double worldY, boolean altDown, boolean ctrlDown) {
HoveredItemSnapshot snapshot = sceneManager.getResource(HoveredItemSnapshot.class, HoveredItemSnapshot.class);
if(null != snapshot) {
switch(snapshot.getType()) {
case HoveredItemSnapshot.TYPE_TRACK:
if(null == this.selectedVehicle) {
this.placeVehicle(snapshot);
} else {
this.moveVehicle(snapshot);
}
break;
case HoveredItemSnapshot.TYPE_VEHICLE:
this.selectVehicle(snapshot);
break;
}
}
}
@Override
public void rightActionPerformed(double worldX, double worldY, boolean altDown, boolean ctrlDown) {
if(null == this.selectedVehicle) {
HoveredItemSnapshot snapshot = sceneManager.getResource(HoveredItemSnapshot.class, HoveredItemSnapshot.class);
if(null != snapshot && snapshot.getType() == HoveredItemSnapshot.TYPE_PLATFORM) {
VehicleRecord record = this.getVehicleRecord(this.projectHolder.getCurrentProject(), snapshot.getId());
this.reorientVehicleAction.setVehicleRecord(record);
this.removeVehicleAction.setVehicleRecord(record);
this.api.showPopup();
}
} else {
this.sceneManager.updateResource(SelectedTrackObjectSnapshot.class, null);
this.selectedVehicle = null;
this.api.setStatusMessage(DEFAULT_STATUS_TEXT);
}
}
@Override
public void deletePressed(double worldX, double worldY) {
if(null != this.selectedVehicle) {
try {
this.history.execute(new RemoveVehicleCmd(this.selectedVehicle));
} catch(CommandExecutionException exception) {
this.dialogBuilder.showError("Error while removing a vehicle", exception);
}
}
}
private void placeVehicle(HoveredItemSnapshot snapshot) {
TrackRecord tr = this.getTrackRecord(this.getWorld(), snapshot.getId());
Object object = this.navigatorController.getSelectedObject();
if(null != object) {
Preconditions.checkState(object instanceof VehicleRecord, "The navigator displays wrong object types: "+object.getClass().getCanonicalName()+"; VehicleRecord expected.");
VehicleRecord vr = (VehicleRecord) object;
try {
this.history.execute(new PlaceVehicleCmd(tr, snapshot.getPosition(), vr));
} catch(CommandExecutionException exception) {
this.dialogBuilder.showError("Error while adding a platform", exception);
}
} else {
this.api.setStatusMessage(SELECT_FROM_NAVIGATOR);
}
}
private void moveVehicle(HoveredItemSnapshot snapshot) {
TrackRecord trackRecord = this.getTrackRecord(this.projectHolder.getCurrentProject().getWorld(), snapshot.getId());
try {
this.history.execute(new MoveVehicleCmd(this.selectedVehicle, snapshot.getPosition(), trackRecord));
} catch(CommandExecutionException exception) {
this.dialogBuilder.showError("Error while moving a vehicle", exception);
}
}
private void selectVehicle(HoveredItemSnapshot snapshot) {
this.selectedVehicle = this.getVehicleRecord(this.projectHolder.getCurrentProject(), snapshot.getId());
this.sceneManager.updateResource(SelectedTrackObjectSnapshot.class,
new SelectedTrackObjectSnapshot(NetworkConst.TRACK_OBJECT_VEHICLE, this.selectedVehicle.getId())
);
this.api.setStatusMessage(PLATFORM_SELECTED_STATUS_TEXT);
}
/**
* Listen for such an event to see if we do not have to remove the platform selection.
*
* @param event
*/
@Subscribe
public void notifyPlatformRemoved(VehicleRemovedEvent event) {
if(null != this.selectedVehicle && event.matches(selectedVehicle)) {
this.selectedVehicle = null;
this.sceneManager.updateResource(SelectedTrackObjectSnapshot.class, null);
this.api.setStatusMessage(DEFAULT_STATUS_TEXT);
}
}
}
|
import { Component, ErrorInfo } from "react";
import { ErrorBoundaryProps, ErrorBoundaryState } from "./types";
class ErrorBoundary extends Component<ErrorBoundaryProps> {
state: ErrorBoundaryState;
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error) {
// Update state so the next render will show the fallback UI.
return { hasError: true, error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
// Example "componentStack":
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
console.error(error, info.componentStack);
this.setState({ error, errorInfo: info });
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return this.props.renderFallback(this.state.error!);
}
return this.props.children;
}
}
export default ErrorBoundary;
|
package com.kp.PatientHub.controller;
import com.kp.PatientHub.service.PatientService;
import com.kp.PatientHub.view.PatientRequest;
import com.kp.PatientHub.view.PatientResponse;
import com.kp.PatientHub.view.SuccessResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api")
public class PatientController {
@Autowired
private PatientService patientService;
@PostMapping(value = "/patient")
public ResponseEntity<PatientResponse> savePatient(@RequestBody PatientRequest patientRequest){
PatientResponse patientResponse=patientService.savePatient(patientRequest);
return ResponseEntity.ok(patientResponse);
}
@PutMapping(value = "/patient/{id}")
public ResponseEntity<PatientResponse> updatePatient(@PathVariable Long id,@RequestBody PatientRequest patientRequest){
PatientResponse patientResponse=patientService.updatePatient(id,patientRequest);
return ResponseEntity.ok(patientResponse);
}
@GetMapping(value = "/patient/{id}")
public ResponseEntity<PatientResponse> findPatientById(@PathVariable Long id){
PatientResponse patientResponse=patientService.findById(id);
return ResponseEntity.ok(patientResponse);
}
@GetMapping(value = "/patients")
public List<PatientResponse> findAllPatients(){
return patientService.findAllPatients();
}
@DeleteMapping(value = "/patient/{id}")
public SuccessResponse deletePatient(@PathVariable Long id){
return patientService.deletePatientById(id);
}
}
|
import React, { useState, useEffect } from "react";
import Button from "react-bootstrap/Button";
import StudentModal from "../Common/StudentModal";
import Table from "react-bootstrap/Table";
import { useSelector, useDispatch } from "react-redux";
import {
fetchStudents,
getAllNationality,
fetchStudentNationality,
} from "../../Redux/Action/studentAction";
const Registrar = () => {
const [showModal, setShowModal] = React.useState(false);
const [SelectedStudentDetails, setSelectedStudentDetails] = React.useState(
{}
);
const [isRegistrarWantToEdit, setIsRegistrarWantToEdit] = useState(false);
const [approvedStudent, setApprovedStudent] = useState([]);
const dispatch = useDispatch();
const studentsData = useSelector((state) => state.student.students);
const nationalityData = useSelector((state) => state.student.nationalityData);
useEffect(() => {
dispatch(fetchStudents());
dispatch(getAllNationality());
}, [fetchStudents, getAllNationality, showModal]);
useEffect(() => {
studentsData.forEach((student) => {
dispatch(fetchStudentNationality(student.ID));
});
}, [dispatch, studentsData]);
const handleModal = () => {
setSelectedStudentDetails("");
setShowModal(true);
};
const clickStudentDataHandler = (studentDetails) => {
setSelectedStudentDetails(studentDetails);
setShowModal(true);
};
const handleEditStudentDetails = () => {
setSelectedStudentDetails([]);
setIsRegistrarWantToEdit(true);
};
const clickApprovedStudentListHandler = (studentDetails) => {
setSelectedStudentDetails(studentDetails);
setShowModal(true);
};
const hideModal = () => {
setShowModal(false);
setIsRegistrarWantToEdit(false);
};
return (
<div className="mx-5 tableContainer">
<Button variant="primary" className="px-5 my-4" onClick={handleModal}>
Add Student
</Button>
<StudentModal
SelectedStudentDetails={SelectedStudentDetails}
setSelectedStudentDetails={setSelectedStudentDetails}
showModal={showModal}
isRegistrarWantToEdit={isRegistrarWantToEdit}
onHide={hideModal}
approvedStudent={approvedStudent}
setApprovedStudent={setApprovedStudent}
/>
{!!studentsData?.length && (
<>
<h2>Pending Students</h2>
<Table
responsive="sm"
className="table-responsive table-hover table-bordered mb-0"
>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Nationality</th>
<th>Date of Birth</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
{studentsData?.map((student, i) => {
return (
<tr onClick={() => clickStudentDataHandler(student)}>
<td>{student?.firstName}</td>
<td>{student?.lastName}</td>
<td>{nationalityData[student.ID]?.nationality?.Title}</td>
<td>{student?.dateOfBirth}</td>
<td>
<Button
variant="danger"
onClick={handleEditStudentDetails}
>
Edit
</Button>
</td>
</tr>
);
})}
</tbody>
</Table>
</>
)}
{/* approved student list */}
{!!approvedStudent?.length && (
<>
<h2 className="mt-5">Approved Students</h2>
<Table
responsive="sm"
className="table-responsive table-hover table-bordered mb-0"
>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Nationality</th>
<th>Date of Birth</th>
</tr>
</thead>
<tbody>
{approvedStudent?.map((student, i) => {
return (
<tr onClick={() => clickApprovedStudentListHandler(student)}>
<td>{student?.firstName}</td>
<td>{student?.lastName}</td>
<td>{nationalityData[student.ID]?.nationality?.Title}</td>
<td>{student?.dateOfBirth}</td>
</tr>
);
})}
</tbody>
</Table>
</>
)}
</div>
);
};
export default Registrar;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Meteora</title>
<link rel="shortcut icon" href="./assets/favicon.png" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-md bg-black navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#"><h1 class="m-0"><img class="d-block" src="assets/logo-meteora.png" alt="Logo da loja Meteora"></h1></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Lojas</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Novidades</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Promoção</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2 rounded-0" type="search" placeholder="Digite um produto" aria-label="Search">
<button class="btn btn-outline-light rounded-0" type="submit">Buscar</button>
</form>
</div>
</div>
</nav>
<div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-indicators">
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active"
aria-current="true" aria-label="Slide 1"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1"
aria-label="Slide 2"></button>
<button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2"
aria-label="Slide 3"></button>
</div>
<div class="carousel-inner">
<div class="carousel-item active ">
<img class="img-fluid d-md-none " src="./assets/Mobile/banner1-mobile.png" alt="banner1">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/banner1-tablet.png" alt="banner1">
<img class="img-fluid d-none d-xl-block" style="width: 100%;" src="./assets/Desktop/banner1-desktop.png" alt="banner1">
<div class="carousel-caption d-none d-md-block d-xl-none">
<h5>First slide label</h5>
<p>Some representative placeholder content for the first slide.</p>
</div>
</div>
<div class="carousel-item">
<img class="img-fluid d-md-none " src="./assets/Mobile/banner2-mobile.png" alt="banner2">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/banner2-tablet.png" alt="banner2">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/banner2-desktop.png" alt="banner2">
<div class="carousel-caption d-none d-md-block">
<h5>Second slide label</h5>
<p>Some representative placeholder content for the second slide.</p>
</div>
</div>
<div class="carousel-item">
<img class="img-fluid d-md-none " src="./assets/Mobile/banner3-mobile.png" alt="banner3">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/banner3-tablet.png" alt="banner3">
<img class="img-fluid d-none d-xxl-block" src="./assets/Desktop/banner3-desktop.png" alt="banner3">
<div class="carousel-caption d-none d-md-block">
<h5>Third slide label</h5>
<p>Some representative placeholder content for the third slide.</p>
</div>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions"
data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions"
data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<h2 class="text-center my-3 my-xl-5">Busque por categoria:</h2>
<div class="container row mx-auto g-4">
<div class="col-6 col-md-4 col-xxl-2">
<div class="card rounded-0 border-0">
<img class="img-fluid d-md-none "src="./assets/Mobile/categorias/categoria-camiseta.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/categorias/categoria-camiseta.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/categorias/categoria-camiseta.png" alt="">
<div class="card-body bg-black">
<p class="text-center text-light">Camisetas</p>
</div>
</div>
</div>
<div class="col-6 col-md-4 col-xxl-2">
<div class="card">
<img class="img-fluid d-md-none " src="./assets/Mobile/categorias/categoria-bolsas.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/categorias/categoria-bolsas.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/categorias/categoria-bolsa.png" alt="">
<div class="card-body bg-black">
<p class="text-center text-light">Bolsas</p>
</div>
</div>
</div>
<div class="col-6 col-md-4 col-xxl-2">
<div class="card">
<img class="img-fluid d-md-none " src="./assets/Mobile/categorias/categoria-calcados.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/categorias/categoria-calcados.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/categorias/categoria-calcados.png" alt="">
<div class="card-body bg-black">
<p class="text-center text-light">Calçados</p>
</div>
</div>
</div>
<div class="col-6 col-md-4 col-xxl-2">
<div class="card">
<img class="img-fluid d-md-none " src="./assets/Mobile/categorias/categoria-calcas.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/categorias/categoria-calcas.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/categorias/categoria-calcas.png" alt="">
<div class="card-body bg-black">
<p class="text-center text-light">Calças</p>
</div>
</div>
</div>
<div class="col-6 col-md-4 col-xxl-2">
<div class="card">
<img class="img-fluid d-md-none " src="./assets/Mobile/categorias/categoria-casacos.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/categorias/categoria-casacos.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/categorias/categoria-casacos.png" alt="">
<div class="card-body bg-black">
<p class="text-center text-light">Casacos</p>
</div>
</div>
</div>
<div class="col-6 col-md-4 col-xxl-2">
<div class="card">
<img class="img-fluid d-md-none" src="./assets/Mobile/categorias/categoria-oculos.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/categorias/categoria-oculos.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/categorias/categoria-oculos.png" alt="">
<div class="card-body bg-black">
<p class="text-center text-light">Óculos</p>
</div>
</div>
</div>
</div>
<h2 class="container text-center my-3 my-xl-5">Produtos que estão bombando!</h2>
<div class="container row mx-auto g-4">
<div class="col-12 col-md-6 col-xl-4">
<div class="card">
<img class="img-fluid d-md-none " src="./assets/Mobile/produtos/camiseta.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/produtos/camiseta.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/produtos/camiseta.png" alt="">
<div class="card-body">
<h5 class="card-title">Camiseta conforto</h5>
<p class="card-text">
Multicores e tamanhos. Tecido de algodão 100%, fresquinho para o verão. Modelagem unissex.
</p>
<p>R$ 70,00</p>
<a href="#" class="btn btn-primary btn-purple border-0 rounded-0">Ver mais</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="card">
<img class="img-fluid d-md-none" src="./assets/Mobile/produtos/calca.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/produtos/calca.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/produtos/calca.png" alt="">
<div class="card-body">
<h5 class="card-title">Calça Alfaiataria</h5>
<p class="card-text">
Modelo Wide Leg alfaiataria em linho. Uma peça pra vida toda!
</p>
<p>R$ 30,00</p>
<a href="#" class="btn btn-primary btn-purple border-0 rounded-0">Ver mais</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="card">
<img class="img-fluid d-md-none" src="./assets/Mobile/produtos/tenis.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/produtos/tenis.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/produtos/tenis.png" alt="">
<div class="card-body">
<h5 class="card-title">Tênis Chunky</h5>
<p class="card-text">
Snicker casual com solado mais alto e modelagem robusta. Modelo unissex.
</p>
<p>R$ 30,00</p>
<a href="#" class="btn btn-primary btn-purple border-0 rounded-0">Ver mais</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="card">
<img class="img-fluid d-md-none" src="./assets/Mobile/produtos/jaqueta-jeans.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/produtos/jaqueta-jeans.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/produtos/jaqueta-jeans.png" alt="">
<div class="card-body">
<h5 class="card-title">Jaqueta Jeans</h5>
<p class="card-text">
Modelo unissex oversized com gola de camurça. Atemporal e autêntica!
</p>
<p>R$ 30,00</p>
<a href="#" class="btn btn-primary btn-purple border-0 rounded-0">Ver mais</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="card">
<img class="img-fluid d-md-none" src="./assets/Mobile/produtos/oculos.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/produtos/oculos.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/produtos/oculos.png" alt="">
<div class="card-body">
<h5 class="card-title">Óculos Redondo</h5>
<p class="card-text">
Armação metálica em grafite com lentes arredondadas. Sem erro!
</p>
<p>R$ 30,00</p>
<a href="#" class="btn btn-primary btn-purple border-0 rounded-0">Ver mais</a>
</div>
</div>
</div>
<div class="col-12 col-md-6 col-xl-4">
<div class="card">
<img class="img-fluid d-md-none" src="./assets/Mobile/produtos/bolsa.png" alt="">
<img class="img-fluid d-none d-md-block d-xl-none" src="./assets/Tablet/produtos/bolsa.png" alt="">
<img class="img-fluid d-none d-xl-block" src="./assets/Desktop/produtos/bolsa.png" alt="">
<div class="card-body">
<h5 class="card-title">Bolsa coringa</h5>
<p class="card-text">
Bolsa camel em couro sintético de alta duração. Ideal para acompanhar você por uma vida!
</p>
<p>R$ 30,00</p>
<a href="#" class="btn btn-primary btn-purple border-0 rounded-0">Ver mais</a>
</div>
</div>
</div>
</div>
<section class="pb-4 bg-black text-light my-3">
<h2 class="text-center">Conheça todas nossas facilidades</h2>
<div class="d-flex flex-column flex-lg-row justify-content-center align-items-center gap-3 ps-3 pe-3">
<div class="divs-facilidades d-flex">
<div>
<i class="bi bi-x-diamond fs-1 text-yellow"></i>
</div>
<div>
<div class="ms-3 mb-1 text-yellow">PAGUE PELO PIX</div>
<div class="texto-menor ms-3">Ganhe 5% OFF em
pagamentos via PIX</div>
</div>
</div>
<div class="divs-facilidades d-flex">
<div><i class="bi bi-arrow-repeat fs-1 text-yellow"></i></div>
<div>
<div class="ms-3 mb-1 text-yellow">TROCA GRÁTIS</div>
<div class="texto-menor ms-3">Fique livre para trocar em até 30 dias.</div>
</div>
</div>
<div class="divs-facilidades d-flex">
<div><i class="bi bi-flower1 fs-1 text-yellow"></i></div>
<div>
<div class="ms-3 mb-1 text-yellow">SUSTENTABILIDADE</div>
<div class="texto-menor ms-3">Moda responsável, que respeita o meio ambiente.</div>
</div>
</div>
</div>
</section>
<form class="border border-secondary container text-center my-3 my-xl-5 p-3 text-center">
<h5>Quer receber nossas novidades, promoções exclusivas e 10% OFF na primeira compra? Cadastre-se!</h5>
<div class="input-group my-3">
<input type="email" placeholder="Digite seu e-mail" aria-label="Digite seu e-mail"
aria-describedby="button-addon2" class="form-control border-secondary rounded-0"/>
<button type="button" id="button-addon2" class="btn btn-light border-secondary rounded-0">Enviar</button>
</div>
</form>
<footer class="text-center bg-black text-light">
<p class="py-3">2023 <i class="bi bi-c-circle"></i> Desenvolvido por Alura</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
</body>
</html>
|
import React from 'react';
import { useMyVariable } from '../context/MyVariableContext';
import styles from '../styles/typea.module.css';
type TagsProps = {
tags: { topicsCovered: string, references: string, emotions: string, other: string },
setTags: React.Dispatch<React.SetStateAction<{ topicsCovered: string, references: string, emotions: string, other: string }>>
}
const Tags: React.FC<TagsProps> = ({ tags, setTags }) => {
const { myVariable } = useMyVariable();
// Set the initial state using myVariable.summary.tags
const initialState = myVariable.summary && myVariable.summary.tags ? myVariable.summary.tags : {
topicsCovered: "",
references: "",
emotions: "",
other: ""
};
const [localTags, setLocalTags] = React.useState(initialState);
React.useEffect(() => {
setTags(localTags);
}, [localTags, setTags]);
return (
<div>
<h3>Tags</h3>
<input
className={styles['form-input']}
type="text"
placeholder="Topics Covered"
value={localTags.topicsCovered}
onChange={(e) => setLocalTags({ ...localTags, topicsCovered: e.target.value })}
/>
<input
className={styles['form-input']}
type="text"
placeholder="References"
value={localTags.references}
onChange={(e) => setLocalTags({ ...localTags, references: e.target.value })}
/>
<input
className={styles['form-input']}
type="text"
placeholder="Emotions"
value={localTags.emotions}
onChange={(e) => setLocalTags({ ...localTags, emotions: e.target.value })}
/>
<input
className={styles['form-input']}
type="text"
placeholder="Other / General"
value={localTags.other}
onChange={(e) => setLocalTags({ ...localTags, other: e.target.value })}
/>
</div>
);
};
export default Tags;
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Database\Factories\PostFactory;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'body',
'author_name',
];
protected static function newFactory(): PostFactory
{
return new PostFactory();
}
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable');
}
}
|
<script>
"use strict"
let SOCKET = null;
function argv() {
let result = {};
for (var arg of window.location.hash.substring(1).split("&")) {
let pos = arg.indexOf("=");
if (pos >= 0) {
result[arg.substring(0, pos)] = decodeURIComponent(arg.substring(pos + 1));
}
}
return result;
}
var MAX_CONSOLE_LINES = 10000;
const convertArrayToObject = (array, key) => {
const initialValue = {};
return array.reduce((obj, item) => {
return {
...obj,
[item[key]]: item,
};
}, initialValue);
};
var AppMain = {
name: 'app-main',
data() {
let self = this;
let console = {
lines: [],
get ready() {
return self.conn.ready;
},
submit(text) {
self.consoleInput(text);
},
};
let consoleTopic = {
title: "Console",
is: "panel-console",
groupid: "Console",
props: {
console: console,
},
icon: {
url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAjklEQVR4nO3VPQqEMBCG4fcSLnok2VsnhaBWa2Gv3mNsYiNkCncSRPPBNJPiIUN+oORt+QIbIMa1Aq0GrwnQoxYNlsQVzXth60iBbz1qB4zAJzfch970By5X4Ar4hf4MNLlgwk6nsDbwdLg6jbrOBQ+Rw+WVp9FbwF3kOmmws4AtIgW+zX/sE6JOg0uelx3XxAOblnvqngAAAABJRU5ErkJggg==",
style: {
filter: "invert(1.0)",
opacity: "0.8",
}
}
};
return {
// Connection information
conn: {
address: "ws://localhost:30145/",
error: null,
paused: false,
ready: false,
},
// WebSocket instance, null if disconnected
socket: null,
// Current topic being shown
currentTopic: consoleTopic,
// Page content
pages: {},
// Console
console: console,
consoleTopic: consoleTopic,
// Settings UI
settings: {
cvars: {
sendPropValue(cvar, value = undefined) {
if (value === undefined) {
value = self.settings.cvars[cvar];
}
else {
self.settings.cvars[cvar] = value;
}
self.sendCmd("@" + cvar + " " + value);
},
fetchSettings() {
self.sendCmd("@settings!");
},
},
ui: {
icons: {},
tabs: [],
},
},
};
},
computed: {
sidebarTopics() {
return [
this.consoleTopic,
...this.settings.ui.tabs.map(tab => ({
title: tab.title,
is: "panel-settings",
groupid: "Settings",
props: {
cvars: this.settings.cvars,
tab: tab,
},
icon: this.settings.ui.icons[tab.title],
})),
...Object.keys(this.pages).sort().map(page => ({
title: page,
is: "panel-xss",
groupid: "XSS",
props: {
page: this.pages[page],
console: this.console,
},
icon: null,
})),
];
}
},
methods: {
connect() {
this.conn.error = null;
this.conn.paused = false;
this.conn.ready = false;
if (this.socket) {
this.disconnect(null);
}
// Move the window location to reflect the connection address
window.location.hash = "address=" + encodeURIComponent(this.conn.address);
let sock = new WebSocket(this.conn.address);
this.socket = window.SOCKET = sock;
sock.onopen = e => {
this.conn.ready = true;
this.clear();
};
sock.onmessage = e => {
try {
if (e.data.startsWith("{")) {
let data = JSON.parse(e.data);
switch (data.target) {
case 'console/log':
this.consoleLog("" + data.message);
break;
case 'debug/write':
this.writePage(data.message.scope, data.message.content);
break;
case 'settings/cvars':
for (let line of data.message.split("\n")) {
let [key, value] = line.split("=", 2);
this.settings.cvars[key] = value;
}
break;
case 'settings/ui':
this.settings.ui = JSON.parse(data.message);
break;
default:
console.log(data.target, data.message);
break;
}
}
else {
let [line, text] = a.data.split("\n", 2);
this.writePage(line, text);
}
}
catch (ex) {
console.error(ex);
}
};
sock.onclose = e => {
this.disconnect(null);
}
sock.onerror = ex => {
this.conn.error = "Can't establish a connection to the server.";
console.error(ex);
this.disconnect(ex);
};
},
disconnect() {
if (this.socket) {
this.socket.close();
this.socket = window.SOCKET = null;
}
this.conn.ready = false;
this.settings.ui.tabs = [];
},
writePage(scope, content) {
if (!this.conn.paused) {
if (!this.pages[scope]) {
this.pages[scope] = {};
}
this.pages[scope].html = "" + content;
}
},
// Clears the pages and console
clear() {
this.pages = {};
this.console.lines = [];
},
changeCurrentTopic(topic) {
this.currentTopic = topic;
},
consoleInput(text) {
if (this.socket) {
this.console.lines.push("> " + text);
this.socket.send(text);
}
else {
this.console.lines.push("Please connect to the host first.");
}
},
consoleClear() {
this.console.lines = [];
},
consoleLog(line) {
this.console.lines.push(line);
if (this.console.lines.length > (MAX_CONSOLE_LINES + 100)) {
this.console.lines = this.console.lines.slice(this.console.lines.length - MAX_CONSOLE_LINES)
}
},
sendCmd(cmd) {
if (this.socket) {
this.socket.send(cmd);
}
},
},
mounted() {
let args = argv();
if ('address' in args) {
this.conn.address = args.address;
this.connect();
}
},
template: '#app-main',
};
</script>
<template id="app-main">
<div class="app-main">
<div class="h">
<div class="logo">Aurascope</div>
<div>
<input type="text" v-model="conn.address" @keydown.enter="connect()" :readonly="socket != null" :disabled="socket != null">
<widget-button v-if="socket == null" @click="connect()" icon="icon-power" label="Connect"></widget-button>
<widget-button v-if="socket != null" @click="disconnect()" icon="icon-power" label="Disconnect"></widget-button>
</div>
<div>
<widget-button v-if="conn.paused" @click="conn.paused = false;" icon="icon-play" label="Play"></widget-button>
<widget-button v-if="!conn.paused" @click="conn.paused = true;" icon="icon-pause" label="Pause"></widget-button>
<widget-button @click="clear()" icon="icon-clear" label="Clear"></widget-button>
</div>
</div>
<div class="m">
<app-sidebar :topics="sidebarTopics" @select-topic="changeCurrentTopic"></app-sidebar>
<keep-alive>
<component v-if="currentTopic != null" :is="currentTopic.is" :key="currentTopic.title" v-bind="currentTopic.props"></component>
<panel-console v-else :console="console"></panel-console>
</keep-alive>
</div>
</div>
</template>
<style>
html, body, #app, .app-main, .app-main {
font-family: 'Roboto', 'Segoe UI', 'Verdana', sans-serif;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
.app-main {
display: grid;
grid-template: 42px calc(100% - 42px) / auto;
}
.app-main > .h {
color: rgb(196, 196, 196);
background-color: rgb(60, 60, 60);
padding: 2px 0;
display: grid;
grid-template: auto / 200px auto 160px;
}
.app-main > .h > .logo {
line-height: 38px;
user-select: none;
text-transform: uppercase;
font-weight: lighter;
padding-left: 10px;
letter-spacing: 5px;
}
.app-main > .h button {
margin: 4px 2px;
padding: 0 10px;
}
.app-main > .h input {
width: 400px;
margin: 4px 2px;
}
.app-main > .h > div {
display: flex;
}
.app-main > .m {
color: rgb(204, 204, 204);
background-color: rgb(30, 30, 30);
display: grid;
grid-template: 100% / 200px auto;
}
</style>
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.2 <0.9.0;
contract MultiSig {
address[] public owners;
uint256 public numConfirmationsRequired;
struct Transaction {
address to;
uint256 value;
bool executed;
}
mapping(uint256 => mapping(address => bool)) isConfirmed;
Transaction[] public transactions;
event TransactionSubmitted(
uint256 transactionId,
address sender,
address receiver,
uint256 amount
);
event TransactionConfirmed(uint256 transactionId);
event TransactionExecuted(uint256 transactionId);
constructor(address[] memory _owners, uint256 _numConfirmationsRequired) {
require(_owners.length > 1, "Onwers Required Must Be Greater than 1");
require(
_numConfirmationsRequired > 0 &&
numConfirmationsRequired <= _owners.length,
"Num of confirmations are not in sync with the number of owners"
);
for (uint256 i = 0; i < _owners.length; i++) {
require(_owners[i] != address(0), "Invalid Owner");
owners.push(_owners[i]);
}
numConfirmationsRequired = _numConfirmationsRequired;
}
function submitTransaction(address _to) public payable {
require(_to != address(0), "Invalid Receiver's Address");
require(msg.value > 0, "Transfer Amount Must Be Greater Than 0");
uint256 transactionId = transactions.length;
transactions.push(
Transaction({to: _to, value: msg.value, executed: false})
);
emit TransactionSubmitted(transactionId, msg.sender, _to, msg.value);
}
function confirmTransaction(uint256 _transactionId) public {
require(_transactionId < transactions.length, "Invalid Transaction Id");
require(
!isConfirmed[_transactionId][msg.sender],
"Transaction Is Already Confirmed By The Owner"
);
isConfirmed[_transactionId][msg.sender] = true;
emit TransactionConfirmed(_transactionId);
if (isTransactionConfirmed(_transactionId)) {
executeTransaction(_transactionId);
}
}
function executeTransaction(uint256 _transactionId) public payable {
require(_transactionId < transactions.length, "Invalid Transaction Id");
require(
!transactions[_transactionId].executed,
"Transaction is already executed"
);
(bool success, ) = transactions[_transactionId].to.call{
value: transactions[_transactionId].value
}("");
require(success, "Transaction Execution Failed");
transactions[_transactionId].executed = true;
emit TransactionExecuted(_transactionId);
}
function isTransactionConfirmed(uint256 _transactionId)
internal
view
returns (bool)
{
require(_transactionId < transactions.length, "Invalid Transaction Id");
uint256 confimationCount; //initially zero
for (uint256 i = 0; i < owners.length; i++) {
if (isConfirmed[_transactionId][owners[i]]) {
confimationCount++;
}
}
return confimationCount >= numConfirmationsRequired;
}
}
|
/*
* Author - Ben Wegher
* Date - 6/10/2014
* Class - AlertListItem.java
* Description - This class specifies the attributes that define an Alert.
*/
package myApp.list;
import myApp.androidappa.Constants;
import myApp.androidappa.R;
public class AlertListItem {
private String title; // name of the alert
private int icon; // id for email or text icon
private String contact; // phone # or email
private String when; // "enter" or "exit"
private String message; // the message being sent
private int location; // still unsure how it will be stored
private boolean active = false;
// Constructors
public AlertListItem(){
this.title = "alert name";
this.contact = "contact@email.com";
this.message = "Hey mom, I'm leaving school now. See you soon!";
this.icon = Constants.EMAIL;
this.location = Constants.LOCATION; // TODO -- change this
this.when = "EXIT";
}
// public AlertListItem(String title, int icon, String contact, String message){
// this.title = title;
// this.icon = icon;
// this.contact = contact;
// this.message = message;
// }
public AlertListItem(String title, int icon, String when, String contact, String message){
this.title = title;
this.icon = icon;
this.when = when;
this.contact = contact;
this.message = message;
}
public AlertListItem(String title, String contact, int location, String message, String when, int icon){
this.title = title;
this.icon = icon;
this.when = when;
this.contact = contact;
this.message = message;
this.location = location;
}
// GETTERS
public String getTitle(){
return this.title;
}
public int getIcon(){
return this.icon;
}
// Used to retrieve the drawable icon resource
public int getIconID() {
int returnMe = -1;
if(this.icon == Constants.EMAIL)
returnMe = R.drawable.ic_action_email;
else if(this.icon == Constants.TEXT)
returnMe = R.drawable.ic_action_chat;
return returnMe;
}
public int getLocation() {
return location;
}
public String getContact(){
return this.contact;
}
public String getWhen(){
return this.when;
}
public int getWhenInt() {
if(this.when.equals("ENTER"))
return Constants.ENTER;
else
return Constants.EXIT;
}
public String getMessage() {
return message;
}
public boolean getActive() {
return active;
}
// SETTERS
public void setTitle(String title){
this.title = title;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setLocation(int location) {
this.location = location;
}
public void setContact(String contact){
this.contact = contact;
}
public void setWhen(String when){
this.when = when;
}
public void setMessage(String message) {
this.message = message;
}
public void setActive(boolean active) {
this.active = active;
}
}
|
from copy import deepcopy
from random import random
import numpy as np
import networkx as nx
import igraph as ig
def convertGraph(networkx_graph):
edgeList = nx.to_pandas_edgelist(networkx_graph).values
return ig.Graph(edgeList)
def unWeightIC(g, S, p=0.3):
"""
无权重的IC模型
Input: graph object, set of seed nodes, propagation probability
and the number of Monte-Carlo simulations
Output: average number of nodes influenced by the seed nodes
"""
g = convertGraph(g)
new_active, A = S[:], S[:]
while new_active:
# For each newly active node, find its neighbors that become activated
new_ones = []
for node in new_active:
success = np.random.uniform(0, 1, len(g.neighbors(node, mode="out"))) < p
new_ones += list(np.extract(success, g.neighbors(node, mode="out")))
new_active = list(set(new_ones) - set(A))
# Add newly activated nodes to the set of activated nodes
A += new_active
return A
def weightIC(G, S, p=.3):
"""
:param G: networkx graph
:param S: nodes set
:param p: propagation probability
:return: resulted influenced set of vertices (including S)
"""
edges = G.edges
for edge in edges:
G.edges[edge[0], edge[1]]['weight'] = 1
T = deepcopy(S)
Acur = deepcopy(S)
Anext = []
i = 0
while Acur:
for u in Acur:
for v in G[u]:
if v not in T:
w = G[u][v]['weight']
if random() < 1 - (1 - p) ** w:
Anext.append((v, u))
Acur = [edge[0] for edge in Anext]
i += 1
T.extend(Acur)
Anext = []
return T
|
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">
<meta charset="UTF-8">
<title>belt exam</title>
</head>
<body>
<div class="container mx-auto " style="width:800px;">
<h3 class="text-center mt-2">Login and Registration</h3>
<div class="container d-flex justfiy-content-around">
<div class="container p-3 w-50">
<h5>Registration</h5>
<p class="text-danger"><form:errors path="user.*"/></p>
<p class="text-danger"><c:out value="${error}" /></p>
<form:form method="POST" action="/registration" modelAttribute="user" >
<div class="row my-2">
<form:label path="firstname" class="col-3">First Name:</form:label>
<form:input type="text" path="firstname" class="col-5"/>
</div>
<div class="row my-2">
<form:label path="lastname" class="col-3">Last Name:</form:label>
<form:input type="text" path="lastname" class="col-5"/>
</div>
<div class="row my-2">
<form:label path="email" class="col-3">Email:</form:label>
<form:input type="text" path="email" class="col-5"/>
</div>
<div class="row my-2">
<form:label path="password" class="col-3">Password:</form:label>
<form:password path="password" class="col-5"/>
</div>
<div class="row my-2">
<form:label path="passwordConfirmation" class="col-3">Password Confirmation:</form:label>
<form:password path="passwordConfirmation" class="col-5"/>
</div>
<div class="row my-2">
<div class="container">
<button class="btn btn-primary" type="submit" value="Register!">Submit</button>
</div>
</div>
</form:form>
</div>
<div class="container p-3 w-50 ml-3">
<h5>Login</h5>
<p class="text-danger"><c:if test="${logoutMessage != null}">
<c:out value="${logoutMessage}"></c:out>
</c:if></p>
<p class="text-danger"><c:if test="${errorMessage != null}">
<c:out value="${errorMessage}"></c:out>
</c:if></p>
<form method="post" action="/login">
<div class="row my-2">
<label for="username" class="col-3">Email</label>
<input type="text" id="username" name="username" class="col-3"/>
</div>
<div class="row my-2">
<label for="password" class="col-3">Password</label>
<input type="password" id="password" name="password" class="col-3"/>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<div class="row my-2">
<div class="container">
<button class="btn btn-primary" type="submit" value="Login!">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
|
package com.newdon.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.newdon.base.Insert;
import com.newdon.base.NewDonResult;
import com.newdon.base.Update;
import com.newdon.entity.CustomerNature;
import com.newdon.entity.CustomerNature;
import com.newdon.service.CustomerNatureService;
import com.newdon.service.CustomerNatureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @version 1.0
* @ClassName CustomerNatureService
* @Auther: Dong
* @Date: 2018/11/29 10:30
* @Description: TODO
**/
@RequestMapping("/newdon/customerNature")
@RestController
@Slf4j
public class CustomerNatureController {
@Autowired
private CustomerNatureService customerNatureService;
@PostMapping(value = "/query")
public NewDonResult query(CustomerNature customerNature, Integer page, Integer rows) {
if (null == page || page < 0) {
page = 1;
}
if (null == rows || rows < 0) {
rows = 10;
}
EntityWrapper<CustomerNature> wrapper = new EntityWrapper();
wrapper.setEntity(customerNature);
Page<CustomerNature> pageInfo = this.customerNatureService.selectPage(new Page<>(page, rows), wrapper);
return NewDonResult.build(200, "OK", pageInfo);
}
@PostMapping(value = "/insert")
public NewDonResult insert(@Validated(Insert.class) @RequestBody CustomerNature customerNature, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return NewDonResult.build(400, "FAILED", bindingResult.getFieldError().getDefaultMessage());
}
boolean insert = this.customerNatureService.insert(customerNature);
if (insert) {
return NewDonResult.build(200, "OK", customerNature.getId());
} else {
return NewDonResult.build(500, "FAILED", null);
}
}
@PostMapping(value = "/update")
public NewDonResult update(@Validated(Update.class) @RequestBody CustomerNature customerNature, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return NewDonResult.build(400, "FAILED", bindingResult.getFieldError().getDefaultMessage());
}
boolean b = this.customerNatureService.updateById(customerNature);
if (b) {
return NewDonResult.build(200, "OK", customerNature.getId());
} else {
return NewDonResult.build(500, "FAILED", null);
}
}
@PostMapping(value = "/delete")
public NewDonResult delete(@RequestParam("id") Long id) {
boolean b = this.customerNatureService.deleteById(id);
if (b) {
return NewDonResult.build(200, "OK", id);
} else {
return NewDonResult.build(500, "FAILED", null);
}
}
}
|
rm(list=ls())
print(Sys.time())
#set the working director
set.seed(123)
input.path="/proj/nobackup/sens2019512/wharf/ssayols/ssayols-sens2019512/github/casc_microbiome/Demo/0_Data/"
output.path="/proj/nobackup/sens2019512/wharf/ssayols/ssayols-sens2019512/github/casc_microbiome/Demo/1_simulations/"
dir.create(output.path, showWarnings = FALSE)
ncores=5
##load libraries
library(rio)
library(BiocParallel)
library(ordinal)
# load data
dades=import(paste(input.path,"/random_data_covar_1batch.tsv",sep=""))
# regression functions
ordinal.fun <- function(y, x,data) {
tryCatch({
fit <- eval(parse(text=paste("clm(as.factor(",y,") ~ ",x,", data = data)",sep="")))
coef <- summary(fit)$coefficients
# ci <- confint(fit)
if (is.finite(coef[x, 2])) {
data.frame(var.x=x,var.y=y,estimate = coef[x, 1],
# lower=ci["x",1],
# upper=ci["x",2],
se=coef[x,2],p.value = coef[x, 4],n=length(fit$fitted.values),aic=AIC(fit))
} else {
data.frame(var.x=x,var.y=y,estimate = NA,
# lower=NA,upper=NA,
se=NA,p.value = NA,n=NA,aic=NA)
}
}, error = function(e) {
data.frame(var.x=x,var.y=y,estimate = NA,
# lower=NA,upper=NA,
se=NA,p.value = NA,n=NA,aic=NA)
})
}
log.op="log1p"
rank.op=""
#variables to assess
noms=grep("X.",names(dades),value=T)
#outcome
yi="casctot"
print("#### model ####")
print(paste("lm model",log.op,rank.op))
#remove individuals with NAs in the outcome
dades=dades[which(is.na(dades[,yi])==F),]
#log1p transform
dades[,noms]=apply(dades[,noms], 2, log1p)
#run the models
print("##### time #####")
system.time(res.ordinal<-bplapply(noms,function(x){
res.ordinal<-ordinal.fun(yi,x,dades)
data.frame(res.ordinal)
}, BPPARAM = MulticoreParam(ncores)))
res.ordinal <- do.call(rbind, res.ordinal)
write.table(res.ordinal,file=paste(output.path,"/res_ordinal.fun_CASC_",log.op,rank.op,"_1batch.tsv",sep=""),
col.names = T,row.names = F,sep="\t")
print(Sys.time())
|
import { useNavigation } from "@react-navigation/native";
import React from "react";
import { Text, View, StyleSheet, Image, Pressable, Platform } from 'react-native';
const MealsOverViewItem = ({ title, imagePath, durations, Complexcity, Affordability, onPressed }) => {
return (
<View style={styles.outerViewContainer}>
<Pressable
onPress={onPressed}
style={({ pressed }) => (pressed ? styles.buttonPressed : null)}
android_ripple={{ color: '#ccc' }}>
<View>
<Image style={styles.imageStyle} source={{ uri: imagePath }} />
<Text style={styles.textStyling}>{title}</Text>
</View>
<View style={styles.viewForDetail}>
<Text style={styles.textStyling}>{durations}</Text>
<Text style={styles.textStyling}>{Complexcity.toUpperCase()}</Text>
<Text style={styles.textStyling}>{Affordability.toUpperCase()}</Text>
</View>
</Pressable>
</View>
)
}
const styles = StyleSheet.create({
outerViewContainer: {
margin: 16,
backgroundColor: 'white',
borderRadius: 4,
elevation: 4,
shadowColor: 'black',
shadowOpacity: 0.25,
shadowOffset: { width: 0, height: 2 },
shadowRadius: 8,
overflow: Platform.OS === 'android' ? 'hidden' : 'visible'
},
imageStyle: {
width: '100%',
height: 200
},
textStyling: {
fontStyle: 'italic',
fontSize: 20,
color: 'black',
textAlign: 'center',
margin: 8
},
buttonPressed: {
opacity: 0.75
},
viewForDetail: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
}
})
export default MealsOverViewItem;
|
import React, { useContext, useState } from 'react'
import { Link, Navigate } from 'react-router-dom'
import { Context, server } from '../main';
import { toast } from 'react-hot-toast';
import axios from 'axios';
const Login = () => {
const { isAuthenticated, setisAuthenticated, loading, setLoading } = useContext(Context);
const [email,setEmail] = useState("");
const [password,setPassword] = useState("");
const submitHandler = async (e) =>{
e.preventDefault();
setLoading(true);
try {
const { data } = await axios.post(`${server}/users/login`,{
email, password
},{
headers:{
"Content-Type": "application/json"
},
withCredentials: true,
}
);
toast.success(data.message);
setisAuthenticated(true);
setLoading(false);
} catch (error) {
toast.error(error.response.data.message);
setisAuthenticated(false);
setLoading(false);
}
};
if(isAuthenticated) return <Navigate to="/" />
return (
<div className='login'>
<section>
<form onSubmit={submitHandler}>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
type="email"
placeholder='Email'
required
/>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="password"
placeholder='Password'
required
/>
<button disabled={loading} type="submit">Login</button>
<h4>Or</h4>
<Link to="/register">Sign Up</Link>
</form>
</section>
</div>
);
};
export default Login;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="{{ url_for('static', filename='icone_page.png') }}" type="image/x-icon">
<title>Register</title>
<!-- External CSS -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Internal CSS -->
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light bg-light sticky-top">
<div class="container">
<a class="navbar-brand rounded p-2 bg-primary text-light fs-5 fw-bold font-monospace" href="#">PFA</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="#">
AHP <img src="{{ url_for('static', filename='la-prise-de-decision.png') }}" alt="AHP Icon" style="width: 20px; height: 20px;">
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">
Topsys <img src="{{ url_for('static', filename='choix.png') }}" alt="Topsys Icon" style="width: 20px; height: 20px;">
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Registration Form -->
<div class="container col-md-6">
<div class="card mt-5">
<h1 class="text-center mt-4 fs-4 font-monospace">Register New User or Login Existing Account</h1>
<div class="card-body">
<form action="{{ url_for('register') }}" method="post">
<div class="mb-3">
<label for="fullname" class="form-label">Your Name</label>
<input type="text" class="form-control" id="fullname" name="fullname" placeholder="Enter your Name">
</div>
<div class="mb-3">
<label for="email" class="form-label">Your Email</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your Email">
</div>
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter your Username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
</div>
<div class="mb-3">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-success" role="alert">
{{ message }}
</div>
{% endfor %}
{% endif %}
{% endwith %}
</div>
<div class="d-grid gap-2">
<input type="submit" class="btn btn-primary btn-lg" value="Register">
</div>
</form>
<p class="text-center mt-3">Already have an account? <a href="{{ url_for('login') }}">Login</a></p>
</div>
</div>
</div>
<!-- Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/5.1.3/js/bootstrap.min.js"></script>
{% if success %}
<script>
document.addEventListener('DOMContentLoaded', (event) => {
const successAlert = document.querySelector('.alert-success');
if (successAlert) {
setTimeout(() => {
window.location.href = "{{ url_for('login') }}";
}, 1000); // Redirect after 3 seconds
}
});
</script>
{% endif %}
</body>
</html>
|
from odoo import models, fields, api
from odoo.exceptions import ValidationError
class HrJob(models.Model):
_inherit = "hr.job"
active = fields.Boolean(default=True)
actual_number_of_employees = fields.Integer(string='实际员工数量', compute='test_compute_employees', store=True)
@api.depends('employee_ids.job_id', 'employee_ids.active', 'employee_ids.is_delete')
def test_compute_employees(self):
employee_data = self.env['hr.employee'].read_group([('job_id', 'in', self.ids),
('is_delete', '=', False),
], ['job_id'], ['job_id'])
result = dict((data['job_id'][0], data['job_id_count']) for data in employee_data)
for job in self:
job.actual_number_of_employees = result.get(job.id, 0)
class FsnJobCreateAudit(models.Model):
_name = 'fsn_job_create_audit'
_description = 'FSN岗位创建审核'
_rec_name='job_name'
_order = "date desc"
job_id = fields.Many2one("hr.job", string="岗位id")
date = fields.Date(string="申请日期", required=True)
job_name = fields.Char(string="岗位名称", required=True)
department_id = fields.Many2one('hr.department', string='部门', required=True)
state = fields.Selection([('待审批', '待审批'), ('已审批', '已审批')], string="状态", default="待审批")
# 确认弹窗
def confirmation_button(self):
button_type = self._context.get("type")
name = ""
if button_type == "fallback":
name = "确认回退吗?"
elif button_type == "through":
name = "确认通过吗?"
action = {
'name': name,
'view_mode': 'form',
'res_model': 'fsn_job_create_audit',
'view_id': self.env.ref('fsn_employee.fsn_job_create_audit_form').id,
'type': 'ir.actions.act_window',
'res_id': self.id,
'target': 'new'
}
return action
# 状态改变
def action_state_changes(self):
button_type = self._context.get("type")
if button_type == "fallback":
if self.state == "已审批":
self.state = "待审批"
self.job_id.unlink()
elif button_type == "through":
if self.state == "待审批":
job_id = self.job_id.create({
"name": self.job_name,
"department_id": self.department_id.id
})
self.job_id = job_id.id
self.state = "已审批"
def write(self, vals):
if self.state != "待审批":
if "state" in vals and len(vals) == 1:
pass
else:
raise ValidationError(f"审批过程中的单据, 不可修改!。")
return super(FsnJobCreateAudit, self).write(vals)
def unlink(self):
for record in self:
if record.state != "待审批":
raise ValidationError(f"审批过程中的单据, 不可删除!。")
return super(FsnJobCreateAudit, self).unlink()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.