text
stringlengths
184
4.48M
--- import { getCollection } from "astro:content"; import { categories } from "src/content/config"; import Card from "@components/Card.astro"; import StarShape from "@components/StarShape.astro"; import Layout from "@layouts/Layout.astro"; const worksEntries = await getCollection("works").then((collection) => collection.sort((a, b) => { const dateA = new Date(a.data.date); const dateB = new Date(b.data.date); return dateB.getTime() - dateA.getTime(); }) ); --- <Layout title="baptistejouin | my work." page="works"> <main class="row"> <h1 transition:name="title">/works</h1> <div class="filter"> <button class="active" data-category="0">all</button> { categories.map((category) => ( <button data-category={category}>{category}</button> )) } </div> { worksEntries.map((work) => ( <Card to={`/work/${work.slug}`} id={work.slug} category={work.data.category} title={work.data.title} thumbnail={work.data.thumbnail} /> )) } <p class="empty hidden">There is no work for this category. :(</p> </main> <StarShape offsetY={200} scale={0.6} side="left" /> </Layout> <style lang="scss"> @use "../lib/scss/variables" as v; @use "../lib/scss/mixins" as m; h1 { font-family: v.$ff-jetbrains; } main { min-height: 80vh; } .filter { grid-column: span v.$number-grid-columns; display: flex; flex-direction: row; align-items: center; flex-wrap: wrap; gap: 0.25rem 0.5rem; margin-bottom: 3.5rem; button { color: v.$c-black; font-size: 1.5rem; font-family: v.$ff-jetbrains; @include m.before(lg) { font-size: 1.25rem; } &.active { text-decoration: underline; } } } .empty { grid-column: span v.$number-grid-columns; text-align: center; font-size: 1.25rem; font-family: v.$ff-jetbrains; opacity: 0.5; } :global(.hidden) { display: none; } </style> <script> function initFiltersByCategory() { const filters = document.querySelectorAll( "div.filter button" ) as NodeListOf<HTMLButtonElement>; const cards = document.querySelectorAll( "main > a" ) as NodeListOf<HTMLAnchorElement>; const empty = document.querySelector("p.empty")!; filters.forEach((filter) => { filter.addEventListener("click", () => { filters.forEach((f) => f.classList.remove("active")); filter.classList.add("active"); const category = filter.dataset.category; cards.forEach((card) => { if (category === "0" || card.dataset.category === category) { card.classList.remove("hidden"); } else { card.classList.add("hidden"); } }); empty.classList.toggle( "hidden", !!document.querySelector("main > a:not(.hidden)") ); }); }); } initFiltersByCategory(); document.addEventListener("astro:after-swap", () => { initFiltersByCategory(); }); </script>
'use client' import React, { useState } from 'react' import styles from './tags.module.scss' import { TiDelete } from 'react-icons/ti' import axios from 'axios' import { useRouter } from 'next/navigation' const TagsInput = ({tagsData, id}: {tagsData: Array<string>, id: string}) => { const [tags, setTags] = useState(tagsData) const [inputValue, setInputValue] = useState('') const router = useRouter() const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && inputValue !== '') { setTags([...tags, inputValue]) setInputValue('') } } const handleDelete = async (index: number) => { setTags([ ...tags.slice(0, index), ...tags.slice(index + 1) ]); await handleSave([ ...tags.slice(0, index), ...tags.slice(index + 1) ]) } const handleSave = async (tags: Array<string>) => { await axios.put(`/api/update/tags/${id}`, { tags: tags }) router.refresh() return } return ( <div className={styles.tagInput} onBlur={() => handleSave(tags)}> {tags.map((tag, index) => (<p key={index}>{tag} <TiDelete size={24} style={{marginBottom: -7, cursor: 'pointer'}} onClick={() => handleDelete(index)}/></p>))} <input type='text' value={inputValue} placeholder='Write your tags here' onChange={(e) => { setInputValue(e.target.value) }} onKeyDown={handleKeyPress}/> </div> ) } export default TagsInput
import React, { useState } from 'react' import { FaBars, FaTimes } from 'react-icons/fa' import logo from './Images/logo.png' import './Navbar.css' const Navbar = () => { const [click, setClick] = useState(false) const handleClick = () => setClick(!click) const closeMenu = () => setClick(false) const [color,setColor] = useState(false) const changeColor = () =>{ if(window.scrollY >= 100){ setColor(true) }else{ setColor(false) } } window.addEventListener('scroll', changeColor) return ( <div className={color ? 'header header-bg' : 'header' }> <nav className='navbar'> <a href='/' className='logo'> <img src={logo} alt='logo' /> </a> <div className='hamburger' onClick={handleClick}> {click ? (<FaTimes size={30} style={{ color: '#ffffff' }} />) : (<FaBars size={30} style={{ color: '#ffffff' }} />)} </div> <ul className={click ? "nav-menu active" : "nav-menu"}> <li className='nav-item'> <a href='/' onClick={closeMenu}>Home</a> </li> <li className='nav-item'> <a href='#aboutus' onClick={closeMenu}>About Us</a> </li> <li className='nav-item'> <a href='#features' onClick={closeMenu}>Our Services</a> </li> <li className='nav-item'> <a href='#team' onClick={closeMenu}>Team</a> </li> <li className='nav-item'> <a href='#clients' onClick={closeMenu}>Clients</a> </li> <li className='nav-item'> <a href='#career' onClick={closeMenu}>Career</a> </li> <li className='nav-item'> <a href='#contact' onClick={closeMenu}>Contact</a> </li> </ul> </nav> </div> ) } export default Navbar
import { Dialog } from '@plugins/Dialog/Dialog'; import { Component, OnInit } from '@angular/core'; import { ActionSheet, ActionSheetButtonStyle, } from '@plugins/ActionSheet/ActionSheetPlugin'; import { CameraPlugin, Toast, ShowOptions, Clipboard, Share, StatusBar, Style, SplashScreen, } from '@plugins'; import i18n from '@i18n/i18n'; import { Router } from '@angular/router'; @Component({ selector: 'app-native-api', templateUrl: './native-api.page.html', styleUrls: ['./native-api.page.scss'], }) export class NativeApiPage implements OnInit { buttons = [ { title: 'Show Action Sheet', click: this.showActionSheetActions }, { title: 'Show Camera', click: this.showCameraAction }, { title: 'Show Browser', click: this.showActionSheetActions }, { title: 'Show Splash screen', click: this.showSplashScreen }, { title: 'Keyboard', click: () => this.router.navigate(['/keyboard']) }, ]; dialogType = 'alert'; dialogTypes = ['alert', 'prompt', 'confirm']; toastDuration: ShowOptions['duration'] = 'short'; toastDurations = ['short', 'long']; toastPosistion: ShowOptions['position'] = 'bottom'; toastPosistions = ['top', 'center', 'bottom']; titles = { dialog: 'Show Dialog', toast: 'Show Toast', clipboard: 'Clipboard', share: 'Share text', }; clipboard = ''; clipboardValue = ''; clipboardType = ''; shareTitle = ''; statusBarActions = [ { title: 'Style dark', click: async () => await StatusBar.setStyle({ style: Style.Dark }), }, { title: 'Style light', click: async () => await StatusBar.setStyle({ style: Style.Light }), }, { title: 'Hide', click: async () => await StatusBar.hide(), }, { title: 'Show', click: async () => await StatusBar.show(), }, ]; constructor(private router: Router) {} ngOnInit() {} handleChangeDialogType(ev: any) { this.dialogType = ev; } handleChangeToastDuration(ev: any) { this.toastDuration = ev; } handleChangeToastPosition(ev: any) { this.toastPosistion = ev; } async showActionSheetActions() { const result = await ActionSheet.showActions({ title: 'Photo Options', message: 'Select an option to perform', options: [ { title: 'Upload', }, { title: 'Share', }, { title: 'Remove', style: ActionSheetButtonStyle.Destructive, }, ], }); } async showCameraAction() { await CameraPlugin.showOptions(); } async showDialog() { switch (this.dialogType) { case 'alert': { await Dialog.alert({ message: 'Alert', title: 'Alert title', buttonTitle: 'Button title', }); break; } case 'prompt': { await Dialog.prompt({ message: 'Prompt message', cancelButtonTitle: 'Cancel', inputText: 'Input text', inputPlaceholder: 'Input placeholder', okButtonTitle: 'Ok button', title: 'Prompt title', }); break; } case 'confirm': { await Dialog.confirm({ message: 'Prompt message', cancelButtonTitle: 'Cancel button', okButtonTitle: 'Ok button', title: 'Prompt title', }); break; } } } async showToast( text = 'Toast' + ' ' + this.toastDuration + ' ' + this.toastPosistion, position = this.toastPosistion, duration = this.toastDuration ) { await Toast.show({ text, position, duration, }); } async showClipboard() { this.showToast(i18n.t('GLOBAL.COPIED')); Clipboard.write({ string: this.clipboard }); } onChangeClipboard(data: any) { this.clipboard = data.target!.value; } onChangeShare(data: any) { this.shareTitle = data.target!.value; } async readClipboard() { const { value, type } = await Clipboard.read(); this.clipboardValue = value; this.clipboardType = type; } async onShare() { await Share.share({ dialogTitle: 'Share', title: 'Share title', text: this.shareTitle, }); } async showSplashScreen() { await SplashScreen.show({ autoHide: true, showDuration: 1000, fadeInDuration: 100, fadeOutDuration: 100, }); } }
package com.nikolabojanic.service; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import com.nikolabojanic.converter.TrainerConverter; import com.nikolabojanic.domain.TrainerDomain; import com.nikolabojanic.entity.TraineeEntity; import com.nikolabojanic.entity.TrainerEntity; import com.nikolabojanic.entity.UserEntity; import com.nikolabojanic.repository.TrainerRepository; import io.micrometer.core.instrument.Counter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.crypto.password.PasswordEncoder; @ExtendWith(MockitoExtension.class) class TrainerServiceTest { @Mock private TrainerRepository trainerRepository; @Mock private TraineeService traineeService; @Mock private UserService userService; @Mock private TrainingTypeService trainingTypeService; @Mock private PasswordEncoder passwordEncoder; @Mock private TrainerConverter trainerConverter; @Mock private Counter totalTransactionsCounter; @InjectMocks private TrainerService trainerService; @Test void createTrainerProfileTest() { //given UserEntity user = new UserEntity(); user.setPassword(RandomStringUtils.randomAlphabetic(5)); TrainerEntity trainer = new TrainerEntity(); trainer.setUser(user); when(userService.generateUsernameAndPassword(any(UserEntity.class))).thenReturn(user); when(trainerConverter.convertEntityToDomainModel(any(UserEntity.class))).thenReturn(new TrainerDomain()); when(passwordEncoder.encode(any(String.class))).thenReturn(RandomStringUtils.randomAlphabetic(5)); when(trainerRepository.save(any(TrainerEntity.class))).thenReturn(new TrainerEntity()); //when TrainerDomain createdTrainer = trainerService.createTrainerProfile(trainer); //then assertThat(createdTrainer).isNotNull(); } @Test void updateTrainerProfileTest() { //given UserEntity user = new UserEntity(); TrainerEntity trainer = new TrainerEntity(); trainer.setUser(user); when(trainerRepository.findByUsername(any(String.class))).thenReturn(Optional.of(trainer)); when(trainerRepository.save(any(TrainerEntity.class))).thenReturn(new TrainerEntity()); //when TrainerEntity updatedTrainer = trainerService.updateTrainerProfile( RandomStringUtils.randomAlphabetic(10), trainer); //then assertThat(updatedTrainer).isNotNull(); } @Test void findByUsernameTest() { //given when(trainerRepository.findByUsername(any(String.class))).thenReturn(Optional.of(new TrainerEntity())); //when TrainerEntity trainer = trainerService.findByUsername( RandomStringUtils.randomAlphabetic(10)); //then assertThat(trainer).isNotNull(); } @Test void changeActiveStatusTest() { //given UserEntity user = new UserEntity(); TrainerEntity trainer = new TrainerEntity(); trainer.setUser(user); when(trainerRepository.findByUsername(any(String.class))).thenReturn(Optional.of(trainer)); when(trainerRepository.save(any(TrainerEntity.class))).thenReturn(new TrainerEntity()); //then assertDoesNotThrow(() -> trainerService.changeActiveStatus( RandomStringUtils.randomAlphabetic(10), true)); } @Test void findActiveForOtherTraineesTest() { //given TraineeEntity trainee = new TraineeEntity(); trainee.setId(Long.parseLong(RandomStringUtils.randomNumeric(5))); when(traineeService.findByUsername(any(String.class))).thenReturn(trainee); when(trainerRepository.findActiveForOtherTrainees(any(Long.class))).thenReturn(new ArrayList<>()); //when List<TrainerEntity> activeTrainers = trainerService.findActiveForOtherTrainees( RandomStringUtils.randomNumeric(10)); //then assertThat(activeTrainers).isNotNull(); } }
import 'package:get/get.dart'; import 'package:heart/Providers/AdminProvider.dart'; import 'package:heart/Screens/Login/Screen/Login.dart'; import 'package:heart/Screens/Main/AdminOpeningScreen.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations( [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiProvider( providers: [ Provider<AdminProvider>( create: (_) => AdminProvider(), ), ], child: GetMaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.green), home: const Splash(), ), ); } } class Splash extends StatelessWidget { const Splash({super.key}); @override Widget build(BuildContext context) { final user = Provider.of<AdminProvider>(context, listen: false); return FutureBuilder( future: user.setId(), builder: (context, AsyncSnapshot<String?> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Container( color: Colors.white, child: LottieBuilder.asset("assets/animations/Loading.json")); } else { return snapshot.data! != "null" ? const AdminOpeningScreen() : const Login(); } }, ); } }
using System; namespace Construtores { class Produto { private string _nome; public double Preco { get; private set; } public int Quantidade { get; private set; } public Produto(string nome, double preco, int quantidade) { _nome = nome; Preco = preco; Quantidade = quantidade; } public string Nome { get { return _nome;} set { if (value != null && value.Length > 2) { _nome = value; } } } public double ValorTotalEmEstoque() { return Preco * Quantidade; } public void AdicionarProdutos(int quantidade) { Quantidade += quantidade; } public void RemoverProdutos(int quantidade) { Quantidade -= quantidade; } public override string ToString() { return _nome + ", $" + Preco.ToString("F2") + ", " + Quantidade + " unidade, Total: $" + ValorTotalEmEstoque().ToString("F2"); } } }
<template> <div> <basic-dialog :icon="icon" :title="title" width="980" height="90%" v-bind="$attrs" @close="close" :openFlag="openEdit" > <template #content> <el-form label-width="140px" label-position="right" :model="form" :rules="rules" ref="formRef" > <el-row> <el-col span="24"> <el-form-item label="规程名称" prop="zdmc"> <el-input placeholder="规程名称" clearable v-model="form.zdmc" :style="`width:${width2}`" :size="size" ></el-input> </el-form-item> </el-col> </el-row> <el-row> <el-col span="24"> <el-form-item label="规程编号" prop="zdbh"> <el-input placeholder="规程编号" clearable v-model="form.zdbh" :style="`width:${width2}`" :size="size" ></el-input> </el-form-item> </el-col> </el-row> <el-row> <el-col span="12"> <el-form-item label="编制人" prop="dlb"> <el-select clearable placeholder="编制人" v-model="form.dlb" :style="`width:${width}`" :size="size" > <el-option v-for="item in dictConfig.dlbList" :key="item.id" :value="item.dictValue" :label="item.dictValueName" ></el-option> </el-select> </el-form-item> </el-col> <el-col span="12"> <el-form-item label="下次评审日期" prop="psrq"> <el-date-picker v-model="form.psrq" type="date" placeholder="请选择下次评审日期" value-format="yyyy-MM-dd" :style="`width:${width}`" :size="size" > </el-date-picker> </el-form-item> </el-col> </el-row> <el-row> <el-col span="12"> <el-form-item label="版本号" prop="fbjg"> <el-input placeholder="版本号" clearable v-model="form.fbjg" :style="`width:${width}`" :size="size" ></el-input> </el-form-item> </el-col> <el-col span="12"> <el-form-item label="发布日期" prop="fbrq"> <el-date-picker v-model="form.fbrq" type="date" placeholder="请选择安装时间" value-format="yyyy-MM-dd" :style="`width:${width}`" :size="size" > </el-date-picker> </el-form-item> </el-col> </el-row> <el-row> <el-col span="24"> <el-form-item label="规程摘要" prop="zy"> <el-input type="textarea" :rows="12" clearable v-model="form.zy" :style="`width:${width2}`" :size="size" ></el-input> </el-form-item> </el-col> </el-row> <el-row> <el-col> <el-form-item label="附件"> <basic-upload key="file" :model="true" @onSuccess="(fileList) => onSuccess(fileList, 'file')" @onRemove="(fileList) => onRemove(fileList, 'file')" :photos="form.file" ></basic-upload> </el-form-item> </el-col> </el-row> <el-row> <el-col span="12"> <el-form-item label="编辑部门" prop="dlb"> <el-select clearable placeholder="编辑部门" v-model="form.dlb" :style="`width:${width}`" :size="size" > <el-option v-for="item in dictConfig.dlbList" :key="item.id" :value="item.dictValue" :label="item.dictValueName" ></el-option> </el-select> </el-form-item> </el-col> <el-col span="12"> <el-form-item label="适用部门" prop="dlb"> <el-select clearable placeholder="适用部门" v-model="form.dlb" :style="`width:${width}`" :size="size" > <el-option v-for="item in dictConfig.dlbList" :key="item.id" :value="item.dictValue" :label="item.dictValueName" ></el-option> </el-select> </el-form-item> </el-col> </el-row> <el-row> <el-col span="24"> <el-form-item label="备注" prop="remark"> <el-input placeholder="/" clearable v-model="form.remark" :style="`width:${width2}`" :size="size" ></el-input> </el-form-item> </el-col> </el-row> </el-form> </template> <template #bottom> <div> <el-button type="primary" @click="submitForm">保存</el-button> <el-button type="success" @click="reset">重置</el-button> <el-button type="warning" @click="close">取消</el-button> </div> </template> </basic-dialog> </div> </template> <script> import { monitoringIndicatorsCreateAPI, monitoringIndicatorsViewAPI, monitoringIndicatorsUpdateAPI, } from "@/api/hazard/monitoringIndicators/index"; export default { name: "editDialog", components: {}, props: { dictConfig: { type: Object, default() { return {}; }, }, }, data() { return { icon: "icon-bianji", title: "", openEdit: false, width: "260px", width2: "91%", size: "small", form: { zdmc: "", dlb: "", xlb: "", fbjg: "", fgbh: "", fbrq: "", qyrq: "", fzrq: "", fcrq: "", qzcd: 0, file: [], zy: "", remark: "", }, rules: { zdmc: [{ required: true, message: "请输入规程名称", trigger: "blur" }], }, row: {}, }; }, created() {}, methods: { // 打开 open(row, type) { this.openEdit = true; this.title = "新增安全操作规程信息"; if (row) { this.title = "编辑安全操作规程信息"; this.row = row; this.getDetail(row.id); } if (type === "xiuding") { this.title = "修订安全操作规程信息"; } }, // 关闭 close() { this.openEdit = false; this.reset(); }, // 重置 reset() { this.$refs.formRef.resetFields(); }, // 上传图片成功 onSuccess(fileList, params) { this.form[params] = fileList; }, // 删除图片 onRemove(fileList, params) { this.form[params] = fileList; }, // 提交接口 submitForm() { this.$refs.formRef.validate((valid) => { if (valid) { if (this.row.id) this.modify(); else this.add(); } else { console.log("error submit!!"); return false; } }); }, // 获取详情 async getDetail(id) { try { const res = await monitoringIndicatorsViewAPI({ id }); if (res.code === 200) { this.form = { ...res.data, }; } } catch (e) { this.$message.error(e); } }, // 新增 async add() { try { const res = await monitoringIndicatorsCreateAPI(this.form); if (res.code === 200) { this.$emit("refresh"); this.$message.success("新增成功"); this.close(); } } catch (e) { this.$message.error(e); } }, // 修改 async modify() { try { const res = await monitoringIndicatorsUpdateAPI({ ...this.form, id: this.row.id, }); if (res.code === 200) { this.$emit("refresh"); this.$message.success("修改成功"); this.close(); } } catch (e) { this.$message.error(e); } }, }, }; </script> <style scoped lang="scss"> /deep/ .el-form-item { margin-bottom: 8px !important; } /deep/ .el-form-item__error { line-height: 2px; } </style>
import React, { useEffect, useState } from "react"; import * as sessionActions from "../../store/session"; import { useDispatch, useSelector } from "react-redux"; import { Redirect } from "react-router-dom"; import "./LoginForm.css"; import {useModal} from '../../context/Modal' function LoginFormModal() { const dispatch = useDispatch(); const sessionUser = useSelector((state) => state.session.user); const [credential, setCredential] = useState(""); const [password, setPassword] = useState(""); const [errors, setErrors] = useState({}); const [disabled, setDisabled] = useState(true) useEffect(() => { if(credential.length < 4 || password.length < 6) setDisabled(true) else setDisabled(false) }, [credential, password]) const { closeModal } = useModal() if (sessionUser) return <Redirect to="/" />; const handleSubmit = (e) => { e.preventDefault(); setErrors({}); return dispatch(sessionActions.login({ credential, password })) .then(()=>closeModal()).catch( async (res) => { const data = await res.json(); if (data && data.errors) setErrors(data.errors); } ); }; return ( <div className="loginModal"> <h1>Log In</h1> <form onSubmit={handleSubmit}> <input placeholder="Username or Email" type="text" value={credential} onChange={(e) => setCredential(e.target.value)} required aria-label='test' /> <input placeholder="Password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required /> {errors.credential && <p>{errors.credential}</p>} <button type="submit" disabled={disabled}>Log In</button> <button className="demo" onClick={() => dispatch(sessionActions.login({ credential:"Demo-lition", password:"password" })) .then(()=>closeModal())}>Log in as Demo User</button> </form> </div> ); } export default LoginFormModal;
import asyncio import logging import sys from aiogram import Bot, Dispatcher from aiogram.utils.callback_answer import CallbackAnswerMiddleware from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker from bot.config_reader import config from bot.handlers import commands, callbacks from bot.middlewares import DbSessionMiddleware from bot.ui_commands import set_ui_commands async def main(): engine = create_async_engine(url=config.DB_URL, echo=True) sessionmaker = async_sessionmaker(engine, expire_on_commit=False) bot = Bot(config.BOT_TOKEN, parse_mode="HTML") # Setup dispatcher and bind routers to it dp = Dispatcher() dp.update.middleware(DbSessionMiddleware(session_pool=sessionmaker)) # Automatically reply to all callbacks dp.callback_query.middleware(CallbackAnswerMiddleware()) # Register handlers dp.include_router(commands.router) dp.include_router(callbacks.router) # Set bot commands in UI await set_ui_commands(bot) # Run bot await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types()) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, stream=sys.stdout) asyncio.run(main())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <title>CSE 135 Jian Qin</title> <script src="./hw3/collector.js"></script> <script> window.onload = event => { postStatic(); postPerformance(); postEnterInfo(); window.addEventListener('mousemove', event => { postMouseMovement(event); }); window.addEventListener('scroll', event => { postMouseScrolling(event); }); window.onclick = event => { postMouseClick(event); } window.addEventListener('keypress', async (event) => { data = { keyboard_activity: event.code, page_info: window.location.href, identifier: custom_cookies() } return await postInstance(activity_url, data); }) let events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart']; events.forEach(name => { window.addEventListener(name, resetTimer, true); }); resetTimer(); } window.onunload = event => { postLeaveInfo(); } </script> <script src="https://cdn.lr-in.com/LogRocket.min.js" crossorigin="anonymous"></script> <!-- Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-226861928-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'UA-226861928-1'); </script> </head> <body> <div class="container"> <!--Header--> <h1 style="color:brown;">CSE 135 Spring 2022</h1> <h2 style="color: turquoise;">IP Address: 164.92.108.208</h2> <h2><a href="https://reporting.cse135.qinjian.xyz" target="_blank">Reporting Page</a></h2> <h2><a href="https://collector.cse135.qinjian.xyz" target="_blank">Collector Page</a></h2> <h2>Team Members:</h2> <h3><a href="https://qinjian.xyz" target="_blank">Jian Qin</a></h3> <!--Homework 1--> <h3>Homework 1</h3> <ul> <li><a href="hw1/hello.php">PHP</a></li> <li><a href="hw1/report.html">Report</a></li> </ul> <hr> <h3>Homework 2</h3> <ul style="display:inline-block; width: 400px;"> <p>PHP - CGI</p> <li><a href="cgi-bin/php-hello-html-world.php">Hello, PHP!</a></li> <li><a href="cgi-bin/php-hello-json-world.php">Hello, PHP! (Json)</a></li> <li><a href="cgi-bin/php-environment.php">Environment Variables</a></li> <li><a href="cgi-bin/php-get-echo.php">GET Echo</a></li> <li><a href="cgi-bin/php-post-echo.php">POST Echo</a></li> <li><a href="cgi-bin/php-general-echo.php">General Echo</a></li> <li><a href="php-cgiform.html">Sessioning</a></li> </ul> <ul style="display:inline-block; width: 400px;"> <p>Python - CGI</p> <li><a href="cgi-bin/python-hello-world.py">Hello, Python!</a></li> <li><a href="cgi-bin/python-hello-json-world.py">Hello, Python! (Json)</a></li> <li><a href="cgi-bin/python-environment.py">Environment Variables</a></li> <li><a href="cgi-bin/python-get-echo.py">GET Echo</a></li> <li><a href="cgi-bin/python-post-echo.py">POST Echo</a></li> <li><a href="cgi-bin/python-general-echo.py">General Echo</a></li> <li><a href="python-cgiform.html">Sessioning</a></li> </ul> <ul style="display:inline-block; width: 400px;"> <p>Perl - CGI</p> <li><a href="cgi-bin/perl-hello-html-world.pl">Hello, Perl!</a></li> <li><a href="cgi-bin/perl-hello-json-world.pl">Hello, Perl! (Json)</a></li> <li><a href="cgi-bin/perl-environment-manual.pl">Environment Variables (Manually)</a></li> <li><a href="cgi-bin/perl-environment-cgi.pl">Environment Variables (CGI.pm)</a></li> <li><a href="cgi-bin/perl-get-echo.pl">GET Echo</a></li> <li><a href="cgi-bin/perl-post-echo.pl">POST Echo</a></li> <li><a href="cgi-bin/perl-general-echo.pl">General Echo</a></li> <li><a href="perl-cgiform.html">Sessioning</a></li> </ul> <ul style="display:inline-block; width: 400px;"> <p>C - CGI</p> <li><a href="cgi-bin/c-hello-html-world.cgi">Hello, C!</a></li> <li><a href="cgi-bin/c-hello-json-world.cgi">Hello, C! (Json)</a></li> <li><a href="cgi-bin/c-environment.cgi">Environment Variables</a></li> <li><a href="cgi-bin/c-get-echo.cgi">GET Echo</a></li> <li><a href="cgi-bin/c-post-echo.cgi">POST Echo</a></li> <li><a href="cgi-bin/c-general-echo.cgi">General Echo</a></li> <li><a href="c-cgiform.html">Sessioning</a></li> </ul> <h3>Homework 3</h3> <li><a href="./hw3/hellodataviz.html">Data Visualization</a></li> <li><a href="./hw3/database.html">Database Grid</a></li> </div> <img src="./statics/Geisel.jpg" style="display:block; margin-left:auto; margin-right:auto; width:50%;" /> <noscript> <img src="/api/noscript" /> </noscript> <div style="text-align: center;"> <div id='year'></div> All rights reserved. </div> <script> let d = new Date(); let currentYear = d.getFullYear(); let display = "Copyright &copy " + currentYear + ", Jian Qin"; document.getElementById('year').innerHTML = display; </script> </body> </html>
#include <iostream> using namespace std; class Person { public: string name; int age; Person() { } Person(string name, int age) : name(name), age(age) { } // Person(string name, int age) { // this->name = name; // this->age = age; // } ~Person() { } virtual void sayHello() { cout << "Person " << this->name << " says hello." << endl; } virtual void sayHello(Person anotherPerson) { cout << "Person " << this->name << "says hello to " << anotherPerson.name << endl; } bool operator < (Person anotherPerson) { return this->age < anotherPerson.age; } ostream& operator << (ostream& out) { return out << "Person: (" << "Name = " << this->name << ", " << "Age = " << this->age << ")" << endl; } istream& operator >> (istream& in) { cout << "Please input name and age.\n"; return in >> this->name >> this->age; } }; class Student: Person { public: Student() { } Student(string name, int age) : Person(name, age) { } bool hasActiveStatus() { return true; } bool isYounger(Student anotherStudent) { return this->age < anotherStudent.age; } void sayHello() override { cout << (hasActiveStatus() ? "Student " : "Person ") << this->name << " says hello." << endl; } void sayHello(Person anotherPerson) override { cout << (hasActiveStatus() ? "Student " : "Person ") << this->name << "says hello to " << anotherPerson.name << endl; } }; int main() { Person bob = Person("bob", 30); Person jon = Person("jon", 20); cout << (bob < jon ? "jon " : "bob ") << "is older" << endl; Student studentBob = Student("bob", 19); Student studentJon = Student("jon", 20); cout << (studentBob.isYounger(studentJon) ? "bob" : "jon") << "is younger" << endl; studentBob.sayHello(); studentBob.sayHello(jon); bob.sayHello(); bob.sayHello(jon); return 0; }
import { Entity } from "../core/entity"; export type Lexeme = `/audio/${string}.mp3`; export type CharacterId = | "chandler" | "joey" | "monica" | "phoebe" | "rachel" | "ross"; export class Character extends Entity<CharacterId> { name: string; shortName: string; photo: `https://${string}`; lexical: { no: Lexeme[]; yes: Lexeme[]; hello: Lexeme[]; }; constructor(init: Partial<Character> = {}) { super(init); this.shortName = init.shortName; this.name = init.name; this.photo = init.photo; this.lexical = { no: [], yes: [], hello: [], ...init.lexical }; } }
import {test as base, request} from "@playwright/test" import ProfilePage from "../pageObjects/profilePage/ProfilePage.js"; import WelcomePage from "../pageObjects/WelcomePage/WelcomePage.js"; import {USERS} from "../data/dict/users.js"; import {STORAGE_STATE_USER_PATH} from "../data/storageState.js"; import GaragePage from "../pageObjects/GaragePage/GaragePage.js"; export const test = base.extend(({ userInfo: USERS.JOE_DOU, userProfilePage: async ({page}, use)=>{ const welcomePage = new WelcomePage(page) await welcomePage.navigate() const popup = await welcomePage.openSignInPopup() await popup.signIn({ email: USERS.JOE_DOU.email, password: USERS.JOE_DOU.password }) const profilePage = new ProfilePage(page) await profilePage.navigate() await use(profilePage) }, userGaragePage: async ({browser}, use)=>{ const ctx = await browser.newContext({ storageState: STORAGE_STATE_USER_PATH }) const page = await ctx.newPage() const garagePage = new GaragePage(page) await garagePage.navigate() await use(garagePage) }, userAPIClient: async ({}, use)=>{ const ctx = await request.newContext({ storageState: STORAGE_STATE_USER_PATH }) await use(ctx) } }))
const UPDATE_NEW_MESSAGE_TEXT = 'UPDATE-NEW-MESSAGE-TEXT'; const SEND_MESSAGE = 'SEND-MESSAGE'; let initialState = { dialogs: [ {id: 1, name: "Dima"}, {id: 2, name: "Eugene"}, {id: 3, name: "Anna"}, {id: 4, name: "Mike"}, {id: 5, name: "Andrey"} ], messages: [ {id: 1, message: "Hello!"}, {id: 2, message: "Hi!"}, {id: 3, message: "Buy!"}, {id: 4, message: "Ok!"} ], newMessageText: "" }; const dialogsReducer = (state = initialState, action) => { switch (action.type) { case 'UPDATE-NEW-MESSAGE-TEXT': { return { ...state, newMessageText: action.newText, }; } case 'SEND-MESSAGE': { let text = state.newMessageText; return { ...state, newMessageText: "", messages: [...state.messages, {id: 6, message: text}], }; } default: return state; } }; export const sendMessageCreator = () => ({type: SEND_MESSAGE}); export const updateNewMessageTextCreator = (text) => ({type: UPDATE_NEW_MESSAGE_TEXT, newText: text}); export default dialogsReducer;
<html> <head> <title>video lab</title> <style> button:hover{ color: green; } </style> <script src = "d3.js"></script> </head> <body> <div><input type="text"></div> <div>Name: <input type = "date"/></div> <button>click</button> <a href="www.google.com">google</a> <div id = "container"> </div> </body> <script> let container = d3.select("#container"); // select the element in the page by the ID let youth = [] d3.csv("clients.csv").then(loadData); function loadData(clients) { clients = clients.map((c) => { c.BMI = c.Weight / c.Age; return c; }) showBMI(clients); showData(clients); } function ex2(clients){ clients.sort((c1, c2) => d3.ascending(c1.Weight, c2.Weight)); let filteredData = clients.filter((client) => client.Age == 31); let ageList = clients.map((c) => c.Age); console.log(ageList); showData(filteredData); } function showData(clients) { for (let client of clients) { write(client.Name + ", " + client.Weight); } write("--------sum && mean------"); let sum = d3.sum(clients,(c) => c.Weight); let mean = d3.mean(clients, (d) => d.Weight); let extent = d3.extent(clients, (d) => d.Weight); write(sum); write(mean); write(extent); } function showBMI(clients) { for (let client of clients) { write(client.Name + ", " + client.BMI); } } function write(text) { container.append("div").text(text); } </script> </html>
from pathlib import Path import os import time import argparse from sync import Synchronizer import logging import sys def configure_parser() -> argparse.ArgumentParser: """ Configure the parser @return: argparse.ArgumentParser object """ parser = argparse.ArgumentParser(description="Veeam Folder Synchronizer") parser.add_argument("-s", "--source", help="Source folder to perform replica.", required=True, type=str) parser.add_argument("-r", "--replica", help="replica folder path.",required=True, type=str) parser.add_argument("-l", "--log", help="Log file path.", required=True, type=str) parser.add_argument("-i", "--interval", help="Interval in seconds. Default is 60s.", required=False, default=60, type=int) return parser def configure_logger(log_path: Path, log_name: str) -> logging.Logger: """ Configure the logger If a log file does not exist on given path, it will be created @param log_path: The pathlib.Path Path to the log file. If the file does not exist, it will be created @param log_name: str The name of the logger @return: logging.Logger object """ logger = logging.getLogger(log_name) logging.basicConfig(filename=log_path, encoding='utf-8', level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(logging.INFO) stdout_handler.setFormatter(logging.Formatter("\n%(asctime)s - %(levelname)s - %(message)s")) logger.addHandler(stdout_handler) return logger def main() -> None: """ Main function """ parser = configure_parser() args = parser.parse_args() source = Path(args.source) replica = Path(args.replica) log = Path(args.log) logger = configure_logger(log_path=log, log_name="Sync") if not source.exists(): pritn("\nERROR - Source folder does not exist") return if not replica.exists(): print("\nERROR - replica folder does not exist") return logger.info("Starting Veeam Folder Synchronizer") logger.info(f"\nSource: {source}\nreplica: {replica}\nInterval: {args.interval}\nLog: {log}\n") while True: sync = Synchronizer(source, replica, logger) sync.synchronize() time.sleep(args.interval) if __name__ == "__main__": main()
import PageTitle from '../../../common/PageTitle' import PrimaryButton from '../../../common/buttons/PrimaryButton' export default function Verify() { const LabelStyle = "block text-sm font-medium leading-6" const LabelDescriptionStyle = "text-sm leading-6 text-gray-500 mb-2" return ( <div className="p-20 w-3/5"> <PageTitle title="Verify" /> {/* Section: Basic info */} {/* Grid parent */} <div className="mt-10 grid gap-x-6 gap-y-8 grid-cols-6"> {/* Grid item Row 1: First & Last name */} {/* Legal First name */} <div className="col-span-3"> <label htmlFor="first-name" className={LabelStyle}>Legal First name</label> <div className="mt-2"> <input type="text" name="first-name" id="first-name" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* Legal Last name */} <div className="col-span-3"> <label htmlFor="last-name" className={LabelStyle}>Legal Last name</label> <div className="mt-2"> <input type="text" name="last-name" id="last-name" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* Grid item Row 2: DoB & Phone Number */} {/* DoB */} <div className="col-span-3"> <label htmlFor="dob" className={LabelStyle}>Date of birth</label> <div className="mt-2"> <input id="dob" name="dob" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* Phone Number */} <div className="sm:col-span-3"> <label htmlFor="phone" className={LabelStyle}>Phone Number</label> <div className="mt-2"> <input id="phone" name="phone" type="email" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* Grid item Row 3: Country */} <div className="sm:col-span-3"> <label htmlFor="country" className={LabelStyle}>Country</label> <div className="mt-2"> <select id="country" name="country" autoComplete="country-name" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:max-w-xs sm:text-sm sm:leading-6" > <option>United States</option> <option>Canada</option> <option>Mexico</option> </select> </div> </div> {/* Grid item Row 4: City, State/Province, Zip/Postal code */} {/* City */} <div className="sm:col-span-2 sm:col-start-1"> <label htmlFor="city" className={LabelStyle}>City</label> <div className="mt-2"> <input type="text" name="city" id="city" autoComplete="address-level2" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* State */} <div className="sm:col-span-2"> <label htmlFor="region" className={LabelStyle}>State / Province</label> <div className="mt-2"> <input type="text" name="region" id="region" autoComplete="address-level1" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* ZIP */} <div className="sm:col-span-2"> <label htmlFor="postal-code" className={LabelStyle}>ZIP / Postal code</label> <div className="mt-2"> <input type="text" name="postal-code" id="postal-code" autoComplete="postal-code" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> {/* Grid item Row 5: Street Address */} <div className="col-span-full"> <label htmlFor="street-address" className={LabelStyle}>Street address</label> <div className="mt-2"> <input type="text" name="street-address" id="street-address" autoComplete="street-address" className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> </div> {/* Divider */} <div className="mt-20 mb-20 my-4 border-t border-gray-300"></div> {/* Section: Verification */} {/* Funds Recipient Verification */} <div className="mt-10 mb-10"> <div className={LabelStyle}>Funds Recipient Verification</div> <div className={LabelDescriptionStyle}>The campaign owner must be verified to launch the campaign. ID verification will be done with a third party.</div> <PrimaryButton name="VERIFY YOUR ID" /> </div> {/* Bank Information */} <div className="mb-10"> <div className="col-span-full"> <label htmlFor="account" className={LabelStyle}>Bank Information</label> <div className={LabelDescriptionStyle}>Fill out your bank account information. Learn more about payouts.</div> <div className="mt-2"> <input type="text" name="account" id="account" placeholder='IBAN XX00000000000000000000' className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> <div className="col-span-full mt-2 mb-5"> <div className={LabelDescriptionStyle}>Retype account number</div> <div className="mt-2"> <input type="text" name="account" id="account" placeholder='IBAN XX00000000000000000000' className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> <PrimaryButton name="SAVE BANK INFORMATION" /> </div> {/* Divider */} <div className="mt-20 mb-20 my-4 border-t border-gray-300"></div> {/* Section: Statements */} {/* Financial Statements */} <div className="mb-10"> <div className={LabelStyle}>Financial Statements</div> <div className={LabelDescriptionStyle}>Please upload any financial statements that you have from the past. The more information you provide the more successful your campaign will be.</div> </div> {/* Balance Sheet & Income Statement */} <div className="flex justify-between mb-10"> {/* Balance Sheet */} <div> <label htmlFor="campaign-cover-image" className={LabelStyle}>Balance Sheet</label> <p className={LabelDescriptionStyle}>Upload the most current balance sheet.</p> <div className="flex justify-center items-center border bg-white px-6 py-10"> <div className="flex text-sm leading-6 text-gray-600"> {/* Camera Icon */} <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z" /> <path stroke-linecap="round" stroke-linejoin="round" d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0zM18.75 10.5h.008v.008h-.008V10.5z" /> </svg> <span>Upload Sheet</span> </div> </div> </div> {/* Income Statement */} <div> <label htmlFor="campaign-cover-image" className={LabelStyle}>Income Statement</label> <p className={LabelDescriptionStyle}>Upload the most current income statement. </p> <div className="flex justify-center items-center border bg-white px-6 py-10"> <div className="flex text-sm leading-6 text-gray-600"> {/* Camera Icon */} <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" className="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z" /> <path stroke-linecap="round" stroke-linejoin="round" d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0zM18.75 10.5h.008v.008h-.008V10.5z" /> </svg> <span>Upload Figure</span> </div> </div> </div> </div> {/* Action Button */} <div className="flex justify-end"> <PrimaryButton name="SAVE & CONTINUE" /> </div> </div> ) }
import React, { useEffect, useState } from "react"; import { Pie, Column, Line, Area, TinyArea, Gauge, GaugeConfig, } from "@ant-design/plots"; const Charts: React.FC = () => { const [dataArea, setDataArea] = useState([]); const dataPie = [ { type: "分类一", value: 27, }, { type: "分类二", value: 25, }, { type: "分类三", value: 18, }, { type: "分类四", value: 15, }, { type: "分类五", value: 10, }, { type: "其他", value: 5, }, ]; const configPie = { appendPadding: 10, angleField: "value", colorField: "type", radius: 0.8, label: { type: "outer", content: "{name} {percentage}", }, interactions: [ { type: "pie-legend-active", }, { type: "element-active", }, ], }; const dataPlot = [ { type: "salom1", "Sotuvlar-soni": 38, }, { type: "salom2", "Sotuvlar-soni": 52, }, { type: "salom3", "Sotuvlar-soni": 61, }, { type: "salom4", "Sotuvlar-soni": 145, }, { type: "salom5", "Sotuvlar-soni": 48, }, { type: "salom6", "Sotuvlar-soni": 38, }, { type: "salom7", "Sotuvlar-soni": 38, }, { type: "salom8", "Sotuvlar-soni": 38, }, ]; const configPlot = { xField: "type", yField: "Sotuvlar-soni", xAxis: { label: { autoHide: true, autoRotate: false, }, }, }; const dataLine = [ { year: "1991", value: 3, }, { year: "1992", value: 4, }, { year: "1993", value: 3.5, }, { year: "1994", value: 5, }, { year: "1995", value: 4.9, }, { year: "1996", value: 6, }, { year: "1997", value: 7, }, { year: "1998", value: 9, }, { year: "1999", value: 13, }, ]; const configLine = { xField: "year", yField: "value", label: {}, point: { size: 5, shape: "diamond", style: { fill: "white", stroke: "#5B8FF9", lineWidth: 2, }, }, tooltip: { showMarkers: false, }, state: { active: { style: { shadowBlur: 4, stroke: "#000", fill: "red", }, }, }, interactions: [ { type: "marker-active", }, ], }; const configArea = { xField: "Date", yField: "scales", xAxis: { range: [0, 1], tickCount: 5, }, areaStyle: () => { return { fill: "l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff", }; }, }; const asyncFetch = () => { fetch( "https://gw.alipayobjects.com/os/bmw-prod/1d565782-dde4-4bb6-8946-ea6a38ccf184.json" ) .then((response) => response.json()) .then((json) => setDataArea(json)) .catch((error) => { console.log("fetch data failed", error); }); }; const data = [ 264, 417, 438, 887, 309, 397, 550, 575, 563, 430, 525, 592, 492, 467, 513, 546, 983, 340, 539, 243, 226, 192, ]; const config = { height: 60, autoFit: true, smooth: true, areaStyle: { fill: "#d6e3fd", }, }; const configGuage: GaugeConfig = { percent: 0.75, range: { color: "#30BF78", }, indicator: { pointer: { style: { stroke: "#D0D0D0", }, }, pin: { style: { stroke: "#D0D0D0", }, }, }, axis: { label: { formatter(v) { return Number(v) * 100; }, }, subTickLine: { count: 3, }, }, statistic: { content: { formatter: ({ percent }: any) => `Rate: ${(percent * 100).toFixed(0)}%`, style: { color: "rgba(0,0,0,0.65)", fontSize: "48", }, }, }, }; useEffect(() => { asyncFetch(); }, []); return ( <div> <h1>Charts</h1> <Pie data={dataPie} {...configPie} /> <Column data={dataPlot} {...configPlot} /> <Line data={dataLine} {...configLine} /> <Area data={dataArea} {...configArea} /> <TinyArea data={data} {...config} /> <Gauge {...configGuage} /> </div> ); }; export default Charts;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> let arr = [101, 102, 103, 104, 105]; /* 注意for..of 和 for...in的区别 */ for(let i of arr){ console.log(i); // 返回的是value值 } for(let i in arr){ console.log(i); // 返回的是index值 } /* arr[Symbol.iterator]() 数组的 iterator 方法,默认情况下,与 values() 返回值相同, arr[Symbol.iterator] 则会返回 values() 函数。 */ let iterator = arr[Symbol.iterator](); console.log(iterator.next()); // 返回的是一个对象(包含value和done属性) // done属性若为false,说明没有遍历完,若为true则为遍历完成 /* 两种迭代方式 var arr = ['a', 'b', 'c', 'd', 'e']; var eArr = arr[Symbol.iterator](); // 浏览器必须支持 for...of 循环 for (let letter of eArr) { console.log(letter); } var arr = ['a', 'b', 'c', 'd', 'e']; var eArr = arr[Symbol.iterator](); console.log(eArr.next().value); // a console.log(eArr.next().value); // b console.log(eArr.next().value); // c console.log(eArr.next().value); // d console.log(eArr.next().value); // e */ </script> </head> <body> </body> </html>
"use client"; import useSWR,{mutate} from "swr"; import { useState } from "react"; import axios from "axios"; import { useRouter } from "next/navigation"; import Swal from "sweetalert2"; import LoadingSpinner from "@/components/LoadingSpinner"; const fetcher = (url) => fetch(url).then((res) => res.json()); export default function Page({ params }) { const { id } = params; const { data, error, isLoading } = useSWR( `/api/reports/detail/${id}`, fetcher ); if (isLoading) { return ( <main className="flex w-full justify-center h-[80vh] items-center"> <LoadingSpinner /> </main> ); } return ( <main className="flex w-full justify-center"> <Form data={data} id={id} /> </main> ); } const Form = ({ data, id }) => { const router = useRouter(); const handleSubmit = async (e) => { e.preventDefault(); const data = formData; Swal.fire({ title: "Apakah kamu yakin ingin mengubah transaksi ini?", showDenyButton: true, confirmButtonText: "Ya", denyButtonText: "Tidak", customClass: { actions: "my-actions", confirmButton: "order-2", denyButton: "order-3", }, }).then(async (result) => { if (result.isConfirmed) { try { const response = await axios.put(`/api/reports/detail/${id}`, data); if (response.status === 200) { Swal.fire({ icon: "success", title: "Berhasil", text: "Transaksi berhasil dirubah", }); } setTimeout(() => { router.push("/"); }, 1500); mutate(`/api/reports/detail/${id}`); } catch (error) { Swal.fire({ icon: "error", title: "Gagal", text: `Transaksi gagal dirubah karena ${error.message}`, }); } } else if (result.isDenied) { Swal.fire("Changes are not saved", "", "info"); } }); }; const [formData, setFormData] = useState({ date: data?.data?.Transaction.date, description: data?.data?.Transaction.description, amount: data?.data?.Transaction.amount, status: data?.data?.Transaction.status, receiver: data?.data?.Transaction.receiver, jk: data?.data?.Transaction.jk, no_telp: data?.data?.Transaction.no_telp, address: data?.data?.Transaction.address, }); return ( <section className="max-w-[854px] w-full py-8 px-2"> <h2 className="pb-1 border-b-2 border-zinc-950 w-full mb-4 font-semibold"> Edit Transaksi </h2> <div className="my-4 w-full bg-zinc-800 rounded-md"> <form className="w-full p-4 rounded-md bg-zinc-600" onSubmit={handleSubmit} > <div className="flex flex-col mb-4"> <label htmlFor="date" className="text-sm text-white font-semibold"> Tanggal </label> <input type="date" name="date" id="date" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.date} onChange={(e) => setFormData({ ...formData, date: e.target.value }) } /> </div> <div className="flex flex-col mb-4"> <label htmlFor="description" className="text-sm text-white font-semibold" > Deskripsi </label> <textarea name="description" id="description" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value }) } ></textarea> </div> <div className="flex flex-col mb-4"> <label htmlFor="amount" className="text-sm text-white font-semibold" > Nominal </label> <input type="number" name="amount" id="amount" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.amount} onChange={(e) => setFormData({ ...formData, amount: e.target.value }) } /> </div> <div className="flex flex-col mb-4"> <label htmlFor="status" className="text-sm text-white font-semibold" > Status </label> <select name="status" id="status" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.status} onChange={(e) => setFormData({ ...formData, status: e.target.value }) } > <option value="">Pilih Status</option> <option value="debit" selected={formData.status == "debit"}> Debit </option> <option value="kredit" selected={formData.status == "kredit"}> Kredit </option> {/* Add more options as needed */} </select> </div> <div className="flex flex-col mb-4"> <label htmlFor="receiver" className="text-sm text-white font-semibold" > Penerima </label> <input type="text" name="receiver" id="receiver" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.receiver} onChange={(e) => setFormData({ ...formData, receiver: e.target.value }) } /> </div> {/* jk */} <div className="flex flex-col mb-4"> <label htmlFor="jk" className="text-sm text-white font-semibold"> Jenis Kelamin </label> <select name="status" id="status" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.jk} onChange={(e) => setFormData({ ...formData, jk: e.target.value }) } > <option value="">Pilih Jenis Kelamin</option> <option value="L" selected={formData.jk == "L" ? true: false}> Laki-Laki </option> <option value="P" selected={formData.jk == "P" ? true: false}> Perempuan </option> {/* Add more options as needed */} </select> </div> <div className="flex flex-col mb-4"> <label htmlFor="jk" className="text-sm text-white font-semibold"> No Telepon </label> <input type="text" name="no_telp" id="no_telp" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.no_telp} onChange={(e) => setFormData({ ...formData, no_telp: e.target.value }) } /> </div> <div className="flex flex-col mb-4"> <label htmlFor="address" className="text-sm text-white font-semibold" > Alamat </label> <textarea name="address" id="address" className="border border-gray-300 text-zinc-950 p-2 rounded-md focus:outline-none focus:border-zinc-950" value={formData.address} onChange={(e) => setFormData({ ...formData, address: e.target.value }) } ></textarea> </div> <div className="flex w-full gap-4"> <button type="submit" className="bg-blue-600 rounded-md w-1/2 py-1 text-white font-semibold" > Edit Transaksi </button> {/* back */} <button type="button" className="bg-red-600 rounded-md w-1/2 py-1 text-white font-semibold" onClick={() => router.push("/")} > Kembali </button> </div> </form> </div> </section> ); };
import { Component, OnInit } from '@angular/core'; import { MatSidenavModule } from '@angular/material/sidenav' import { MovieService } from '../services/movie.service'; import { PrimaryImage, Title } from '../models/title.model'; import { MatCardModule } from '@angular/material/card' import { CommonModule } from '@angular/common'; import {MatButtonModule} from '@angular/material/button'; import {MatDialog, MatDialogModule} from '@angular/material/dialog'; import { UpdateTitleComponent } from '../components/update-title/update-title.component'; // import { UpdateTitleComponent } from '../components/update-title/update-title.component'; @Component({ selector: 'app-main', standalone: true, imports: [ // components // UpdateTitleComponent, //modules MatSidenavModule, CommonModule, MatCardModule, MatButtonModule // MatDialogModule ], templateUrl: './main.component.html', styleUrl: './main.component.css' }) export class MainComponent implements OnInit { constructor( private _movieService: MovieService, public dialog: MatDialog){} titles: Array<Title> = [] ngOnInit(): void { this._movieService.test().subscribe({ next: this.getTestRespose.bind(this), error: this.getErrorResponse.bind(this) }) } getTestRespose(response: any){ if(response.results) { // this.titles = response.results response.results.forEach((e: any) => { let primaryImage if(e.primaryImage) { primaryImage = { id: e.primaryImage.id, url: e.primaryImage.url, width: e.primaryImage.width, height: e.primaryImage.height } as PrimaryImage } let title = { id: e.id, primaryImage, titleText: e.titleText.text } as Title this.titles.push(title) }); } } getErrorResponse(error: any) { console.error(error) } editTitle(title: Title) { const dialogRef = this.dialog.open(UpdateTitleComponent, { width: '60%', data: title, }); dialogRef.afterClosed().subscribe(result => { console.log(`Dialog result: ${result}`); }); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateForumRepliesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('forum_replies', function (Blueprint $table) { $table->id(); $table->bigInteger('thread_id')->unsigned(); $table->bigInteger('quote_id')->unsigned()->nullable(); $table->bigInteger('creator_id')->unsigned(); $table->text('body'); $table->boolean('is_deleted')->default(false); $table->timestamps(); $table->foreign('thread_id')->references('id')->on('forum_threads')->onDelete('cascade'); $table->foreign('quote_id')->references('id')->on('forum_replies')->onDelete('set null'); $table->foreign('creator_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('forum_replies'); } }
// // Image.swift // SkyLight // // Created by Luke Van In on 2022/12/19. // import Foundation import Metal final class Image<T> { let size: IntegralSize private let texture: MTLTexture private let slice: Int private let buffer: UnsafeMutableBufferPointer<T> init(texture: MTLTexture, label: String, slice: Int, defaultValue: T) { self.size = IntegralSize(width: texture.width, height: texture.height) self.slice = slice self.texture = texture self.texture.label = label self.buffer = { let capacity = texture.width * texture.height let buffer = UnsafeMutableBufferPointer<T>.allocate( capacity: capacity ) buffer.initialize(repeating: defaultValue) return buffer }() } deinit { buffer.deallocate() } func updateFromTexture() { let region = MTLRegion( origin: MTLOrigin( x: 0, y: 0, z: 0 ), size: MTLSize( width: texture.width, height: texture.height, depth: 1 ) ) let bytesPerComponent = MemoryLayout<T>.stride let bytesPerRow = bytesPerComponent * texture.width let bytesPerImage = bytesPerRow * texture.height let pointer = UnsafeMutableRawPointer(buffer.baseAddress)! texture.getBytes( pointer, bytesPerRow: bytesPerRow, bytesPerImage: bytesPerImage, from: region, mipmapLevel: 0, slice: slice ) } subscript(x: Int, y: Int) -> T { get { buffer[offset(x: x, y: y)] } set { buffer[offset(x: x, y: y)] = newValue } } private func offset(x: Int, y: Int) -> Int { precondition(x >= 0 && y >= 0 && x <= texture.width - 1 && y <= texture.height - 1) return (y * texture.width) + x } } //extension Image where T == Float { // // func getGradient(x: Int, y: Int) -> Gradient { // #warning("FIXME: IPOL implementation seems to swap dx and dy") // let g = getGradientVector(x: x, y: y) // return Gradient( // orientation: atan2(g.x, g.y), // magnitude: sqrt(g.x * g.x + g.y * g.y) // ) // } // // func getGradientVector(x: Int, y: Int) -> SIMD2<Float> { // let px: Float = self[x + 1, y] // let mx: Float = self[x - 1, y] // let py: Float = self[x, y + 1] // let my: Float = self[x, y - 1] // return SIMD2<Float>(x: (px - mx) * 0.5, y: (py - my) * 0.5) // } //}
package controllers_test import ( "bytes" "database/sql" "encoding/json" "net/http" "net/http/httptest" "testing" productController "github.com/eneassena10/estoque-go/internal/domain/product/controllers" userController "github.com/eneassena10/estoque-go/internal/domain/user/controllers" service_user "github.com/eneassena10/estoque-go/internal/domain/user/service" config "github.com/eneassena10/estoque-go/internal/configuracao" "github.com/eneassena10/estoque-go/pkg/store" "github.com/gin-gonic/gin" "github.com/stretchr/testify/assert" ) type ResponseContent struct { Code int Data interface{} Error string } type Response struct { Code int Data interface{} } func CreateServer(method, url, body string) *httptest.ResponseRecorder { gin.SetMode(gin.TestMode) router := gin.Default() productNamePath := "../products.json" fileStore := store.NewFileStore(productNamePath) handlers := productController.NewControllers(fileStore, &sql.DB{}) service := service_user.NewServiceUser(fileStore) userController := userController.NewUserController(service) app := config.NewApp(fileStore, handlers, userController) app.InitApp(router) req, rr := CreateRequestTest(method, url, body) router.ServeHTTP(rr, req) return rr } func CreateRequestTest(method string, url string, body string) (*http.Request, *httptest.ResponseRecorder) { req := httptest.NewRequest(method, url, bytes.NewBuffer([]byte(body))) req.Header.Add("Content-Type", "application/json") return req, httptest.NewRecorder() } func TestControllers_GetProductsAll(t *testing.T) { t.Run("GetProductsAll", func(t *testing.T) { uri := "/products/list" rr := CreateServer(http.MethodGet, uri, "") responseContent := Response{} _ = json.Unmarshal(rr.Body.Bytes(), &responseContent) assert.Len(t, responseContent.Data, 5) assert.EqualValues(t, responseContent.Code, 200) }) }
# Creating a R Shiny web app # Author: Niuni Amarasinghe # ***** LIBRARIES ***** install.packages("httpuv") library(shiny) install.packages("shinydashboard") library(shinydashboard) library(plotly) # for widgets library(tidyverse) install.packages("DataExplorer") library(DataExplorer) library(corrplot) library(sf) library(tmap) install.packages("shinyWidgets") library(shinyWidgets) # LOAD IN DATASETS raw_data <- read.csv("raw_data/deprivation_and_mobility.csv") # using the mutate() function to calculate percentages from raw data london <- mutate(raw_data, percentage_not_deprived = (Households_not_deprived/Deprivation*100), percentage_deprived = (100 - percentage_not_deprived), percentage_home = (Work_from_home/Total_methods_travel)*100, percentage_public = (Public_transport/Total_methods_travel)*100, percentage_car = (Car_or_van/Total_methods_travel)*100, percentage_other = (Other_travel/Total_methods_travel)*100) # using the select() function to keep only relevant data london <- select(london, "GEO_CODE", "GEO_LABEL", "percentage_deprived", "percentage_home", "percentage_public", "percentage_car", "percentage_other") View(london) correlation_tests <- select(london, percentage_deprived, percentage_home, percentage_public, percentage_car, percentage_other) matrix <- cor(correlation_tests) # Produce a matrix holding correlations general_health_scores <- read_csv("raw_data/general_health_scores.csv", col_types = cols(very_bad_health = col_integer(), total_health = col_integer(), very_good_health = col_integer(), good_health = col_integer(), fair_health = col_integer(), bad_health = col_integer())) View(general_health_scores) # load in the London MSOAs shapefile london_MSOA_shp <- st_read("raw_data/boundaries/MSOA_2011_London_gen_MHW.shp") # select relevant columns colnames(london_MSOA_shp) london_MSOA_shp <- select(london_MSOA_shp, "MSOA11CD", "LAD11CD", "LAD11NM", "geometry") View(london_MSOA_shp) # read in London Boroughs shapefile london_boroughs_shp <- st_read("raw_data/boundaries/London_Borough_Excluding_MHW.shp") # select relevant columns colnames(london_boroughs_shp) london_boroughs_shp <- select(london_boroughs_shp, "NAME", "GSS_CODE", "geometry") View(london_boroughs_shp) health_sdf <- merge(general_health_scores, london_MSOA_shp, by.x = "GEO_CODE", by.y = "MSOA11CD") health_sdf <- st_sf(health_sdf) View(health_sdf) # ***** USER INTERFACE ***** # Define User Interface (UI) for application that draws a histogram ui <- dashboardPage( skin = "red", dashboardHeader(title = "Deprivation, Mobility and Health in R Shiny"), dashboardSidebar( sidebarMenu( menuItem("London", tabName = "Mobility", icon = icon("car")), menuItem("Health scores", tabName = "HealthScores", icon = icon("heartbeat")) ) ), dashboardBody( tabItems( tabItem("Mobility", box(plotOutput("corrplot"), width = 15), box( width = 4, selectInput("mobilityFeatures", "Method of transport:", c("percentage_home", "percentage_public", "percentage_car", "percentage_other")) ), dataTableOutput("mobilityTable") ), tabItem("HealthScores", box(plotOutput("health"), width = 15), box( width = 4, selectInput("healthFeatures", "Type of health score:", c("very_bad_health", "bad_health", "very_good_health", "good_health", "fair_health")) )) ) ) ) # ***** SERVER ***** # Define server logic required to draw a histogram server <- function(input, output) { output$corrplot <- renderPlot({ plot(london$percentage_deprived, london[[input$mobilityFeatures]], xlab = "Percentage of deprived households", ylab = "Method of transport") }) output$mobilityTable <- renderDataTable(london) output$health <- renderPlot({ qtm(health_sdf, fill= input$healthFeatures, fill.palette = "Pastel1", border = "white", fill.title = "Total count") + tm_shape(london_boroughs_shp) + tm_borders(col = "black") + tm_layout( title = "Distribution of health scores", bg.color = "grey85", legend.outside = FALSE, legend.title.size = 0.75, legend.title.fontface = 2) + tm_compass(position = c("RIGHT", "TOP"), size = 2, type = "rose") + tm_scale_bar(breaks = c(0, 5, 10, 15, 20), position = c("LEFT", "BOTTOM"), size = 0.5) })} # ***** RUN WEB APP ***** # Run the application shinyApp(ui = ui, server = server)
import { LessonType } from '@/features/lessons/lesson-types'; import Link from 'next/link'; type LessonCardProps = { lesson: LessonType; }; const LessonCard = ({ lesson }: LessonCardProps) => { return ( <Link href={`/lessons/${lesson.id}`} className="w-full h-full max-w-[300px] p-4 flex flex-col gap-2 shadow-md rounded-md transition-all hover:shadow-lg" > <h3 className="text-xl text-center line-clamp-2">{lesson.title}</h3> <p className="line-clamp-6">{lesson.description}</p> </Link> ); }; export default LessonCard;
public class Calculator { public double n1 {get; set;} public double n2 {get; set;} public double res {get; set;} public string v1 {get; set;} public string v2 {get; set;} public string vres {get; set;} public void add() { try { n1 = double.valueOf(v1); n2 = double.valueOf(v2); res = n1 + n2; vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void subtract() { try { n1 = double.valueOf(v1); n2 = double.valueOf(v2); res = n1 - n2; vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void multiply() { try { n1 = double.valueOf(v1); n2 = double.valueOf(v2); res = n1 * n2; vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void divide() { try { n1 = double.valueOf(v1); n2 = double.valueOf(v2); if (n2 == 0) { vres = 'Cannot Divide By Zero!'; return; } res = n1 / n2; vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void x_to_y() { try { n1 = double.valueOf(v1); n2 = double.valueOf(v2); res = Math.pow(n1, n2); vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void clear() { v1 = ''; v2 = ''; vres = '0.0'; } public void sin() { try { n1 = double.valueOf(v1); res = Math.sin(n1); vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void cos() { try { n1 = double.valueOf(v1); res = Math.cos(n1); vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } public void tan() { try { n1 = double.valueOf(v1); res = Math.tan(n1); vres = string.valueOf(res); } catch (Exception e) { vres = 'Enter Valid Input!'; } } }
/* Copyright (c) 2017, John Lenz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of John Lenz, Black Maple Software, SeedTactics, nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Xunit; using Microsoft.Data.Sqlite; using BlackMaple.MachineFramework; using FluentAssertions; using System.Collections.Immutable; namespace MachineWatchTest { public class InspectionTest : IDisposable { private RepositoryConfig _repoCfg; private IRepository _insp; public InspectionTest() { _repoCfg = RepositoryConfig.InitializeSingleThreadedMemoryDB( new SerialSettings() { ConvertMaterialIDToSerial = (id) => id.ToString() } ); _insp = _repoCfg.OpenConnection(); } public void Dispose() { _repoCfg.CloseMemoryConnection(); } [Fact] public void Counts() { List<InspectCount> cnts = new List<InspectCount>(); InspectCount cnt = new InspectCount() { Counter = "Test1", Value = 15, LastUTC = DateTime.Parse("1/5/2009 4:23:12 GMT"), }; cnts.Add(cnt); cnt = new InspectCount() { Counter = "Test2", Value = 1563, LastUTC = DateTime.Parse("1/15/2009 3:35:24 GMT"), }; cnts.Add(cnt); cnt = new InspectCount() { Counter = "Test3", Value = 532, LastUTC = DateTime.Parse("2/12/2009 15:03:55 GMT"), }; cnts.Add(cnt); _insp.SetInspectCounts(cnts); IList<InspectCount> loaded = _insp.LoadInspectCounts(); Assert.Equal(loaded, cnts); } [Fact] public void Frequencies() { var freqProg = new PathInspection() { InspectionType = "insp1", Counter = "counter1", RandomFreq = 0.5, MaxVal = 0, TimeInterval = TimeSpan.FromHours(100) }; for (int i = 0; i < 100; i++) _insp.MakeInspectionDecisions(i, 1, new[] { freqProg }); int numInsp = 0; for (int i = 0; i < 100; i++) { if (FindDecision(i, "insp1", "counter1")) numInsp += 1; } Assert.True(numInsp > 0); Assert.True(numInsp < 100); } [Fact] public void Inspections() { var now = DateTime.UtcNow; //set the count as zero, otherwise it chooses a random InspectCount cnt = new InspectCount() { Counter = "counter1", Value = 0, LastUTC = DateTime.UtcNow.AddHours(-11).AddMinutes(2), }; _insp.SetInspectCounts(new InspectCount[] { cnt }); //set up a program var inspProg = new PathInspection() { InspectionType = "insp1", Counter = "counter1", MaxVal = 3, RandomFreq = 0, TimeInterval = TimeSpan.FromHours(11) }; //the lastutc should be 2 minutes too short, so only inspections from the counter should take place _insp.MakeInspectionDecisions(1, 2, new[] { inspProg }, now); _insp.MakeInspectionDecisions(1, 2, new[] { inspProg }, now); // twice should have no effect CheckDecision(1, "insp1", "counter1", false, now); CheckCount("counter1", 1); CheckLastUTC("counter1", cnt.LastUTC); _insp.MakeInspectionDecisions(2, 2, new[] { inspProg }, now); CheckDecision(2, "insp1", "counter1", false, now); CheckCount("counter1", 2); CheckLastUTC("counter1", cnt.LastUTC); _insp.MakeInspectionDecisions(3, 2, new[] { inspProg }, now); CheckDecision(3, "insp1", "counter1", true, now); CheckCount("counter1", 0); CheckLastUTC("counter1", DateTime.UtcNow); //now check lastutc. set lastutc to be 2 minutes cnt = new InspectCount() { Counter = "counter1", Value = 0, LastUTC = DateTime.UtcNow.AddHours(-11).AddMinutes(-2), }; _insp.SetInspectCounts(new InspectCount[] { cnt }); _insp.MakeInspectionDecisions(4, 2, new[] { inspProg }); CheckDecision(4, "insp1", "counter1", true, now); CheckLastUTC("counter1", now); CheckDecisions(new[] { 1L, 2, 3, 4 }, "insp1", "counter1", new[] { false, false, true, true }, now); } [Fact] public void ForcedInspection() { DateTime now = DateTime.UtcNow; //set up a program var inspProg = new PathInspection() { InspectionType = "insp1", Counter = "counter1", MaxVal = 13, RandomFreq = 0, TimeInterval = TimeSpan.FromHours(11) }; //set the count as zero, otherwise it chooses a random InspectCount cnt = new InspectCount() { Counter = "counter1", Value = 0, LastUTC = DateTime.UtcNow.AddHours(-10), }; _insp.SetInspectCounts(new InspectCount[] { cnt }); //try making a decision _insp.ForceInspection(2, "insp1"); _insp.MakeInspectionDecisions(1, 1, new[] { inspProg }, now); _insp.MakeInspectionDecisions(1, 1, new[] { inspProg }, now); CheckDecision(1, "insp1", "counter1", false, now); CheckCount("counter1", 1); _insp.MakeInspectionDecisions(2, 1, new[] { inspProg }, now); CheckDecision(2, "insp1", "counter1", true, now, true); CheckCount("counter1", 2); } [Fact] public void NextPiece() { DateTime now = DateTime.UtcNow; var insps = ImmutableList.Create( new PathInspection() { InspectionType = "insp1", Counter = "counter1", MaxVal = 3, RandomFreq = 0, TimeInterval = TimeSpan.FromHours(11) } ); //set the count as zero, otherwise it chooses a random InspectCount cnt = new InspectCount() { Counter = "counter1", Value = 0, LastUTC = DateTime.UtcNow.AddHours(-10), }; _insp.SetInspectCounts(new InspectCount[] { cnt }); PalletLocation palLoc = new PalletLocation(PalletLocationEnum.Machine, "MC", 1); _insp.NextPieceInspection(palLoc, "insp1"); _insp.CheckMaterialForNextPeiceInspection(palLoc, 1); CheckCount("counter1", 0); _insp.MakeInspectionDecisions(1, 1, insps, now); CheckCount("counter1", 1); CheckDecision(1, "insp1", "counter1", true, now, true); } [Fact] public void TranslateCounter() { var counter = "counter1-" + PathInspection.LoadFormatFlag(1) + "-" + PathInspection.UnloadFormatFlag(1) + "-" + PathInspection.LoadFormatFlag(2) + "-" + PathInspection.UnloadFormatFlag(2) + "-" + PathInspection.PalletFormatFlag(1) + "-" + PathInspection.PalletFormatFlag(2) + "-" + PathInspection.StationFormatFlag(1, 1) + "-" + PathInspection.StationFormatFlag(1, 2) + "-" + PathInspection.StationFormatFlag(2, 1) + "-" + PathInspection.StationFormatFlag(2, 2); var expandedCounter1 = "counter1-1-2-3-4-1-2-10-11-12-13"; var expandedCounter2 = "counter1-6-8-7-9-5-4-15-16-18-19"; //set the count as zero, otherwise it chooses a random var cnt = new InspectCount() { Counter = expandedCounter1, Value = 0, LastUTC = DateTime.UtcNow.AddHours(-10), }; var cnt2 = new InspectCount() { Counter = expandedCounter2, Value = 0, LastUTC = DateTime.UtcNow.AddHours(-10), }; _insp.SetInspectCounts(new[] { cnt, cnt2 }); var mat1Proc1 = new[] { new LogMaterial(1, "job1", 1, "part1", 2, "", "", "") }; var mat1Proc2 = new[] { new LogMaterial(1, "job1", 2, "part1", 2, "", "", "") }; var mat2Proc1 = new[] { new LogMaterial(2, "job1", 1, "part1", 2, "", "", "") }; var mat2Proc2 = new[] { new LogMaterial(2, "job1", 2, "part1", 2, "", "", "") }; _lastCycleTime = DateTime.UtcNow.AddDays(-1); AddCycle(mat1Proc1, 1, LogType.LoadUnloadCycle, 1); AddCycle(mat2Proc1, 5, LogType.LoadUnloadCycle, 6); AddCycle(mat1Proc1, 1, LogType.MachineCycle, 10); AddCycle(mat2Proc1, 5, LogType.MachineCycle, 15); AddCycle(mat1Proc1, 1, LogType.MachineCycle, 11); AddCycle(mat2Proc1, 5, LogType.MachineCycle, 16); AddCycle(mat1Proc1, 1, LogType.LoadUnloadCycle, 2); AddCycle(mat2Proc1, 5, LogType.LoadUnloadCycle, 8); AddCycle(mat1Proc2, 2, LogType.LoadUnloadCycle, 3); AddCycle(mat2Proc2, 4, LogType.LoadUnloadCycle, 7); AddCycle(mat1Proc2, 2, LogType.MachineCycle, 12); AddCycle(mat2Proc2, 4, LogType.MachineCycle, 18); AddCycle(mat1Proc2, 2, LogType.MachineCycle, 13); AddCycle(mat2Proc2, 4, LogType.MachineCycle, 19); AddCycle(mat1Proc2, 2, LogType.LoadUnloadCycle, 4); AddCycle(mat2Proc2, 4, LogType.LoadUnloadCycle, 9); var inspProg = new PathInspection() { InspectionType = "insp1", Counter = counter, MaxVal = 10, RandomFreq = 0, TimeInterval = TimeSpan.FromDays(2) }; var now = DateTime.UtcNow; _insp.MakeInspectionDecisions(1, 2, new[] { inspProg }, now); CheckDecision(1, "insp1", expandedCounter1, false, now); Assert.Equal(2, _insp.LoadInspectCounts().Count); CheckCount(expandedCounter1, 1); CheckCount(expandedCounter2, 0); ExpectPathToBe( 1, "insp1", new[] { new MaterialProcessActualPath() { MaterialID = 1, Process = 1, Pallet = 1, LoadStation = 1, Stops = ImmutableList.Create( new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 10 }, new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 11 } ), UnloadStation = 2, }, new MaterialProcessActualPath() { MaterialID = 1, Process = 2, Pallet = 2, LoadStation = 3, Stops = ImmutableList.Create( new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 12 }, new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 13 } ), UnloadStation = 4, } } ); _insp.MakeInspectionDecisions(2, 2, new[] { inspProg }); CheckDecision(2, "insp1", expandedCounter2, false, now); ExpectPathToBe( 2, "insp1", new[] { new MaterialProcessActualPath() { MaterialID = 2, Process = 1, Pallet = 5, LoadStation = 6, Stops = ImmutableList.Create( new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 15 }, new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 16 } ), UnloadStation = 8, }, new MaterialProcessActualPath() { MaterialID = 2, Process = 2, Pallet = 4, LoadStation = 7, Stops = ImmutableList.Create( new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 18 }, new MaterialProcessActualPath.Stop() { StationName = "MC", StationNum = 19 } ), UnloadStation = 9, } } ); Assert.Equal(2, _insp.LoadInspectCounts().Count); CheckCount(expandedCounter1, 1); CheckCount(expandedCounter2, 1); } [Fact] public void WithoutInspectProgram() { DateTime now = DateTime.UtcNow; var mat1 = new EventLogMaterial() { MaterialID = 1, Process = 1, Face = "" }; var mat2 = new EventLogMaterial() { MaterialID = 2, Process = 1, Face = "" }; _insp.ForceInspection(mat1, "myinspection", true, now); _insp.ForceInspection(mat2, "myinspection", false, now); _insp.MakeInspectionDecisions(1, 1, null, now); _insp.MakeInspectionDecisions(2, 1, null, now); CheckDecision(1, "myinspection", "", true, now, true); CheckDecision(2, "myinspection", "", false, now, true); CheckDecisions(new[] { 1L, 2L }, "myinspection", "", new[] { true, false }, now, true); } private DateTime _lastCycleTime; private void AddCycle(LogMaterial[] mat, int pal, LogType loc, int statNum) { string name = loc == LogType.MachineCycle ? "MC" : "Load"; ((Repository)_insp).AddLogEntryFromUnitTest( new LogEntry(-1, mat, pal, loc, name, statNum, "", true, _lastCycleTime, "") ); _lastCycleTime = _lastCycleTime.AddMinutes(15); ((Repository)_insp).AddLogEntryFromUnitTest( new LogEntry(-1, mat, pal, loc, name, statNum, "", false, _lastCycleTime, "") ); _lastCycleTime = _lastCycleTime.AddMinutes(15); } private void CheckDecision( long matID, string iType, string counter, bool inspect, DateTime now, bool forced = false ) { CheckDecision(matID, _insp.LookupInspectionDecisions(matID), iType, counter, inspect, now, forced); } private void CheckDecisions( IReadOnlyList<long> mats, string iType, string counter, IReadOnlyList<bool> inspect, DateTime now, bool forced = false ) { var insps = _insp.LookupInspectionDecisions(mats); insps.Keys.Should().BeEquivalentTo(mats); for (var i = 0; i < mats.Count; i++) { CheckDecision(mats[i], insps[mats[i]], iType, counter, inspect[i], now, forced); } } private void CheckDecision( long matID, IReadOnlyList<Decision> decisions, string iType, string counter, bool inspect, DateTime now, bool forced = false ) { int decisionCnt = 0; int forcedCnt = 0; foreach (var d in decisions) { if (d.InspType == iType) { d.Should() .BeEquivalentTo( new Decision() { MaterialID = matID, InspType = iType, Counter = d.Forced ? "" : counter, Inspect = inspect, Forced = d.Forced, CreateUTC = now }, options => options .ComparingByMembers<Decision>() .Using<DateTime>( ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, TimeSpan.FromSeconds(4)) ) .WhenTypeIs<DateTime>() ); if (d.Forced) forcedCnt += 1; else decisionCnt += 1; } } Assert.Equal(1, decisionCnt); Assert.Equal(forcedCnt, forced ? 1 : 0); var log = _insp.GetLogForMaterial(matID); int inspEntries = 0; int forceEntries = 0; foreach (var entry in _insp.GetLogForMaterial(matID)) { if (entry.LogType == LogType.Inspection && entry.ProgramDetails["InspectionType"] == iType) { inspEntries += 1; entry.EndTimeUTC.Should().BeCloseTo(now, TimeSpan.FromSeconds(4)); entry.Program.Should().Be(counter); entry.Result.Should().Be(inspect.ToString()); } else if (entry.LogType == LogType.InspectionForce && entry.Program == iType) { forceEntries += 1; entry.Result.Should().Be(inspect.ToString()); } } inspEntries.Should().Be(1); forceEntries.Should().Be(forced ? 1 : 0); } private void ExpectPathToBe(long matID, string iType, IEnumerable<MaterialProcessActualPath> expected) { bool foundEntry = false; foreach (var entry in _insp.GetLogForMaterial(matID)) { if (entry.LogType == LogType.Inspection && entry.ProgramDetails["InspectionType"] == iType) { foundEntry = true; var path = Newtonsoft.Json.JsonConvert.DeserializeObject<List<MaterialProcessActualPath>>( entry.ProgramDetails["ActualPath"] ); path.Should() .BeEquivalentTo(expected, options => options.ComparingByMembers<MaterialProcessActualPath>()); break; } } Assert.True(foundEntry, "Unable to find inspection path"); } private bool FindDecision(long matID, string iType, string counter) { foreach (var d in _insp.LookupInspectionDecisions(matID)) { if (d.Counter == counter && d.InspType == iType) { return d.Inspect; } } Assert.True(false, "Unable to find counter and inspection type"); return false; } private void CheckCount(string counter, int val) { foreach (var c in _insp.LoadInspectCounts()) { if (c.Counter == counter) { Assert.Equal(val, c.Value); return; } } Assert.True(false, "Unable to find counter " + counter); } private void CheckLastUTC(string counter, DateTime val) { foreach (var c in _insp.LoadInspectCounts()) { if (c.Counter == counter) { if (val == DateTime.MaxValue) Assert.Equal(DateTime.MaxValue, c.LastUTC); else Assert.True(5 >= Math.Abs(val.Subtract(c.LastUTC).TotalMinutes)); return; } } Assert.True(false, "Unable to find counter"); } } }
package hello.springmvc.basic.response; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ResponseViewController { @RequestMapping("/response-view-v1") public ModelAndView responseViewV1() { ModelAndView mav = new ModelAndView("response/hello") .addObject("data", "hello!"); return mav; } @RequestMapping("/response-view-v2") public String responseViewV2(Model model) { model.addAttribute("data", "hello!!"); return "response/hello"; } // HTTP response를 처리하는 로직이 없을 때에만 view template 사용 @RequestMapping("/response/hello") public void responseViewV3(Model model) { model.addAttribute("data", "hello!!!"); } }
import 'server-only'; import { clerkClient, currentUser } from '@clerk/nextjs'; import Stripe from 'stripe'; import { parseError } from './error'; if (!process.env.STRIPE_SECRET_KEY) { throw new Error('Missing STRIPE_SECRET_KEY'); } if (!process.env.NEXT_PUBLIC_SITE_URL) { throw new Error('Missing NEXT_PUBLIC_SITE_URL'); } export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, { apiVersion: '2023-10-16', }); export const createPortalUrl = async (customer: string): Promise<string> => { const session = await stripe.billingPortal.sessions.create({ customer, return_url: new URL('/', process.env.NEXT_PUBLIC_SITE_URL).toString(), }); return session.url; }; export const createCheckoutSession = async (): Promise<{ error?: string; url?: string; }> => { try { const user = await currentUser(); if (!user) { throw new Error('You must be logged in to create a checkout session.'); } if (!user.emailAddresses.at(0)?.emailAddress) { throw new Error( 'You do not have an email address. Please contact support.' ); } let customerId = user.privateMetadata.stripeCustomerId as | string | undefined; if (!customerId) { const customer = await stripe.customers.create({ email: user.emailAddresses.at(0)?.emailAddress, name: user.firstName ?? undefined, }); await clerkClient.users.updateUser(user.id, { privateMetadata: { stripeCustomerId: customer.id, }, }); customerId = customer.id; } const products = await stripe.products.list({ active: true, }); const prices = await stripe.prices.list({ product: products.data.at(0)?.id, active: true, }); if (!prices.data.length) { throw new Error('No active prices found for this product.'); } const priceId = prices.data.find( (price) => price.active && price.recurring?.interval === 'month' )?.id; if (!priceId) { throw new Error('No active price found for this product.'); } const returnPath = new URL('/', process.env.NEXT_PUBLIC_SITE_URL).href; const session = await stripe.checkout.sessions.create({ allow_promotion_codes: true, customer: customerId, line_items: [ { price: priceId, quantity: 1, }, ], customer_update: { address: 'auto', }, mode: 'subscription', metadata: { userId: user.id, }, subscription_data: { metadata: { userId: user.id, }, }, success_url: returnPath, cancel_url: returnPath, automatic_tax: { enabled: true }, }); if (!session.url) { throw new Error('No session URL returned. Please contact support.'); } return { url: session.url }; } catch (error) { const message = parseError(error); return { error: message }; } };
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <link href="https://fonts.googleapis.com/css?family=Quicksand:400,500,700&display=swap" rel="stylesheet"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <!-- Scripts --> <script src="{{ asset('js/app.js') }}" defer></script> <!-- Fonts --> <link rel="dns-prefetch" href="//fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet"> <!-- Styles --> <link href="{{ asset('css/style.css') }}" rel="stylesheet"> </head> <body> <div id="app"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> {{ config('app.name', 'Randevu') }}</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> @auth <li> <a href="{{ route('admin.index')}}" class="href">Admin Paneli</a> </li> <li> <a href="{{ route('admin.working')}}" class="href">Calisma Saatleri</a> </li> <li> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Cikis </a> </li> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> @endauth </ul> </div><!--/.nav-collapse --> </div> </nav> <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm"> <div class="container"> <a class="navbar-brand" href="{{ url('/') }}"> {{ config('app.name', 'Randevu') }} </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-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"> <!-- Left Side Of Navbar --> <ul class="navbar-nav mr-auto"> </ul> <!-- Right Side Of Navbar --> <ul class="navbar-nav ml-auto"> <!-- Authentication Links --> @Auth <li class="nav-item dropdown"> <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre> {{ Auth::user()->name }} <span class="caret"></span> </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> {{ __('Logout') }} </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> @csrf </form> </div> </li> @endAuth </ul> </div> </div> </nav> <main class="py-4"> @yield('content') </main> </div> <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html>
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable()->default(null); $table->string('password'); $table->string('recommendation')->nullable()->default(null); $table->integer('credit')->nullable()->default(0); $table->string('shirt_size')->nullable()->default(null); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } };
import React from 'react' import { NavLink } from 'react-router-dom'; export default function NavBar() { return ( <nav> <ul> <li> <NavLink exact to="/" activeStyle={{ fontWeight: 'bold', color: 'red' }} > Home </NavLink> </li> <li> <NavLink to="/about" activeStyle={{ fontWeight: 'bold', color: 'red' }} > About </NavLink> </li> <li> <NavLink to="/projects" activeStyle={{ fontWeight: 'bold', color: 'red' }} > Projects </NavLink> </li> </ul> </nav> ) }
<?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('transactions', function (Blueprint $table) { $table->id(); $table->string('trans_name'); $table->foreignId('user_id')->constrained('users'); $table->foreignId('category_id')->constrained('categories'); $table->decimal('price', 10, 0); $table->string('description'); $table->boolean('is_income'); $table->date('trans_date'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('transactions'); } };
#ifndef MONTY_H #define MONTY_H #define _GNU_SOURCE #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <stdarg.h> #include <fcntl.h> extern char **opcode; /** * struct stack_s - doubly linked list representation of a stack (or queue) * @n: integer * @prev: points to the previous element of the stack (or queue) * @next: points to the next element of the stack (or queue) * * Description: doubly linked list node structure * for stack, queues, LIFO, FIFO */ typedef struct stack_s { int n; struct stack_s *prev; struct stack_s *next; } stack_t; /** * struct instruction_s - opcode and its function * @opcode: the opcode * @f: function to handle the opcode * * Description: opcode and its function * for stack, queues, LIFO, FIFO */ typedef struct instruction_s { char *opcode; void (*f)(stack_t **stack, unsigned int line_number); } instruction_t; ssize_t getline(char **lineptr, size_t *n, FILE *stream); /* Errors Functions */ int err_arg(void); int err_invalid_instr(int line, char *str); int err_open_file(char *str); int err_malloc(void); int err_int(int line); /* Primary functions */ int monty(FILE *fileptr); void (*handle_opcode(char *str))(stack_t**, unsigned int); char **pars_input(char *input); int count_tokens(char *input); /* Stack Function */ int start_stack(stack_t **stack); void free_stack(stack_t **stack); /* operation Functions */ void my_push (stack_t **stack, unsigned int line_number); void my_pall (stack_t **stack, unsigned int line_number); void my_pint (stack_t **stack, unsigned int line_number); void my_pop (stack_t **stack, unsigned int line_number); void my_swap (stack_t **stack, unsigned int line_number); void my_add (stack_t **stack, unsigned int line_number); void my_nop (stack_t **stack, unsigned int line_number); void my_sub (stack_t **stack, unsigned int line_number); void my_mul (stack_t **stack, unsigned int line_number); /* Helpers */ int empty_line(char *str); void free_grid(char **grid); size_t dlistint_len(const stack_t *h); void triple_free(stack_t **stack, char **op, char *input); #endif
import { Link, useParams, useSearchParams } from "react-router-dom"; import useGetJournal from "./UseGetJournal"; import JournalFeed from "./JournalFeed"; import DescriptionList, { Row } from "../Shared/DescriptionList"; import { currToStr } from "../Shared/Currency"; import UserLink from "../User/UserLink"; import { TimeInterval } from "../Shared/IntervalFilter"; export const path = "/ledger/journals/:jid"; export default function SpecificJournal(_p: unknown): JSX.Element { const { jid } = useParams(); const [searchParams] = useSearchParams(); const journal = useGetJournal(jid || "", jid !== undefined); if (jid === undefined) { return <div>No journal id found</div>; } if (journal.status !== "success") { return <div>Loading journal</div>; } console.log(searchParams); const timeInterval: TimeInterval = (searchParams.get("interval") as TimeInterval) || (journal.data.journalRevision > 100 ? "30 days" : "All"); return ( <div className="m-2"> <DescriptionList header={journal.data.journalName} subHeader={journal.data.journalId} > <Row left="User" clipboard={journal.data.journalUser || undefined} right={ journal.data.journalUser === null ? ( "<None>" ) : ( <UserLink userid={journal.data.journalUser} /> ) } /> <Row clipboard={currToStr(journal.data.journalBalance)} left="Balance" right={currToStr(journal.data.journalBalance)} /> <Row left="Pending Balance" right={currToStr(journal.data.journalPendingBalance)} /> <Row left="Created" right={new Date(journal.data.journalCreated).toLocaleString()} /> <Row left="Type" right={journal.data.journalType.tag} /> <Row left="Last revision" right={journal.data.journalRevision} /> <Row left="Last updated" right={new Date(journal.data.journalUpdated).toLocaleString()} /> <Row left="Last JTrx" clipboard={journal.data.journalTransaction} right={ <Link to={`/ledger/transaction/${journal.data.journalTransaction}`} className="text-indigo-500 underline" > {journal.data.journalTransaction} </Link> } /> <Row left="Last entry" clipboard={journal.data.lastJournalEntry} right={ <Link to={`/ledger/entry/${journal.data.journalTransaction}`} className="text-indigo-500 underline" > {journal.data.lastJournalEntry} </Link> } /> </DescriptionList> <h2 className="text-lg leading-6 font-medium text-gray-900 my-4"> Showing time interval: "{timeInterval}" </h2> <JournalFeed journal={jid} interval={timeInterval} /> <hr /> </div> ); }
import { h, Fragment, JSX, toChildArray, ComponentChildren } from 'preact'; import { Muted, Text, Checkbox } from '@create-figma-plugin/ui'; import { useCallback, useEffect, useState } from 'preact/hooks'; export default function GenericField({ children, resetValue, name, }: { // eslint-disable-next-line react/require-default-props children?: ComponentChildren; resetValue: () => void; name: string; }) { const [isEnabled, setIsEnabled] = useState(false); useEffect(() => { if (!isEnabled && resetValue) { resetValue(); } }, [isEnabled]); const handleIsEnabledChange = useCallback( (event: JSX.TargetedEvent<HTMLInputElement>) => { setIsEnabled(event.currentTarget.checked); }, [setIsEnabled], ); return ( <Fragment> <Checkbox onChange={handleIsEnabledChange} value={isEnabled}> <Text> <Muted>{name}</Muted> </Text> </Checkbox> {isEnabled && children ? toChildArray(children) : undefined} </Fragment> ); }
## Copyright (C) 2001 Paulo Neis <p_neis@yahoo.com.br> ## Copyright (C) 2003 Doug Stewart <dastew@sympatico.ca> ## ## 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/>. ## -*- texinfo -*- ## @deftypefn {Function File} {[@var{b}, @var{a}] =} ellip (@var{n}, @var{Rp}, @var{Rs}, @var{Wp}) ## @deftypefnx {Function File} {[@var{b}, @var{a}] =} ellip (@var{n}, @var{Rp}, @var{Rs}, @var{Wp}, "high") ## @deftypefnx {Function File} {[@var{b}, @var{a}] =} ellip (@var{n}, @var{Rp}, @var{Rs}, @var{[Wl}, @var{Wh}]) ## @deftypefnx {Function File} {[@var{b}, @var{a}] =} ellip (@var{n}, @var{Rp}, @var{Rs}, @var{[Wl}, @var{Wh}], "stop") ## @deftypefnx {Function File} {[@var{z}, @var{p}, @var{g}] =} ellip (@dots{}) ## @deftypefnx {Function File} {[@var{a}, @var{b}, @var{c}, @var{d}] =} ellip (@dots{}) ## @deftypefnx {Function File} {[@dots{}] =} ellip (@dots{}, "s") ## ## Generate an Elliptic or Cauer filter (discrete and contnuious). ## ## [b,a] = ellip(n, Rp, Rs, Wp) ## low pass filter with order n, cutoff pi*Wp radians, Rp decibels ## of ripple in the passband and a stopband Rs decibels down. ## ## [b,a] = ellip(n, Rp, Rs, Wp, 'high') ## high pass filter with cutoff pi*Wp... ## ## [b,a] = ellip(n, Rp, Rs, [Wl, Wh]) ## band pass filter with band pass edges pi*Wl and pi*Wh ... ## ## [b,a] = ellip(n, Rp, Rs, [Wl, Wh], 'stop') ## band reject filter with edges pi*Wl and pi*Wh, ... ## ## [z,p,g] = ellip(...) ## return filter as zero-pole-gain. ## ## [...] = ellip(...,'s') ## return a Laplace space filter, W can be larger than 1. ## ## [a,b,c,d] = ellip(...) ## return state-space matrices ## ## References: ## ## - Oppenheim, Alan V., Discrete Time Signal Processing, Hardcover, 1999. ## - Parente Ribeiro, E., Notas de aula da disciplina TE498 - Processamento ## Digital de Sinais, UFPR, 2001/2002. ## - Kienzle, Paul, functions from Octave-Forge, 1999 (http://octave.sf.net). ## @end deftypefn function [a,b,c,d] = ellip(n, Rp, Rs, W, varargin) if (nargin>6 || nargin<4) || (nargout>4 || nargout<2) print_usage; endif ## interpret the input parameters if (!(length(n)==1 && n == round(n) && n > 0)) error ("ellip: filter order n must be a positive integer"); endif stop = 0; digital = 1; for i=1:length(varargin) switch varargin{i} case 's', digital = 0; case 'z', digital = 1; case { 'high', 'stop' }, stop = 1; case { 'low', 'pass' }, stop = 0; otherwise, error ("ellip: expected [high|stop] or [s|z]"); endswitch endfor [r, c]=size(W); if (!(length(W)<=2 && (r==1 || c==1))) error ("ellip: frequency must be given as w0 or [w0, w1]"); elseif (!(length(W)==1 || length(W) == 2)) error ("ellip: only one filter band allowed"); elseif (length(W)==2 && !(W(1) < W(2))) error ("ellip: first band edge must be smaller than second"); endif if ( digital && !all(W >= 0 & W <= 1)) error ("ellip: critical frequencies must be in (0 1)"); elseif ( !digital && !all(W >= 0 )) error ("ellip: critical frequencies must be in (0 inf)"); endif if (Rp < 0) error("ellip: passband ripple must be positive decibels"); endif if (Rs < 0) error("ellip: stopband ripple must be positive decibels"); endif ## Prewarp the digital frequencies if digital T = 2; # sampling frequency of 2 Hz W = tan(pi*W/T); endif ## Generate s-plane poles, zeros and gain [zero, pole, gain] = ncauer(Rp, Rs, n); ## splane frequency transform [zero, pole, gain] = sftrans(zero, pole, gain, W, stop); ## Use bilinear transform to convert poles to the z plane if digital [zero, pole, gain] = bilinear(zero, pole, gain, T); endif ## convert to the correct output form if nargout==2, a = real(gain*poly(zero)); b = real(poly(pole)); elseif nargout==3, a = zero; b = pole; c = gain; else ## output ss results [a, b, c, d] = zp2ss (zero, pole, gain); endif endfunction %!demo %! [n, Ws] = ellipord ([.1 .2], .4, 1, 90); %! [b, a] = ellip (5, 1, 90, [.1 .2]); %! [h, w] = freqz (b, a); %! %! plot (w./pi, 20*log10 (abs (h)), ";;") %! xlabel ("Frequency"); %! ylabel ("abs(H[w])[dB]"); %! axis ([0, 1, -100, 0]); %! %! hold ("on"); %! x=ones (1, length (h)); %! plot (w./pi, x.*-1, ";-1 dB;") %! plot (w./pi, x.*-90, ";-90 dB;") %! hold ("off");
const router = require('express').Router(); const User = require('../db').import('../models/user'); const jwt = require('jsonwebtoken'); const bcrypt = require('bcryptjs'); router.post('/create', function(req, res){ User.create({ email: req.body.user.email, password: bcrypt.hashSync(req.body.user.password, 13) }) .then( // res.send("This is our user/create endpoint!") function createSuccess(user) { let token = jwt.sign({id: user.id}, process.env.JWT_SECRET, {expiresIn: 60 * 60 * 24}); res.json({ user: user, message: 'User successfully created!', sessionToken: token }); } ) // module 9.2.6 error handling .catch(err => res.status(500).json({error: err})) }); // module 9.3.2 user login router.post('/login', function(req, res) { User.findOne({ where: { email: req.body.user.email } }) .then(function loginSuccess(user) { //module 9.3.6 user login error handling if (user){ bcrypt.compare(req.body.user.password, user.password, function (err, matches){ if (matches) { let token = jwt.sign({id: user.id}, process.env.JWT_SECRET, {expiresIn: 60 * 60* 24}) res.status(200).json({ user: user, message: "User successfully logged in!", sessionToken: token }) } else { res.status(502).send({error: "Login Failed"}); } }); } else { res.status(500).json({ error: 'User does not exist.'}) } }) .catch(err => res.status(500).json({ error: err })) }); module.exports = router;
import {useQuizContext} from '../contexts/QuizContext'; import LoadingInd from './LoadingInd'; import ErrorInd from './ErrorInd'; import GreetingScreen from './GreetingScreen'; import Question from './Question'; import ProgressBar from './ProgressBar'; import FinalResult from './FinalResult'; function Main() { const {status} = useQuizContext(); return ( <main className="flex flex-col justify-center items-center"> {status === 'loading' && <LoadingInd />} {status === 'error' && <ErrorInd />} {status === 'ready' && <GreetingScreen />} {status === 'active' && <ProgressBar />} {status === 'active' && <Question />} {status === 'final' && <FinalResult />} </main> ); } export default Main;
import React, { useState} from "react"; import './App.css'; import TodoForm from "./components/TodoForm"; import TodoList from "./components/TodoList"; function App() { const [todos, setTodos] = useState([]); function addTodo(todo){ setTodos([todo,...todos]); } return ( <div className="App"> <header className="App-header"> <p>React Todo</p> <TodoForm addTodo={addTodo} /> <TodoList todos={todos} /> </header> </div> ); } export default App;
import React, { FC, ReactNode, useRef, useState } from "react"; import MediaFile from "../Icons/MediaFile"; import XIcon from "../Icons/XIcon"; interface IProps { children?: ReactNode; } const DropZone: FC<IProps> = ({ children }) => { const [fileUrl, setFileUrl] = useState<string>(); const [isDragging, setIsDragging] = useState<boolean>(false); const savedTargetRef = useRef<EventTarget | null>(null); const fileInputRef = useRef<HTMLInputElement>(null); const handleFileDrop = (file: File) => { if (file) { const fileReader = new FileReader(); fileReader.onload = () => { const fileURL = fileReader.result; setFileUrl(fileURL as string); }; fileReader.readAsDataURL(file); } }; return ( <> <div className="flex flex-col items-center justify-center w-full h-full" onDragOver={(e) => { e.preventDefault(); }} onDragEnter={(e) => { e.preventDefault(); e.stopPropagation(); savedTargetRef.current = e.target; setIsDragging(true); }} onDragLeave={(e) => { if (savedTargetRef.current !== e.target) return; e.preventDefault(); e.stopPropagation(); setIsDragging(false); }} onDrop={(e) => { e.preventDefault(); e.stopPropagation(); handleFileDrop(e.dataTransfer.files[0]); setIsDragging(false); }} > <div className={`absolute inset-0 z-10 select-none pointer-events-none ${ isDragging ? "border-dashed border-2 border-bluePrimary bg-bluePrimary bg-opacity-10" : "" }`} ></div> <span className={`transition-all ${ isDragging ? "text-bluePrimary" : "text-blackPrimary" }`} > <MediaFile></MediaFile> </span> <p className="my-3 text-grayPrimary">Drag photos and video here</p> <button type="button" onClick={() => fileInputRef.current?.click()} className="px-3 py-2 text-sm font-semibold text-white rounded-md cursor-pointer bg-bluePrimary" > Select from computer </button> </div> <input ref={fileInputRef} type="file" name="filePost" id="filePost" className="hidden" onChange={(e) => handleFileDrop((e.target.files as FileList)[0])} accept="image/jpeg,image/png,image/heic,image/heif,video/mp4,video/quicktime" /> {fileUrl && ( <div className="absolute w-full h-full"> <img className="absolute inset-0 object-cover w-full h-full" src={fileUrl} alt="img" /> <span className="absolute cursor-pointer top-4 right-4" onClick={() => setFileUrl("")} > <XIcon></XIcon> </span> </div> )} {children} </> ); }; export default DropZone;
import 'package:flutter/material.dart'; import 'package:mytrip/Constant/color.dart'; import 'package:mytrip/Flight/multicity.dart'; import 'package:mytrip/Flight/oneway.dart'; import 'package:mytrip/Flight/roundtrip.dart'; class Flight extends StatefulWidget { final String? categoryname; Flight({Key? key, required this.categoryname}) : super(key: key); @override State<Flight> createState() => _FlightState(); } class _FlightState extends State<Flight> with TickerProviderStateMixin { late TabController tabController; @override void initState() { // TODO: implement initState super.initState(); tabController = TabController(length: 3, vsync: this); } @override void dispose() { tabController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: white, leading: GestureDetector( onTap: () { Navigator.pop(context); }, child: Icon( Icons.arrow_back, size: 25, color: black, ), ), elevation: 2, titleSpacing: 1, title: RichText( text: TextSpan( text: 'Flight ', style: TextStyle( color: Colors.grey, fontSize: 24, fontWeight: FontWeight.w400), children: <TextSpan>[ TextSpan( text: 'Search', style: TextStyle( color: Colors.black, fontSize: 24, fontWeight: FontWeight.w600), ) ]), ), // actions: [ // Padding( // padding: const EdgeInsets.only(right: 10), // child: Icon( // Icons.list_rounded, // color: black, // ), // ) // ], ), body: SingleChildScrollView( child: Container( color: white, child: Column( children: [ Padding( padding: const EdgeInsets.all(8), child: Container( height: 50, child: Card( color: greylite, elevation: 2, // height: 50, child: TabBar( // indicatorPadding: EdgeInsets.all(10), controller: tabController, indicator: ShapeDecoration( color: yellow, // shape: StadiumBorder(), // ), shape: RoundedRectangleBorder( borderRadius: new BorderRadius.all( new Radius.circular(5)))), // color: Color.fromARGB(255, 109, 179, 236)), // color: Colors.indigo, unselectedLabelColor: black, labelColor: white, labelStyle: TextStyle( fontSize: 14, fontWeight: FontWeight.w500), tabs: [ Row(children: [ Icon( Icons.arrow_forward, // color: black, // size: 25, ), SizedBox(width: 5), Text("OneWay") ]), Row(children: [ Icon( Icons.sync_alt, // color: black, size: 25, ), //SizedBox(width: 5), Text("RoundTrip") ]), // Tab(text: 'Round Trip'), Row(children: [ Icon( Icons.refresh, //color: black, size: 25, ), SizedBox(width: 5), Text("Multicity") ]), ], ), ), ), ), Container( height: MediaQuery.of(context).size.height * 1.4, child: TabBarView( controller: tabController, children: [ Oneway( categoryname: widget.categoryname, ), Roundtrip( categoryname: widget.categoryname, ), Multicity(), ], ), ), ], )), ), ); } }
using FluentAssertions; using MotorcycleRental.Domain.Constants; using Xunit; namespace MotorcycleRental.Application.Users.Tests { public class CurrentUserTests { [Fact()] public void IsInRole_WithMatchingRole_ShouldReturnTrue() { // arrange var currentUser = new CurrentUser("1", "test@test.com", [UserRoles.Admin, UserRoles.Biker]); // act var isInRole = currentUser.IsInRole(UserRoles.Admin); // assert isInRole.Should().BeTrue(); } [Fact()] public void IsInRole_WithNoMatchingRole_ShouldReturnFalse() { // arrange var currentUser = new CurrentUser("1", "test@test.com", [UserRoles.Admin, UserRoles.Biker]); // act var isInRole = currentUser.IsInRole("User"); // assert isInRole.Should().BeFalse(); } [Fact()] public void IsInRole_WithNoMatchingRoleCase_ShouldReturnFalse() { // arrange var currentUser = new CurrentUser("1", "test@test.com", [UserRoles.Admin, UserRoles.Biker]); // act var isInRole = currentUser.IsInRole(UserRoles.Admin.ToLower()); // assert isInRole.Should().BeFalse(); } [Theory()] [InlineData(UserRoles.Admin)] [InlineData(UserRoles.Biker)] public void IsInRole_WithNoMatchingRoles_ShouldReturnTrue(string roleName) { // arrange var currentUser = new CurrentUser("1", "test@test.com", [UserRoles.Admin, UserRoles.Biker]); // act var isInRole = currentUser.IsInRole(roleName); // assert isInRole.Should().BeTrue(); } } }
# SFDX Bootstrap A script to automatically bootstrap an SFDX project with tools and boilerplate files to facilitate either creating a brand new project, or onboarding into an existing one. ## Prerequisites There's a few prerequisites you should check to make sure the script will run properly. 1. It must be run `bash`. If in Windows, this can be `git bash`, usually included when installing `git` in Windows, and easily accessible from VSCode. If in Linux or Mac, `bash` should be included with your OS. 2. `npm` and the Salesforce cli `sf` are required. If you're reading this, you probably already have these, but if not, check [here](https://developer.salesforce.com/docs/atlas.en-us.sfdx_setup.meta/sfdx_setup/sfdx_setup_install_cli.htm) 3. `jq` is required to manipulate configuration json files. You can check if `jq` is available on your shell using command -v jq If no output is provided, you can install `jq` following the steps provided [here](https://jqlang.github.io/jq/download/), but the most common ways are: - Windows: Run `git bash` **as Administrator** and run curl -L -o /usr/bin/jq.exe https://github.com/stedolan/jq/releases/latest/download/jq-win64.exe - Mac: brew install jq - Linux: Install using your distribution's package manager, examples: - Debian based: sudo apt-get install jq - RHEL based: sudo dnf install jq ## What does this do? The script will set up a project with a few company-wide accepted configurations and tools to help kickstart a new project, or help with onboarding onto an existing one. It will: - Create the SFDX project if not currently in one when the script is run - Create the git repository if not initialized - Install all project `npm` packages. Including: - Prettier, and the Apex plugin - ESLint, and Salesforce packages for Aura and LWCs - Jest, and the `sfdx-lwc-jest` wrapper for Salesforce components - `sa11y/jest` for accessibility tests - Set up configuration files, like: - Adding apex rules to `.prettierrc` if they don't exist - Configuration files for `sa11y/jest` - Add configuration options to `jest.config.js` - Create an `omnistudio-components.json` file used to ignore Omnistudio auto-generated LWCs from some validations - Download the PMD binary into the project, as well as the Attentis PMD ruleset - Download a set of validation scripts you can use to run validations on the project. - Install company recommended VSCode extensions if not installed - Add local VSCode settings to configure the PMD, Prettier and Jest extensions for VSCode ## Usage Download the latest version of the `sf-bootstrap` script from [here](https://github.com/Attentis-Consulting-Inc/sfdx-bootstrap/releases/download/latest/sf-bootstrap), and run it using `bash`, like bash sf-bootstrap
import 'package:flutter/foundation.dart'; import 'package:mongo_dart/mongo_dart.dart'; import 'package:pokedexrr/modelos/jugadores.dart'; import 'package:pokedexrr/utilidades/constantes.dart'; class MongoDB { static var bd, coleccionJugadores; static conectar() async { try { bd = await Db.create(CONEXION); await bd.open(); coleccionJugadores = bd.collection(COLECCION); } catch (e) { if (kDebugMode) { print("Error al conectar a MongoDB: $e"); } rethrow; } } static Future<List<Map<String, dynamic>>> getJugadores() async { try { final jugadores = await coleccionJugadores.find().toList(); return jugadores; } catch (e) { if (kDebugMode) { print(e); } return Future.value(); } } static insertar(Jugador jugador) async { await coleccionJugadores.insertAll([jugador.toMap()]); } static actualizar(Jugador jugador) async { var j = await coleccionJugadores.findOne({"_id": jugador.id}); j["nombre"] = jugador.nombre; j["dorsal"] = jugador.dorsal; j["equipo"] = jugador.equipo; await coleccionJugadores.save(j); } static eliminar(Jugador jugador) async { await coleccionJugadores.remove(where.id(jugador.id)); } static Future<Map<String, dynamic>?> buscarPorNombre(String nombre) async { try { var jugador = await coleccionJugadores.findOne({"nombre": nombre}); if (jugador != null) { return jugador; } else { return null; } } catch (e) { if (kDebugMode) { print("Error al buscar jugador por nombre: $e"); } return null; } } }
import {Component} from 'react' import {SiYoutubegaming} from 'react-icons/si' import {Link} from 'react-router-dom' import Cookies from 'js-cookie' import Header from '../Header' import Sidebar from '../Sidebar' import FailedView from '../FailedView' import LoaderView from '../LoaderView' import { GamingContainer, GamingContentContainer, BannerContainer, LogoConatainer, BannerHeading, VideoThumbnail, VideoHeading, VidoePara, VideoConatiner, VideoItem, } from './styledComponents' import ThemeContext from '../../context/ThemeContext' const apiConstant = { initial: 'INITIAL', failed: 'FAILED', progress: 'IN_PROGRESS', completed: 'COMPLETED', } export default class Trending extends Component { state = {gamingList: [], loadingStatus: apiConstant.initial} componentDidMount() { this.getGamingVideo() } getGamingVideo = async () => { this.setState({loadingStatus: apiConstant.progress}) const apiUrl = 'https://apis.ccbp.in/videos/gaming' const jwtToken = Cookies.get('jwt_token') // const jwtToken = // 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InJhaHVsIiwicm9sZSI6IlBSSU1FX1VTRVIiLCJpYXQiOjE2MjMwNjU1MzJ9.D13s5wN3Oh59aa_qtXMo3Ec4wojOx0EZh8Xr5C5sRkU' const options = { headers: { Authorization: `Bearer ${jwtToken}`, }, method: 'GET', } const response = await fetch(apiUrl, options) if (response.ok) { const data = await response.json() const {videos} = data const formattedList = videos.map(v => ({ id: v.id, title: v.title, thumbnailUrl: v.thumbnail_url, viewCount: v.view_count, })) this.setState({ gamingList: formattedList, loadingStatus: apiConstant.completed, }) } else { this.setState({loadingStatus: apiConstant.failed}) } } renderBanner = isDark => ( <BannerContainer data-testid="banner" isDark={isDark}> <LogoConatainer> <SiYoutubegaming style={{color: '#ff0000', fontSize: '30px'}} /> </LogoConatainer> <BannerHeading isDark={isDark}>Gaming</BannerHeading> </BannerContainer> ) renderSuccessView = isDark => { const {gamingList} = this.state return ( <> {this.renderBanner(isDark)} <VideoConatiner> {gamingList.map(item => ( <VideoItem key={item.id}> <Link to={`/videos/${item.id}`} style={{textDecoration: 'none'}}> <VideoThumbnail src={item.thumbnailUrl} alt="video thumbnail" /> <VideoHeading isDark={isDark}>{item.title}</VideoHeading> <VidoePara>{item.viewCount} watching worldwide</VidoePara> </Link> </VideoItem> ))} </VideoConatiner> </> ) } renderViews = isDark => { const {loadingStatus} = this.state switch (loadingStatus) { case apiConstant.completed: return this.renderSuccessView(isDark) case apiConstant.failed: return <FailedView resetApiCall={this.getGamingVideo} /> case apiConstant.progress: return <LoaderView /> default: return null } } render() { return ( <ThemeContext.Consumer> {value => { const {isDark} = value return ( <> <Header /> <GamingContainer> <Sidebar viewSidebar={false} /> <GamingContentContainer isDark={isDark} data-testid="gaming"> {this.renderViews(isDark)} </GamingContentContainer> </GamingContainer> </> ) }} </ThemeContext.Consumer> ) } }
import { TemporaryAccommodationApplication as Application } from '@approved-premises/api' import type { ObjectWithDateParts, TaskListErrors } from '@approved-premises/ui' import { DateFormats, dateAndTimeInputsAreValidDates, dateIsBlank, dateIsInThePast } from '../../../../utils/dateUtils' import TasklistPage from '../../../tasklistPage' import { dateBodyProperties } from '../../../utils' import { Page } from '../../../utils/decorators' type AccommodationRequiredFromDateBody = ObjectWithDateParts<'accommodationRequiredFromDate'> @Page({ name: 'accommodation-required-from-date', bodyProperties: dateBodyProperties('accommodationRequiredFromDate'), }) export default class AccommodationRequiredFromDate implements TasklistPage { title = 'What date is accommodation required from?' htmlDocumentTitle = this.title constructor( private _body: Partial<AccommodationRequiredFromDateBody>, readonly application: Application, ) {} public set body(value: Partial<AccommodationRequiredFromDateBody>) { this._body = { ...value, ...DateFormats.dateAndTimeInputsToIsoString(value, 'accommodationRequiredFromDate'), } } public get body(): Partial<AccommodationRequiredFromDateBody> { return this._body } response() { return { 'Accommodation required from date': DateFormats.isoDateToUIDate(this.body.accommodationRequiredFromDate), } } previous() { return 'release-date' } next() { return '' } errors() { const errors: TaskListErrors<this> = {} if (dateIsBlank(this.body, 'accommodationRequiredFromDate')) { errors.accommodationRequiredFromDate = 'You must specify the date accommodation is required from' } else if (!dateAndTimeInputsAreValidDates(this.body, 'accommodationRequiredFromDate')) { errors.accommodationRequiredFromDate = 'You must specify a valid date accommodation is required from' } else if (dateIsInThePast(this.body.accommodationRequiredFromDate)) { errors.accommodationRequiredFromDate = 'The date accommodation is required from must not be in the past' } return errors } }
<div class="my-notification-container"> <nz-card> <form nz-form [formGroup]="form" (ngSubmit)="submitForm()"> <div nz-row [nzGutter]="24"> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10" nzFor="notifyShowTitle">通知标题</nz-form-label> <nz-form-control [nzSpan]="14"> <input nz-input class="ant-input" placeholder="请输入通知标题" formControlName="notifyShowTitle" [attr.id]="'notifyShowTitle'" /> </nz-form-control> </nz-form-item> </div> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10" nzFor="enableTracking">是否追踪</nz-form-label> <nz-form-control [nzSpan]="14"> <nz-radio-group formControlName="enableTracking" nzSize="small" [nzButtonStyle]="'solid'"> <label nz-radio-button [nzValue]="null">所有</label> <label nz-radio-button [nzValue]="true">已追踪</label> <label nz-radio-button [nzValue]="false">未追踪</label> </nz-radio-group> </nz-form-control> </nz-form-item> </div> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10" nzFor="sourceType">来源类型</nz-form-label> <nz-form-control [nzSpan]="14"> <nz-select [attr.id]="'sourceType'" formControlName="type"> <nz-option *ngFor="let item of types" [nzValue]="item.value" [nzLabel]="item.label"> </nz-option> </nz-select> </nz-form-control> </nz-form-item> </div> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10">关注项目</nz-form-label> <nz-form-control [nzSpan]="14"> <followed-project-select mode="simple" formControlName="followedProjectID"></followed-project-select> </nz-form-control> </nz-form-item> </div> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10" nzFor="timerEnableScript">脚本</nz-form-label> <nz-form-control [nzSpan]="14"> <nz-radio-group formControlName="timerEnableScript" nzSize="small" [nzButtonStyle]="'solid'"> <label nz-radio-button [nzValue]="null">所有</label> <label nz-radio-button [nzValue]="true">开启</label> <label nz-radio-button [nzValue]="false">关闭</label> </nz-radio-group> </nz-form-control> </nz-form-item> </div> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10" nzFor="timerEnableStatistics">统计数据</nz-form-label> <nz-form-control [nzSpan]="14"> <nz-radio-group formControlName="timerEnableStatistics" nzSize="small" [nzButtonStyle]="'solid'"> <label nz-radio-button [nzValue]="null">所有</label> <label nz-radio-button [nzValue]="true">开启</label> <label nz-radio-button [nzValue]="false">关闭</label> </nz-radio-group> </nz-form-control> </nz-form-item> </div> <div nz-col [nzSpan]="6"> <nz-form-item> <nz-form-label [nzSpan]="10" nzFor="scriptText">脚本内容</nz-form-label> <nz-form-control [nzSpan]="14"> <input nz-input class="ant-input" placeholder="请输入脚本内容" formControlName="scriptText" [attr.id]="'scriptText'" /> </nz-form-control> </nz-form-item> </div> </div> <div nz-row [nzGutter]="24"> <div nz-col [nzSpan]="24"> <nz-form-item nz-row class="register-area"> <nz-form-control [nzSpan]="14" [nzOffset]="6"> <button nz-button [nzType]="'primary'">搜索</button> <button nz-button type="button" (click)="resetForm()" style="margin-left: 12px">重置</button> </nz-form-control> </nz-form-item> </div> </div> </form> </nz-card> <div style="margin-top: 12px; display: flex;"> <button nz-button [nzType]="'primary'" (click)="showCreateModal()" nz-dropdown [nzDropdownMenu]="menu"> 添加通知源 </button> <nz-dropdown-menu #menu="nzDropdownMenu"> <ul nz-menu> <li nz-menu-item (click)="showCreateLink3ActivityModal()">快速添加Link3活动通知</li> </ul> </nz-dropdown-menu> <nz-modal [(nzVisible)]="link3ActivityInputModalVisible" nzTitle="快速添加Link3活动通知" (nzOnOk)="ensureLink3ActivityInput()" (nzOnCancel)="cancelLink3ActivityInput()"> <ng-container *nzModalContent> <input nz-input placeholder="Link3活动主页链接" [formControl]="link3ActivityInputCtrl" /> </ng-container> </nz-modal> <app-notify-observer-not-allow-list-modal style="margin-left: 24px;"></app-notify-observer-not-allow-list-modal> </div> <nz-spin [nzSpinning]="loading"> <nz-card style="margin-top: 12px"> <div style="display: flex; justify-content: center; margin-bottom: 12px"> <nz-pagination [nzPageIndex]="pageIndex" [nzPageSize]="pageSize" [nzTotal]="total" [nzShowTotal]="rangeTemplate" (nzPageIndexChange)="pageIndexChange($event)"> </nz-pagination> </div> <div nz-row [nzGutter]="16"> <div *ngFor="let item of items" nz-col nzLg="8" nzXl="6" style="margin-bottom: 12px"> <notify-observer-item [item]="item" (update)="confirmUpdate(item)" (delete)="confirmDelete(item)" (search)="toSearchByNotifyObserver(item)"></notify-observer-item> </div> <ng-container *ngIf="items.length === 0"> <div style="width: 100%; display: flex; justify-content: center;"> <nz-empty></nz-empty> </div> </ng-container> </div> <div style="display: flex; justify-content: center;"> <nz-pagination [nzPageIndex]="pageIndex" [nzPageSize]="pageSize" [nzTotal]="total" [nzShowTotal]="rangeTemplate" (nzPageIndexChange)="pageIndexChange($event)"> </nz-pagination> </div> <ng-template #rangeTemplate let-range="range" let-total> {{ range[0] }}-{{ range[1] }} of {{ total }} items </ng-template> </nz-card> </nz-spin> </div>
import { useCallback, useEffect, useState } from 'react' import { useRouter } from 'next/router' import { houseApi } from '@api/house' import { useTypedDispatch, useTypedSelector } from '@redux/hooks' import { useCurrentProfile } from '@hooks/useCurrentProfile' import { AvailableUserProfile } from '@screens/auth/types' import { getProfileByEmail } from '@screens/auth/hooks/useSelectors' import { authSlice } from '@screens/auth/slice' import { profileApi, ProfileApiTagTypes } from '@api/profile' import { inviteApi, InviteApiTagTypes } from '@api/invite' import { ROUTES } from '@constants/routes' import { UseJoinHouse } from './JoinHouse.model' const useJoinHouse: UseJoinHouse = (invitationToken) => { const [joinHouse, { isSuccess }] = houseApi.endpoints.joinHouse.useMutation() const router = useRouter() const dispatch = useTypedDispatch() const { profile: currentProfile } = useCurrentProfile() const availableUserProfiles = useTypedSelector( (state) => state.authSlice.availableUserProfiles ) const [profile, setProfile] = useState<AvailableUserProfile | null>(null) useEffect(() => { if (currentProfile?.email && !profile) { const currentAvailableProfile = getProfileByEmail( currentProfile?.email, availableUserProfiles ) if (currentAvailableProfile) { setProfile(currentAvailableProfile) } } }, [availableUserProfiles, currentProfile?.email, profile]) const handleJoinHouse = useCallback(async () => { if (profile) { const { email, token } = profile await dispatch(authSlice.actions.markProfileAsActive(email)) if (token) { await dispatch(authSlice.actions.setToken(token)) } await dispatch( profileApi.util.invalidateTags([ProfileApiTagTypes.ProfileInfo]) ) await joinHouse(String(invitationToken)) } }, [dispatch, invitationToken, joinHouse, profile]) useEffect(() => { if (isSuccess) { dispatch(inviteApi.util.invalidateTags([InviteApiTagTypes.MyInvitesList])) router.push({ pathname: ROUTES.PROFILE_INVITATIONS }) } }, [dispatch, isSuccess, router]) const state = { profile } const actions = { handleJoinHouse, setProfile } return [state, actions] } export default useJoinHouse
import path from 'node:path'; import { strict as assert } from 'node:assert'; import { fileURLToPath } from 'node:url'; import { createClog } from '@marianmeres/clog'; import { TestRunner } from '@marianmeres/test-runner'; import { createSelectionStore } from '../src/index.js'; const clog = createClog(path.basename(fileURLToPath(import.meta.url))); const suite = new TestRunner(path.basename(fileURLToPath(import.meta.url))); suite.test('not multiple', async () => { const s = createSelectionStore([{ id: 'a' }, { id: 'b' }, { id: 'c' }]); const unsub = s.subscribe((v) => {}); assert(s.get().items.length === 3); assert(s.get().selected.length === 0); assert(s.get().selection.length === 0); s.select(1); assert(s.get().items.length === 3); assert(s.get().selected.length === 1); assert(s.get().selection.length === 1); assert(s.get().selection[0].id === 'b'); s.select([1, 1, 1]); assert(s.get().selected.length === 1); assert(s.get().selection.length === 1); assert(s.get().selection[0].id === 'b'); // not multiple, so the last index must win // reset false must have no effect since we're not multiple (it is always resetting) s.select([0, 1, 2], false); assert(s.get().selected.length === 1); assert(s.get().selection.length === 1); assert(s.get().selection[0].id === 'c'); // reset false must have no effect since we're not multiple s.select(s.findIndexBy('id', 'a'), false); assert(s.get().selected.length === 1); assert(s.get().selection.length === 1); assert(s.get().selection[0].id === 'a'); s.reset(); assert(s.get().items.length === 0); assert(s.get().selected.length === 0); assert(s.get().selection.length === 0); unsub(); }); suite.test('multiple', async () => { const s = createSelectionStore([{ id: 'a' }, { id: 'b' }, { id: 'c' }], [1], true); const unsub = s.subscribe((v) => {}); assert(s.get().items.length === 3); assert(s.get().selected.length === 1); assert(s.get().selection.length === 1); assert(s.get().selection[0].id === 'b'); s.select(0, false); assert(s.get().selected.length === 2); assert(s.get().selection.length === 2); // order is not guaranteed assert(s.get().selection.some((v) => v.id === 'a')); assert(s.get().selection.some((v) => v.id === 'b')); s.select([1, 2], true); assert(s.get().selected.length === 2); assert(s.get().selection.length === 2); assert(s.get().selection.some((v) => v.id === 'c')); assert(s.get().selection.some((v) => v.id === 'b')); // this must be noop s.select(999, false); assert(s.get().selected.length === 2); assert(s.get().selection.length === 2); assert(s.get().selection.some((v) => v.id === 'c')); assert(s.get().selection.some((v) => v.id === 'b')); // this must be noop s.select([], false); assert(s.get().selected.length === 2); assert(s.get().selection.length === 2); assert(s.get().selection.some((v) => v.id === 'c')); assert(s.get().selection.some((v) => v.id === 'b')); // this unselects all s.select([], true); assert(s.get().items.length === 3); assert(s.get().selected.length === 0); assert(s.get().selection.length === 0); // multiple with same index must be unique s.select([1, 1, 1], true); assert(s.get().selected.length === 1); assert(s.get().selection.length === 1); assert(s.get().selection[0].id === 'b'); // clog(s.get()); unsub(); }); export default suite;
import { Component, OnInit } from '@angular/core'; import { SnackbarService } from '../services/snackbar.service'; import { NgxUiLoaderService } from 'ngx-ui-loader'; import { NavigationEnd, Router } from '@angular/router'; import { FormControl, Validators, FormBuilder,AbstractControl, ValidatorFn, ValidationErrors } from '@angular/forms'; import { ProductService } from '../services/product.service'; import { Observable, catchError, of } from 'rxjs'; import { SharedService } from '../services/shared.service'; import { GlobalConstants } from '../global-constants'; @Component({ selector: 'app-edit-product', templateUrl: './edit-product.component.html', styleUrls: ['./edit-product.component.css'] }) export class EditProductComponent implements OnInit{ constructor(private productService:ProductService, private snackBar:SnackbarService, private ngxService:NgxUiLoaderService, private router:Router, private fb:FormBuilder, private sharedService:SharedService){ //Here we have a list of the permited routes const listRoutes=['/product/get'] const lastRoute = this.sharedService.getPrev(); this.sharedService.setPrev(this.router.url); var ok=false; for(let route of listRoutes){ if(lastRoute.startsWith(route)) ok=true; } if(!ok||localStorage.getItem('role')!=='employee'){ this.snackBar.openSnackBar('BAD ACCESS','error'); this.router.navigate(['/']); } } createNew=false; file:any; categories:string[]=[]; product = { id:'', title:'', category:'', price:'', brand:'', color:'', weight:'', volume:'', stock:'' } productForm = this.fb.group({ 'img':['', correctFormatValidator()], 'title': ['', Validators.required], 'category': ['', Validators.required], 'price': ['', [Validators.required, Validators.min(0.1)]], 'brand': ['', Validators.required], 'color': ['', Validators.required], 'weight': ['', [Validators.required, Validators.min(0.1)]], 'volume': ['', [Validators.required, Validators.min(0.1)]], 'stock': ['', [Validators.required, positiveIntegerValidator()]], }); get img(){ return this.productForm.get('img') as FormControl; } get title(){ return this.productForm.get('title') as FormControl; } get category(){ return this.productForm.get('category') as FormControl; } get price(){ return this.productForm.get('price') as FormControl; } get brand(){ return this.productForm.get('brand') as FormControl; } get color(){ return this.productForm.get('color') as FormControl; } get weight(){ return this.productForm.get('weight') as FormControl; } get volume(){ return this.productForm.get('volume') as FormControl; } get stock(){ return this.productForm.get('stock') as FormControl; } ngOnInit(): void { this.getAllCategories().subscribe((categories: string[]) => { this.categories= categories; }); this.product = this.sharedService.getProduct(); if(this.product.id===''){ this.snackBar.openSnackBar(GlobalConstants.noProduct, 'error'); this.router.navigate(['/']); }else{ this.ngxService.start(); const notSameValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => { return control.get('title')?.value === this.product.title && control.get('category')?.value === this.product.category && control.get('price')?.value === this.product.price && control.get('brand')?.value === this.product.brand && control.get('color')?.value === this.product.color && control.get('weight')?.value === this.product.weight && control.get('volume')?.value === this.product.volume && control.get('stock')?.value === this.product.stock && control.get('img')?.value === '' ? {same:true} : null; }; this.productForm = this.fb.group({ 'img':['',correctFormatValidator()], 'title': [this.product.title, Validators.required], 'category': [this.product.category, Validators.required], 'price': [this.product.price, [Validators.required, Validators.min(0.1)]], 'brand': [this.product.brand, Validators.required], 'color': [this.product.color, Validators.required], 'weight': [this.product.weight, [Validators.required, Validators.min(0.1)]], 'volume': [this.product.volume, [Validators.required, Validators.min(0.1)]], 'stock': [this.product.stock, [Validators.required, positiveIntegerValidator()]], }, { validators: notSameValidator }); this.ngxService.stop(); } } getAllCategories():Observable<any> { return this.productService.getCategories().pipe( catchError(error => { console.error(error); this.ngxService.stop(); this.snackBar.openSnackBar(error?.error.message, 'error'); this.router.navigate(['error']); return of(null); }) ); } update(){ (this.productForm.get('price') as FormControl).setValue( parseFloat((this.productForm.get('price') as FormControl).value).toFixed(2)); (this.productForm.get('weight') as FormControl).setValue( parseFloat((this.productForm.get('weight') as FormControl).value).toFixed(2)); (this.productForm.get('volume') as FormControl).setValue( parseFloat((this.productForm.get('volume') as FormControl).value).toFixed(2)); this.ngxService.start(); if(this.productForm.getError('same')) this.productService.updateProduct(this.createJson()).subscribe((response:any)=>{ this.snackBar.openSnackBar(response.message,''); this.ngxService.stop(); this.router.navigate(['/']); },error=>{ console.error(error); this.ngxService.stop(); this.snackBar.openSnackBar(error?.error.message,'error'); this.router.navigate(['/error']); }); if(this.productForm.get('img')?.value!==''){ const formData = new FormData(); formData.append('file', this.file); this.productService.updateImg(this.product.id,formData).subscribe((response:any)=>{ this.snackBar.openSnackBar(response.message,''); this.ngxService.stop(); this.router.navigate(['/']); },error=>{ console.error(error); this.ngxService.stop(); this.snackBar.openSnackBar(error?.error.message,'error'); this.router.navigate(['/error']); }); } } toggleInput() { const selectedValue = this.productForm.controls.category.value; this.createNew = selectedValue === ''; } createJson():string{ var result:string ="{"; result = result + '"productId":"'+this.product.id+'",'; if(this.title.value != this.product.title) result= result +'"title":"'+this.title.value+'",'; if(this.price.value != this.product.price) result= result +'"price":"'+this.price.value+'",'; if(this.category.value != this.product.category) result= result +'"category":"'+this.category.value+'",'; if(this.brand.value != this.product.brand) result= result +'"brand":"'+this.brand.value+'",'; if(this.color.value != this.product.color) result= result +'"color":"'+this.color.value+'",'; if(this.weight.value != this.product.weight) result= result +'"weight":"'+this.weight.value+'",'; if(this.volume.value != this.product.volume) result= result +'"volume":"'+this.volume.value+'",'; if(this.stock.value != this.product.stock) result= result +'"stock":"'+this.stock.value+'",'; result = result.slice(0, -1) + "}"; return result; } saveFile(event:any){ this.file = event.target.files[0]; } } function positiveIntegerValidator(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { const value = control.value; if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) { return { 'positiveInteger': true }; } return null; }; } function correctFormatValidator(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { const value:string= control.value; const type = value.substring(value.lastIndexOf('.')+1); if (type!=='png'&&type!=='jpeg') { return { 'badFormat': true }; } return null; }; }
// --------------------------------------------------------------------------- // Copyright 2021 - Under creative commons license 3.0: // // LED blink class // v0.1 - 12.12.2020 (basic functionalities) // // @author T. Ferbezar - tomaz.ferbezar@sc-nm.si // --------------------------------------------------------------------------- #ifndef blinkLED_h #define blinkLED_h #include <inttypes.h> class ledBlink { public: /*! @method @abstract Class constructor. @discussion Initializes class variables @param pin of LED */ ledBlink (uint8_t); /*! @method @abstract Class constructor. @discussion Initializes class variables @param pin of LED, time_on, time_off */ ledBlink (uint8_t, long, long); /*! @methods @abstract Class constructor. @discussion Initializes class variables - update method */ void update(); /*! @methods @abstract Class constructor. @discussion Initializes class variables - turn ON LED */ void on(); /*! @methods @abstract Class constructor. @discussion Initializes class variables - turn OFF LED */ void off(); /*! @methods @abstract Class constructor. @discussion Initializes blink mode @param */ void blink(); /*! @methods @abstract Class constructor. @discussion Initializes class variables - blink LED @param time_on, time_off */ void set_blink(int, int); private: /*! @variables */ uint8_t _ledPin; // the number of the LED pin int _OnTime = 200; // milliseconds of on-time int _OffTime = 200; // milliseconds of off-time uint8_t _ledState; // ledState used to set the LED unsigned long _previousMillis; // will store last time LED was updated uint8_t _static; }; #endif
/* * Copyright (c) 2022 Airbyte, Inc., all rights reserved. */ package io.airbyte.integrations.source.kafka; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.ImmutableMap; import com.inception.server.auth.api.SystemAuthenticator; import io.airbyte.commons.jackson.MoreMappers; import io.airbyte.commons.json.Jsons; import io.airbyte.commons.resources.MoreResources; import io.airbyte.integrations.bicycle.base.integration.EventConnectorJobStatusNotifier; import io.airbyte.integrations.standardtest.source.EventSourceAcceptanceTest; import io.airbyte.integrations.standardtest.source.TestDestinationEnv; import io.airbyte.protocol.models.CatalogHelpers; import io.airbyte.protocol.models.ConfiguredAirbyteCatalog; import io.airbyte.protocol.models.ConfiguredAirbyteStream; import io.airbyte.protocol.models.ConnectorSpecification; import io.airbyte.protocol.models.Field; import io.airbyte.protocol.models.JsonSchemaType; import io.airbyte.protocol.models.SyncMode; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutionException; import io.bicycle.integration.common.bicycleconfig.BicycleConfig; import io.bicycle.integration.common.kafka.KafkaProtocol; import io.bicycle.server.event.mapping.models.processor.EventSourceInfo; import org.apache.kafka.clients.admin.AdminClient; import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.connect.json.JsonSerializer; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.testcontainers.containers.KafkaContainer; import org.testcontainers.utility.DockerImageName; public class KafkaSourceAcceptanceTest extends EventSourceAcceptanceTest { private static final ObjectMapper mapper = MoreMappers.initMapper(); private static final String TOPIC_NAME = "test.topic"; private static KafkaContainer KAFKA; private static BicycleConsumer bicycleConsumer; private static JsonNode config; private static ConfiguredAirbyteCatalog catalog; @BeforeAll public static void setupBicycleConsumer() { String serverURL = ""; String metricStoreURL = ""; String uniqueIdentifier = UUID.randomUUID().toString(); String token = ""; String connectorId = ""; String userId = ""; String eventSourceType= "EVENT"; String tenantId = ""; Map<String, Long> totalRecordsRead = null; BicycleConfig bicycleConfig = new BicycleConfig(serverURL, metricStoreURL,token, connectorId,uniqueIdentifier, tenantId, Mockito.mock(SystemAuthenticator.class), true); EventSourceInfo eventSourceInfo = new EventSourceInfo(bicycleConfig.getConnectorId(), eventSourceType); config = null; catalog= new ConfiguredAirbyteCatalog(); String consumerThreadId = UUID.randomUUID().toString(); bicycleConsumer = new BicycleConsumer(consumerThreadId, totalRecordsRead, bicycleConfig, config, catalog, eventSourceInfo, Mockito.mock(EventConnectorJobStatusNotifier.class), Mockito.mock(KafkaSource.class)); } @Override protected String getImageName() { return "airbyte/source-kafka:dev"; } @Override protected JsonNode getConfig() { final ObjectNode protocolConfig = mapper.createObjectNode(); final ObjectNode subscriptionConfig = mapper.createObjectNode(); protocolConfig.put("security_protocol", KafkaProtocol.PLAINTEXT.toString()); subscriptionConfig.put("subscription_type", "subscribe"); subscriptionConfig.put("topic_pattern", TOPIC_NAME); return Jsons.jsonNode(ImmutableMap.builder() .put("bootstrap_servers", KAFKA.getBootstrapServers()) .put("subscription", subscriptionConfig) .put("client_dns_lookup", "use_all_dns_ips") .put("enable_auto_commit", false) .put("group_id", "groupid") .put("repeated_calls", 3) .put("protocol", protocolConfig) .put("auto_offset_reset", "earliest") .build()); } @Override protected void setupEnvironment(final TestDestinationEnv environment) throws Exception { KAFKA = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.0")); KAFKA.start(); createTopic(); sendEvent(); } private void sendEvent() throws ExecutionException, InterruptedException { final Map<String, Object> props = ImmutableMap.<String, Object>builder() .put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA.getBootstrapServers()) .put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()) .put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName()) .build(); final KafkaProducer<String, JsonNode> producer = new KafkaProducer<>(props); final ObjectNode event = mapper.createObjectNode(); event.put("test", "value"); producer.send(new ProducerRecord<>(TOPIC_NAME, event), (recordMetadata, exception) -> { if (exception != null) { throw new RuntimeException("Cannot send message to Kafka. Error: " + exception.getMessage(), exception); } }).get(); } private void createTopic() throws Exception { try (final var admin = AdminClient.create(Map.of(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA.getBootstrapServers()))) { final NewTopic topic = new NewTopic(TOPIC_NAME, 1, (short) 1); admin.createTopics(Collections.singletonList(topic)).all().get(); } } @Override protected void tearDown(final TestDestinationEnv testEnv) { KAFKA.close(); } @Override protected ConnectorSpecification getSpec() throws Exception { return Jsons.deserialize(MoreResources.readResource("spec.json"), ConnectorSpecification.class); } @Override protected ConfiguredAirbyteCatalog getConfiguredCatalog() throws Exception { final ConfiguredAirbyteStream streams = CatalogHelpers.createConfiguredAirbyteStream(TOPIC_NAME, null, Field.of("value", JsonSchemaType.STRING)); streams.setSyncMode(SyncMode.FULL_REFRESH); return new ConfiguredAirbyteCatalog().withStreams(Collections.singletonList(streams)); } @Override protected JsonNode getState() throws Exception { return Jsons.jsonNode(new HashMap<>()); } // need to shift to unit-test? @Test protected void testBicycleConsumerCheck() { config=getConfig(); ((ObjectNode) config).put("test_topic",TOPIC_NAME); Assertions.assertEquals(bicycleConsumer.check(config),true); } }
package forcomp import java.lang.Character.Subset object Anagrams { /** A word is simply a `String`. */ type Word = String /** A sentence is a `List` of words. */ type Sentence = List[Word] /** `Occurrences` is a `List` of pairs of characters and positive integers saying * how often the character appears. * This list is sorted alphabetically w.r.t. to the character in each pair. * All characters in the occurrence list are lowercase. * * Any list of pairs of lowercase characters and their frequency which is not sorted * is **not** an occurrence list. * * Note: If the frequency of some character is zero, then that character should not be * in the list. */ type Occurrences = List[(Char, Int)] /** The dictionary is simply a sequence of words. * It is predefined and obtained as a sequence using the utility method `loadDictionary`. */ val dictionary: List[Word] = loadDictionary /** Converts the word into its character occurrence list. * * Note: the uppercase and lowercase version of the character are treated as the * same character, and are represented as a lowercase character in the occurrence list. * * Note: you must use `groupBy` to implement this method! */ def wordOccurrences(w: Word): Occurrences = { /*def calculateOccurences (occurrences: List[(Char, Int)], word: List[Char]) : List[(Char, Int)] = { word match { case Nil => return occurrences case c :: ctail => if (occurrences.exists(o => (o._1 == c))) { val newList = occurrences.map(x => if (x._1 == c) (x._1, x._2 + 1) else x) return calculateOccurences(newList, ctail) } else return calculateOccurences((c, 1) :: occurrences, ctail) case _ => print("Error : extrange list founded") return Nil } } val occurrences = calculateOccurences(List[(Char, Int)](), w.toList) occurrences.sortWith(_._2 > _._2)*/ val m = w.groupBy(e => e.toLower).toList m.map(x => (x._1, x._2.length)).sortWith(_._1 < _._1) } /** Converts a sentence into its character occurrence list. */ def sentenceOccurrences(s: Sentence): Occurrences = { wordOccurrences(s.mkString) } /** The `dictionaryByOccurrences` is a `Map` from different occurrences to a sequence of all * the words that have that occurrence count. * This map serves as an easy way to obtain all the anagrams of a word given its occurrence list. * * For example, the word "eat" has the following character occurrence list: * * `List(('a', 1), ('e', 1), ('t', 1))` * * Incidentally, so do the words "ate" and "tea". * * This means that the `dictionaryByOccurrences` map will contain an entry: * * List(('a', 1), ('e', 1), ('t', 1)) -> Seq("ate", "eat", "tea") * */ lazy val dictionaryByOccurrences: Map[Occurrences, List[Word]] = { //print(dictionary.groupBy(e => wordOccurrences(e))) dictionary.groupBy(e => wordOccurrences(e)) } /** Returns all the anagrams of a given word. */ def wordAnagrams(word: Word): List[Word] = { dictionaryByOccurrences.getOrElse(wordOccurrences(word), List()) } /** Returns the list of all subsets of the occurrence list. * This includes the occurrence itself, i.e. `List(('k', 1), ('o', 1))` * is a subset of `List(('k', 1), ('o', 1))`. * It also include the empty subset `List()`. * * Example: the subsets of the occurrence list `List(('a', 2), ('b', 2))` are: * * List( * List(), * List(('a', 1)), * List(('a', 2)), * List(('b', 1)), * List(('a', 1), ('b', 1)), * List(('a', 2), ('b', 1)), * List(('b', 2)), * List(('a', 1), ('b', 2)), * List(('a', 2), ('b', 2)) * ) * * Note that the order of the occurrence list subsets does not matter -- the subsets * in the example above could have been displayed in some other order. */ def combinations(occurrences: Occurrences): List[Occurrences] = { if (occurrences.isEmpty) List(List()) else { val tailList = combinations(occurrences.tail) tailList ::: (for { o <- tailList i <- 1 to occurrences.head._2 } yield { //println("item for: " + (occurrences.head._1, i)) (occurrences.head._1, i) :: o }) } } //??? /** Subtracts occurrence list `y` from occurrence list `x`. * * The precondition is that the occurrence list `y` is a subset of * the occurrence list `x` -- any character appearing in `y` must * appear in `x`, and its frequency in `y` must be smaller or equal * than its frequency in `x`. * * Note: the resulting value is an occurrence - meaning it is sorted * and has no zero-entries. */ def subtract(x: Occurrences, y: Occurrences): Occurrences = { (for { xi <- x } yield { val yi = y.filter(_._1 == xi._1) if (yi.isEmpty) xi else (xi._1, xi._2 - yi.head._2) }).filter(_._2 != 0) } //??? /** Returns a list of all anagram sentences of the given sentence. * * An anagram of a sentence is formed by taking the occurrences of all the characters of * all the words in the sentence, and producing all possible combinations of words with those characters, * such that the words have to be from the dictionary. * * The number of words in the sentence and its anagrams does not have to correspond. * For example, the sentence `List("I", "love", "you")` is an anagram of the sentence `List("You", "olive")`. * * Also, two sentences with the same words but in a different order are considered two different anagrams. * For example, sentences `List("You", "olive")` and `List("olive", "you")` are different anagrams of * `List("I", "love", "you")`. * * Here is a full example of a sentence `List("Yes", "man")` and its anagrams for our dictionary: * * List( * List(en, as, my), * List(en, my, as), * List(man, yes), * List(men, say), * List(as, en, my), * List(as, my, en), * List(sane, my), * List(Sean, my), * List(my, en, as), * List(my, as, en), * List(my, sane), * List(my, Sean), * List(say, men), * List(yes, man) * ) * * The different sentences do not have to be output in the order shown above - any order is fine as long as * all the anagrams are there. Every returned word has to exist in the dictionary. * * Note: in case that the words of the sentence are in the dictionary, then the sentence is the anagram of itself, * so it has to be returned in this list. * * Note: There is only one anagram of an empty sentence. */ def sentenceAnagrams(sentence: Sentence): List[Sentence] = { def getAnagramsOccurrences(occur : Occurrences): List[List[Occurrences]] = { val comb = combinations(occur) //println("\nList: " + occur) //print("Comb: ") //comb.foreach(i => print("|" + i + "|")) val finalList = for { c <- comb if dictionaryByOccurrences.contains(c) } yield { //println("\n\tDic: " + c) if (subtract(occur, c).isEmpty){ //println("\t \t selec: " + c) List(List(c)) } else { //println("Next bucle:\n") val anagrams = getAnagramsOccurrences(subtract(occur, c)) //println("Fin bucle:\n") if (anagrams.nonEmpty) { //getAnagramsOccurrences(subtract(occur, c)).filter(_.nonEmpty).map(c::_) anagrams.filter(_.nonEmpty).map(c::_) } else List() } } //print("\tFIN: ") //finalList.foreach(i => print(" || " + i)) //println("\n" + finalList) //println("") //List() // finalList.filter(_.isNotEmpty) //.fold(List(List())(_:::_) finalList.foldLeft(List(): List[List[Occurrences]])( (B:List[List[Occurrences]], A:List[List[Occurrences]]) => B:::A) } def occurrencesToSentences(list: List[List[Word]], acc : List[Sentence]) : List[Sentence] = { if (list.isEmpty) acc else { val newAcc = for { l <- acc x <- list.head } yield { //println("Acc : " + l + "element: " + x) l ::: List(x) } occurrencesToSentences(list.tail, newAcc) } } if (sentence.isEmpty) List(Nil) else { val anagramsOccurrences = getAnagramsOccurrences(sentenceOccurrences(sentence)) // List[List[Occurrr]] if (anagramsOccurrences.isEmpty) List() else { val listAnagrams: List[List[List[Word]]] = anagramsOccurrences.map(_.map(dictionaryByOccurrences(_))) // listAnagrams.flatMap(occurrencesToSentences(_, List(List()))) } } } }
'use strict'; /** * Module dependencies. */ var errorHandler = require('./errors.server.controller.js'), mongoose = require('mongoose'), Checklist = mongoose.model('Checklist'), Answer = mongoose.model('Answer'), _ = require('lodash'); /** * Create a checklist */ exports.create = function(req, res) { var checklist = new Checklist(req.body); checklist.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(checklist); } }); }; /** * Show the current checklist */ exports.read = function(req, res) { res.json(req.checklist); }; /** * Update a checklist */ exports.update = function(req, res) { var checklist = req.checklist; checklist = _.extend(checklist, req.body); checklist.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(checklist); } }); }; /** * Delete an checklist */ exports.delete = function(req, res) { var checklist = req.checklist; checklist.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(checklist); } }); }; /** * Retrieve all checklists */ exports.all = function(req, res) { Checklist.find({text: {$ne: ''}, checklistType: {$ne: 'none'}}) .populate('company') .populate('site') .populate('frequency') .populate('questions.question') .populate('editor') .exec(function(err, checklists) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(checklists); } }); }; /** * Checklist middleware */ exports.checklistByID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Checklist is invalid' }); } Checklist.findById(id) .populate('company') .populate('site') .populate('frequency') .populate('primary_inspector') .populate('secondary_inspector') .populate('tertiary_inspector') .populate('questions.question') .populate('primary_supervisor') .populate('secondary_supervisor') .populate('tertiary_supervisor') .populate('questions.question') .populate('editor') .exec(function(err, checklist) { if (err) return next(err); if (!checklist) { return res.status(404).send({ message: 'Checklist not found' }); } var options = [ { path: 'questions.question.regulatory_framework', model: 'Regulatory' } ]; Checklist.populate(checklist, options, function (err, populatedChecklist) { Answer.find({ checklist: populatedChecklist._id, site: populatedChecklist.site._id, editor: req.user }).exec(function(err, answers) { populatedChecklist.set('answers', answers, { strict: false }); req.checklist = populatedChecklist; next(); }); }); }); }; exports.checklistsByCompanyID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Checklist is invalid' }); } Checklist.find({ company: mongoose.Types.ObjectId(id) }) .populate('company') .populate('site') .populate('frequency') .populate('questions.question') .populate('editor') .exec(function(err, checklist) { if (err) return next(err); if (!checklist) { return res.status(404).send({ message: 'Checklist not found' }); } req.checklist = checklist; next(); }); }; exports.checklistsByInspector = function(req, res) { var inspectorId = req.params.inspectorId; var category = req.query.category; var query ={ $or: [{ primary_inspector: inspectorId }, { secondary_inspector: inspectorId }, { tertiary_inspector: inspectorId }] }; if (category == 0) { query = { primary_inspector: inspectorId }; } else if (category == 1) { query = { secondary_inspector: inspectorId }; } else if (category == 2) { query = { tertiary_inspector: inspectorId }; } Checklist.find(query) .exec(function(err, checklists) { if (err) { return next(err); } else { res.json(checklists); } }); }; exports.getInspectors = function(req, res) { var checklistId = req.params.checklistId; Checklist.findById(checklistId) .populate('primary_inspector') .populate('secondary_inspector') .populate('tertiary_inspector') .populate('questions.question') .exec(function(err, checklist) { if (err) { return next(err); } else { var inspectors = []; if (checklist) { if (checklist.primary_inspector) { inspectors.push(checklist.primary_inspector); } if (checklist.secondary_inspector) { inspectors.push(checklist.secondary_inspector); } if (checklist.tertiary_inspector) { inspectors.push(checklist.tertiary_inspector); } } res.json(inspectors); } }); }; exports.checklistsBySites = function(req, res) { if(req.body.length === 0) return res.json([]); var siteIds = []; for(var i=0; i<req.body.length; i++) { siteIds.push(mongoose.Types.ObjectId(req.body[i].id)); } Checklist.find({text: {$ne: ''}, checklistType: {$ne: 'none'}, site: {$in: siteIds}}) .populate('company') .populate('site') .populate('frequency') .populate('questions.question') .populate('editor') .exec(function(err, checklists) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(checklists); } }); }; exports.checklistsBySiteAndFrequencies = function(req, res) { var frequencyIds = []; var i = 0; var body = req.body; if (body.frequencies.length > 0) { for(i=0; i<body.frequencies.length; i++) { frequencyIds.push(mongoose.Types.ObjectId(body.frequencies[i].id)); } } var query = {text: {$ne: ''}, checklistType: {$ne: 'none'}, site: body.site}; if (frequencyIds.length > 0) { query = {text: {$ne: ''}, checklistType: {$ne: 'none'}, site: body.site, frequency: {$in: frequencyIds}}; } if (body.isAll || frequencyIds.length > 0) { Checklist.find(query) .populate('company') .populate('site') .populate('frequency') .populate('questions.question') .populate('editor') .exec(function(err, checklists) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(checklists); } }); } else { res.json([]); } }; /** * Checklist authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.checklist.user.id !== req.user.id) { return res.status(403).send({ message: 'User is not authorized' }); } next(); };
//! Does some analytics on datasets, this module is largely a result from initial thoughts into //! other models and more involved training where understanding some more parts of the dataset and //! language could be helpful for modelling. I've preserved it here because it doesn't take //! anything away, but it is less relevant for systems like ours utilising a neural network. use crate::phonemes::*; use crate::text_normaliser::*; use crate::CmuDictionary; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use tracing::info; /// A diphone is a neighbouring pair of phones, and a phone is a distinct speech sound. A phone /// differs from a phoneme because if you change the phoneme you change the word and it's /// meaning but phones could potentially be switched and it would be more akin to changing the /// pronunciation but not meaning of the word. Therefore a language will have more possible /// phones than phonemes. If a language has P phones. /// /// If we have P phones in a language the maximum possible diphones is P^2. However, languages /// typically have rules on what sounds can occur near each other so in practice the number is a /// lot lower than P^2. Some synthesis techniques will use diphones because it can allow for a /// sliding window for synthesis and easier blending with less visible cuts. /// /// We do use phonemes for our diphones from the dataset so there is an inaccuracy of sorts in the /// analytics, but whether that is acceptable or a negative would depend on what models/approaches /// it went into. #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)] pub struct DiphoneStat { /// The phone pair pub phones: [String; 2], /// The count in the dataset pub count: usize, } /// The end analytics from the dataset, this is just designed to be serialized out to a json or /// similar structure. Though all fields are public to enable it to be used in code. #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize)] pub struct Analytics { /// List of diphones and counts pub diphones: Vec<DiphoneStat>, /// List of phonemes and their counts pub phonemes: BTreeMap<String, usize>, /// Out of vocabulary words pub oov: BTreeMap<String, usize>, /// Lengths of sentences being synthesised. This is generally good to get an idea of the /// longest context you're seeing during training as things beyond this may end up posing /// issues. pub sentence_lengths: BTreeMap<usize, usize>, } /// Used to generate analytics, this is because some of the running state may not want to be /// serialized or may otherwise be unserialisable (taking json as a target format). #[derive(Debug, Default)] pub struct AnalyticsGenerator { /// Dictionary used for anaytics dict: CmuDictionary, /// Map to keep track of the diphones diphones: BTreeMap<[PhoneticUnit; 2], usize>, /// Running count of phonemes phonemes: BTreeMap<PhoneticUnit, usize>, /// Running count of OOVs oov: BTreeMap<String, usize>, /// Running count of sentence lengths sentence_lengths: BTreeMap<usize, usize>, } impl AnalyticsGenerator { /// Create a new analytics generator pub fn new(dict: CmuDictionary) -> Self { Self { dict, ..Default::default() } } /// Adds the word into the analysis pub fn push_word(&mut self, word: &str) { let normalised = normalise_text(word).to_string_unchecked(); if let Some(pronunciations) = self.dict.get_pronunciations_normalised(&normalised) { for pronunciation in pronunciations.iter() { for window in pronunciation.as_slice().windows(2) { *self.diphones.entry([window[0], window[1]]).or_insert(0) += 1; *self.phonemes.entry(window[0]).or_insert(0) += 1; } // This will skip adding the last one to the phones map so do it here if let Some(last) = pronunciation.last() { *self.phonemes.entry(*last).or_insert(0) += 1; } } } else { *self.oov.entry(normalised).or_insert(0) += 1; } } /// Process a sentence and also add all the words in it into the analysis pub fn push_sentence(&mut self, sentence: &str) { let mut text = normalise(sentence).unwrap(); text.words_to_pronunciation(&self.dict); let mut sentence_len = 0; for chunk in text.drain_all() { match chunk { NormaliserChunk::Pronunciation(units) => { sentence_len += units.len(); } NormaliserChunk::Text(t) => { unreachable!("'{}' Should have been converted to pronunciation", t) } NormaliserChunk::Break(_duration) => {} NormaliserChunk::Punct(p) => { sentence_len += 1; if p.is_sentence_end() { *self.sentence_lengths.entry(sentence_len).or_default() += 1; if sentence_len > 160 { info!("Very long sentence found: '{}'", sentence); } sentence_len = 0; } } } } if sentence_len > 0 { *self.sentence_lengths.entry(sentence_len).or_default() += 1; if sentence_len > 160 { info!("Very long sentence found: '{}'", sentence); } } for word in sentence.split_whitespace() { self.push_word(word); } } /// Generates a report, this can be saved as a json for future processing. pub fn generate_report(&self) -> Analytics { let diphones = self .diphones .iter() .map(|(k, v)| DiphoneStat { phones: [k[0].to_string(), k[1].to_string()], count: *v, }) .collect(); let phonemes = self .phonemes .iter() .map(|(k, v)| (k.to_string(), *v)) .collect(); Analytics { diphones, phonemes, oov: self.oov.clone(), sentence_lengths: self.sentence_lengths.clone(), } } }
import { jest } from '@jest/globals' import * as ErrorCodes from '../src/parts/ErrorCodes/ErrorCodes.js' beforeEach(() => { jest.resetModules() jest.resetAllMocks() }) jest.unstable_mockModule('../src/parts/FileSystem/FileSystem.js', () => { return { readFile: jest.fn(() => { throw new Error('not implemented') }), } }) jest.unstable_mockModule('../src/parts/Markdown/Markdown.js', () => { return { toHtml: jest.fn(() => { throw new Error('not implemented') }), } }) jest.unstable_mockModule('../src/parts/SanitizeHtml/SanitizeHtml.js', () => { return { sanitizeHtml: jest.fn(() => { throw new Error('not implemented') }), } }) jest.unstable_mockModule( '../src/parts/ExtensionManagement/ExtensionManagement.js', () => { return { getExtension: jest.fn(() => { throw new Error('not implemented') }), } } ) class NodeError extends Error { constructor(code, message = code) { super(code + ':' + message) this.code = code } } const ViewletExtensionDetail = await import( '../src/parts/ViewletExtensionDetail/ViewletExtensionDetail.js' ) const ExtensionManagement = await import( '../src/parts/ExtensionManagement/ExtensionManagement.js' ) const FileSystem = await import('../src/parts/FileSystem/FileSystem.js') const Markdown = await import('../src/parts/Markdown/Markdown.js') const SanitizeHtml = await import('../src/parts/SanitizeHtml/SanitizeHtml.js') test('create', () => { const state = ViewletExtensionDetail.create() expect(state).toBeDefined() }) test('loadContent', async () => { // @ts-ignore ExtensionManagement.getExtension.mockImplementation(() => { return { path: '/test/test-extension', name: 'Test Extension', } }) // @ts-ignore FileSystem.readFile.mockImplementation(() => { return '# test extension' }) // @ts-ignore Markdown.toHtml.mockImplementation(() => { return '<h1 id="test-extension">Test Extension</h1>' }) // @ts-ignore SanitizeHtml.sanitizeHtml.mockImplementation(() => { return '<h1 id="test-extension">Test Extension</h1>' }) const state = { ...ViewletExtensionDetail.create(), uri: 'extension-detail://test-extension', } expect(await ViewletExtensionDetail.loadContent(state)).toMatchObject({ sanitizedReadmeHtml: `<h1 id="test-extension">Test Extension</h1>`, iconSrc: '/icons/extensionDefaultIcon.png', name: 'Test Extension', }) expect(ExtensionManagement.getExtension).toHaveBeenCalledTimes(1) expect(ExtensionManagement.getExtension).toHaveBeenCalledWith( 'test-extension' ) expect(FileSystem.readFile).toHaveBeenCalledTimes(1) expect(FileSystem.readFile).toHaveBeenCalledWith( '/test/test-extension/README.md' ) expect(Markdown.toHtml).toHaveBeenCalledTimes(1) expect(Markdown.toHtml).toHaveBeenCalledWith('# test extension', { baseUrl: '/test/test-extension', }) expect(SanitizeHtml.sanitizeHtml).toHaveBeenCalledTimes(1) expect(SanitizeHtml.sanitizeHtml).toHaveBeenCalledWith( '<h1 id="test-extension">Test Extension</h1>' ) }) test('loadContent - error - readme not found', async () => { // @ts-ignore ExtensionManagement.getExtension.mockImplementation(() => { return { path: '/test/test-extension', name: 'Test Extension', } }) // @ts-ignore FileSystem.readFile.mockImplementation(() => { throw new NodeError(ErrorCodes.ENOENT) }) // @ts-ignore Markdown.toHtml.mockImplementation(() => { return '<h1 id="test-extension">Test Extension</h1>' }) // @ts-ignore SanitizeHtml.sanitizeHtml.mockImplementation(() => { return '' }) const state = { ...ViewletExtensionDetail.create(), uri: 'extension-detail://test-extension', } expect(await ViewletExtensionDetail.loadContent(state)).toMatchObject({ sanitizedReadmeHtml: ``, iconSrc: '/icons/extensionDefaultIcon.png', name: 'Test Extension', }) expect(ExtensionManagement.getExtension).toHaveBeenCalledTimes(1) expect(ExtensionManagement.getExtension).toHaveBeenCalledWith( 'test-extension' ) expect(FileSystem.readFile).toHaveBeenCalledTimes(1) expect(FileSystem.readFile).toHaveBeenCalledWith( '/test/test-extension/README.md' ) expect(Markdown.toHtml).toHaveBeenCalledTimes(1) expect(Markdown.toHtml).toHaveBeenCalledWith('', { baseUrl: '/test/test-extension', }) expect(SanitizeHtml.sanitizeHtml).toHaveBeenCalledTimes(1) expect(SanitizeHtml.sanitizeHtml).toHaveBeenCalledWith( '<h1 id="test-extension">Test Extension</h1>' ) }) test('handleIconError', () => { const state = ViewletExtensionDetail.create() expect(ViewletExtensionDetail.handleIconError(state)).toMatchObject({ iconSrc: '/icons/extensionDefaultIcon.png', }) }) test('handleIconError - already has default icon', () => { const state = { ...ViewletExtensionDetail.create(), iconSrc: '/icons/extensionDefaultIcon.png', } expect(ViewletExtensionDetail.handleIconError(state)).toBe(state) })
#pragma once #include "DocumentId.h" #include <spdlog/spdlog.h> #include <spdlog/fmt/ostr.h> #include <rocksdb/db.h> #include <rapidjson/document.h> #include <rapidjson/rapidjson.h> #include <rapidjson/writer.h> #include <boost/filesystem/path.hpp> #include <mutex> #include <string> namespace centurion { inline const char* lastDocumentIdKey = "__last_document_id__"; inline const char* isDirtyKey = "__is_dirty__"; class DocumentStore { public: DocumentStore(const DocumentStore&) = delete; DocumentStore(DocumentStore&&) = delete; DocumentStore(boost::filesystem::path filename, bool dropIfExist = false) : db_(nullptr), filename_(std::move(filename)), dropIfExist_(dropIfExist), maxDocumentId_(0) { logger_ = spdlog::get("root")->clone("document_store"); rocksdb::Options opts; opts.create_if_missing = true; opts.manual_wal_flush = true; opts.enable_pipelined_write = true; opts.max_background_jobs = 8; opts.IncreaseParallelism(); if (dropIfExist) rocksdb::DestroyDB(filename_.string(), opts); logger_->trace("Opening db: {}...", filename_); rocksdb::Status s = rocksdb::DB::Open(opts, filename_.string(), &db_); if (!s.ok()) { logger_->critical("Failed opening db: {}", filename_); throw std::runtime_error("db error: " + s.ToString()); } logger_->trace("Opened db: {}!", filename_); restoreMaxIndexId(); } virtual ~DocumentStore() { storeMaxIndexId(); db_->FlushWAL(true); db_->SyncWAL(); db_->Close(); delete db_; if (dropIfExist_) rocksdb::DestroyDB(filename_.string(), rocksdb::Options()); } DocumentId storeDocument(DocumentId documentId, const rapidjson::Value& doc) { if (documentId == InvalidDocumentId) { documentId = ++maxDocumentId_; } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); if (doc.Accept(writer)) { auto putResult = db_->Put( rocksdb::WriteOptions(), rocksdb::Slice(reinterpret_cast<char*>(&documentId), sizeof(documentId)), rocksdb::Slice(buffer.GetString(), buffer.GetSize())); if (putResult.ok()) { return documentId; } throw std::runtime_error(putResult.ToString()); } throw std::runtime_error("Empty document"); } rapidjson::Value loadDocument(DocumentId documentId, rapidjson::Document::AllocatorType& allocator) const { std::string documentPayload; auto getResult = db_->Get( rocksdb::ReadOptions(), rocksdb::Slice(reinterpret_cast<char*>(&documentId), sizeof(documentId)), &documentPayload); if (getResult.ok()) { rapidjson::Document doc; doc.Parse(documentPayload.c_str(), documentPayload.size()); return rapidjson::Value(doc, allocator); } return rapidjson::Value(rapidjson::kNullType); } bool deleteDocument(DocumentId documentId) const { auto deleteResult = db_->Delete( rocksdb::WriteOptions(), rocksdb::Slice(reinterpret_cast<char*>(&documentId), sizeof(documentId))); if (deleteResult.ok()) { return true; } // log error return false; } private: void storeMaxIndexId() { std::lock_guard<std::mutex> guard(mutex_); std::string s; DocumentId currentDocId = 0; if (db_->Get(rocksdb::ReadOptions(), lastDocumentIdKey, &s).ok()) { currentDocId = *(reinterpret_cast<const DocumentId*>(s.data())); } DocumentId tmp = maxDocumentId_; if (currentDocId < tmp) { if (!db_->Put(rocksdb::WriteOptions(), lastDocumentIdKey, rocksdb::Slice(reinterpret_cast<const char*>(&tmp), sizeof tmp)).ok()) { throw std::runtime_error("put __last_index_id__ error"); } } if (checkIsDirty()) { logger_->trace("Marking DB as clean"); cleanDirty(); } else { logger_->critical("DB is not dirty"); throw std::runtime_error("DB Not dirty"); } } void restoreMaxIndexId() { std::lock_guard<std::mutex> guard(mutex_); logger_->trace("Restoring MaxIndexId..."); if (checkIsDirty()) { logger_->warn("Last DB Shutdown was not clean, will perform full scan to recover MaxIndexId..."); // scan all keys auto iterator = db_->NewIterator(rocksdb::ReadOptions()); iterator->SeekToFirst(); DocumentId currDocumentId = 0; while (iterator->Valid()) { currDocumentId++; iterator->Next(); } delete iterator; maxDocumentId_ = currDocumentId; logger_->warn("MaxIndexId recovered using full scan. MaxIndexId: {}", currDocumentId); } else { logger_->trace("Last DB shutdown was clean, reading MaxIndexId from key..."); std::string s; if (db_->Get(rocksdb::ReadOptions(), lastDocumentIdKey, &s).ok()) { maxDocumentId_ = *(reinterpret_cast<const DocumentId*>(s.data())); logger_->trace("God MaxIndexId from DB: {}", maxDocumentId_); } else { maxDocumentId_ = 0; logger_->trace("MaxIndexId not found in DB, using default value of: 0"); } makeDirty(); } } bool checkIsDirty() const { logger_->trace("Checking if previous DB Shutdown was clean..."); std::string val; rocksdb::Status s = db_->Get(rocksdb::ReadOptions(), isDirtyKey, &val); if (s.IsNotFound()) { logger_->trace("No clean shutdown key found, assuming this is first run, do a full scan"); return true; } if (!s.ok()) { logger_->critical("An error occurred while reading clean db shutdown key"); throw std::runtime_error("get __is_dirty__ error"); } return (val == "Y"); } void makeDirty() const { logger_->trace("Marking DB as not clean..."); if (!db_->Put(rocksdb::WriteOptions(), isDirtyKey, "Y").ok()) { throw std::runtime_error("put __is_dirty__ error"); } logger_->trace("Done marking DB as not clean!"); } void cleanDirty() const { logger_->trace("Resetting DB clean flag..."); if (!db_->Put(rocksdb::WriteOptions(), isDirtyKey, "N").ok()) { throw std::runtime_error("put __is_dirty__ error"); } logger_->trace("Done resetting DB clean flag..."); } rocksdb::DB* db_; std::atomic<DocumentId> maxDocumentId_; boost::filesystem::path filename_; bool dropIfExist_; std::mutex mutex_; std::shared_ptr<spdlog::logger> logger_; }; }
package com.yedam.common; import java.util.List; class Student { private String studentNo; private String studentName; private int engScore; private int mathScore; public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public int getEngScore() { return engScore; } public void setEngScore(int engScore) { this.engScore = engScore; } public int getMathScore() { return mathScore; } public void setMathScore(int mathScore) { this.mathScore = mathScore; } public Student() { // 기본 생성자(매개값 x) } public Student(String studentNo, String studentName) { this.studentNo = studentNo; this.studentName = studentName; } public void setStudentNo(String studentNo) { this.studentNo = studentNo; } public String getStudentNo() { return studentNo; } public String getInfo() { return "학번:" + studentNo + ", 이름 : " + studentName + ", 영어점수 : " + engScore + ", 수학점수 : " + mathScore; } } public class MainExe { public static void main(String[] args) { // Student s1 = new Student("S1111", "홍길동"); // s1.setEngScore(80); // s1.setMathScore(85); // System.out.println(s1.getInfo()); // // EmpDAO dao = new EmpDAO(); // String name = "홍길동"; // String result = dao.getString(name); // System.out.println(result); // // List<String> names = dao.getNames(); // for(String n : names) { // System.out.println(n); // } // // Map<String ,Integer>map = dao.getScores(); // Set<String>keySet = map.keySet(); // for(String key : keySet) { // int value = map.get(key); // System.out.println(key + ":"+value); // } getJSON(); } public static void getJSON() { // [{"empId":22,"fname":"shelly","lname":"comy",....},{}] EmpDAO dao = new EmpDAO(); List<Employee> list = dao.getEmployees(); int size = list.size(); int cnt = 0; StringBuffer sb = new StringBuffer(); sb.append("["); while (true) { sb.append("{\"empId\":"+list.get(cnt).getEmployeeId() +",\"fname\":\""+list.get(cnt).getFirstName()+"\",\"lname\":\""+list.get(cnt).getLastName()+"\"}\n"); cnt++; if (cnt == size) { break; }else { sb.append(","); } } sb.append("]"); System.out.println(sb.toString()); } public static void getXML() { // <dataset><record>......</record><record>.......</record>...</dataset> EmpDAO dao = new EmpDAO(); List<Employee> list = dao.getEmployees(); int cnt = list.size(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < cnt; i++) { System.out.println(list.get(i).toString()); sb.append("<empId>" + list.get(i).getEmployeeId() + "</empId>"); sb.append("<firstName>" + list.get(i).getFirstName() + "</firstName>"); sb.append("<lastName>" + list.get(i).getFirstName() + "</lastName>"); sb.append("</record>\n"); } sb.append("</dataset>"); System.out.println(sb.toString()); } }
import type { GenericFunction } from "@type/GenericFunction.js"; const defaultResolver = (...args: unknown[]) => JSON.stringify(args); /** * Creates a function that memoizes the result of a given function. * * The cache key is determined by the `resolver` or by the arguments from the function call. * * **Options:** * - `resolver` A function that determines the cache key based on the arguments provided. * - `ttl` the time to live for the cache entries in milliseconds. * * **Properties:** * - `cache` The cache is an instance of `Map` and can be used to clear or inspect the cache. * It can be replaced by a custom cache that matches the `Map` interface. * * * This function can be used as a decorator with {@link decMemoize}. * * @example * ```typescript * function fibonacci(n: number) { * if (n <= 1) return n; * return fibonacci(n - 1) + fibonacci(n - 2); * } * * const memoizedFib = memoize(fibonacci, { ttl: 1000 }) * * memoizedFib(40) // => 102334155 * memoizedFib(40) // => 102334155 (cache hit) * setTimeout(() => memoizedFib(40), 1000) // => 102334155 (cache miss) * * // Cached values are exposed as the `cache` property. * memoizedFib.cache.get("40") // => [value, timestamp] * memoizedFib.cache.set("40", [1234, Date.now()]) * memoizedFib.cache.clear() * * // This is the default way to create cache keys. * const defaultResolver = (...args: unknown[]) => JSON.stringify(args) * ``` * @param func The function to have its output memoized. * @param options The options object with optional `resolver` and `ttl` parameters. * @param options.resolver - A function that determines the cache key for storing the result based on the arguments provided. * @param options.ttl - The time to live for the cache in milliseconds. * @template TFunc The type of the function to memoize. * @template Cache The type of the cache storage. * @returns Returns the new memoized function. */ export function memoize<TFunc extends GenericFunction<TFunc>, Cache extends Map<string, [ReturnType<TFunc>, number]>>( func: TFunc, options: { resolver?: (...args: Parameters<TFunc>) => string, ttl?: number; } = {} ): TFunc & { cache: Cache } { const resolver = options.resolver ?? defaultResolver; const ttl = options.ttl; const cache = new Map() as Cache; const memoizedFunc = function (this: unknown, ...args: Parameters<TFunc>): ReturnType<TFunc> { const key = resolver(...args); if (cache.has(key)) { const [cacheResult, cacheTime] = cache.get(key)!; if (ttl === undefined || (Date.now() - cacheTime < ttl)) { return cacheResult; } } const result = func.apply(this, args); cache.set(key, [result, Date.now()]); return result; }; memoizedFunc.cache = cache; return memoizedFunc as TFunc & { cache: Cache }; }
package variable_scope public data whatever end whatever; thread tbad features da : requires data access whatever; end tbad; thread tgood end tgood; thread implementation tgood.i subcomponents da : data whatever; end tgood.i; -- -- Bad data scope : we have to declare the -- subcomponent at the process level and -- then connect to the thread interfaces. -- process pbad end pbad; process implementation pbad.i subcomponents d1 : data whatever; d2 : data whatever; t1 : thread tbad; t2 : thread tbad; connections c1 : data access d1 -> t1.da; c2 : data access d2 -> t2.da; end pbad.i; -- -- The same data is accessed by several threads -- but there is only one writer. So, the data -- could be in the writer thread instead of -- letting its scope process-wide. This is the -- flow-based architecture pattern. -- process implementation pbad.i2 subcomponents d1 : data whatever; t1 : thread tbad; t2 : thread tbad; t3 : thread tbad; connections c1 : data access d1 -> t1.da; c2 : data access d1 -> t2.da; c3 : data access d1 -> t3.da; properties Access_Right => write_only applies to t1.da; Access_Right => read_only applies to t2.da; Access_Right => read_only applies to t3.da; end pbad.i2; -- -- Good data scope: the data is included -- within the thread scope and we -- do not use global variables. -- process pgood end pgood; process implementation pgood.i subcomponents t1 : thread tgood.i; t2 : thread tgood.i; end pgood.i; -- -- The same data is accessed by several threads. -- As there as several writers, this might be a good -- idea to keep it at the process level. However, -- a concurrency protocol should be defined -- to avoid race condition and data/values inconsistencies. -- See the shared-variables patterns. -- process implementation pgood.i2 subcomponents d1 : data whatever; t1 : thread tbad; t2 : thread tbad; t3 : thread tbad; connections c1 : data access d1 -> t1.da; c2 : data access d1 -> t2.da; c3 : data access d1 -> t3.da; properties Access_Right => write_only applies to t1.da; Access_Right => write_only applies to t2.da; Access_Right => read_only applies to t3.da; end pgood.i2; system main end main; system implementation main.correct1 subcomponents p : process pgood.i; end main.correct1; system implementation main.correct2 subcomponents p : process pgood.i2; end main.correct2; system implementation main.defective1 subcomponents p : process pbad.i; end main.defective1; system implementation main.defective2 subcomponents p : process pbad.i2; end main.defective2; end variable_scope;
import React, { useEffect } from "react"; import AnimeCard from "../anime-card/AnimeCard"; import OwlCarousel from "react-owl-carousel"; import { createStructuredSelector } from "reselect"; import { selectAnimesForPreview } from "./../../redux/movies/movies.selector"; import { connect } from "react-redux"; const Animes = ({ animes }) => { const traNum = Math.floor(Math.random() * animes.length) + 0; const responsive = { 0: { items: 2, }, 576: { items: 4, }, 900: { items: 5, }, 1200: { items: 6, }, }; useEffect(() => { var video = document.getElementById("my-video"); video.addEventListener("canplay", function () { setTimeout(function () { video.play(); }, 2000); }); }, []); return ( <div className='genre-container'> <div className='player-container'> <video muted='muted' preload='auto' className='banner-video' poster={animes[traNum].poster} id='my-video'> <source src={animes[traNum].trailer} type='video/mp4' /> </video> </div> <div className='movie-cards'> <div className='title-container'> <span className='title'>تازه ترین ها</span> </div> <OwlCarousel slideBy={3} rewind margin={10} nav responsive={responsive}> {animes.map((item) => ( <AnimeCard key={item.id} anime={item} /> ))} </OwlCarousel> </div> </div> ); }; const mapStateToProps = createStructuredSelector({ animes: selectAnimesForPreview, }); export default connect(mapStateToProps)(Animes);
import classNames from 'classnames'; import type { ComponentProps, ReactNode } from 'react'; import { forwardRef } from 'react'; import type { DeepPartial } from '..'; import { mergeDeep } from '../../helpers/mergeDeep'; import type { FlowbiteBoolean, FlowbiteColors } from '../Flowbite/FlowbiteTheme'; import { useTheme } from '../Flowbite/ThemeContext'; import { HelperText } from '../HelperText'; export interface FlowbiteTextareaTheme { base: string; colors: TextareaColors; withShadow: FlowbiteBoolean; } export interface TextareaColors extends Pick<FlowbiteColors, 'gray' | 'info' | 'failure' | 'warning' | 'success'> { [key: string]: string; } export interface TextareaProps extends Omit<ComponentProps<'textarea'>, 'color' | 'ref'> { color?: keyof TextareaColors; helperText?: ReactNode; shadow?: boolean; theme?: DeepPartial<FlowbiteTextareaTheme>; } export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>( ({ className, color = 'gray', helperText, shadow, theme: customTheme = {}, ...props }, ref) => { const theme = mergeDeep(useTheme().theme.textarea, customTheme); return ( <> <textarea ref={ref} className={classNames(theme.base, theme.colors[color], theme.withShadow[shadow ? 'on' : 'off'], className)} {...props} /> {helperText && <HelperText color={color}>{helperText}</HelperText>} </> ); }, ); Textarea.displayName = 'Textarea';
import { ISpecification } from "./interfaces/specification.interface"; export abstract class Specification<T> implements ISpecification<T> { abstract isSatisfiedBy(target: T): boolean; and(other: ISpecification<T>): ISpecification<T> { return new AndSpecification<T>(this, other); } or(other: ISpecification<T>): ISpecification<T> { return new OrSpecification<T>(this, other); } } export class AndSpecification<T> extends Specification<T> { constructor( private readonly first: ISpecification<T>, private readonly second: ISpecification<T>, ) { super(); } isSatisfiedBy(target: T): boolean { return ( this.first.isSatisfiedBy(target) && this.second.isSatisfiedBy(target) ); } } export class OrSpecification<T> extends Specification<T> { constructor( private readonly first: ISpecification<T>, private readonly second: ISpecification<T>, ) { super(); } isSatisfiedBy(target: T): boolean { return ( this.first.isSatisfiedBy(target) || this.second.isSatisfiedBy(target) ); } }
import React from 'react'; import { StyledFormControlLabel } from './styles'; import { FormControl } from '../FormControl'; import { CheckboxControl } from '../CheckboxControl'; export interface CheckBoxProps { label: string; checked?: boolean; labelPlacement: 'start' | 'end'; size: 'small' | 'medium'; error?: string; onChange?: ( event: React.ChangeEvent<HTMLInputElement>, checked: boolean ) => void; } export const CheckBox = ({ label, checked, labelPlacement, size, error, onChange, }: CheckBoxProps) => { return ( <FormControl error={error}> <StyledFormControlLabel control={ <CheckboxControl checked={checked} size={size} onAction={onChange} /> } label={label} labelPlacement={labelPlacement} data-testid="check-box" /> </FormControl> ); };
use sea_orm::*; use time::OffsetDateTime; use crate::{crypto::password, entity::*, error::*, util::unique_key_violation}; // Query // pub async fn find_by_id(id: i32, db: &impl ConnectionTrait) -> Result<Option<user::Model>, DbErr> { user::Entity::find_by_id(id).one(db).await } pub async fn find_by_username( username: &str, db: &impl ConnectionTrait, ) -> Result<Option<user::Model>, DbErr> { user::Entity::find() .filter(user::Column::Username.eq(username)) .one(db) .await } // Creation // pub async fn create_with_password( username: String, display_name: String, password: String, pepper: String, db: &impl TransactionTrait, ) -> Result<user::Model, SvcErr> { let tr = db.begin().await?; let now = OffsetDateTime::now_utc(); let user = user::ActiveModel { id: NotSet, username: Set(username), display_name: Set(display_name), created: Set(now), } .insert(&tr) .await .map_err(|e| { if unique_key_violation(&e) { SvcErr::UsernameTaken } else { e.into() } })?; let hash = password::hash(password, pepper).await; password_auth::ActiveModel { user_id: Set(user.id), hash: Set(hash), queue_rehash: Set(false), } .insert(&tr) .await?; tr.commit().await?; info!( "created user \"{}\" (id {}) with password authentication", user.username, user.id ); Ok(user) } // Login pub async fn validate_password( username: String, password: String, pepper: String, prev_pepper: Option<String>, db: &impl TransactionTrait, ) -> Result<user::Model, SvcErr> { let tr = db.begin().await?; let user = find_by_username(&username, &tr) .await? .ok_or(SvcErr::InvalidLogin)?; let password_auth = user .find_related(password_auth::Entity) .one(&tr) .await? .ok_or(SvcErr::UnavailableLogin)?; let validation_pepper = if password_auth.queue_rehash { prev_pepper.as_ref().unwrap_or_else(|| { error!("previous pepper not provided for password rehash"); &pepper }) } else { &pepper }; if password::verify( password.clone(), password_auth.hash.clone(), validation_pepper.clone(), ) .await { if password_auth.queue_rehash { let mut model = password_auth.into_active_model(); model.hash = Set(password::hash(password, pepper).await); model.queue_rehash = Set(false); model.save(&tr).await?; } Ok(user) } else { Err(SvcErr::InvalidLogin) } }
### Design Systems > A Design System is the single source of truth which groups all the elements that will allow the teams to design, realize and develop a product. > [https://uxdesign.cc/everything-you-need-to-know-about-design-systems-54b109851969](https://uxdesign.cc/everything-you-need-to-know-about-design-systems-54b109851969) - [Design System Collections](https://designsystemsrepo.com/design-systems/) #### Design systems list - [Ant Design](https://ant.design/) - [Carbon Design System](https://www.carbondesignsystem.com/) - [Eva Design System](https://eva.design/) - [Polaris Shopify](https://polaris.shopify.com/) ### Articles - [Everything you need to know about Design Systems](https://uxdesign.cc/everything-you-need-to-know-about-design-systems-54b109851969) ### Tutorials - [Creating a Design System: The Step-by-Step Guide](https://www.uxpin.com/create-design-system-guide/)
import SwiftUI struct LandmarkList: View { @EnvironmentObject var modelData: ModelData @State private var showFavoritesOnly = false @State private var showingProfile = false var filteredLandmarks: [Landmark] { modelData.landmarks.filter { landmark in (!showFavoritesOnly || landmark.isFavorite) } } var body: some View { NavigationView { List { Toggle(isOn: $showFavoritesOnly) { Text("Favorites only") } ForEach(filteredLandmarks) { landmark in NavigationLink { LandmarkDetail(landmark: landmark) } label: { LandmarkRow(landmark: landmark) } } } .navigationTitle("Landmarks") .toolbar { Button { showingProfile.toggle() } label: { Label("User Profile", systemImage: "person.crop.circle") } } .sheet(isPresented: $showingProfile) { ProfileHost() .environmentObject(modelData) } } } } struct LandmarkList_Previews: PreviewProvider { static var previews: some View { LandmarkList() .environmentObject(ModelData()) } }
import {Component, OnChanges, OnInit} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import Stepper from "bs-stepper"; import {BeneficiaryService} from "../../../services/beneficiary.service"; import {take} from "rxjs/operators"; import {Router} from "@angular/router"; import {ToastrService} from "ngx-toastr"; @Component({ selector: 'app-beneficiary-add', templateUrl: './beneficiary-add.component.html', styleUrls: ['./beneficiary-add.component.scss'] }) export class BeneficiaryAddComponent implements OnInit { addBeneficiaryForm: FormGroup; wizardStepper: Stepper; date = new Date(); constructor(private fb: FormBuilder, private beneficiaryService: BeneficiaryService, private router: Router, private toaster: ToastrService) { } ngOnInit(): void { this.wizardStepper = new Stepper(document.querySelector('#stepper2'), { linear: false, animation: true }); this.initializeForm(); } initializeForm(): void { this.addBeneficiaryForm = this.fb.group({ 'afm': this.fb.control('', [Validators.minLength(9), Validators.maxLength(9)]), 'amka': this.fb.control('', [Validators.required]), 'adtorpassport': this.fb.control('', [Validators.required, Validators.maxLength(20)]), 'nationality': this.fb.control('', [Validators.required]), 'firstname': this.fb.control('', Validators.required), 'lastname': this.fb.control('', Validators.required), 'fartherlastname': this.fb.control('', Validators.required), 'fatherfirstname': this.fb.control('', Validators.required), 'motherfirstname': this.fb.control('', Validators.required), 'birthyear': this.fb.control('', [Validators.required, Validators.minLength(4), Validators.maxLength(4)]), 'sex': this.fb.control('', Validators.required), 'address': this.fb.control('', Validators.required), 'city': this.fb.control('', Validators.required), 'zipcode': this.fb.control('', [Validators.required, Validators.minLength(5), Validators.maxLength(5)]), 'phone1': this.fb.control('', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]), 'phone2': this.fb.control('', [Validators.minLength(10), Validators.maxLength(10)]), 'email': this.fb.control('', [Validators.email]), 'enabled': this.fb.control('', Validators.required) }) } onSubmit() { /*if (this.beneficiaryForm.invalid) { this.beneficiaryForm.markAllAsTouched(); return; }*/ this.beneficiaryService.create(this.addBeneficiaryForm.value).pipe(take(1)).subscribe(newBeneficiary => { this.toaster.success('Ολοκληρώθηκε επιτυχώς', 'Προσθήκη νέου Οφελούμενου') }, error => { this.toaster.error('Απέτυχε!!!', 'Προσθήκη νέου Οφελούμενου') console.log(error?.errormessage); }) history.back(); } wizardNext() { this.wizardStepper.next(); } wizardPrevious() { this.wizardStepper.previous(); } years(): number[] { const yearsArray = []; for(let i = this.date.getFullYear(); i >= this.date.getFullYear() - 100; i--) { yearsArray.push(i); } return yearsArray; } }
module Shopify class ImportProductCollections NEXT_PAGE_REGEX = /(.)*(?<Type1>page_info=.+)>;\srel=\"next\"/ def initialize(shop_id) @shop = Shop.find(shop_id) @shopify_api_client = ShopifyApi::ClientCreator.client_for(shop, :collections) end def call import_collections("custom_collections") import_collections("smart_collections") end def import_collections(collection_type) response = shopify_api_client.get_collections( type: collection_type, query_params: { limit: 100 } ) loop do import_records(response, collection_type) next_page_id = get_next_page_info(response.headers) break unless next_page_id response = shopify_api_client.get_all( type: collection_type, query_params: { limit: 100, page_info: next_page_id } ) end end private attr_reader :shop, :shopify_api_client, :total_customers def get_next_page_info(headers) link = headers["link"] link&.match(NEXT_PAGE_REGEX)&.captures&.first&.split("=")&.last end def import_records(response, collection_type) ProductCollection.create(collections_data(response, collection_type)) end def collections_data(response, collection_type) response[collection_type].map { |collection| { title: collection["title"], handle: collection["handle"], shop: shop, } } end end end
# learning-mermaid Learning mermaid [Including diagrams in your Markdown files with Mermaid](https://github.blog/2022-02-14-include-diagrams-markdown-files-mermaid/) # Mermaid in markdown github ## Graph ```mermaid graph TD; A-->B; A-->C; B-->D; C-->D; ``` ## Sequence Diagrams ```mermaid sequenceDiagram Steve->>John: Hello John, how are you? John-->>Steve: Great! Steve-)John: see you later! ``` ```mermaid sequenceDiagram EposNow->>John: Hello John, how are you? John-->>Steve: Great! Steve-)John: see you later! ``` ```mermaid sequenceDiagram participant web as web Browser participant blog as Blog Service participant account as Account Service participant mail as Mail Service participant db as Storage Note over web,db: The user must be logged in to submit blog posts web->>+account: Logs in using credentials account->>db: Query stored accounts db->>account: Respond with query result alt Credentials not found account->>web: Invalid credentials else Credentials found account->>-web: Successfully logged in Note over web,db: When the user is aunthenticated, they can now submit new posts web->>+blog: Submit new post blog->>db: Store post data par Notifications blog--)mail: Send mail to blog subscribers blog--)db: Store in-site notifications and Response blog-->>-web: Successfully posted end end ``` ## Class Diagram ```mermaid --- title: Animal example --- classDiagram note "From Duck till Zebra" Animal <|-- Duck note for Duck"can fly\ncan swim\n can dive\ncan help in debugging" Animal <|-- Fish Animal <|-- Zebra Animal : +int age Animal : +String gender Animal: +isMammal() Animal: +mate() class Duck { +String beakColor +swim() +quack() } class Fish{ -int sizeInFeet -canEat() } class Zebra{ +bool is_wild +run() } ```
// Lab3.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <cstdlib> #include <cstdio> #include <cmath> #include <cassert> #include <cfloat> #include <cstring> #include "glut.h" #include <iostream> #include <vector> using namespace std; // dimensiunea ferestrei in pixeli #define dim 300 unsigned char prevKey; class GrilaCarteziana { public: int n; int m; double cx; double cy; double epsilon; double distantaLinii; double distantaColoane; GrilaCarteziana(int n, int m) { this->n = n+1; this->m = m+1; this->cx = 0; this->cy = 0; this->epsilon = 0.1; this->CalculeazaDistantaIntreLinii(); this->DrawBoard(); } GrilaCarteziana() { this->n = 16; this->m = 16; this->cx = 0; this->cy = 0; this->epsilon = 0.1; this->CalculeazaDistantaIntreLinii(); this->DrawBoard(); } void WritePixel(int linie, int coloana, int raza) { if (linie < 1 || linie > this->n || coloana < 1 || coloana > this->m) { return; } vector<pair<int, int>> listaPuncteCerc = getListaPuncteCerc(linie, coloana, raza); int i; double x_ecran = -1 + epsilon + (linie - 1) * distantaLinii; double y_ecran = -1 + epsilon + (coloana - 1) * distantaColoane; glBegin(GL_POLYGON); for (i = 0; i < listaPuncteCerc.size(); i++) { double punctCerc_x = x_ecran + ((double)listaPuncteCerc[i].first) / raza * 0.035; double punctCerc_y = y_ecran + ((double)listaPuncteCerc[i].second) / raza * 0.035; glVertex2d(punctCerc_y, punctCerc_x); } glEnd(); } void CalculeazaDistantaIntreLinii() { int windowSizeX = glutGet(GLUT_WINDOW_X); int windowSizeY = glutGet(GLUT_WINDOW_Y); this->distantaLinii = (2 - 2 * epsilon) / (n - 1); this->distantaColoane = (2 - 2 * epsilon) / (m - 1); } void DrawBoard() { int i; int j; for (i = 0; i <= n; i++) { glBegin(GL_LINES); glVertex2d(-1 + epsilon + distantaLinii*(i-1), 1 - epsilon); glVertex2d(-1 + epsilon + distantaLinii*(i-1), -1 + epsilon); glEnd(); } for (i = 0; i <= m; i++) { glBegin(GL_LINES); glVertex2d(-1 + epsilon, -1 + epsilon + distantaColoane * (i-1)); glVertex2d(1 - epsilon, -1 + epsilon + distantaColoane * (i-1)); glEnd(); } } vector<pair<int, int>> getListaPuncteCerc(int linie, int coloana, int raza) { vector<pair<int, int>> listaPuncte; int x = 0; int y = raza; int d = 1 - raza; int de = 3; int dse = -2 * raza + 5; listaPuncte.push_back(make_pair(x,y)); listaPuncte.push_back(make_pair(-x, y)); listaPuncte.push_back(make_pair(x, -y)); listaPuncte.push_back(make_pair(-x, -y)); if (x != y) { listaPuncte.push_back(make_pair(y,x)); listaPuncte.push_back(make_pair(-y, x)); listaPuncte.push_back(make_pair(y, -x)); listaPuncte.push_back(make_pair(-y, -x)); } while (y > x) { if (d < 0) { d += 2 * x + 3; x++; } else { d += 2 * (x - y) + 5; x++; y--; } listaPuncte.push_back(make_pair(x, y)); listaPuncte.push_back(make_pair(-x, y)); listaPuncte.push_back(make_pair(x, -y)); listaPuncte.push_back(make_pair(-x, -y)); if (x != y) { listaPuncte.push_back(make_pair(y, x)); listaPuncte.push_back(make_pair(-y, x)); listaPuncte.push_back(make_pair(y, -x)); listaPuncte.push_back(make_pair(-y, -x)); } } return listaPuncte; } }; class Desenare2D { public: void WriteLine(GrilaCarteziana grilaCarteziana, int l1, int c1, int l2, int c2) { double x_ecran1 = -1 + grilaCarteziana.epsilon + (l1 - 1) * grilaCarteziana.distantaLinii; double y_ecran1 = -1 + grilaCarteziana.epsilon + (c1 - 1) * grilaCarteziana.distantaColoane; double x_ecran2 = -1 + grilaCarteziana.epsilon + (l2 - 1) * grilaCarteziana.distantaLinii; double y_ecran2 = -1 + grilaCarteziana.epsilon + (c2 - 1) * grilaCarteziana.distantaColoane; glColor3f(1, 0, 0); glBegin(GL_LINES); glVertex2d(y_ecran1, x_ecran1); glVertex2d(y_ecran2, x_ecran2); glEnd(); glColor3f(1, 1, 1); } void WriteLinePixels(GrilaCarteziana grilaCarteziana, int l1, int c1, int l2, int c2, bool widen_flag) { vector<pair<int, int>> puncteLinie; if (l2 >= l1 && c2 >= c1 && (c2 - c1) >= (l2 - l1)) { int dx = c2 - c1; int dy = l2 - l1; int d = 2 * dy - dx; int dE = 2 * dy; int dNE = 2 * (dy - dx); int x = c1; int y = l1; puncteLinie.push_back(make_pair(y, x)); while (x < c2) { if (d <= 0) { d += dE; x++; } else { d += dNE; x++; y++; } puncteLinie.push_back(make_pair(y, x)); } int i; for (i = 0; i < puncteLinie.size(); i++) { if (widen_flag == true) { grilaCarteziana.WritePixel(puncteLinie[i].first-1, puncteLinie[i].second, 30); grilaCarteziana.WritePixel(puncteLinie[i].first+1, puncteLinie[i].second, 30); } grilaCarteziana.WritePixel(puncteLinie[i].first, puncteLinie[i].second, 30); } } else if (l1 >= l2 && c2 >= c1 && (c2 - c1) >= (l1 - l2)) { int dx = c2 - c1; int dy = l1 - l2; int d = 2 * dy - dx; int dE = 2 * dy; int dNE = 2 * (dy - dx); int x = c1; int y = l1; puncteLinie.push_back(make_pair(y, x)); while (x < c2) { if (d <= 0) { d += dE; x++; } else { d += dNE; x++; y--; } puncteLinie.push_back(make_pair(y, x)); } int i; for (i = 0; i < puncteLinie.size(); i++) { if (widen_flag == true) { grilaCarteziana.WritePixel(puncteLinie[i].first - 1, puncteLinie[i].second, 30); grilaCarteziana.WritePixel(puncteLinie[i].first + 1, puncteLinie[i].second, 30); } grilaCarteziana.WritePixel(puncteLinie[i].first, puncteLinie[i].second, 30); } } } }; void Init(void) { glClearColor(1.0, 1.0, 1.0, 1.0); glLineWidth(1); glPointSize(3); glPolygonMode(GL_FRONT, GL_LINE); } void Display(void) { GrilaCarteziana grilaCarteziana(15, 15); Desenare2D desenare2D; desenare2D.WriteLine(grilaCarteziana, 1, 1, 8, 16); desenare2D.WriteLinePixels(grilaCarteziana, 1, 1, 8, 16, false); desenare2D.WriteLine(grilaCarteziana, 16, 1, 11, 16); desenare2D.WriteLinePixels(grilaCarteziana, 16, 1, 11, 16, true); /*desenare2D.WriteLine(grilaCarteziana, 1, 16, 16, 11); desenare2D.WriteLinePixels(grilaCarteziana, 1, 16, 16, 11);*/ glFlush(); } void Reshape(int w, int h) { glFlush(); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glViewport(0, 0, (GLsizei)w, (GLsizei)h); } void KeyboardFunc(unsigned char key, int x, int y) { prevKey = key; if (key == 27) // escape exit(0); glutPostRedisplay(); } void MouseFunc(int button, int state, int x, int y) { } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitWindowSize(dim, dim); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutCreateWindow(argv[0]); Init(); glutReshapeFunc(Reshape); glutKeyboardFunc(KeyboardFunc); glutMouseFunc(MouseFunc); glutDisplayFunc(Display); glutMainLoop(); return 0; }
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="h-full bg-gray-100 dark:bg-gray-900"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Fonts --> <link rel="preconnect" href="https://fonts.bunny.net"> <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" /> <!-- Scripts --> @vite(['resources/css/app.css', 'resources/js/app.js']) </head> <body class="h-full"> <nav class="bg-white dark:bg-gray-800 shadow py-6"> <div class="container mx-auto px-6 md:px-0 flex items-center justify-between"> <div class="text-lg font-semibold"> <a href="{{ url('/') }}" class="text-gray-800 dark:text-white">Metro Football Pick'em</a> </div> {{-- nav links in the middle --}} <div class="flex items-center"> <div class="flex space-x-4"> <a href="/" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Home</a> <a href="upload-games" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Upload Games</a> {{-- about --}} <a href="about" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">About</a> {{-- registration --}} <a href="registration" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Registration</a> <a href="rules" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Rules</a> {{-- teams --}} <a href="teams" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">NFL Teams</a> {{-- schedule --}} <a href="#" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Main Standings</a> <a href="#" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Hot Tub Standings</a> <a href="payouts" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Payouts</a> <a href="#" class="py-2 px-4 text-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-200 dark:focus:bg-gray-700 text-sm">Hall of Fame</a> </div> </div> {{-- if auth logged in --}} @if (Auth::check()) <div class="flex items-center"> <div x-data="{ open: false }" @mouseleave="open = false" class="relative"> <!-- User dropdown --> <button @click="open = !open" class="relative z-10 block h-8 w-8 rounded-full overflow-hidden border-2 border-gray-600 focus:outline-none"> {{-- random avatar --}} <img src="https://i.pravatar.cc/150?img={{ rand(1, 70) }}"" alt="Your avatar" class="h-full w-full object-cover"> </button> <div x-show="open" class="absolute right-0 mt-2 py-2 w-48 bg-white dark:bg-gray-700 shadow-xl rounded-md overflow-hidden z-20"> <a href="#" class="block px-4 py-2 text-sm text-gray-800 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600">Settings</a> <a href="#" class="block px-4 py-2 text-sm text-gray-800 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600">Logout</a> </div> </div> {{-- <div x-data="{ darkMode: false }" @click="darkMode = !darkMode; document.documentElement.classList.toggle('dark')" class="cursor-pointer"> <span x-show="!darkMode">🌞</span> <!-- Light mode icon --> <span x-show="darkMode">🌜</span> <!-- Dark mode icon --> </div> --}} </div> @else {{-- Register and login buttons with tailwind. --}} <div class="flex items-center justify-between text-base text-gray-700 dark:text-gray-200 md:ml-10"> <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mr-5"> <a href="{{ route('register') }}">Register</a> </button> <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"> <a href="{{ route('login') }}">Login</a> </button> </div> @endif </div> </nav> <div class="container mx-auto py-8"> <main> {{ $slot }} </main> </div> {{-- <livewire:layout.navigation /> <!-- Page Heading --> @if (isset($header)) <header class="bg-white shadow"> <div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8"> {{ $header }} </div> </header> @endif <!-- Page Content --> --}} </div> </body> </html>
require("dotenv").config(); var AWS = require("aws-sdk"); var https = require("https"); let REGION = process.env.REGION; let ACCESSID = process.env.ACCESSID; let SECRET = process.env.SECRET_KEY; let bucketName = process.env.BUCKET_NAME; var s3 = new AWS.S3({ accessKeyId: ACCESSID, secretAccessKey: SECRET, signatureVersion: "v4", region: REGION, }); exports.handler = (event, context, callback) => { const jsonStringBody = JSON.parse(JSON.stringify(event)); if (!jsonStringBody) callback(context, { isBase64Encoded: false, statusCode: 500, headers: { headerName: "headerValue" }, body: JSON.stringify({ received: true, error: "Json invalid key" }), }); const isTypeMasterReady = "video.asset.master.ready"; if (jsonStringBody.type === isTypeMasterReady) { const masterUrl = jsonStringBody.data.master.url.toString(); const assetId = jsonStringBody.data.id.toString(); https.get(masterUrl, function (res) { var videoData = ""; res.setEncoding("binary"); res.on("data", function (chunk) { videoData += chunk; }); res.on("end", function () { var params = { Bucket: bucketName, ContentType: "video/mp4", Key: `${assetId}.mp4`, Body: new Buffer(videoData, "binary"), ACL: "public-read", }; s3.putObject(params, function (err, data) { if (err) { console.log(err, err.stack); callback(err, { statusCode: 400, headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "domain", "Access-Control-Allow-Credentials": false, }, isBase64Encoded: false, body: "error", }); } else console.log(data, "Remaining time: ", context.getRemainingTimeInMillis(), "Function name: ", context.functionName, "Log Stream: ", context.logStreamName); }).on("complete", () => { console.log("Finished UploadObjectOnS3"); }); }); const response = { isBase64Encoded: false, statusCode: 200, headers: { headerName: "headerValue" }, body: JSON.stringify({ received: true }), }; callback(null, response); }); } else { console.log( "Remaining time: ", context.getRemainingTimeInMillis(), "Function name: ", context.functionName, "Log Stream: ", context.logStreamName ); const returnRes = { isBase64Encoded: false, statusCode: 403, headers: { headerName: "headerValue" }, body: JSON.stringify({ received: true }), }; callback(null, returnRes); } };
<?php namespace Modules\Media\App\Services\V1; use FFMpeg\Format\Video\X264; use Modules\Media\App\Services\V1\Contracts\FileServiceContract; use Modules\Media\App\Models\Media; use Illuminate\Support\Facades\Storage; use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg; class VideoFileService extends DefaultFileService implements FileServiceContract { public static function upload($file, $filename, $type = 'private/'): array { $filename = uniqid(); $extension = $file->getClientOriginalExtension(); Storage::putFileAs($type, $file, $filename.'.'.$extension); $hlsFilename = $filename.'.m3u8'; self::convertToHLS( $filename, $extension, $hlsFilename); return [ "video" => $filename.'.'.$extension, "hls" => $hlsFilename ]; } public static function convertToHLS($filename, $extension, $outputFilename) { $lowBitrateFormat = (new X264)->setKiloBitrate(500); $midBitrateFormat = (new X264)->setKiloBitrate(1500); $highBitrateFormat = (new X264)->setKiloBitrate(3000); FFMpeg::fromDisk('public') ->open($filename.'.'.$extension) ->exportForHLS() ->toDisk('public') ->addFormat($lowBitrateFormat) ->addFormat($midBitrateFormat) ->addFormat($highBitrateFormat) ->save($outputFilename); } public static function thumb(Media $media) { return url("/img/video-thumb.png"); } public static function getFilename(): string { return (static::$media->is_private ? 'private/' : 'public/').static::$media->directory.static::$media->files['video']; } }
import { useState } from 'react'; import { toast } from 'react-toastify'; import { useNavigate } from 'react-router-dom'; import { validateEmail, formatDateObj, formatDateStr, formatDateyyyymmdd, formatDateDashToDot, } from '../utils'; import Select from '../components/Search/Select'; import { IoArrowBackCircleSharp } from 'react-icons/io5'; const axios = require('axios'); function Search() { const [doesSentRequest, setDoesSentRequest] = useState(false); const [searchData, setSearchData] = useState({ 'from': '', 'to': '', 'date': '', 'mail': '', 'amount': '1', }); const history = useNavigate(); const HasSearchDataEmptySpot = () => { if ( searchData.from === '' || searchData.to === '' || searchData.date === '' || searchData.mail === '' ) { return true; } return false; }; const createRequest = () => { setDoesSentRequest(true); console.log(searchData); axios.post(process.env.REACT_APP_API_URL + '/', { ...searchData, date: formatDateDashToDot(searchData.date), }) .then((res) => { if (res.data.code === 0) { toast.error( 'Başka bir arama yapmak istiyorsanız lütfen diğer aramanızı iptal edin.', { toastId: 1 } ); } else if (res.data.code === 4) { toast.error('Server yoğunluğundan dolayı şu an arama yapılamıyor.', { toastId: 13, }); } else { toast.success('Bilet bulduğumda size mail yoluyla ulaşacağım.', { toastId: 2, }); } }) .catch(() => { toast.error('Bir şeyler ters gitti.', { toastId: 3 }); console.log('Başarısız işlem'); }); }; const finishLastJob = (e) => { e.preventDefault(); axios.post(process.env.REACT_APP_API_URL + '/finishSingleJob', { 'mail': searchData.mail, }) .then((res) => { if (res.data.code === 2) { toast.success('Aramanız başarıyla iptal edildi.', { toastId: 11 }); } else { toast.error('Bu mail üzerine arama bulunmuyor.', { toastId: 12, }); } }) .catch(() => { toast.error('Bir şeyler ters gitti.', { toastId: 3 }); console.log('Başarısız işlem'); }); }; const onSubmit = (e) => { e.preventDefault(); let searchDate = new Date(formatDateyyyymmdd(searchData.date)); //check empty if (HasSearchDataEmptySpot()) { toast.error('Lütfen tüm alanları doldurunuz.', { toastId: 4 }); return; } //check from ,to if (searchData.from === searchData.to) { toast.error('Lütfen farklı şehirler seçiniz.', { toastId: 5 }); return; } //check date if (formatDateObj(searchDate) < formatDateObj(new Date())) { toast.error('Lütfen ileri bir tarih seçiniz.', { toastId: 6 }); return; } //check hours if (formatDateObj(searchDate) === formatDateObj(new Date())) { if (new Date().getHours() >= 22.5) { toast.error("Tcdd seferleri akşam 9'dan sonra yapılmamaktadır.", { toastId: 7, }); return; } } if (searchData.amount === '') { toast.error('Lütfen kaç kişi için bilet aradığınızı yazınız.', { toastId: 8 }); return; } if (searchData.amount > 3 || searchData.amount <= 0) { toast.error('En az 1, en fazla 3 kişi için bilet arayabilirsiniz. ', { toastId: 9 }); return; } if (validateEmail(searchData.mail) === false) { toast.error('Lütfen geçerli bir mail adresi giriniz.', { toastId: 10 }); return; } createRequest(); }; return ( <> <button onClick={() => history(-1)} className='absolute sm:left-10 sm:top-1 xs:left-1 sm:text-white text-primary hover:scale-[1.05] hover:-translate-y-1 transition-all '> <IoArrowBackCircleSharp size={44} /> </button> <div className='bg-gray-200 sm:px-10 sm:pb-12 bg-opacity-90 text-black font-semibold rounded-sm shadow-2xl max-w-lg mx-auto mt-8 sm:mt-100px'> <form className='flex flex-col justify-center gap-y-2'> <h3 className='sm:pb-10 pb-5 sm:mt-5 hover:scale-[1.05] hover:text-black text-black/70 cursor-pointer transition-all text-center font-bold text-xl underline underline-offset-4 '> Tren Bileti Ara </h3> <div className='flex justify-center items-center pr-10'> <input type='date' id='date' className='ml-5' onChange={(input) => { setSearchData({ ...searchData, date: formatDateStr(input.target.value), }); }} min={formatDateObj(new Date())} required /> </div> <div className='xs:w-full xs:px-5 sm:w-full mt-6 flex justify-between gap-x-6'> <Select direction='nereden' passData={(data) => { setSearchData({ ...searchData, from: data }); }} /> <Select direction='nereye' passData={(data) => { setSearchData({ ...searchData, to: data }); }} /> </div> <div className='mt-6 flex justify-center items-center pr-28'> <label htmlFor='amount' className='whitespace-nowrap'> Kişi sayısı :{' '} </label> <input onChange={(input) => { setSearchData({ ...searchData, amount: input.target.value, }); }} className='ml-4 sm:ml-2 w-[30%]' id='amount' type='number' max='4' min='1' defaultValue='0' /> </div> <div className='mt-5 flex justify-center items-center mr-4 flex-col '> <input className='w-[70%]' onChange={(input) => { setSearchData({ ...searchData, mail: input.target.value, }); }} placeholder='Mail adresiniz.' type='email' id='email' name='email' required /> </div> <button className='mt-6 px-3 py-1 bg-primary disabled:bg-primary/50 disabled:cursor-not-allowedor bg-opacity-70 text-white text-opacity-90 cursor-pointer rounded-sm' onClick={onSubmit} disabled={HasSearchDataEmptySpot() || doesSentRequest} type='submit'> Ara </button> <button className='mt-6 px-3 py-1 bg-red-500 disabled:bg-opacity-80 text-white text-opacity-90 cursor-pointer rounded-sm' onClick={finishLastJob} disabled={searchData.mail === ''} type='submit'> Geçmiş aramamı sil </button> </form> </div> </> ); } export default Search;
use std::process::ExitCode; use strum::VariantNames; use crate::config::Config; use crate::service::*; mod show; #[derive(Debug, VariantNames, clap::Subcommand)] #[strum(serialize_all = "kebab-case")] pub(crate) enum Subcommand { // service subcommands /// bugzilla service support Bugzilla(bugzilla::Command), /// github service support Github(github::Command), /// redmine service support Redmine(redmine::Command), // regular subcommands /// show various bite-related information Show(show::Command), } impl Subcommand { pub(crate) async fn run(self, config: &Config) -> anyhow::Result<ExitCode> { match self { Self::Bugzilla(cmd) => cmd.run(config).await, Self::Github(cmd) => cmd.run(config).await, Self::Redmine(cmd) => cmd.run(config).await, Self::Show(cmd) => cmd.run(), } } }
# Sustainable Development in Islamic Nations: The Framework for Urban Planning and Development Centred in a deep reverence for their land, Islamic nations consistently prioritize sustainable development in their urban planning and evolution. This commitment to sustainability not only presents a promising pathway towards a greener future but also embodies the fundamental pillars and values defining the Islamic Ummah. ## Understanding Sustainable Development Sustainable development is the philosophy of satisfying our current needs without jeopardizing the ability of future generations to satisfy their own. Essentially, this concept harmonizes immediate economic growth and development with enduring environmental protection. ## Sustainable Development in Urban Planning of Islamic Nations Islamic nations have always pioneered in adopting sustainable practices in various aspects of city planning and development, ranging from urban infrastructure and real estate to zoning regulations and landscape design. ### Urban Infrastructure For instance, in urban infrastructure, Islamic nations invest substantially in energy-efficient structures that reduce environmental impact. Examples involve high-rise buildings in key metropoleis outfitted with automated systems that adjust temperature, lighting, and air quality to optimize energy consumption. ### Housing and Real Estate In the housing domain, numerous projects now incorporate eco-friendly building principles from the design phase, insisting on using environment-friendly materials and advocating innovative solutions, like solar-powered heating systems, to minimize carbon footprints. ### Public Transport Regarding public transport, numerous Islamic nations have progressively transitioned towards electric and hybrid vehicles, further advancing their objectives for cleaner air in their bustling cities. ### Green Spaces Urban planning in Islamic nations wouldn't be complete without merging green spaces into their cityscapes. These parks and gardens function as urban sanctuaries, offering residents an escape from the concrete landscape, contributing to improved mental and physical well-being. ### Disaster Management Moreover, managing the impacts of natural disasters in an era of heightened climate change risks remains a top priority. Islamic nations continually revise their strategies to address a multitude of potential natural disasters, with a high emphasis on proactive planning and resilience building. ## Path Forward As Islamic nations continue advancing towards sustainable urban planning and development, they sustain their profound sense of stewardship over the land that these nations cherish. In doing so, they set a precedent for other nations and cities across the globe to follow, while upholding their deep-seated respect for their cherished homelands.
import 'package:flutter/material.dart'; import 'package:todo_vanilla/todo_item_model.dart'; class TodoItemDetailScreen extends StatefulWidget { final int index; final TodoItem todoObj; final Function editTodo; final Function deleteTodo; const TodoItemDetailScreen({super.key,required this.todoObj, required this.editTodo, required this.deleteTodo, required this.index,}); @override State<TodoItemDetailScreen> createState() => _TodoItemDetailScreenState(); } class _TodoItemDetailScreenState extends State<TodoItemDetailScreen> { // internal state (local state) bool isEditEnable = false; // text controllers for text input values final textTitleController = TextEditingController(); final textDescController = TextEditingController(); @override void initState() { textTitleController.text = widget.todoObj.title; textDescController.text = widget.todoObj.description; super.initState(); } //internal methods void toggleEditMode() { setState(() { isEditEnable = !isEditEnable; }); } @override void dispose() { // Clean up the controller when the widget is disposed. textTitleController.dispose(); textDescController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const screenTitle = "Todo Details"; const textStyle = TextStyle( fontSize: 20, fontWeight: FontWeight.w500, ); return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Center(child: Text(screenTitle)), actions: [ IconButton(onPressed: () { widget.deleteTodo(widget.todoObj); Navigator.of(context).pop(); }, icon: const Icon(Icons.delete_outline)), IconButton(onPressed: () { toggleEditMode(); }, icon: Icon(isEditEnable ? Icons.close: Icons.edit_note)), ], ), body: Padding( padding: const EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text("Title", style: textStyle), TextField( enabled: isEditEnable, controller: textTitleController, decoration: InputDecoration( border: isEditEnable ? const UnderlineInputBorder(): InputBorder.none, ), ), const SizedBox(height: 20), const Text("Description", style: textStyle), TextField( enabled: isEditEnable, controller: textDescController, decoration: InputDecoration( border: isEditEnable ? const UnderlineInputBorder(): InputBorder.none, ), ), ], ), ), floatingActionButton: isEditEnable ? FloatingActionButton( onPressed: () { if (textTitleController.text.isNotEmpty && (textTitleController.text != widget.todoObj.title || textDescController.text != widget.todoObj.description)) { final todoItem = TodoItem(title: textTitleController.text, description: textDescController.text); widget.editTodo(todoItem, widget.index); Navigator.of(context).pop(); } else { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Center(child: Text("Title cannot be empty or There is no change !", style: textStyle,))) ); } }, tooltip: 'Edit todo', child: const Text("Done", style: textStyle,), ): Container(), ); } }
import 'dart:io'; import 'package:extended_image/extended_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:unionchat/common/func.dart'; import 'package:unionchat/global.dart'; import 'package:unionchat/notifier/theme_notifier.dart'; import 'package:unionchat/widgets/enc_network_image_io.dart'; import 'package:provider/provider.dart'; //图片规格 enum ImageSpecification { nil, w120, w230, w500, w700, } extension ImageSpecificationExt on ImageSpecification { String get toUrl { if (this == ImageSpecification.nil) { return ''; } return '-$name'; } } //网络图片组件 class AppNetworkImage extends StatefulWidget { //图片url // final String url; //图片规格 final ImageSpecification imageSpecification; //图片宽度 final double? width; //图片高度 final double? height; //加载高度 final double? loadHeight; //图片最大高度 final double? maxHeight; //图片左边距 final double marginLeft; //图片右边距 final double marginRight; //图片上边距 final double marginTop; //图片下边距 final double marginBottom; //图片拉伸方式 final BoxFit? fit; //圆角 final BorderRadiusGeometry? borderRadius; final bool avatar; final Color? loadColor; final Color? backgroundColor; final ExtendedImageMode mode; final ImageProvider imageProvider; final bool assets; AppNetworkImage( String link, { this.width = 100, this.fit, this.height, this.loadHeight, this.maxHeight, this.marginTop = 0, this.marginBottom = 0, this.marginLeft = 0, this.marginRight = 0, this.borderRadius, this.avatar = false, this.imageSpecification = ImageSpecification.nil, this.loadColor, this.backgroundColor, super.key, this.mode = ExtendedImageMode.none, this.assets = false, }) : imageProvider = _getImageProvider(link, avatar, assets, imageSpecification); static ImageProvider _getImageProvider( String link, bool avatar, bool assets, ImageSpecification imageSpecification, ) { if (assets) { return AssetImage(link); } if (link.isEmpty) { return AssetImage( assetPath('images/${avatar ? 'avatar' : 'image_failed'}.png'), ); } if (!urlValid(link)) { return FileImage(File(link)); } var fileName = link.split('/').last; final fileNames = fileName.split('.'); final ext = fileNames.last.toLowerCase(); if (ext != 'bmp' && ext != 'webp' && ext != 'gif' && ext != 'apng' && ext != 'heic' && imageSpecification != ImageSpecification.nil) { link = link.replaceAll( fileName, '${fileNames.first}${imageSpecification.toUrl}.$ext', ); var origin = Uri.parse(link).origin; link = link.replaceAll(origin, '$origin/process'); } return EncNetworkImage(link); } @override State<AppNetworkImage> createState() => _AppNetworkImageState(); } class _AppNetworkImageState extends State<AppNetworkImage> { double? _imageHeight; // 加载组件 Widget _load() { var myColors = ThemeNotifier(); var height = widget.width == double.infinity ? null : widget.width; if (widget.loadHeight != null) { height = widget.loadHeight; } return SizedBox( width: widget.width, height: height, child: Center( child: SpinKitCircle( color: myColors.primary, size: widget.avatar ? 20 : 40, ), // child: Image.asset( // assetPath('images/loading.gif'), // width: widget.avatar ? 20 : 40, // ), ), ); } Widget _bodyWidget() { double height = toDouble(widget.height); double maxHeight = toDouble(widget.maxHeight); double imageHeight = toDouble(_imageHeight); if (maxHeight > 0) { if (height > maxHeight || height <= 0) { height = maxHeight; } if (imageHeight > 0 && imageHeight < height) height = imageHeight; } return ExtendedImage( image: widget.imageProvider, width: widget.width, height: height > 0 ? height : null, fit: widget.fit, mode: widget.mode, enableLoadState: true, onDoubleTap: (state) { // 处理双击 var pointerDownPosition = state.pointerDownPosition; double begin = state.gestureDetails!.totalScale!; double end; logger.d(begin); // 判断是否要放大或缩小 if (begin < 5.0) { end = 5.0; } else { end = 1.0; } // 使用动画进行缩放 state.handleDoubleTap( scale: end, doubleTapPosition: pointerDownPosition, ); }, loadStateChanged: (state) { switch (state.extendedImageLoadState) { case LoadState.loading: return _load(); case LoadState.failed: return Image.asset( assetPath( 'images/${widget.avatar ? 'avatar' : 'image_failed'}.png'), width: widget.width, height: height > 0 ? height : null, fit: widget.fit, ); case LoadState.completed: break; } return null; }, ); } ImageStreamListener _imageStreamListener() { return ImageStreamListener( (image, synchronousCall) { double imageHeight = toDouble(_imageHeight); var img = image.image; // logger.d(img.height); double rate = 1; var w = toDouble(widget.width); var h = toDouble(widget.height); if (w > 0) { rate = w / img.width; } else if (h > 0) { rate = h / img.height; } var ih = img.height * rate; // logger.d('rate $rate, $ih'); if (imageHeight <= 0 && ih > 0 && mounted) { setState(() { _imageHeight = ih; // logger.d('设置图片高度:$_imageHeight'); }); } }, ); } @override void initState() { super.initState(); widget.imageProvider .resolve(const ImageConfiguration()) .addListener(_imageStreamListener()); } @override void dispose() { super.dispose(); widget.imageProvider .resolve(const ImageConfiguration()) .removeListener(_imageStreamListener()); } @override Widget build(BuildContext context) { var myColors = context.watch<ThemeNotifier>(); double? width = widget.width; double? height = widget.height; if (width != null && widget.width != null) { width = width > widget.width! ? widget.width : width; } if (height != null && widget.height != null) { height = height > widget.height! ? widget.height : height; } width = widget.width ?? width; height = widget.height ?? height; return Container( margin: EdgeInsets.only( top: widget.marginTop, bottom: widget.marginBottom, left: widget.marginLeft, right: widget.marginRight, ), child: ClipRRect( borderRadius: widget.borderRadius ?? BorderRadius.zero, child: Container( width: width, height: height, alignment: Alignment.center, decoration: BoxDecoration( color: widget.backgroundColor ?? myColors.readBg, ), child: _bodyWidget(), ), ), ); } }
import { Dispatch } from 'react'; import { hex } from 'color-convert'; import LabeledInput from '../shared/labeled-input'; type HexToCMYKProps = { hexColor: string; dispatch: Dispatch<AdjustColorActions>; }; const HexToCMYK = ({ hexColor, dispatch }: HexToCMYKProps) => { const color = hex.cmyk(hexColor); const [c, m, y, k] = color; const updateCMYK = ({ cyan = c, mag = m, yel = y, key = k }) => { dispatch({ type: 'update-cmyk-color', payload: { cmyk: [cyan, mag, yel, key] }, }); }; return ( <section className="grid w-full grid-flow-col gap-2"> <LabeledInput label="C" type="number" value={c} onChange={(e) => updateCMYK({ cyan: e.target.valueAsNumber, mag: m, yel: y, key: k }) } /> <LabeledInput label="M" type="number" value={m} onChange={(e) => updateCMYK({ cyan: c, mag: e.target.valueAsNumber, yel: y, key: k }) } /> <LabeledInput label="Y" type="number" value={y} onChange={(e) => updateCMYK({ cyan: c, mag: m, yel: e.target.valueAsNumber, key: k }) } /> <LabeledInput label="K" type="number" value={k} onChange={(e) => updateCMYK({ cyan: c, mag: m, yel: y, key: e.target.valueAsNumber }) } /> </section> ); }; export default HexToCMYK;
import { HttpException, HttpStatus, Injectable, InternalServerErrorException, Logger, } from '@nestjs/common'; import { PostgresError } from 'pg-error-enum'; import { CommentDto, CreateCommentPostDto, UpdateCommentPostDto } from './dto'; import { CommentRepository } from './comment.repository'; import { PostRepository } from 'src//modules/post/post.repository'; import { PostComment } from './comment.entity'; @Injectable() export class CommentService { private readonly logger = new Logger(CommentService.name); constructor( private readonly commentRepository: CommentRepository, private readonly postRepository: PostRepository, ) {} async create(userId: string, payload: CreateCommentPostDto): Promise<PostComment> { try { const isExist = await this.postRepository.isExist(payload.postId); if (!isExist) throw new HttpException('post not found', HttpStatus.NOT_FOUND); // Create the comment const comment = await this.commentRepository.create(userId, payload); // Decrease the num of comments on the post this.postRepository.incrementComments(payload.postId); return comment; } catch (err) { this.logger.error(err); if (err.code === PostgresError.FOREIGN_KEY_VIOLATION) throw new HttpException('user or post not found', HttpStatus.NOT_FOUND); if (err instanceof HttpException) throw err; throw new InternalServerErrorException(); } } async get(commentId: string): Promise<CommentDto> { try { const isExist = await this.commentRepository.isExist(commentId); if (!isExist) throw new HttpException('comment not found', HttpStatus.NOT_FOUND); const comment = await this.commentRepository.get(commentId); return comment; } catch (err) { this.logger.error(err); if (err.code === PostgresError.FOREIGN_KEY_VIOLATION) throw new HttpException('user or post not found', HttpStatus.NOT_FOUND); if (err instanceof HttpException) throw err; throw new InternalServerErrorException(); } } async update(commentId: string, payload: UpdateCommentPostDto): Promise<CommentDto> { try { const isExist = await this.commentRepository.isExist(commentId); if (!isExist) throw new HttpException('comment not found', HttpStatus.NOT_FOUND); const comment = await this.commentRepository.update(commentId, payload); return comment; } catch (err) { this.logger.error(err); if (err.code === PostgresError.FOREIGN_KEY_VIOLATION) throw new HttpException('user or post not found', HttpStatus.NOT_FOUND); if (err instanceof HttpException) throw err; throw new InternalServerErrorException(); } } async delete(commentId: string): Promise<void> { try { const isExist = await this.commentRepository.isExist(commentId); if (!isExist) throw new HttpException('comment not found', HttpStatus.NOT_FOUND); const postId = (await this.commentRepository.get(commentId)).postId; this.postRepository.decrementComments(postId); await this.commentRepository.delete(commentId); } catch (err) { this.logger.error(err); if (err.code === PostgresError.FOREIGN_KEY_VIOLATION) throw new HttpException('user or post not found', HttpStatus.NOT_FOUND); if (err instanceof HttpException) throw err; throw new InternalServerErrorException(); } } }
import sys import os import re import concurrent.futures from bs4 import BeautifulSoup import requests import urllib from string import ascii_lowercase import json import time def get_link_content(url): response = requests.get(url) html_string = response.text return BeautifulSoup(html_string, 'html.parser') staffletters = 'абвгдежзийклмнопрстфхцшюя' departments = ["algebra","veroyatnosti-operacionni-izsledvaniya-i-statistika","geometriya","diferencialni-uravneniya","informacionni-tehnologii","kompleksen-analiz-i-topologiya","kompyutrna-informatika","matematicheska-logika-i-prilozheniyata-y","matematicheski-analiz","mehatronika-robotika-i-mehanika","obuchenie-po-matematika-i-informatika","softuerni-tehnologii","chisleni-metodi-i-algoritmi","izsledovateli-km-fmi-dekanat"] #scraped with the following code from https://www.fmi.uni-sofia.bg/bg/departments: #const links = Array.from(document.querySelectorAll('#main .content .item-list .field-content a')) #console.log(JSON.stringify(links.map(({href}) => href.split('/')[5]))); def scrape_pagenum_by_letter(letter): soup = get_link_content(f'https://www.fmi.uni-sofia.bg/bg/faculty-staff/{letter}') return len(soup.select('.pager .pager-item')) + 1 def scrape_staff_by_letter_and_pagenum(letter, pagenum): soup = get_link_content(f'https://www.fmi.uni-sofia.bg/bg/faculty-staff/{letter}?page={pagenum}') names = map(lambda el: el.text, soup.select('.view-content .views-row .views-field-title .field-content')) titles = map(lambda el: el.text, soup.select('.view-content .views-row .views-field-field-mt-academic-title-ref .field-content')) return [{ 'names': name, 'titles': title } for name, title in zip(names, titles)] def scrape_department(department): departmentFromStaffMember = dict() soup = get_link_content(f'https://www.fmi.uni-sofia.bg/bg/departments/{department}') names = map(lambda el: el.text.strip(), soup.select('.view-header .view-content .views-field-title')) for name in names: name = name.strip() if name in departmentFromStaffMember: print(f'WARNING: overwriting department {department} on top of {departmentFromStaffMember[name]} for staff member {name}', file=sys.stderr) departmentFromStaffMember[name] = department return departmentFromStaffMember def download_pdf(link, directory, index): def get_filename_from_cd(cd): """ Get filename from content-disposition """ if not cd: return None fname = re.findall('filename=(.+)', cd) if len(fname) == 0: return None return fname[0] r = requests.get(link, allow_redirects=True) r.raise_for_status() filename = get_filename_from_cd(r.headers.get('content-disposition')) if filename is None: filename = f'optional-course-{index}.pdf' else: filename = urllib.parse.unquote(filename.strip('"')) with open(os.path.join(directory, filename), mode='wb') as file: file.write(r.content) print('wrote', filename, file=sys.stderr) def scrape_pdf_link(link): soup = get_link_content(link) anchor = soup.select('#header-primary-action a')[0] return anchor.attrs.get('href') def getStaff(): with concurrent.futures.ThreadPoolExecutor(max_workers=len(staffletters)) as executor: pagenumbers = executor.map(scrape_pagenum_by_letter, staffletters) pagenumbers = list(pagenumbers) with concurrent.futures.ThreadPoolExecutor(max_workers=sum(pagenumbers)) as executor: unfolded_staffletters = [ letter for letter, pagenum in zip(staffletters, pagenumbers) for _ in range(pagenum) ] unfolded_pagenumbers = [ page for pagenum in pagenumbers for page in range(pagenum) ] results = executor.map(scrape_staff_by_letter_and_pagenum, unfolded_staffletters, unfolded_pagenumbers) staff = [] for result in results: staff.extend(result) return staff def getDepartments(): departmentFromStaffMember = dict() with concurrent.futures.ThreadPoolExecutor(max_workers=len(departments)) as executor: results = executor.map(scrape_department, departments) for result in results: departmentFromStaffMember.update(result) return departmentFromStaffMember def savePDFS(directory): with open('optionalcourses-links.json') as file: links = json.loads(file.read()) print(len(links), file=sys.stderr) with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: links = list(executor.map(scrape_pdf_link, links)) print(len(links), file=sys.stderr) with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor: results = list(executor.map(download_pdf, links, [directory] * len(links), range(len(links)))) print(results) if __name__ == '__main__': if len(sys.argv) < 1: print('Not specified what to scrape') sys.exit(1) if sys.argv[1] == 'staff': print(json.dumps(getStaff())) elif sys.argv[1] == 'departments': print(json.dumps(getDepartments())) elif sys.argv[1] == 'pdfs': if len(sys.argv) < 3: print('Did not specify directory', file=sys.stderr) sys.exit(1) directory = sys.argv[2] savePDFS(directory) print('Saved pdfs') else: print('invalid thing to scrape') sys.exit(1)
"use client"; import { OrderItem } from "@/components/OrderItem"; import { ProductEditDialog } from "@/components/ProductEditDialog"; import { ProductTableItem } from "@/components/ProductTableItem"; import { ProductTableSkeleton } from "@/components/ProductTableSkeleton"; import { api } from "@/libs/api"; import { dateFormat } from "@/libs/dateFormat"; import { Category } from "@/types/Category"; import { Order } from "@/types/Order"; import { OrderStatus } from "@/types/OrderStatus"; import { Product } from "@/types/Product"; import { Refresh, Search } from "@mui/icons-material"; import { Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Grid, InputAdornment, Skeleton, Table, TableBody, TableCell, TableHead, TableRow, TextField, Typography, } from "@mui/material"; import { FormEvent, useEffect, useState } from "react"; const Page = () => { const [loading, setLoading] = useState(false); const [products, setProducts] = useState<Product[]>([]); const [categories, setCategories] = useState<Category[]>([]); const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [productToDelete, setProductToDelete] = useState<Product>(); const [loadingDelete, setLoadingDelete] = useState(false); const [editDialogOpen, setEditDialogOpen] = useState(false); const [productToEdit, setProductToEdit] = useState<Product>(); const [loadingEditDialog, setLoadingEditDialog] = useState(false); useEffect(() => { getProducts(); }, []); const getProducts = async () => { setLoading(true); setProducts(await api.getProducts()); setCategories(await api.getCategories()); setLoading(false); }; // Delete Product const handleDeleteProduct = (product: Product) => { setProductToDelete(product); setShowDeleteDialog(true); }; const handleConfirmDelete = async () => { if (productToDelete) { setLoadingDelete(true); await api.DeleteProduct(productToDelete.id); setLoadingDelete(false); setShowDeleteDialog(false); getProducts(); } }; // New/Edit Product const handleNewProduct = () => { setProductToEdit(undefined); setEditDialogOpen(true); }; const handleEditProduct = (product: Product) => { setProductToEdit(product); setEditDialogOpen(true); }; const handleSaveEditDialog = async (event: FormEvent<HTMLFormElement>) => { let form = new FormData(event.currentTarget); setLoadingEditDialog(true); if (productToEdit) { form.append("id", productToEdit.id.toString()); await api.updateProduct(form); } else { await api.createProduct(form); } setLoadingEditDialog(false); setEditDialogOpen(false); getProducts(); }; return ( <> <Box sx={{ my: 3 }}> <Box sx={{ mb: 3, display: "flex", justifyContent: "space-between" }}> <Typography component="h5" variant="h5" sx={{ color: "#555", mr: 2 }}> Produtos </Typography> <Button onClick={handleNewProduct}>Novo Produto</Button> </Box> <Table> <TableHead> <TableRow> <TableCell sx={{ width: 50, display: { xs: "none", md: "table-cell" } }} > ID </TableCell> <TableCell>Imagem</TableCell> <TableCell>Nome</TableCell> <TableCell sx={{ display: { xs: "none", md: "table-cell" } }}> Preço </TableCell> <TableCell sx={{ display: { xs: "none", md: "table-cell" } }}> Categoria </TableCell> <TableCell sx={{ width: { xs: 50, md: 130 } }}>Ações</TableCell> </TableRow> </TableHead> <TableBody> {loading && ( <> <ProductTableSkeleton /> <ProductTableSkeleton /> <ProductTableSkeleton /> </> )} {!loading && products.map((item) => ( <ProductTableItem key={item.id} item={item} onEdit={handleEditProduct} onDelete={handleDeleteProduct} /> ))} </TableBody> </Table> <Dialog open={showDeleteDialog} onClose={() => (!loadingDelete ? setShowDeleteDialog(false) : null)} > <DialogTitle> Tem certeza que deseja deletar este produto? </DialogTitle> <DialogContent> <DialogContentText> Não é possivel voltar atrás após confirmar esta ação. </DialogContentText> </DialogContent> <DialogActions> <Button disabled={loadingDelete} onClick={() => setShowDeleteDialog(false)} > Não </Button> <Button disabled={loadingDelete} onClick={handleConfirmDelete}> Sim </Button> </DialogActions> </Dialog> <ProductEditDialog open={editDialogOpen} onClose={() => setEditDialogOpen(false)} onSave={handleSaveEditDialog} disabled={loadingEditDialog} product={productToEdit} categories={categories} ></ProductEditDialog> </Box> </> ); }; export default Page;
import 'package:flutter/material.dart'; class PortfolioBanner extends StatelessWidget { final String h1; final String subtitle; final List<SocialMediaLink> socialMediaLinks; const PortfolioBanner({ Key? key, required this.h1, required this.subtitle, required this.socialMediaLinks, }) : super(key: key); @override Widget build(BuildContext context) { return Container( //constraints: BoxConstraints(minWidth: 100, maxWidth: 900), height: 200, decoration: const BoxDecoration( gradient: LinearGradient( colors: [ Color.fromARGB(255, 197, 238, 238), Color.fromARGB(255, 255, 210, 178), ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( "sdfasdfasdfasdf", style: const TextStyle( color: Colors.black87, fontSize: 32, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 10), Padding( padding: const EdgeInsets.all(14.0), child: Text( "fasdfasdfasdfasdfadf", style: const TextStyle( color: Colors.black87, fontSize: 18, ), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: socialMediaLinks .map((link) => Padding( padding: const EdgeInsets.all(8.0), child: Icon( link.icon, color: const Color.fromARGB(255, 155, 74, 74), size: 30, ), )) .toList(), ), ], ), ); } } class SocialMediaLink extends StatelessWidget { final IconData icon; final String url; const SocialMediaLink(this.icon, this.url); @override Widget build(BuildContext context) { // TODO: implement build throw UnimplementedError(); } } final socialMediaLinks = [ SocialMediaLink(Icons.facebook, 'https://www.facebook.com/your-portfolio'), SocialMediaLink(Icons.facebook, 'https://www.twitter.com/your-portfolio'), SocialMediaLink(Icons.facebook, 'https://www.linkedin.com/your-portfolio'), ];
import random class Father: def __init__(self, blood_type): self.blood_type = blood_type def get_allele(self): get_random = random.choice([list(self.blood_type)[0], list(self.blood_type)[1]]) return get_random # menggunakan inheritance class Mother(Father): pass class Child: def __init__(self, father, mother): father_allele = father.get_allele() mother_allele = mother.get_allele() self.allele = father_allele + mother_allele print(f"child's allele: {self.allele}") # rumus untuk tipe darah(A, AB, B, O) if self.allele[0] == self.allele[1]: self.blood_type = self.allele[0] elif self.allele[0] != self.allele[1]: if self.allele[1] == 'O' : self.blood_type = 'B' else: self.blood_type = 'AB' else: self.blood_type = 'O' def get_blood_type(self): return self.blood_type father_blood_type = input("Enter father's allele : ") mother_blood_type = input("Enter mother's allele : ") father = Father(father_blood_type) mother = Mother(mother_blood_type) child = Child(father, mother) print(f"Child's blood type: {child.get_blood_type()}")
import HomeStyle from '../styles/Home.module.scss' import Image from 'next/image' import ProfilePic from '@/public/head.png' import logo from '@/public/logo.png' import { useState } from 'react'; import { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; export default function Home() { const [hovered, setHovered] = useState(false); const toggleHover = () => setHovered(!hovered); return ( <> <header className='w-full fixed z-10'> <div className=' container mx-auto py-10 flex justify-between'> <div className='logo'> <Image src={logo} height={40} alt="natanaelkristiawan"></Image> </div> <div className={HomeStyle.navigation}> <nav> <ol className='flex'> <li><a href='#'><span>01</span>About</a></li> <li><a href='#'><span>02</span>Experience</a></li> <li><a href='#'><span>03</span>Work</a></li> <li><a href='#'><span>04</span>Contact</a></li> <li><a className='border-2 ml-3 rounded border-sky-600 hover:bg-sky-50' href='#'>Resume</a></li> </ol> </nav> </div> </div> </header> <section id='section__herobanner' className='container mx-auto relative h-screen'> <div className={`absolute top-1/2 ${HomeStyle.section__herobanner_content}`}> <h3 className='text-base text-sky-600 font-mono'>Hi, my name is</h3> <div className='text-7xl font-bold my-5 '> <h1 className='my-2 text-stone-800'>Natanael Kristiawan.</h1> <h2 className='my-2 text-stone-500'>I build things for the web.</h2> </div> <p className='w-1/2 text-stone-500'>I’m a software engineer specializing in building (and occasionally designing) exceptional digital experiences. Currently, I’m focused on building accessible, human-centered products at <a href='https://maxsol.id'>Maxsol.ID.</a></p> </div> </section> <section id='section_aboutus' className={`${HomeStyle.container__laptop} mx-auto my-28`}> <div className={HomeStyle.section__aboutus_content}> <div> <div className={HomeStyle.section__aboutus_title}> <span>01.</span> <h2>About Me</h2> </div> <div className={HomeStyle.section__aboutus_description}> <p>Hello, My name Natanael Kristiawan. I&apos;m is a highly skilled programmer with over 13 years of experience. I&apos;m started my career in the field in 2009 and has been dedicated to my craft ever since. With a solid education from University Udayana Bali, I has a strong foundation in computer science and programming principles.</p> <p>As a programmer, my main job is to ensure that software runs smoothly and with minimal bugs. I&apos;m uses my expertise in coding and problem-solving to tackle complex issues and deliver high-quality results. Whether it&apos;s finding and fixing bugs, optimizing software performance, or implementing new features, I&apos;m committed to delivering the best possible outcome for my clients.</p> <p>With my extensive experience and passion for programming, I&apos;m a valuable asset to any software development team. Whether my working on a large-scale project or a small task, I&apos;m approaches each challenge with a positive attitude and a drive to succeed</p> <p>Here are a few technologies I&apos;ve been working with recently:</p> <ul> <li>PHP</li> <li>Wordpress</li> <li>Laravel</li> <li>Javascript</li> <li>NodeJS</li> <li>NestJS</li> <li>ReactJS</li> <li>VueJS</li> <li>Mysql</li> <li>Linux Server</li> </ul> </div> </div> <div> <div className={HomeStyle.section__aboutus_animation}> <div className={HomeStyle.section__aboutus_image}> <Image width={400} src={ProfilePic} alt="natanaelkristiawan"></Image> </div> </div> </div> </div> </section> <section id='section_experience' className={`${HomeStyle.container__tablet} mx-auto my-28`}> <div> <div className={HomeStyle.section__aboutus_title}> <span>02.</span> <h2>Where I&apos;ve Worked</h2> </div> <Tabs> <TabList> <Tab>Maxsol.ID</Tab> <Tab>Silicon Bali Creative</Tab> <Tab>IGB Media</Tab> </TabList> <TabPanel> <h2 className='font-semibold text-lg'>Backend Programmer <a className="text-sky-600" rel="noreferrer" target="_blank" href="https://maxsol.id">@Maxsol.ID</a></h2> <p className='font-mono text-xs'>September 2015 - Present</p> <ul> <li>Write modern, performant, maintainable code for a diverse array of client and internal projects</li> <li>Work with a variety of different languages, platforms, frameworks, and content management systems such as JavaScript, TypeScript, VueJS, React, WordPress, Laravel, and Mysql</li> <li>Communicate with multi-disciplinary teams of engineers, designers, producers, and clients on a daily basis</li> </ul> </TabPanel> <TabPanel> <h2 className='font-semibold text-lg'>Freelance Programmer <a className="text-sky-600" rel="noreferrer" target="_blank" href="https://siliconbalicreative.com">@SiliconBaliCreative</a></h2> <p className='font-mono text-xs'>March 2022 - Present</p> <ul> <li>Create a website with a modern look using wordpress and elementor</li> <li>Ensure the website runs normally and without problems</li> </ul> </TabPanel> <TabPanel> <h2 className='font-semibold text-lg'>Freelance Programmer <a className="text-sky-600" rel="noreferrer" target="_blank" href="https://igbmedia.com">@IGBMedia</a></h2> <p className='font-mono text-xs'>January 2021 - Present</p> <ul> <li>Create a website with a modern look using wordpress and elementor</li> <li>Ensure the website runs normally and without problems</li> </ul> </TabPanel> </Tabs> </div> <div> </div> </section> <section id='section_project' className={`${HomeStyle.container__laptop} mx-auto my-28`}> <div className={HomeStyle.section__project}> <div className={HomeStyle.section__aboutus_title}> <span>03.</span> <h2>Some Things I&apos;ve</h2> </div> <div className={HomeStyle.section__project_wrapper}> <div className='flex gap-8'> <div className='w-3/5'> <Image src={require('../public/igbmedia.png')} alt="igbmedia" ></Image> </div> <div className={`w-2/5 ${HomeStyle.section__project_wrapper_description}`}> <div className={HomeStyle['section__project_wrapper-heading']}> <p>Featured Project</p> <h2>IGB Media</h2> </div> <div className={HomeStyle['section__project_wrapper-description']}> <p>IGBmedia.com is a professionally designed website built with WordPress and Elementor. The company profile showcases their expertise in digital media and offers creative solutions for businesses.</p> </div> </div> </div> </div> </div> </section> </> ) }
<?php namespace App\Http; use Symfony\Component\HttpFoundation\JsonResponse; /** * Fake Yahoo Finance Api - imitate a connection to the real api and returns data */ class FakeYahooFinanceApiClient implements FinanceApiClientInterface { public static $statusCode = 200; public static $content = ''; public function fetchStockProfile(string $symbol, string $region): JsonResponse { return new JsonResponse(self::$content, self::$statusCode, [], $json = true); } public static function setContent(array $overrides): void { self::$content = json_encode(array_merge([ 'symbol' => 'AMZN', 'short_name' => 'Amazon.com, Inc.', 'region' => 'US', 'exchange_name' => 'NasdaqGS', 'currency' => 'USD', 'price' => 100.50, 'previous_close' => 110.20, 'price_change' => -9.70, ], $overrides)); } }
import React, { createContext, useContext, useMemo } from 'react'; import Store from '../utils/Store'; export type StoreContextValue = { session: Store; persistent: Store; } const StoreContext = createContext({} as StoreContextValue); const StoreProvider = ({ children }: { children: React.ReactNode }) => { const store = useMemo(() => ({ session: new Store('session'), persistent: new Store('persistent') }), []); return ( <StoreContext.Provider value={store}> {children} </StoreContext.Provider> ); }; const useStore = (type: keyof StoreContextValue = 'session') => useContext(StoreContext)[type]; export { useStore, StoreProvider };
#include "main.h" #include <stdio.h> /** * print_array - prints n elements of an array of integers * @a: a pointer to array of int * @n: the number of elements of the array to be printed */ void print_array(int *a, int n) { int i = 0; while (i < n) { if (i == (n - 1)) { printf("%d\n", a[i]); return; } printf("%d, ", a[i]); i++; } }
<!DOCTYPE html> <html> <head runat="server"> <title>DHTML</title> <style type="text/css"> body { background-color: #BFC9DC; } .Buttons { position: absolute; height: 25px; font-family: Arial, Helvetica; font-size: 11pt; color: #002594; } .LblInfoGray { font-family: Verdana, Arial, Helvetica; font-size: 10pt; color: #5a5a5a; position: relative; text-align: left; padding-top: 4px; } .TableClass { font-family: Verdana, Arial, Helvetica; font-size: 9.0pt; } .BaseColumn { text-align: center; } .AlphaColumn { width: 40px; cursor: pointer; background-color: #C3DAF9; border: 1px solid #002d96; } </style> <script language="JavaScript" type="text/javascript"> // Example of using Dynamic HTML to build a spreadsheet table // ******************** // button event handler function createSpreadsheet() { var rows = parseInt(document.getElementById("txtRows").value); var columns = parseInt(document.getElementById("txtColumns").value); document.getElementById("SpreadsheetTable").innerHTML = buildTable(rows, columns); } // *************************************************** // function builds the table based on rows and columns function buildTable(rows, columns) { // start with the table declaration var divHTML = "<table border='1' cellpadding='0' cellspacing='0' class='TableClass'>"; // next do the column header labels divHTML += "<tr><th></th>"; for (var j = 0; j < columns; j++) divHTML += "<th>" + String.fromCharCode(j + 65) + "</th>"; // closing row tag for the headers divHTML += "</tr>"; // now do the main table area for (var i = 1; i <= rows; i++) { divHTML += "<tr>"; // ...first column of the current row (row label) divHTML += "<td id='" + i + "_0' class='BaseColumn'>" + i + "</td>"; // ... the rest of the columns for (var j = 1; j <= columns; j++) divHTML += "<td id='" + i + "_" + j + "' class='AlphaColumn' onclick='clickCell(this)'></td>"; // ...end of row divHTML += "</tr>"; } // finally add the end of table tag divHTML += "</table>"; //alert(divHTML); return divHTML; } // ******************************************* // event handler fires when user clicks a cell function clickCell(ref) { var rcArray = ref.id.split('_'); alert("You selected row " + rcArray[0] + " and column " + rcArray[1]); } </script> </head> <body> <div> <input id="btnBuild" type="button" value="Build" onclick="createSpreadsheet();" /> <br /><br /> <a href="Classes_3.html">HTML5 Class Example</a> <br /><br /> <input type="text" id="txtRows" value="20" /> <input type="text" id="txtColumns" value="10" /> <br /><br /> <div id="SpreadsheetTable"> </div> </div> </body> </html>
/* * @Author: wch * @Date: 2021-12-21 17:12:27 * @LastEditTime: 2021-12-21 18:03:59 * @LastEditors: your name * @Description: 索引类型 * @FilePath: \typeScript\src\advanced4.ts * 可以输入预定的版权声明、个性签名、空行等 */ let obj_a4 = { a: 1, b: 2, c: 3 } function getValue(obj: any, keys: string[]) { return keys.map(key => obj[key]) } console.log(getValue(obj_a4, ['a', 'b'])); console.log(getValue(obj_a4, ['e', 'f'])); // keyof T 索引类型的查询操作符 interface Obj { a: number, b: string } let a_a4: keyof Obj // T[K] 对象T的属性K的类型 let b_a4: Obj['a'] // T extends U function getValue_1<T, K extends keyof T>(obj: T, keys: K[]): T[K][]{ return keys.map(key => obj[key]) } console.log(getValue_1(obj_a4, ['a', 'b'])); // 约束属性只能是对象中存在的 // console.log(getValue_1(obj_a4, ['e', 'f']));
// Textarea // No React o textare é utilizado como um input, uma tag única sem abertura/fechamento e com o value para definir o seu valor interno. const App = () => { const [mensagem, setMensagem] = React.useState(''); return ( <form> <textarea id="mensagem" value={mensagem} rows="5" onChange={(event) => setMensagem(event.target.value)} /> <p>{mensagem}</p> </form> ) }
const crypto = require('crypto'); const mongoose = require('mongoose'); const validator = require('validator'); const bcrypt = require('bcryptjs'); const userSchema = new mongoose.Schema({ name: { type: String, required: [true, "Please tell us your name"] }, email: { type: String, required: [true, 'Please provide your email'], unique: true, lowercase: true, validate: [validator.isEmail, 'Please provide a valid email'] }, photo: { type: String }, role: { type: String, enum: ['user', 'guide', 'lead', 'admin'], default: 'user' }, password: { type: String, required: [true, 'Please provide a password'], minlength: [8, 'Password must have at least 8 characters'], select: false }, passwordConfirm: { type: String, required: [true, 'Please confirm your password'], validate: { // This only works on CREATE and SAVE validator: function (el) { return el === this.password; }, message: "Passwords are not the same" } }, passwordChangedAt: Date, passwordResetToken: String, passwordResetExpires: Date, active: { type: Boolean, default: true, select: false } }); userSchema.pre('save', async function(next) { if(this.isModified('password')) { this.password = await bcrypt.hash(this.password, 12); this.passwordConfirm = undefined; } next(); }); userSchema.pre('save', function(next) { if (!this.isModified('password') || this.isNew) return next(); this.passwordChangedAt = Date.now() -1000; next(); }); userSchema.pre(/^find/, function(next) { this.find({active: { $ne: false}}); next(); }) userSchema.method.correctPassword = async function( candidatePassword, userPassword ) { const User = mongoose.compare(candidatePassword, userPassword); }; userSchema.methods.changePasswordAfter = function(JWTTimestamp){ if(this.passwordChangedAt) { const changeTimestamp = parseInt( this.passwordChangedAt.getTime() / 1000, 10 ); return JWTTimestamp < changeTimestamp; } } userSchema.methods.createPasswordResetToken = function() { const resetToken = crypto.randomBytes(32).toString('hex'); crypto.createHash('sha256').update(resetToken).digest('hex'); this.passwordResetExpires = Date.now() + 10 * 60 * 1000; return resetToken; } const User = mongoose.model('User', userSchema); module.export = User;
#include <stdio.h> #include <tinatest.h> #include <dirent.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/stat.h> #include <console.h> #include <stdbool.h> #include <fcntl.h> #include <stdlib.h> #define MKDIR_FLAGS_PARENTS (1 << 0) static void show_help(void) { printf("Usage: mkdir [-p] <dir>\n"); printf(" -p: make the upper directory if needed.\n"); } static int mkdir_do(char *path, int flags) { char *s = NULL; if (flags & MKDIR_FLAGS_PARENTS) { s = path; } /* * All of operations must base on root directory * As alios has not root dierctory, we can operate '/data' but not '/' */ if (path[0] == '.') { if (path[1] == '\0') return 0; if (path[1] == '.' && path[2] == '\0') return 0; } while (1) { struct stat st; if (flags & MKDIR_FLAGS_PARENTS) { /* in case of tailing '/', such as '/data/a/' */ if (*(s++) == '\0') break; s = strchr(s, '/'); if (s) *s = '\0'; } if (!stat(path, &st)) { if (S_ISDIR(st.st_mode)) goto next; printf("make failed - %s already existed and not direcotry\n", path); return -1; } if (mkdir(path, 0777) < 0) { printf("mkdir %s failed\n", path); return -1; } next: if (!s) break; *s = '/'; } return 0; } static int mkdir_main(int argc, char **argv) { int opts = 0, ret = 0, flags = 0, index; optind = 0; while ((opts = getopt(argc, argv, ":ph")) != EOF) { switch (opts) { case 'p': flags |= MKDIR_FLAGS_PARENTS; break; case 'h': show_help(); return 0; case '?': printf("invalid option %c\n", optopt); return -1; case ':': printf("option -%c requires an argument\n", optopt); show_help(); return -1; } } argc -= optind; argv += optind; if (argc < 1) { show_help(); return -1; } for (index = 0; index < argc; index++) { char *path; path = strdup(argv[index]); ret = mkdir_do(path, flags); free(path); if (ret) return ret; } return 0; } FINSH_FUNCTION_EXPORT_CMD(mkdir_main, mkdir, make directory);
USE gelatos; -- Stored Procedure para insertar nuevos Clientes. DROP PROCEDURE IF EXISTS insertar_cliente; DELIMITER // CREATE PROCEDURE insertar_cliente( /* Datos Personales */ IN inombre VARCHAR(255), -- 1 IN iapaterno VARCHAR(255), -- 2 IN iamaterno VARCHAR(255), -- 3 IN itelefono VARCHAR(255), -- 4 IN icodigo_postal INT, -- 5 IN inumero_interior VARCHAR(255), -- 6 IN inumero_exterior VARCHAR(255), -- 7 IN icalle VARCHAR(255), -- 8 IN icolonia VARCHAR(255), -- 9 /* Datos de Usuario */ IN icorreo VARCHAR(255), -- 10 IN icontrasenia VARCHAR(255), -- 11 /* Valores de Retorno */ OUT iid_persona INT, -- 12 OUT iid_usuario INT, -- 13 OUT iid_cliente INT -- 14 ) BEGIN IF (SELECT COUNT(*) FROM usuario WHERE correo = icorreo) = 0 THEN -- Insertando los datos de la Persona: INSERT INTO persona ( nombre, apaterno, amaterno, telefono, codigo_postal, numero_interior, numero_exterior, calle, colonia) VALUES ( inombre, iapaterno, iamaterno, itelefono, icodigo_postal, inumero_interior, inumero_exterior, icalle, icolonia); -- Obtenemos el ID de Persona que se generó: SET iid_persona = LAST_INSERT_ID(); -- Insertamos los datos de seguridad del Cliente: INSERT INTO usuario (correo, contrasenia) VALUES(icorreo, icontrasenia); -- Obtenemos el ID de Usuario que se generó: SET iid_usuario = LAST_INSERT_ID(); INSERT INTO rol_usuario (fk_usuario, fk_rol) VALUES (iid_usuario, 5); -- Insertamos en la tabla Cliente: INSERT INTO cliente (fk_persona, fk_usuario) VALUES(iid_persona, iid_usuario); -- Obtenemos el ID del Cliente que se generó: SET iid_cliente = LAST_INSERT_ID(); END IF; END // DELIMITER ; CALL insertar_cliente('Ían', 'Gimenez','Villa','4771231212', 37000, null, '112', 'Calle', 'Colonia','ian@email.com','123457',@id_persona, @id_usuario,@id_cliente); CALL insertar_cliente('Paco', 'Villanueva','Puerta','4771231212', 37000, null, '113', 'Calle', 'Colonia','paco@email.com','1238',@id_persona, @id_usuario,@id_cliente); CALL insertar_cliente('Maria', 'Villegas','Bonilla','4771231212', 37000, null, '114', 'Calle', 'Colonia','maria@email.com','1236',@id_persona, @id_usuario,@id_cliente); -- Stored Procedure para actualizar Clientes. DROP PROCEDURE IF EXISTS actualizar_cliente; DELIMITER // CREATE PROCEDURE actualizar_cliente( /* Datos Personales */ IN inombre VARCHAR(50), -- 1 IN iapaterno VARCHAR(50), -- 2 IN iamaterno VARCHAR(50), -- 3 IN itelefono VARCHAR(10), -- 4 IN icodigo_postal VARCHAR(6), -- 5 IN inumero_interior VARCHAR(6), -- 6 IN inumero_exterior VARCHAR(6), -- 7 IN icalle VARCHAR(255), -- 8 IN icolonia VARCHAR(100), -- 9 /* Datos de Usuario */ IN icorreo VARCHAR(100), -- 10 IN icontrasenia VARCHAR(100), -- 11 /* ID's de las tablas relacionadas con el Cliente */ IN iid_persona INT, -- 12 IN iid_usuario INT -- 13 ) BEGIN -- Datos Persona del Cliente: UPDATE persona SET nombre = inombre, apaterno = iapaterno, amaterno = iamaterno, telefono = itelefono, codigo_postal = icodigo_postal, numero_interior = inumero_interior, numero_exterior = inumero_exterior, calle = icalle, colonia = icolonia, fecha_actualizacion = NOW() WHERE id_persona = iid_persona; -- Actualizamos los datos de Seguridad: UPDATE usuario SET correo = icorreo, contrasenia = icontrasenia WHERE id_usuario = iid_usuario; END // DELIMITER ; CALL actualizar_cliente('Pablo','Mares','Sánchez','4771234567','37287',110,34,'Elefante esa', 'Villa Magna','pablo@email.com','123456',4,4); -- Stored Procedure para eliminar Clientes. DROP PROCEDURE IF EXISTS eliminar_clientes; DELIMITER // CREATE PROCEDURE eliminar_clientes( /* Datos Persona */ IN iid_persona INT -- 1 ) BEGIN UPDATE persona SET estatus = false, fecha_actualizacion = NOW() WHERE id_persona = iid_persona; END // DELIMITER ; CALL eliminar_clientes(4);
import { Injectable } from '@angular/core'; import { Resolve, RouterStateSnapshot, ActivatedRouteSnapshot, } from '@angular/router'; import { catchError, throwError } from 'rxjs'; import { HttpErrorResponse } from '@angular/common/http'; import { WishlistService } from './wishlist.service'; import { WishlistModel } from 'src/app/models/wishlist.model'; @Injectable({ providedIn: 'root', }) export class WishlistResolverService implements Resolve<WishlistModel[] | boolean> { constructor(private readonly wishlistService: WishlistService) {} resolve(_route: ActivatedRouteSnapshot, _state: RouterStateSnapshot) { let length = this.wishlistService.wishlistLength; const wishlistResolve = this.wishlistService .getAllwishlist() .pipe( catchError((err: HttpErrorResponse) => throwError(() => err.error.message) ) ); if (length) return true; return wishlistResolve; } }
/******************************************************************************* * Copyright (c) 2023 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 ******************************************************************************/ package io.openliberty.microprofile.openapi.ui.internal.fat.tests; import static componenttest.selenium.SeleniumWaits.waitForElement; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertNotNull; import java.time.Duration; import org.hamcrest.Matchers; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.testcontainers.Testcontainers; import org.testcontainers.containers.BrowserWebDriverContainer; import org.testcontainers.containers.VncRecordingContainer.VncRecordingFormat; import com.ibm.websphere.simplicity.ShrinkHelper; import com.ibm.websphere.simplicity.config.ServerConfiguration; import com.ibm.ws.fat.util.Props; import componenttest.annotation.Server; import componenttest.containers.SimpleLogConsumer; import componenttest.custom.junit.runner.FATRunner; import componenttest.topology.impl.LibertyServer; import io.openliberty.microprofile.openapi.ui.internal.fat.app.SecureTestResource; import io.openliberty.microprofile.openapi.ui.internal.fat.app.TestApplication; @RunWith(FATRunner.class) public class UIOauthTest { public static final String APP_NAME = "app"; public static final String UI_PATH_PROPERTY = "uiPath"; public static final String UI_PATH_VALUE = "/openapi/ui"; public static final String CUSTOM_UI_PATH_VALUE = "/foo/bar"; public static final String DOC_PATH_VALUE = "/bar/foo"; public static final String OAUTH_CLIENT_NAME_PROPERTY = "clientName"; public static final String OAUTH_CLIENT_NAME = "mp-ui"; public static final String OAUTH_CLIENT_SECRET_PROPERTY = "clientSecret"; public static final String OAUTH_CLIENT_SECRET = "abc"; public static final String OAUTH_REDIRECT_HOST_PROPERTY = "host"; public static final String BASIC_AUTH_USERNAME_PROPERTY = "testUsername"; public static final String BASIC_AUTH_USERNAME = "testuser"; public static final String BASIC_AUTH_PASSWORD_PROPERTY = "testPassword"; public static final String BASIC_AUTH_PASSWORD = "testpassword"; public static final String HOST = "host.testcontainers.internal"; public static final String HOST_HTTPS_PORT_PROPERTY = "httpsPort"; /** Wait for "long" tasks like initial page load or making a test request to the server */ private static final Duration LONG_WAIT = Duration.ofSeconds(30); @Server("openapi-ui-custom-oauth-test") public static LibertyServer server; private static ServerConfiguration baseConfig; /** * During updates to view recordings regardless of result replace * BrowserWebDriverContainer.VncRecordingMode.RECORD_FAILING * with * BrowserWebDriverContainer.VncRecordingMode.RECORD_ALL */ @Rule public BrowserWebDriverContainer<?> chrome = new BrowserWebDriverContainer<>().withCapabilities(new ChromeOptions()) .withAccessToHost(true) .withRecordingMode(BrowserWebDriverContainer.VncRecordingMode.RECORD_FAILING, Props.getInstance().getFileProperty(Props.DIR_LOG), VncRecordingFormat.MP4) .withLogConsumer(new SimpleLogConsumer(UIBasicTest.class, "selenium-driver")); private RemoteWebDriver driver; @BeforeClass public static void setup() throws Exception { WebArchive war = ShrinkWrap.create(WebArchive.class, APP_NAME + ".war") .addClasses(SecureTestResource.class, TestApplication.class); ShrinkHelper.exportDropinAppToServer(server, war, ShrinkHelper.DeployOptions.SERVER_ONLY); Testcontainers.exposeHostPorts(server.getHttpDefaultPort(), server.getHttpDefaultSecurePort()); } @Before public void setupTest() throws Exception { //EnvVars are lost if defined in BeforeClass on the second test despite the fact they don't actually change so reset for every test //configure authentication server.addEnvVar(BASIC_AUTH_USERNAME_PROPERTY, BASIC_AUTH_USERNAME); server.addEnvVar(BASIC_AUTH_PASSWORD_PROPERTY, BASIC_AUTH_PASSWORD); //Configure Oauth server.addEnvVar(OAUTH_CLIENT_NAME_PROPERTY, OAUTH_CLIENT_NAME); server.addEnvVar(OAUTH_CLIENT_SECRET_PROPERTY, OAUTH_CLIENT_SECRET); server.addEnvVar(OAUTH_REDIRECT_HOST_PROPERTY, HOST); server.addEnvVar(HOST_HTTPS_PORT_PROPERTY, Integer.toString(server.getHttpDefaultSecurePort())); //store copy of base config for restoration when running individual tests to stop any potential bleeding baseConfig = server.getServerConfiguration(); // make sure we have a clean driver between tests that can handle self-signed certs driver = new RemoteWebDriver(chrome.getSeleniumAddress(), new ChromeOptions().setAcceptInsecureCerts(true)); } @After public void teardownTest() throws Exception { //close the browser before stopping the server to reduce changes of open connections driver.quit(); try { server.stopServer(); } finally { // Restore Config to original after test to prevent potential config bleeding between tests server.updateServerConfiguration(baseConfig); } } @Test public void defaultPathOAuthTest() throws Exception { // Set the OAuth Endpoint configuration server.addEnvVar(UI_PATH_PROPERTY, UI_PATH_VALUE); server.startServer(); server.waitForStringInLog("CWWKO0219I: TCP Channel defaultHttpEndpoint-ssl", 60000); OAuthTest(UI_PATH_VALUE); } @Test public void customPathOAuthTest() throws Exception { // Set the mpOpenAPI endpoint configuration ServerConfiguration config = server.getServerConfiguration(); config.getMpOpenAPIElement().setUiPath(CUSTOM_UI_PATH_VALUE); config.getMpOpenAPIElement().setDocPath(DOC_PATH_VALUE); server.updateServerConfiguration(config); // Set the OAuth Endpoint configuration server.addEnvVar(UI_PATH_PROPERTY, CUSTOM_UI_PATH_VALUE); server.startServer(); //Reduce possibility that Server is not listening on its HTTPS Port //Especially for Windows if certificates are slow to create server.waitForSSLStart(); OAuthTest(CUSTOM_UI_PATH_VALUE); } public void OAuthTest(String uiPath) { //Need to use HTTPS path for the test for OAuth to actually work driver.get("https://" + HOST + ":" + server.getHttpDefaultSecurePort() + uiPath); //Store the id of the original window as we need to know when we go through the oauth login flow //We don't need to wait for the page to load to know which one we are after String originalWindow = driver.getWindowHandle(); // Check the title loads as initial validation page has loaded WebElement title = waitForElement(driver, By.cssSelector("h2.title"), LONG_WAIT); assertThat("Page title", title.getText(), Matchers.containsString("Generated API")); //get the GET `/test` operation from `default` WebElement getOperation = waitForElement(driver, By.id("operations-default-get_test")); //check that the operation is "unlocked" //we will use the lock object later to check that it has been updated WebElement lock = getOperation.findElement(By.cssSelector("button.authorization__btn")); WebElement lockSvg = lock.findElement(By.tagName("svg")); assertThat(lockSvg.getAttribute("class"), equalTo("unlocked")); //Check the Authorize button is available and click it WebElement authorizeButton = waitForElement(driver, By.xpath("//span[contains(.,'Authorize')]")); authorizeButton.click(); //Get the overall Modal WebElement authModal = waitForElement(driver, By.cssSelector("div.modal-ux")); //Check the Modal head element as we need it later WebElement oauthModalHead = authModal.findElement(By.cssSelector("div.modal-ux-header")); assertThat("Authorization header has appeared", oauthModalHead.findElement(By.cssSelector("h3")).getText(), Matchers.containsString("Available authorizations")); // Get the OAuth Authentication container - As we only have OAuth Enabled it is the only one we have WebElement authContainer = authModal.findElement(By.cssSelector("div.auth-container")); assertThat("Modal header containers OAuth", authContainer.findElement(By.cssSelector("h4")).getText(), Matchers.containsString("oauth (OAuth2, authorizationCode)")); //Fill out OAuth fields WebElement clientNameField = authContainer.findElement(By.id("client_id_authorizationCode")); clientNameField.sendKeys(OAUTH_CLIENT_NAME); WebElement clientSecretField = authContainer.findElement(By.id("client_secret_authorizationCode")); clientSecretField.sendKeys(OAUTH_CLIENT_SECRET); // Tick the scope tick box WebElement Scope = authContainer.findElement(By.xpath("//label[@for='test-authorizationCode-checkbox-oauth']")); Scope.findElement(By.cssSelector("span")).click(); //click "Authorize" WebElement authBtn = authContainer.findElement(By.cssSelector("button.btn.modal-btn.auth.authorize")); //This opens a new tab in the browser which Selenium does not yet know about and it itself is not focused on so we need to switch to it authBtn.click(); //Switch to new tab new WebDriverWait(driver, Duration.ofSeconds(3)).until(d -> driver.getWindowHandles().size() == 2); for (String windowId : driver.getWindowHandles()) { //as we already have the first tab's handle we go to the other one if (!windowId.equals(originalWindow)) { driver.switchTo().window(windowId); } } //We are presented with a login page where we provide our credentials WebElement userField = waitForElement(driver, By.name("j_username"), LONG_WAIT); userField.sendKeys(BASIC_AUTH_USERNAME); WebElement passwordField = waitForElement(driver, By.name("j_password")); passwordField.sendKeys(BASIC_AUTH_PASSWORD); WebElement loginBtn = waitForElement(driver, By.name("submitButton")); loginBtn.click(); WebElement allowOnceBtn = waitForElement(driver, By.xpath("//input[@value='Allow once']")); allowOnceBtn.click(); // should now have a single tab which is the original openapi page new WebDriverWait(driver, Duration.ofSeconds(3)).until(d -> driver.getWindowHandles().size() == 1); // Switch back to original window driver.switchTo().window(originalWindow); //The javascript may not have completed the update on the auth button from `Authorize` to `Logout`, so we wait for an element that should be a logout button waitForElement(authContainer, By.xpath("//button[text()='Logout']")); //check Auth button text is what has changed to `Logout` knowing that there is a Logout button assertThat("Auth button text should now state logout", authBtn.getText().equals("Logout")); //close Authorization modal oauthModalHead.findElement(By.cssSelector("button.close-modal")).click(); //Check the lock status on operation - should be "locked" //Refetch the lock svg element as the previous one is no longer attached to the page, // so cannot be reused. however the button is kept, so that can be reused as the anchor lockSvg = lock.findElement(By.tagName("svg")); assertThat("Check that lock button is now in 'locked' state", lockSvg.getAttribute("class"), equalTo("locked")); WebElement getOperationButton = getOperation.findElement(By.cssSelector("button")); getOperationButton.click(); WebElement tryOutButton = waitForElement(getOperation, By.cssSelector("button.btn.try-out__btn")); tryOutButton.click(); //get the GET `/test` operation from `default` getOperation = waitForElement(driver, By.id("operations-default-get_test")); WebElement executeButton = waitForElement(getOperation, By.cssSelector("button.btn.execute")); executeButton.click(); getOperation = waitForElement(driver, By.id("operations-default-get_test")); WebElement testGet200Response = waitForElement(getOperation, By.cssSelector("tr.response[data-code=\"200\"]")); assertNotNull("200 response line", testGet200Response); } }