text
stringlengths
184
4.48M
package jtm.activity04; public class Road { private String from; // Start point private String to; // End point private int distance; // distance in km <<<<<<< HEAD /*- #1 ======= /*- TODO #1 >>>>>>> branch1 * Select menu Source — Generate Constructor using Fields... * and create constructor which sets from, to and distance * values of the newly created object */ <<<<<<< HEAD public Road(String from, String to, int distance) { super(); this.from = from; this.to = to; this.distance = distance; } /*- #2 ======= /*- TODO #2 >>>>>>> branch1 * Create constructor without parameters, which sets empty * values or 0 to all object properties */ <<<<<<< HEAD public Road() { this.from = ""; this.to = ""; this.distance = 0; } /*- #3 ======= /*- TODO #3 >>>>>>> branch1 * Select menu: Source — Generate getters and Setters... * and generate public getters/setters for distance, from and to * fields */ <<<<<<< HEAD public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } /*- #4 ======= /*- TODO #4 >>>>>>> branch1 * Select menu: Source — Generate toString()... * and implement this method, that it returns String in form: * "From — To, 00km" * Note that — is not dash ("minus key" in jargon), but m-dash! * See more at: https://en.wikipedia.org/wiki/Dash */ <<<<<<< HEAD @Override public String toString() { return getFrom() + " — " + getTo() + ", " + getDistance() + "km"; } ======= >>>>>>> branch1 }
from django.db import models from datetime import datetime from django.urls import reverse class Bot(models.Model): """ бот """ title = models.CharField(verbose_name="Заголовок", max_length=150, unique=True) token = models.CharField(verbose_name="Токен", max_length=160, unique=True) description = models.TextField("Описание", blank=True, null=True) def __str__(self): return self.token class Meta: verbose_name = "Бот" verbose_name_plural = "Бот" ordering = ['id'] class Chat(models.Model): """ chat_id """ name = models.CharField(verbose_name="Админ", max_length=150, unique=True) chat_id = models.BigIntegerField(verbose_name="Чат", unique=True) token = models.ForeignKey(Bot, verbose_name="Токен", on_delete=models.CASCADE) def __str__(self): return self.name class Meta: verbose_name = "Чат" verbose_name_plural = "Чат" ordering = ['id']
const bcrypt = require('bcrypt'); const { text } = require('body-parser'); const jwt = require('jsonwebtoken'); const userModel = require('../model/user'); const secret = 'test'; exports.SignIn = async (req,res) => { const {email, password} = req.body; try { const existingUser = await userModel.findOne({email}); if(!existingUser) return res.status(404).json({message: "User doesn't exist" }) const isPasswordCorrect = await bcrypt.compare(password, existingUser.password); if(!isPasswordCorrect) return res.status(400).json({ message: "Invalid credentials" }) const token = jwt.sign({email: existingUser.email, password: existingUser.password, id: existingUser._id}, secret, {expiresIn: "1h"}) res.status(200).json({ result: existingUser, token}) } catch (error) { res.status(500).json({message: "Something went wrong"}) } } exports.SignUp = async (req,res) => { const {firstName, lastName, email, password, confirmPassword} = req.body; try { const existingUser = await userModel.findOne({email}); if(existingUser) return res.status(400).json({message: "User already exist" }) if(password !== confirmPassword) return res.status(400).json({ message: "Password Mismatch" }) const hashedPassword = await bcrypt.hash(password, 12); const result = await userModel.create({email: email, password: hashedPassword, name: `${firstName} ${lastName}`}); const token = jwt.sign({email: result.email, id: result._id}, secret, {expiresIn: "1h"}) res.status(201).json({result, token}) } catch (error) { res.status(500).json({message: "Something went wrong"}) console.log(error); } }
import React from "react"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import { BsStarFill, BsStarHalf } from "react-icons/bs"; import CircularLoading from "../../../../UI/CircularLoading/CircularLoading"; const MostMarkets = ({ more_store_visit, loading }) => { return ( <TableContainer component={Paper} sx={{ height: "100%" }} className='shadow-[0px_3px_6px_#00000029] rounded-lg'> <h2 className='p-4 text-[22px] font-medium'>المتاجر الأكثر زيارة</h2> <Table sx={{}} aria-label='simple table'> <TableHead> <TableRow className='bg-[#E6F5F652]' sx={{ "& .MuiTableCell-root.MuiTableCell-head": { fontFamily: "'Tajawal', sans-serif", border: "none", }, }}> <TableCell align='center' className='text-[#52575D] text-base font-medium pr-3'> اسم المتجر </TableCell> <TableCell align='right' className='text-[#52575D] text-base font-medium'> النشاط أو التصنيف </TableCell> <TableCell align='center' className='text-[#52575D] text-base font-medium'> تقييم العملاء </TableCell> </TableRow> </TableHead> <TableBody sx={{ "& .MuiTableRow-root .MuiTableCell-root": { fontFamily: "'Tajawal', sans-serif", border: "none", }, }}> {loading ? ( <TableRow> <TableCell colSpan={3}> <CircularLoading /> </TableCell> </TableRow> ) : ( <> {more_store_visit?.length === 0 ? ( <TableRow> <TableCell colSpan={5}> <p>لاتوجد متاجر حتي الآن</p> </TableCell> </TableRow> ) : ( more_store_visit?.map((row, index) => ( <TableRow key={index} sx={{ "&:last-child td, &:last-child th": { border: 0 }, "& .MuiTableCell-root": { height: "4rem", border: "none", }, }}> <TableCell component='th' scope='row' align='center' className='text-base font-normal '> <span className='text-ellipsis w-32'> {row?.store_name} </span> </TableCell> <TableCell sx={{ display: "flex", alignItems: "right", gap: "0.5rem", }} component='th' scope='row' className='flex flex-row items-center text-base font-normal justify-start'> <img className='img_icons' style={{ minWidth: '35px', minHeight: '35px',maxWidth:'35px',maxHeight:'35px' }} src={row?.activity[0]?.icon} alt='' /> <span className='text-ellipsis w-30'> {" "} {row?.activity[0]?.name} </span> </TableCell> <TableCell align='center' className='text-base font-normal'> <div className='flex items-center justify-center'> <div className='flex justify-between items-center py-1 px-1 w-16 h-6 rounded-md' style={{ backgroundColor: "rgb(164,161,251)" }}> <h2 className='font-medium' style={{ color: "#fff" }}> {row?.rate} </h2> {row?.rate > 3 ? ( <BsStarFill color='#fff' /> ) : ( <BsStarHalf color='#fff' /> )} </div> </div> </TableCell> </TableRow> )) )} </> )} </TableBody> </Table> </TableContainer> ); }; export default MostMarkets;
<?php #S-Cart/Core/Front/Models/ShopPage.php namespace Glumbo\Gracart\Front\Models; use Illuminate\Database\Eloquent\Model; use Cache; use Glumbo\Gracart\Front\Models\ShopStore; class ShopPage extends Model { use \Glumbo\Gracart\Front\Models\ModelTrait; use \Glumbo\Gracart\Front\Models\UuidTrait; public $table = GC_DB_PREFIX.'shop_page'; protected $connection = GC_CONNECTION; protected $guarded = []; public function stores() { return $this->belongsToMany(ShopStore::class, ShopPageStore::class, 'page_id', 'store_id'); } public function descriptions() { return $this->hasMany(ShopPageDescription::class, 'page_id', 'id'); } //Function get text description public function getText() { return $this->descriptions()->where('lang', gc_get_locale())->first(); } public function getTitle() { return $this->getText()->title ?? ''; } public function getDescription() { return $this->getText()->description ?? ''; } public function getKeyword() { return $this->getText()->keyword?? ''; } public function getContent() { return $this->getText()->content; } //End get text description /* *Get thumb */ public function getThumb() { return gc_image_get_path_thumb($this->image); } /* *Get image */ public function getImage() { return gc_image_get_path($this->image); } public function getUrl($lang = null) { return gc_route('page.detail', ['alias' => $this->alias, 'lang' => $lang ?? app()->getLocale()]); } /** * Get page detail * * @param [string] $key [$key description] * @param [string] $type [id, alias] * @param [int] $checkActive * */ public function getDetail($key, $type = null, $checkActive = 1) { if (empty($key)) { return null; } $tableDescription = (new ShopPageDescription)->getTable(); $dataSelect = $this->getTable().'.*, '.$tableDescription.'.*'; $page = $this->selectRaw($dataSelect) ->leftJoin($tableDescription, $tableDescription . '.page_id', $this->getTable() . '.id') ->where($tableDescription . '.lang', gc_get_locale()); $storeId = config('app.storeId'); if (gc_check_multi_shop_installed()) { $tablePageStore = (new ShopPageStore)->getTable(); $tableStore = (new ShopStore)->getTable(); $page = $page->join($tablePageStore, $tablePageStore.'.page_id', $this->getTable() . '.id'); $page = $page->join($tableStore, $tableStore . '.id', $tablePageStore.'.store_id'); $page = $page->where($tableStore . '.status', '1'); $page = $page->where($tablePageStore.'.store_id', $storeId); } if ($type === null) { $page = $page->where($this->getTable() .'.id', $key); } else { $page = $page->where($type, $key); } if ($checkActive) { $page = $page->where($this->getTable() .'.status', 1); } return $page->first(); } protected static function boot() { parent::boot(); // before delete() method call this static::deleting( function ($page) { $page->descriptions()->delete(); $page->stores()->detach(); //Delete custom field (new ShopCustomFieldDetail) ->join(GC_DB_PREFIX.'shop_custom_field', GC_DB_PREFIX.'shop_custom_field.id', GC_DB_PREFIX.'shop_custom_field_detail.custom_field_id') ->where(GC_DB_PREFIX.'shop_custom_field_detail.rel_id', $page->id) ->where(GC_DB_PREFIX.'shop_custom_field.type', 'shop_page') ->delete(); } ); //Uuid static::creating(function ($model) { if (empty($model->{$model->getKeyName()})) { $model->{$model->getKeyName()} = gc_generate_id($type = 'shop_page'); } }); } /** * Start new process get data * * @return new model */ public function start() { return new ShopPage; } /** * build Query */ public function buildQuery() { $tableDescription = (new ShopPageDescription)->getTable(); $dataSelect = $this->getTable().'.*, '.$tableDescription.'.*'; $query = $this->selectRaw($dataSelect) ->leftJoin($tableDescription, $tableDescription . '.page_id', $this->getTable() . '.id') ->where($tableDescription . '.lang', gc_get_locale()); $storeId = config('app.storeId'); if (gc_check_multi_shop_installed()) { $tablePageStore = (new ShopPageStore)->getTable(); $tableStore = (new ShopStore)->getTable(); $query = $query->join($tablePageStore, $tablePageStore.'.page_id', $this->getTable() . '.id'); $query = $query->join($tableStore, $tableStore . '.id', $tablePageStore.'.store_id'); $query = $query->where($tableStore . '.status', '1'); $query = $query->where($tablePageStore.'.store_id', $storeId); } //search keyword if ($this->gc_keyword !='') { $query = $query->where(function ($sql) use ($tableDescription) { $sql->where($tableDescription . '.title', 'like', '%' . $this->gc_keyword . '%') ->orWhere($tableDescription . '.keyword', 'like', '%' . $this->gc_keyword . '%') ->orWhere($tableDescription . '.description', 'like', '%' . $this->gc_keyword . '%'); }); } $query = $query->where($this->getTable() .'.status', 1); $query = $this->processMoreQuery($query); if ($this->random) { $query = $query->inRandomOrder(); } else { if (is_array($this->gc_sort) && count($this->gc_sort)) { foreach ($this->gc_sort as $rowSort) { if (is_array($rowSort) && count($rowSort) == 2) { $query = $query->sort($rowSort[0], $rowSort[1]); } } } } return $query; } }
import { Fragment } from "react"; import styles from "./styles/PageLayout.module.scss"; import Navigation from "./Navigation"; import PageLoading from "./PageLoading"; import classNames from "classnames"; type PageLayoutProps = { children: any, // 子元素 header?: any, // 自定义头部内容 loading?: boolean, // 是否加载 hideHeader?: boolean, // 隐藏头部 title?: string, // 标题头 className?: any, // 页面样式 } const PageHeader = ({ hideHeader, header, title }: any) => { if (hideHeader) return <Fragment /> if (!header) return <Navigation title={title} />; return header; } const PageLayout = (props: PageLayoutProps) => { const { children, loading, header, hideHeader, title, className } = props; if (loading) return <PageLoading />; return ( <div className={classNames(styles.container, className)}> <PageHeader hideHeader={hideHeader} header={header} title={title} /> <Fragment>{children}</Fragment> </div> ) } export default PageLayout;
import { StyleSheet, Text, View, Pressable, Image, FlatList, ListRenderItem, TextInput, } from 'react-native'; import React, {useCallback, useState} from 'react'; import globalStyles from 'styles/globalStyles'; import {percentageHeight, percentageWidth} from 'utils/screen_size'; import {BLACK, BLUE, GREY3, RED, WHITE} from 'styles/colors'; import {_currencyFormat, _onCheckImage} from 'services/fun'; import Spacer from 'components/Spacer'; import Button from 'components/Button'; import Ionicons from 'react-native-vector-icons/Ionicons'; import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons'; import useCartStore from 'store/useCartStore'; import {IMenuItems} from 'types/interfaces'; import Modal from 'react-native-modal'; export default function Footer() { const [isFooterExpanded, setIsFooterExpanded] = useState(false); const [isShowCharge, setIsShowCharge] = useState(false); const [uangDibayar, setUangDibayar] = useState('0'); const formatCurrency = (inputValue: string) => { // let value = parseFloat(inputValue.replace(/,/g, '')) || 0; if (inputValue.length === 0) { setUangDibayar('0'); } else { setUangDibayar(inputValue); } }; const {cartData, minusToCart, addToCart, deleteFromCart} = useCartStore(); const _onMinusCart = (item: any) => minusToCart!(item); const _onPlusCart = (item: any) => addToCart!(item); const _onDeleteFromCart = (id: number) => deleteFromCart!(id); const _onGetTotalrice = useCallback(() => { const totalPrice = cartData.length > 0 && cartData.reduce((acc, curr) => { if (curr?.quantity! > 0) { return acc + parseInt(curr.price) * curr?.quantity!; } return acc; }, 0); return totalPrice; }, [cartData]); console.log('uang dibayar', uangDibayar); const renderItem: ListRenderItem<IMenuItems & {quantity: number}> = ({ item, }) => ( <View style={[globalStyles.row]}> <Image source={_onCheckImage(item.picture)} style={{width: 70, height: 70}} /> <Spacer width={10} /> <View style={[globalStyles.displayFlex]}> <Text style={[globalStyles.headingBold.h3]}>{item.name}</Text> <View style={[globalStyles.row, globalStyles.alignCenter]}> <Text style={[globalStyles.headingBold.h3, {color: BLUE}]}> {_currencyFormat.format(parseInt(item.price, 10))} </Text> <Text style={[globalStyles.headingRegular.h3, {color: GREY3}]}> {' '} / porsi </Text> </View> </View> <View style={[ globalStyles.displayFlex, globalStyles.row, globalStyles.alignCenter, globalStyles.justifyAround, ]}> <Button text="-" textColor={item.quantity === 0 ? BLUE : WHITE} onPress={() => { if (item.quantity > 1) { _onMinusCart(item); } else if (item.quantity === 1) { _onDeleteFromCart(item?.id!); } }} containerStyle={[ styles.btnMinus, {backgroundColor: item.quantity === 0 ? WHITE : BLUE}, ]} /> <View> <Text style={[globalStyles.headingSemibold.h3]}>{item.quantity}</Text> </View> <Button text="+" textColor={WHITE} onPress={() => _onPlusCart(item)} containerStyle={styles.btnPlus} /> </View> <View> <Text style={[globalStyles.headingMedium.h3]}>{item.quantity}X</Text> </View> </View> ); const renderItemModal: ListRenderItem<IMenuItems & {quantity: number}> = ({ item, }) => ( <View style={[ globalStyles.row, globalStyles.alignCenter, { width: percentageWidth(100) - 4 * globalStyles.horizontalDefaultPadding.paddingHorizontal - 10, }, ]}> <Image source={_onCheckImage(item.picture)} style={{width: 70, height: 70}} /> <Spacer width={10} /> <View style={[globalStyles.displayFlex]}> <Text style={[globalStyles.headingBold.h3]}>{item.name}</Text> <View style={[globalStyles.row, globalStyles.alignCenter]}> <Text style={[globalStyles.headingBold.h3, {color: BLUE}]}> {_currencyFormat.format(parseInt(item.price, 10))} </Text> <Text style={[globalStyles.headingRegular.h3, {color: GREY3}]}> {' '} / porsi </Text> </View> </View> <View> <Text style={[globalStyles.headingMedium.h3]}>x{item.quantity}</Text> </View> </View> ); return ( <View style={[globalStyles.absolute, styles.containerFooter]}> <Pressable onPress={() => { if (cartData.length > 0) { setIsFooterExpanded(!isFooterExpanded); } }} style={[ globalStyles.absolute, globalStyles.alignCenter, styles.containerArrow, ]}> <Ionicons name={isFooterExpanded ? 'chevron-down-circle' : 'chevron-up-circle'} size={30} color={BLUE} /> </Pressable> <View style={[ globalStyles.displayFlex, globalStyles.row, globalStyles.justifySpaceBetween, globalStyles.horizontalDefaultPadding, globalStyles.verticalDefaultPadding, ]}> <View style={[globalStyles.row]}> <View> <SimpleLineIcons name="handbag" size={32} color={BLUE} /> <View style={[ globalStyles.absolute, globalStyles.justifyCenter, styles.badgeContainer, ]}> <View> <Text style={[ globalStyles.headingBold.h3, globalStyles.textAlignCenter, styles.badge, ]}> {cartData.length} </Text> </View> </View> </View> <Spacer width={10} /> <Text style={globalStyles.headingBold.h3}> {_currencyFormat.format(_onGetTotalrice())} </Text> </View> {cartData.length > 0 && ( <Button text="Charge" textColor={WHITE} containerStyle={styles.btnCharge} onPress={() => setIsShowCharge(!isShowCharge)} /> )} </View> <View> {isFooterExpanded && ( <View style={[ globalStyles.horizontalDefaultPadding, globalStyles.verticalDefaultPadding, {maxHeight: percentageHeight(50)}, ]}> <FlatList data={cartData} keyExtractor={item => item.id + Math.random().toString()} renderItem={renderItem} contentContainerStyle={{gap: 10}} /> </View> )} </View> <Modal isVisible={isShowCharge}> <View style={[ styles.containerModal, globalStyles.verticalDefaultPadding, globalStyles.horizontalDefaultPadding, ]}> <Ionicons name="close" color={BLACK} size={24} style={globalStyles.textAlignRight} onPress={() => setIsShowCharge(false)} /> <View style={[ globalStyles.row, globalStyles.alignCenter, globalStyles.justifyCenter, ]}> <Ionicons name="restaurant-outline" color={BLUE} size={32} /> <Text style={[globalStyles.headingSemibold.h3, {color: BLUE}]}> Detail Pesanan </Text> </View> <Spacer height={25} /> <View> <FlatList data={cartData} keyExtractor={item => item.id + Math.random().toString()} renderItem={renderItemModal} contentContainerStyle={[globalStyles.alignCenter, {gap: 10}]} horizontal /> </View> <Spacer height={15} /> <View> <View style={[globalStyles.row, globalStyles.alignCenter]}> <View style={[ globalStyles.displayFlex, globalStyles.row, globalStyles.justifySpaceBetween, ]}> <Text style={[ globalStyles.headingBold.h3, globalStyles.displayFlex, ]}> Total{' '} </Text> <Text style={[ globalStyles.headingBold.h3, globalStyles.textAlignCenter, {flex: 0.5}, ]}> :{' '} </Text> </View> <View style={[globalStyles.displayFlex]}> <Text style={[ globalStyles.headingBold.h3, globalStyles.textAlignRight, ]}> {_currencyFormat.format(_onGetTotalrice())} </Text> </View> </View> <View style={[globalStyles.row, globalStyles.alignCenter]}> <View style={[ globalStyles.displayFlex, globalStyles.row, globalStyles.justifySpaceBetween, ]}> <Text style={[ globalStyles.headingBold.h3, globalStyles.displayFlex, ]}> Uang Dibayar{' '} </Text> <Text style={[ globalStyles.headingBold.h3, globalStyles.textAlignCenter, {flex: 0.5}, ]}> :{' '} </Text> </View> <View style={[ globalStyles.displayFlex, {backgroundColor: '#F6F6F6'}, ]}> <TextInput keyboardType="number-pad" value={uangDibayar} onChangeText={formatCurrency} style={[ globalStyles.textAlignRight, globalStyles.headingBold.h3, ]} /> </View> </View> <View style={[globalStyles.row, globalStyles.alignCenter]}> <View style={[ globalStyles.displayFlex, globalStyles.row, globalStyles.justifySpaceBetween, ]}> <Text style={[ globalStyles.headingBold.h3, globalStyles.displayFlex, ]}> Kembalian{' '} </Text> <Text style={[ globalStyles.headingBold.h3, globalStyles.textAlignCenter, {flex: 0.5}, ]}> :{' '} </Text> </View> <View style={[ globalStyles.displayFlex, {backgroundColor: '#DEEBE0'}, ]}> <Text style={[ globalStyles.headingBold.h3, globalStyles.textAlignRight, ]}> {_currencyFormat.format( _onGetTotalrice() - parseInt(uangDibayar), )} </Text> </View> </View> </View> <Spacer height={15} /> <Button text="Cetak Struk" textColor={WHITE} containerStyle={{backgroundColor: BLUE, borderRadius: 10}} onPress={() => setIsShowCharge(false)} /> </View> </Modal> </View> ); } const styles = StyleSheet.create({ btnCharge: { borderRadius: 8, backgroundColor: BLUE, width: 150, height: 40, }, btnPlus: { borderWidth: 1, borderColor: BLUE, backgroundColor: BLUE, width: 25, height: 25, borderRadius: 4, }, containerFooter: { bottom: 0, borderTopWidth: 1, width: percentageWidth(100), backgroundColor: WHITE, }, containerArrow: { top: -17, left: 0, right: 0, zIndex: 2, }, badgeContainer: { top: 0, right: 0, width: 20, height: 20, }, badge: { color: WHITE, fontSize: 10, padding: 2, borderRadius: 10, backgroundColor: RED, }, btnMinus: { borderWidth: 1, borderColor: BLUE, width: 25, height: 25, borderRadius: 4, }, containerModal: { backgroundColor: WHITE, borderRadius: 5, }, });
/** * Module for the UserService. * * @author ef222hr * @version 1.0.0 */ import createError from 'http-errors' /** * Encapsulates a tandem service. */ export class UserService { /** * Sends request to auth service to register user. * * @param {object} req - Express request object. * @returns {boolean} true/false */ async registerUser (req) { // wait response from auth service const user = { username: req.body.username, password: req.body.password, role: req.body.role, } const response = await fetch(process.env.AUTH_REGISTER_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(user) }) if (response.status === 400) { throw createError(400, 'Both username and password must be provided.') } else if (response.status === 409) { throw createError(409, 'The username is already taken.') } else if (!response.ok) { throw new Error('Something went wrong with the register process.') } return response.json() } /** * Sends request to auth service to login user. * * @param {object} req - Express request object. * @returns {object} user - ... */ async loginUser (req) { const credentials = { username: req.body.username, password: req.body.password } const response = await fetch(process.env.AUTH_LOGIN_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(credentials) }) if (response.status === 401) { throw createError(401, 'Wrong username or password.') } else if (!response.ok) { throw new Error('Something went wrong with the login.') } return response.json() } }
// // RequestCharacter.swift // ilegra-marvel // // Created by Michel Anderson Lutz Teixeira on 11/01/2018. // Copyright © 2018 Michel Anderson Lutz Teixeira. All rights reserved. // import Foundation import Alamofire import ObjectMapper /** Class RequestCharacter - Extends: `Request` */ class RequestCharacter: Request{ func loadCharacters(name: String?, page: Int = 0, onComplete: @escaping (_ response: ResponseMarvelInfo) -> Void){ let offset = page * ApiURL.limit var queryParams: [String:String] = ["offset": String(offset), "limit": String(ApiURL.limit)] if let name = name, !name.isEmpty{ queryParams["nameStartsWith"] = name.replacingOccurrences(of: " ", with: "") } let url = ApiURL.basePath + ApiURL.pathCharacters + queryParams.queryString! + ApiURL.getCredentials() Alamofire.request(url).responseJSON { (response) in let statusCode = response.response?.statusCode switch response.result{ case .success(let value): let resultValue = value as? [String: Any] if statusCode == 200{ let model = Mapper<MarvelInfo>().map(JSONObject:resultValue) onComplete(.success(model: model!)) } case .failure(let error): //Status de erro let errorCode = error._code if errorCode == -1009 { let erro = ServerError(msgError: error.localizedDescription, statusCode: errorCode) onComplete(.noConnection(description: erro)) } else if errorCode == -1001 { let erro = ServerError(msgError: error.localizedDescription, statusCode: errorCode) onComplete(.timeOut(desciption: erro)) } }//switch }//alamofire }//loadCharacters }
// // Textify Copyright (C) 2023-2024 Aptivi // // This file is part of Textify // // Textify 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. // // Textify 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 <https://www.gnu.org/licenses/>. // using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.IO; using System.Linq; namespace Textify.Json { /// <summary> /// JSON tools /// </summary> public static class JsonTools { /// <summary> /// Beautifies the JSON text contained in the file. /// </summary> /// <param name="JsonFile">Path to JSON file.</param> /// <returns>Beautified JSON</returns> /// <exception cref="FileNotFoundException"></exception> public static string BeautifyJson(string JsonFile) { // Try to beautify JSON string JsonFileContents = File.ReadAllText(JsonFile); return BeautifyJsonText(JsonFileContents); } /// <summary> /// Minifies the JSON text contained in the file. /// </summary> /// <param name="JsonFile">Path to JSON file.</param> /// <returns>Minified JSON</returns> /// <exception cref="FileNotFoundException"></exception> public static string MinifyJson(string JsonFile) { // Try to minify JSON string JsonFileContents = File.ReadAllText(JsonFile); return MinifyJsonText(JsonFileContents); } /// <summary> /// Beautifies the JSON text. /// </summary> /// <param name="JsonText">Contents of a minified JSON.</param> /// <returns>Beautified JSON</returns> public static string BeautifyJsonText(string JsonText) { // Make an instance of JToken with this text var JsonToken = JToken.Parse(JsonText); // Beautify JSON string BeautifiedJson = JsonConvert.SerializeObject(JsonToken, Formatting.Indented); return BeautifiedJson; } /// <summary> /// Minifies the JSON text. /// </summary> /// <param name="JsonText">Contents of a beautified JSON.</param> /// <returns>Minified JSON</returns> public static string MinifyJsonText(string JsonText) { // Make an instance of JToken with this text var JsonToken = JToken.Parse(JsonText); // Minify JSON string MinifiedJson = JsonConvert.SerializeObject(JsonToken); return MinifiedJson; } /// <summary> /// Finds the JSON object differences between the two JSON object tokens /// </summary> /// <param name="sourceObj">Source object token</param> /// <param name="targetObj">Target object token</param> /// <returns>A JSON object containing differences for objects</returns> public static JObject FindDifferences(JToken sourceObj, JToken targetObj) { var diff = new JObject(); if (!JToken.DeepEquals(targetObj, sourceObj)) { // The objects are not equal. switch (targetObj.Type) { case JTokenType.Object: // Added keys var addedKeys = ((JObject)targetObj).Properties().Select(c => c.Name).Except(((JObject)sourceObj).Properties().Select(c => c.Name)); foreach (var k in addedKeys) { diff[$"+{k}"] = new JObject { ["+"] = targetObj[k].Path }; } // Removed keys var removedKeys = ((JObject)sourceObj).Properties().Select(c => c.Name).Except(((JObject)targetObj).Properties().Select(c => c.Name)); foreach (var k in removedKeys) { diff[$"-{k}"] = new JObject { ["-"] = sourceObj[k].Path }; } // Changed keys var changedKeys = ((JObject)targetObj).Properties().Where(c => !JToken.DeepEquals(c.Value, sourceObj[c.Name])).Select(c => c.Name); foreach (var k in changedKeys) { diff[$"*{k}"] = new JObject { ["*"] = new JObject { ["source"] = sourceObj[k], ["target"] = targetObj[k], } }; } break; case JTokenType.Array: // Additions and subtractions diff["+"] = new JArray(((JArray)targetObj).Except(sourceObj)); diff["-"] = new JArray(((JArray)sourceObj).Except(targetObj)); break; default: diff["+"] = targetObj; diff["-"] = sourceObj; break; } } return diff; } } }
/* * Copyright 2023 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package controllers import cats.data.EitherT import connectors.PreferencesFrontendConnector import helpers.{CssHelpers, SpecBase, UserAnswerData} import models.PaperlessMessages import org.jsoup.Jsoup import org.jsoup.nodes.Document import models.backend.{Correspondence, Residential} import org.mockito.ArgumentMatchers.any import org.mockito.MockitoSugar.when import org.scalatest.BeforeAndAfterEach import org.scalatestplus.mockito.MockitoSugar.mock import play.api.inject.bind import play.api.test.FakeRequest import play.api.test.Helpers._ import uk.gov.hmrc.http.UpstreamErrorResponse import scala.concurrent.Future class RlsInterruptControllerSpec extends SpecBase with BeforeAndAfterEach with CssHelpers with UserAnswerData { "RlsInterrupt Controller" - { "must trigger RLS interrupt" - { "when user has an RLS flag set for main address only" in { val userData = rlsFlagMainAddressUserData val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, routes.IndexController.onPageLoad.url) val result = route(application, request).value status(result) mustEqual SEE_OTHER redirectLocation(result).value mustEqual routes.RlsInterruptController.onPageLoad().url } } "when user has an RLS flag set for postal address only" in { val userData = rlsFlagPostalAddressUserData val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, routes.IndexController.onPageLoad.url) val result = route(application, request).value status(result) mustEqual SEE_OTHER redirectLocation(result).value mustEqual routes.RlsInterruptController.onPageLoad().url } } "when user has an RLS flag set for both main address and postal address" in { val userData = rlsFlagBothAddressesUserData val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, routes.IndexController.onPageLoad.url) val result = route(application, request).value status(result) mustEqual SEE_OTHER redirectLocation(result).value mustEqual routes.RlsInterruptController.onPageLoad().url } } } "must display correct content on RLS interrupt page" - { "when user has an RLS flag set for main address only" in { val userData = rlsFlagMainAddressUserData val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, routes.RlsInterruptController.onPageLoad().url) val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) document.select(govukInsetTextSelector).text() mustEqual "You need to update your main address to receive post from HMRC." document.select(govukSummaryListKeySelector).text() mustEqual "Main address" document.select(govukSummaryListValueSelector).text() mustEqual "Update your main address" document.select(govukSummaryListActionsSelector).text() mustEqual "Update your main address" } } "when user has an RLS flag set for postal address only" in { val userData = rlsFlagPostalAddressUserData val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, routes.RlsInterruptController.onPageLoad().url) val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) document.select(govukInsetTextSelector).text() mustEqual "You need to update your postal address to receive post from HMRC." document.select(govukSummaryListKeySelector).text() mustEqual "Postal address" document.select(govukSummaryListValueSelector).text() mustEqual "Update your postal address All your letters will be sent to this address." document.select(govukSummaryListActionsSelector).text() mustEqual "Update your postal address Remove your postal address" } } "when user has an RLS flag set for both main address and postal address" in { val userData = rlsFlagBothAddressesUserData val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, routes.RlsInterruptController.onPageLoad().url) val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) document.select(govukInsetTextSelector).text() mustEqual "You need to update your main and postal addresses to receive post from HMRC." document.select(govukSummaryListKeySelector).text() mustEqual "Main address Postal address" document.select(govukSummaryListValueSelector).text() mustEqual "Update your main address Update your postal address All your letters will be sent to this address." document.select(govukSummaryListActionsSelector).text() mustEqual "Update your main address Update your postal address Remove your postal address" } } } "must not trigger RLS Interrupt" - { "when user has no RLS flag set for both main address and postal address" in { val userData = rlsFlagNeitherAddressUserData val mockPreferencesFrontendConnector: PreferencesFrontendConnector = mock[PreferencesFrontendConnector] val application = applicationBuilder(userAnswers = Some(emptyUserAnswers), userData = Some(userData)) .overrides(bind[PreferencesFrontendConnector].toInstance(mockPreferencesFrontendConnector)) .build() running(application) { when(mockPreferencesFrontendConnector.getPaperlessStatus(any(), any())) .thenReturn( EitherT[Future, UpstreamErrorResponse, PaperlessMessages]( Future.successful(Right(preferencesFrontendResponse)) ) ) val request = FakeRequest(GET, routes.IndexController.onPageLoad.url) val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) document.select(titleSelector).text() mustEqual "Your profile and settings" } } } "must direct user to update other address (triggering a second RLS interrupt)" - { "when user has updated main address and has an RLS flag set for postal address" in { val userData = rlsFlagBothAddressesUserData val userAnswers = userAnswers_isUkPostcodeSingleResultConfirmedResidential val application = applicationBuilder(userAnswers = Some(userAnswers), userData = Some(userData)).build() running(application) { val request = FakeRequest(GET, changeaddress.routes.AddressConfirmationController.onPageLoad(Residential).url) val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) val link = document.select(govukLinkWithinGovukBodySelector).eq(1) link.text() mustEqual "Update postal address" link.attr("href") mustEqual routes.IndexController.onPageLoad.url } } "when user has updated postal address and has an RLS flag set for main address" in { val userData = rlsFlagBothAddressesUserData val userAnswers = userAnswers_isUkPostcodeSingleResultConfirmedCorrespondence val application = applicationBuilder(userAnswers = Some(userAnswers), userData = Some(userData)) .configure("features.pta-mode" -> false).build() running(application) { val request = FakeRequest(GET, changeaddress.routes.AddressConfirmationController.onPageLoad(Correspondence).url) val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) val link = document.select(govukLinkWithinGovukBodySelector) link.text() mustEqual "Update main address" link.attr("href") mustEqual routes.IndexController.onPageLoad.url } } } "must direct user to index" - { "when user has updated main address and has no RLS flag set for postal address" in { val userData = rlsFlagMainAddressUserData val userAnswers = userAnswers_isUkPostcodeSingleResultConfirmedResidential val application = applicationBuilder(userAnswers = Some(userAnswers), userData = Some(userData)) .configure("features.pta-mode" -> false).build() running(application) { val request = FakeRequest(GET, changeaddress.routes.AddressConfirmationController.onPageLoad(Residential).url).withSession("authToken" -> "123abc") val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) val link = document.select(govukLinkWithinGovukBodySelector).eq(1) link.text() mustEqual "Return to your details" link.attr("href") mustEqual routes.IndexController.onPageLoad.url } } "when user has updated postal address and has no RLS flag set for main address" in { val userData = rlsFlagPostalAddressUserData val userAnswers = userAnswers_isUkPostcodeSingleResultConfirmedCorrespondence val application = applicationBuilder(userAnswers = Some(userAnswers), userData = Some(userData)) .configure("features.pta-mode" -> false).build() running(application) { val request = FakeRequest(GET, changeaddress.routes.AddressConfirmationController.onPageLoad(Correspondence).url).withSession("authToken" -> "123abc") val result = route(application, request).value status(result) mustEqual OK val pageContent = contentAsString(result) val document: Document = Jsoup.parse(pageContent) val link = document.select(govukLinkWithinGovukBodySelector) link.text() mustEqual "Return to your details" link.attr("href") mustEqual routes.IndexController.onPageLoad.url } } } } }
/* Copyright 2022 DigitalOcean Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package crdregistration import ( "context" "testing" "time" "github.com/google/go-cmp/cmp" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextensionsclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestRegister(t *testing.T) { crd := &apiextensionsv1.CustomResourceDefinition{ ObjectMeta: metav1.ObjectMeta{ Name: "tests.example.com", }, Spec: apiextensionsv1.CustomResourceDefinitionSpec{ Group: "example.com", Scope: apiextensionsv1.NamespaceScoped, Names: apiextensionsv1.CustomResourceDefinitionNames{ Plural: "tests", Kind: "Test", ShortNames: []string{"test"}, }, Versions: []apiextensionsv1.CustomResourceDefinitionVersion{{ Name: "v1", Served: true, Storage: true, Schema: &apiextensionsv1.CustomResourceValidation{ OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{Type: "object"}, }, }}, }, } crdDifferentVersion := crd.DeepCopy() crdDifferentVersion.Spec.Versions[0].Name = "v1beta1" tests := []struct { name string crd *apiextensionsv1.CustomResourceDefinition existingCRD *apiextensionsv1.CustomResourceDefinition }{{ name: "create new CRD", crd: crd, existingCRD: nil, }, { name: "update existing CRD", crd: crd, existingCRD: crdDifferentVersion, }} for _, test := range tests { t.Run(test.name, func(t *testing.T) { extensionsclient := apiextensionsclient.NewSimpleClientset() if test.existingCRD != nil { extensionsclient = apiextensionsclient.NewSimpleClientset(test.existingCRD.DeepCopyObject()) } client := &Client{ apiextensionsclient: extensionsclient, } go func() { time.Sleep(100 * time.Millisecond) crd, err := client.apiextensionsclient.ApiextensionsV1().CustomResourceDefinitions().Get(context.Background(), test.crd.Name, metav1.GetOptions{}) if err != nil { t.Errorf("retrieving CRD to update status: %q\n", err) return } crd.Status = apiextensionsv1.CustomResourceDefinitionStatus{ Conditions: []apiextensionsv1.CustomResourceDefinitionCondition{{ Type: apiextensionsv1.Established, Status: apiextensionsv1.ConditionTrue, }}, } _, err = client.apiextensionsclient.ApiextensionsV1().CustomResourceDefinitions().UpdateStatus(context.Background(), crd, metav1.UpdateOptions{}) if err != nil { t.Errorf("updating CRD status: %q\n", err) } }() if err := client.Register(context.Background(), test.crd); err != nil { t.Error(err) } crd, err := client.apiextensionsclient.ApiextensionsV1().CustomResourceDefinitions().Get(context.Background(), test.crd.Name, metav1.GetOptions{}) if err != nil { t.Fatalf("retrieving CRD: %q\n", err) } if diff := cmp.Diff(test.crd.Spec, crd.Spec); diff != "" { t.Errorf("(-want, +got)\n%s", diff) } }) } }
Aquí tienes un programa en Python que permite agregar productos al carro, mostrarlos y realizar el checkout con los descuentos correspondientes: ```python # Diccionario de productos con sus precios products = { '1': {'name': 'Juego Pokemon X para Nintendo 3DS', 'price': 33.77}, '2': {'name': 'Nintendo 3DS XL', 'price': 203}, '3': {'name': 'Juego Mario Kart 7 para Nintendo 3DS', 'price': 27.58}, '4': {'name': 'PlayStation 4', 'price': 348.00}, '5': {'name': 'FIFA 16, PlayStation 4', 'price': 51.19} } # Carro de compras cart = {} def add_to_cart(product_id, quantity): if product_id in products: if product_id in cart: cart[product_id] += quantity else: cart[product_id] = quantity print(f"Se agregaron {quantity} unidades del producto {product_id} al carro.") else: print("Producto inválido.") def view_cart(): if len(cart) > 0: print("Productos en el carro:") for product_id, quantity in cart.items(): product = products[product_id] name = product['name'] price = product['price'] total_price = price * quantity print(f"{name} (x{quantity}): USD {total_price:.2f}") else: print("El carro está vacío.") def checkout(): total_price = 0.0 # Calcular precio total for product_id, quantity in cart.items(): product = products[product_id] price = product['price'] total_price += price * quantity # Aplicar descuento if '1' in cart and '2' in cart and '3' in cart: total_price *= 0.8 elif '4' in cart and '5' in cart: total_price *= 0.85 # Imprimir el valor total del carro print(f"Total a pagar: USD {round(total_price, 1)}") # Programa principal while True: action = input("Ingrese una acción (agregar, ver, checkout): ") if action == 'agregar': product_info = input("Ingrese el ID del producto y la cantidad separados por coma: ") product_id, quantity = product_info.split(',') add_to_cart(product_id, int(quantity)) elif action == 'ver': view_cart() elif action == 'checkout': checkout() break else: print("Acción inválida.") ``` Este programa utiliza un diccionario `products` para almacenar los productos con sus respectivos precios. El carro de compras se representa mediante otro diccionario `cart`, donde las claves son los IDs de los productos y los valores son las cantidades. El programa define tres funciones: - `add_to_cart`: Agrega productos al carro. Verifica si el producto es válido y actualiza la cantidad en el carro. - `view_cart`: Muestra los productos y cantidades en el carro, junto con el precio total de cada producto. - `checkout`: Calcula el precio total del carro teniendo en cuenta los descuentos y lo muestra redondeado a un decimal. En el programa principal, se utiliza un bucle infinito para recibir las acciones del usuario. Dependiendo de la acción ingresada, se llama a la función
import React from 'react'; import { screen } from '@testing-library/dom'; import UserApi from 'apis/components/User'; import userEvent from '@testing-library/user-event'; import Home from '../index'; import { renderWithReduxWithRouter } from '../../../../../utils/testUtility'; import { sleep } from '../../../../../utils/timeUtility'; test('Home without product tour', async () => { renderWithReduxWithRouter( <> <UserApi /> <Home /> </>, {}, ); await sleep(10); expect(screen.queryByText('Go to itineraries')).toBeInTheDocument(); expect( screen.queryByText('See a quick product tour?'), ).not.toBeInTheDocument(); }); test('Home product tour', async () => { process.env.ENV = 'live'; const { history } = renderWithReduxWithRouter( <> <UserApi /> <Home /> </>, {}, ); await sleep(10); expect(screen.queryByText('Go to itineraries')).toBeInTheDocument(); expect(screen.queryByText('See a quick product tour?')).toBeInTheDocument(); const link = screen.queryByTestId('productTourLink'); expect(link).toBeInTheDocument(); userEvent.click(link); expect(history.location.pathname).toBe('/'); expect(history.location.search).toBe('?product_tour_id=241369'); process.env.ENV = undefined; });
/** * Copyright 2021 - 2021 CMPUT301F21T03 (Alpha-Apps). All rights reserved. This document nor any * part of it may be reproduced, stored in a retrieval system or transmitted in any for or by any * means without prior permission of the members of CMPUT301F21T03 or by the professor and any * authorized TAs of the CMPUT301 class at the University of Alberta, fall term 2021. * * Class: GoBackButton * * Description: Sets a listener that responds when a user clicks on a "go back" button. When they * do so it will close the current frame and re-open the the most-recent frame. * * Changelog: * 1.0 Mathew Oct-21-2021 Created * 1.1 Mathew Nov-16-2021 Changed to be an image button */ package com.example.habitapp.Fragments; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.example.habitapp.R; public class GoBackButton extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { // Defines the xml file for the fragment return inflater.inflate(R.layout.go_back, parent, false); } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { // sets a listener for when the button is clicked ImageButton goBackButton = view.findViewById(R.id.go_to_last_page); goBackButton.setOnClickListener(this::goBackButtonPressed); } private void goBackButtonPressed(View view) { // goes back to the previously opened activity getActivity().finish(); } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTravelPackagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('travel_packages', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description')->nullable(); $table->string('departure_from')->nullable(); $table->string('destination'); $table->date('departure_date')->nullable(); $table->date('return_date')->nullable(); $table->decimal('price', 7, 2)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('travel_packages'); } }
import React, { useState, useContext } from 'react' import { AuthContext } from '../context/AuthContext.js' import BASE_URL from '../utlis/config.js' import toast, { Toaster } from 'react-hot-toast' import { useNavigate } from 'react-router' import './login.css' import { LOGIN_FAILURE, LOGIN_START, LOGIN_SUCCESS } from '../contants/actionTypes.js' const Login = () => { const navigate = useNavigate() const [credentials, setCredentials] = useState({ email: undefined, password: undefined }) const { dispatch } = useContext(AuthContext) const handleChange = e => { setCredentials(prev => ({ ...prev, [e.target.id]: e.target.value })) } const handleClick = async e => { e.preventDefault() dispatch({ type: LOGIN_START }) try { const res = await fetch(`${BASE_URL}/auth/login`, { method: 'post', headers: { 'content-type': 'application/json' }, credentials: 'include', body: JSON.stringify(credentials) }) const result = await res.json() if (!res.ok) { toast.error(result.message) } if (res.ok) { toast.success(result.message) } // console.log(result.data) dispatch({ type: LOGIN_SUCCESS, payload: result.data }) navigate('/') } catch (error) { dispatch({ type: LOGIN_FAILURE, payload: error.message }) } } return ( <> <Toaster className="top-center" /> <section> <div className="wrapper" style={{ backgroundImage: 'url(https://img.freepik.com/free-vector/computer-login-concept-illustration_114360-7962.jpg)' }}> <div class="inner"> <form className='form' onSubmit={handleClick}> <h3>Login Form</h3> <div class="form-wrapper"> <label for>Email</label> <input onChange={handleChange} type="text" id='email' placeholder='Email' class="form-control" /> </div> <div class="form-wrapper"> <label for>Password</label> <input onChange={handleChange} type="password" id='password' placeholder='password' class="form-control" /> </div> <button type='submit' onClick={handleClick} className='button'>Login</button> </form> </div> </div> </section > </> ) } export default Login
package vega.uplink.pointing.PtrParameters; import vega.uplink.pointing.PointingElement; public class OffsetRefAxis extends DirectionVector { /** * offsetRefAxis */ public static String OFFSETREFAXIS_TAG="offsetRefAxis"; /** * SC_Xaxis */ public static String SC_X_AXIS_TAG="SC_Xaxis"; /** * Creates a offsetRefAxis Direction vector referenced to SC_Xaxis direction vector * Direction vectors can be defined by referencing to * direction vectors that were previously defined and * got a name assigned. * @param reference Name of the referenced direction vector */ public OffsetRefAxis(){ //super("offsetRefAxis"); this(SC_X_AXIS_TAG); } /** * Creates a offsetRefAxis fixed direction vector expressed in spherical coordinates * For spherical coordinates the element must * contain the child elements <lon> and <lat>. The * cartesian components of the vector are * (cos(lat)*cos(lon), cos(lat)*sin(lon), sin(lat)). * The unit in which longitude and latitude are written must be deg. * The frame attribute specifies relative to which * frame the direction vector is defined. Possible * values are SC, EME2000 and CG. * @param frame The frame where this vector is expressed (SC,EME2000,CG) * @param longitude Longitude expressed in deg. * @param latitude Latitude expressed in deg. */ public OffsetRefAxis(String frame,float longitude,float latitude){ super(OFFSETREFAXIS_TAG,frame,longitude,latitude); } public OffsetRefAxis(PointingElement pm){ super(OFFSETREFAXIS_TAG,pm); } public OffsetRefAxis copy(){ OffsetRefAxis result = new OffsetRefAxis(super.copy()); return result; } /** * Creates a offsetRefAxis Direction vector referenced to another direction vector * Direction vectors can be defined by referencing to * direction vectors that were previously defined and * got a name assigned. * @param reference Name of the referenced direction vector */ public OffsetRefAxis(String reference){ super(OFFSETREFAXIS_TAG,reference); } /** * Creates a fixed offsetRefAxis direction vector expressed in cartesian coordinates * For cartesian coordinates the element must * contain the child elements <x> <y> and <z> that * contain fixed numbers specifying the * components (that must not all be zero). The * direction vector corresponds to the normalization * of the vector. * @param frame The frame where this vector is expressed (SC,EME2000,CG) * @param x The x component of this vector * @param y The y component of this vector * @param z The z component of this vector */ public OffsetRefAxis(String frame,float x,float y, float z){ super(OFFSETREFAXIS_TAG,frame,x,y,z); } /** * Creates a fixed offsetRefAxis direction vector expressed in spherical coordinates * For spherical coordinates the element must * contain the child elements <lon> and <lat>. The * cartesian components of the vector are * (cos(lat)*cos(lon), cos(lat)*sin(lon), sin(lat)). For * spherical coordinates the attribute units must * be provided and must contain a dimension of an * angle. * The frame attribute specifies relative to which * frame the direction vector is defined. Possible * values are SC, EME2000 and CG. * @param frame The frame where this vector is expressed (SC,EME2000,CG) * @param unitLongitude Unit in which the longitude is expressed * @param longitude Longitude * @param unitLatitude Unit in which the latitude is expressed * @param latitude Latitude */ public OffsetRefAxis(String frame,String unitLongitude,float longitude,String unitLatitude,float latitude){ super(OFFSETREFAXIS_TAG,frame,unitLongitude,longitude,unitLatitude,latitude); } /** * Creates a offsetRefAxis direction vector based in Origin and Target * This representation is used to define a direction * vector from two state vectors. * Because state vectors are always defined relative * to inertial frame, the resulting direction vector is * defined relative to inertial frame. * @param origin Origin State vector * @param target Target State vector */ public OffsetRefAxis(String origin,String target){ super(OFFSETREFAXIS_TAG,origin,target); } /** * Creates a offsetRefAxis rotated Direction Vector * This representation allows to define a direction * vector by right-handed rotation of the direction * vector axis around rotationAxis by the angle * rotationAngle. * The axes axis and rotationAxis must both * be defined either relative to SC or inertial frame. * @param axis The axis that this vector reference * @param rotationAxis Rotation axis of the vector * @param rotationAngle Rotation angle. It must be expressed in deg. */ public OffsetRefAxis(String axis,String rotationAxis,float rotationAngle){ super(OFFSETREFAXIS_TAG,axis,rotationAxis,rotationAngle); } /** * Creates a offsetRefAxis rotated Direction Vector * This representation allows to define a direction * vector by right-handed rotation of the direction * vector axis around rotationAxis by the angle * rotationAngle. * The axes axis and rotationAxis must both * be defined either relative to SC or inertial frame. * @param axis The axis that this vector reference * @param rotationAxis Rotation axis of the vector * @param rotationAngleUnit Unit in which the angle of rotation is expressed * @param rotationAngle Rotation angle */ public OffsetRefAxis(String axis,String rotationAxis,String rotationAngleUnit,float rotationAngle){ super(OFFSETREFAXIS_TAG,axis,rotationAxis,rotationAngleUnit,rotationAngle); } }
Demo code for Affine-SIFT (ASIFT) image matching ------------------------------------------------------------------------- ------------------------------------------------------------------------- Jean-Michel Morel (Jean-Michel Morel <morel@cmla.ens-cachan.fr>) Guoshen Yu (yu@cmap.polytechnique.fr) Version 2.1.2, Jan. 9, 2011 This directory contains the C++ code of ASIFT, a fully affine invariant image matching algorithm. ************************** Unix/Linux/Mac Users ************************** For Unix/Linux and Mac users, the code is ready to be compiled. The executable adapted to your computer system is generated after compiling. ************************************************************************** ***************************** Windows Users ****************************** For Windows users, the executable as well as the code is provided. (For the executable, you need to download separately the installation file from http://www.ipol.im/pub/algo/my_affine_sift/ .) ************************************************************************** **************************** Matlab Interface **************************** Although the ASIFT program is standalone and can be executed without Matlab, a Matlab interface is provided (for Unix/Linux/Mac/Windows users). ************************************************************************** If you have any problem using the this program, please contact Guoshen Yu yu@cmap.polytechnique.fr For more information about ASIFT, please see the web page at http://www.ipol.im/pub/algo/my_affine_sift/. You can also try ASIFT using the online demo. The online demo allows testing ASIFT with your own images without installing the program. If you use the ASIFT code or software, please cite the following paper: J.M. Morel and G.Yu, ASIFT: A New Framework for Fully Affine Invariant Image Comparison, SIAM Journal on Imaging Sciences, vol. 2, issue 2, pp. 438-469, 2009. ------------------------------------------------------------------------- ------------------------------------------------------------------------- UNIX/LINUX/MAC USER GUIDE The code is compilable on Unix/Linux and Mac OS. - Compilation. Automated compilation requires the make program. - Library. This code requires the libpng library. You can automatically download, compile and include this library to the compiled program by adding the LOCAL_LIBS=1 option to the make commands. - Image format. Only the PNG format is supported. ------------------------------------------------------------------------- Usage: 1. Download the ASIFT code package and extract it. Go to that directory. 2. Compile the source code (on Unix/Linux/Mac OS). There are two ways to compile the code. (1) RECOMMENDED, with Open Multi-Processing multithread parallelization (http://openmp.org/). Roughly speaking, it accelerates the program using the multiple processors in the computer. Run make OMP=1 OR (2) If the complier does not support OpenMp, run make ATTENTION: If libpng (the official PNG reference library) is not installed in your computer, an option LOCAL_LIBS=1 should be added after make. Example make OMP=1 LOCAL_LIBS=1 The compilation will automatically download and compile libpng and zlib and include the library to the program. 3. Run ASIFT. ./demo_ASIFT imgIn1.png, imgIn2.png imgOutVert.png imgOutHori.png matchings.txt keys1.txt keys2.txt -- imgIn1.png, imgIn2.png: Input images (in png format). -- imgOutVert.png, imgOutHori.png: Output images (vertical/horizontal concatenated). The detected matches are connected by write lines. -- matchings.txt: The file format starts with 1 integer giving the total number of matches. Then each line specifies the coordinates (col1, row1, col2, row2) of a pair of matched points. (col: horizontal axis, from left to right. row: vertical axis, from top to bottom.) -- keys1.txt keys2.txt: ASIFT keypoints in the two images, in the same format as the SIFT keypoints of David Lowe. The file starts with 2 integers giving the total number of keypoints and the length of the descriptor vector for each keypoint (128). Then the location of each keypoint in the image is specified by 4 floating point numbers giving subpixel column and row location, scale, and orientation (in radians from -PI to PI). Finally, the invariant descriptor vector for the keypoint is given as a list of 128 integers in range [0,255]. -- [optional 0/1]. 1: input images resize to an area equal to 800x600 for ASIFT, in keeping the aspect ratio (by default). 0: no resize. The resize is to limit the ASIFT computation time. The results (output images, keypoint coordinates and scales) are normalized to the original image size, so the resize is "transparent" to the user. Example, run ./demo_ASIFT adam1.png adam2.png imgOutVert.png imgOutHori.png matchings.txt keys1.txt keys2.txt You get on the screen "WARNING: The input images are resized to 800x600 for ASIFT. But the results will be normalized to the original image size. Computing keypoints on the two images... 12928 ASIFT keypoints are detected. 8972 ASIFT keypoints are detected. Keypoints computation accomplished in 24 seconds. Matching the keypoints... The two images match! 914 matchings are identified. log(nfa)=-1496.88. Keypoints matching accomplished in 4 seconds." ------------------------------------------------------------------------- ------------------------------------------------------------------------- WINDOWS USER GUIDE (For the executable, you need to download separately the installation file from http://www.ipol.im/pub/algo/my_affine_sift/.) - The provided Windows executable demo_ASIFT.exe has been compiled by the Intel C++ compiler on 32-bit Windows. It is executable on both 32-bit and 64-bit Windows, although it is not optimized for the latter. - The executable has not been extensively tested. If you have any problem using it, please contact Guoshen Yu yu@cmap.polytechnique.fr. - The source code is compilable with the Intel C++ compiler and Visual C++ compiler. To use ASIFT, you do not need to recompile the code, but you want to do so, Intel C++ is recommended since it supports both OpenMP and vectorization. In order to have the code compilable with Intel C++ and Visual C++ compilers, the following minor changes of the code may be required. * In ./io_png/io_png.c #include <png.h> ----> #include "./libs/png/png.h" * In demo_lib_sift.cpp unsigned short distsq = 0; ----> int distsq = 0; ------------------------------------------------------------------------- Usage: 1. Download the installation file demo_ASIFTsetp.exe from http://www.ipol.im/pub/algo/my_affine_sift/ 2. Install the program. Double click the file demo_ASIFTsetp.exe. A small library distributed by Microsoft (Microsoft Visual C++ 2010 Redistributable Package) will be installed to your PC. The ASIFT software will be installed to C:\Program Files\demo_ASIFT 3. Run ASIFT. Run a Dos command prompt (you find it in Start > All Programs > Accessories > Command Prompt) - Go to the ASIFT directory by typing cd C:\Program Files\demo_ASIFT. - Run the ASIFT program by typing demo_ASIFT adam1.png adam2.png imgOutVert.png imgOutHori.png matchings.txt keys1.txt keys2.txt (It follows the same syntax of that for Unix/Linux/Mac described above.) You can of course move the ASIFT directory C:\Program Files\demo_ASIFT to wherever that is more convenient. ------------------------------------------------------------------------- Troubleshooting 1. If you are able to run the program but the results are not written to the output files, check and make sure that you have the write file permission in the demo_ASIFT directory. 2. Microsoft Visual Studio is NOT required to run the program. However, in case you cannot run the program (for example some library or dll is missing), you may try installing a Microsoft Visual Studio and then running again the program. ------------------------------------------------------------------------- ------------------------------------------------------------------------- MATLAB INTERFACE (OPTIONAL) Run ASIFT via Matlab: Open test_demo_ASIFT.m in Matlab and execute the script. The Matlab interface reads most standard image formats. ------------------------------------------------------------------------- ------------------------------------------------------------------------- CREDITS - The epipolar geometry filtering algorithm ORSA of Moisan and Stival is used at the end of the ASIFT algorithm to eliminate false matches. http://www.math-info.univ-paris5.fr/~moisan/epipolar/ - We would like to thank Nicolas Limare for his help on developing the program, and Pierre Moulon for his insights on producing the executable for Windows. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Licensing conditions This software is being made available for research purposes only. It is necessary to obtain a license from Ecole Polytechnique, ENS Cachan, Jean-Michel Morel, and Guoshen Yu for commercial applications. See the file LICENSE in this directory for conditions of use.
import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faShoppingCart } from "@fortawesome/free-solid-svg-icons"; import "./Product.css"; const Product = (props) => { const { name, img, price, ratings, seller } = props.product; const handleToCard = props.handleToCard; return ( <div className="card-body"> <img src={img} alt="" /> <div className="card-info"> <h6 className="product-name">{name}</h6> <p>Price: ${price}</p> <p>Manufacturer: {seller}</p> <p>Rating: {ratings} star</p> </div> <button onClick={() => handleToCard(props.product)} className="btn-card"> add To Card <FontAwesomeIcon icon={faShoppingCart} /> </button> </div> ); }; export default Product;
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Prediction action clicked event. * * @property-read array $other { * Extra information about event. * * - string actionname: The action name * } * * @package tool_inspire * @copyright 2017 David Monllao {@link http://www.davidmonllao.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace tool_inspire\event; defined('MOODLE_INTERNAL') || die(); /** * Event triggered after a user clicked on one of the prediction suggested actions. * * @package tool_inspire * @copyright 2017 David Monllao {@link http://www.davidmonllao.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_clicked extends \core\event\base { /** * Set basic properties for the event. */ protected function init() { $this->data['objecttable'] = 'tool_inspire_predictions'; $this->data['crud'] = 'r'; $this->data['edulevel'] = self::LEVEL_TEACHING; } /** * Returns localised general event name. * * @return string */ public static function get_name() { return get_string('eventactionclicked', 'tool_inspire'); } /** * Returns non-localised event description with id's for admin use only. * * @return string */ public function get_description() { return "The user with id '$this->userid' has clicked '{$this->other['actionname']}' action for the prediction with id '".$this->objectid."'."; } /** * Returns relevant URL. * @return \moodle_url */ public function get_url() { return new \moodle_url('/admin/tool/inspire/prediction.php', array('id' => $this->objectid)); } /** * Custom validations. * * @throws \coding_exception * @return void */ protected function validate_data() { parent::validate_data(); if (!isset($this->objectid)) { throw new \coding_exception('The \'objectid\' must be set.'); } } public static function get_objectid_mapping() { return array('db' => 'tool_inspire_predictions'); } }
import cookieParser from 'cookie-parser'; import cors from 'cors'; import express, { Application, NextFunction, Request, Response } from 'express'; import httpStatus from 'http-status'; import globalErrorHandler from './app/middlewares/globalErrorHandler'; import routes from './app/routes'; const app: Application = express(); const corsOptions = { origin: [ 'http://localhost:3000', 'https://iridescent-dieffenbachia-ca41fb.netlify.app', 'https://book-catalog-app-lac.vercel.app', ], credentials: true, }; app.use(cors(corsOptions)); app.use(cookieParser()); //parser app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use('/api/v1', routes); // global error handler app.use(globalErrorHandler); //handle not found app.use((req: Request, res: Response, next: NextFunction) => { res.status(httpStatus.NOT_FOUND).json({ success: false, message: 'Not Found', errorMessages: [ { path: req.originalUrl, message: 'API Not Found', }, ], }); next(); }); export default app;
import { AxiosResponse } from 'axios'; import { axiosGetApi } from 'service/api/axios'; import { CommentModel, parsingCommentResponseToCommentModel } from 'service/type/model/comment'; import { NewsModel, parsingNewsResponseToNewsModel } from 'service/type/model/news'; export interface CustomApiResponse { statusCode: number; data: number[] | NewsModel[] | CommentModel[] | Error; } export const topNewsRequestApi = async (): Promise<CustomApiResponse> => { try { const result: CustomApiResponse = await axiosGetApi({ endPoint: `topstories.json?print=pretty`, headers: { 'Content-Type': 'application/json', }, }) .then((response: AxiosResponse) => { if (response.status === 200) { return { statusCode: response.status, data: response.data.splice(0, 30), // Only store top 30 news ID }; } else { throw new Error('Error while processing topNewsRequestApi'); } }) .catch((err) => { throw err; }); return result; } catch (err) { return { statusCode: 400, data: err as Error, }; } }; export const newsDetailRequestApi = async (topNews: number[]): Promise<CustomApiResponse> => { try { // [ ========== Bad waterfall ========== ] // const tasks = []; // for (let i = 0; i < topNews.length; i++) { // tasks.push( // await axiosGetApi({ // endPoint: `item/${topNews[i]}.json?print=pretty`, // headers: { // 'Content-Type': 'application/json', // }, // }) // .then((response: AxiosResponse) => { // if (response.status === 200) { // return response.data; // } else { // throw new Error('Error while processing newsDetailRequestApi'); // } // }) // .catch((err) => { // throw err; // }), // ); // } // return { // statusCode: 200, // data: parsingNewsResponseToNewsModel(tasks), // parsing (response => model) // }; // [ ========== Good waterfall ========== ] const tasks = []; for (let i = 0; i < topNews.length; i++) { tasks.push( axiosGetApi({ endPoint: `item/${topNews[i]}.json?print=pretty`, headers: { 'Content-Type': 'application/json', }, }) .then((response: AxiosResponse) => { if (response.status === 200) { return response.data; } else { throw new Error('Error while processing newsDetailRequestApi'); } }) .catch((err) => { throw err; }), ); } const tasksFulfilled = await Promise.all(tasks); return { statusCode: 200, data: parsingNewsResponseToNewsModel(tasksFulfilled), // parsing (response => model) }; } catch (err) { return { statusCode: 400, data: err as Error, }; } }; export const commentsRequestApi = async (kids: number[]): Promise<CustomApiResponse> => { // Only store top 10 commenter's name const kidsLength = kids.length > 10 ? 10 : kids.length; try { const tasks = []; for (let i = 0; i < kidsLength; i++) { tasks.push( axiosGetApi({ endPoint: `item/${kids[i]}.json?print=pretty`, headers: { 'Content-Type': 'application/json', }, }) .then((response: AxiosResponse) => { if (response.status === 200) { return response.data; } else { throw new Error('Error while processing commentsRequestApi'); } }) .catch((err) => { throw err; }), ); } const tasksFulfilled = await Promise.all(tasks); return { statusCode: 200, data: parsingCommentResponseToCommentModel(tasksFulfilled), // parsing (response => model) }; } catch (err) { return { statusCode: 400, data: err as Error, }; } };
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <%@ page trimDirectiveWhitespaces="true"%> <!doctype html> <html> <head> <%@ include file="/WEB-INF/inc/head.jsp"%> <!-- 공통 --> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/css/common.css"> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/css/btn.css"> <!-- read --> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/css/info/com.css" /> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/css/grid.css" /> <!-- sweetalert --> <!-- sweet alert --> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/plugins/sweetalert/sweetalert.css"> <script type="text/javascript" src="${pageContext.request.contextPath}/plugins/sweetalert/sweetalert.min.js"></script> <!-- read.js --> <!-- <script src="${pageContext.request.contextPath}/assets/js/info/list_read.js"></script> --> <!-- list_read.css --> <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/css/info/list_read.css"> </head> <body> <div class="container"> <%@ include file="/WEB-INF/inc/topbar.jsp"%> <br id="space"> <section> <h2 class="noti">${listName}</h2> <small id="small1">AS의 ${smallName1} 올라오는 게시판입니다.</small> <small id="small2"><span class="glyphicon glyphicon-home"></span> &gt; ${smallName2} &gt; ${listName} &gt; 글 작성</small> <hr> <!-- Table --> <input type="hidden" name="listcate" value="${listcate}"> <table class="table" id="com_table1"> <tr> <td colspan="2"><b>[${listName}] ${readListboard.listtitle}</b></td> <td id="noti_category" class="a"><b>${listName}</b></td> </tr> <tr> <td><b>${readListboard.id}</b></td> <td id="date22"><b>${readListboard.wdate}</b></td> <td class="a"><b>${readListboard.hit}</b></td> </tr> <c:if test="${fileList != null}"> <tr> <td colspan="3"><b>첨부파일</b> <c:forEach var="file" items="${fileList}"> <c:url var="downloadUrl" value="/download.do"> <c:param name="file" value="${file.file_dir}/${file.file_name}" /> <c:param name="origin" value="file.originName" /> </c:url> <a href="${downloadUrl}" class="btn btn-link btn-xs">${file.origin_name}</a> </c:forEach></td> </tr> <tr> <td colspan="3" height="500"><c:forEach var="file" items="${fileList}"> <c:if test="${fn:substringBefore(file.content_type, '/') == 'image'}"> <c:url var="downloadUrl" value="/download.do"> <c:param name="file" value="${file.file_dir}/${file.file_name}" /> </c:url> <p> <img src="${downloadUrl}" class="img-responsive" style="margin: auto" /> </p> </c:if> </c:forEach> ${readListboard.listcont}</td> </tr> </c:if> </table> <form id="comment_form" method="post" action="${pageContext.request.contextPath}/listboard/list_comment_insert.do"> <!-- 글 번호 상태 유지 --> <input type='hidden' name='listno' value='${readListboard.listno}' /> <!-- 작성자,비밀번호,이메일은 로그인하지 않은 경우만 입력한다. --> <c:choose> <c:when test="${loginInfo == null }"> <table class="table" id="com_table2"> <tr> <td colspan="2" id="com"><textarea name='content' id="content" disabled="disabled">로그인한 회원만 입력가능합니다.</textarea> </td> <td id="com"> <button type="submit" class="btn btn-primary" id="comm_ok" disabled="disabled">등&nbsp;&nbsp;록</button> </td> </tr> </table> </c:when> <c:otherwise> <table class="table" id="com_table2"> <tr> <td colspan="2" id="com"><textarea name='content' id="content"></textarea></td> <td id="com"> <button type="submit" class="btn btn-primary" id="comm_ok">등&nbsp;&nbsp;록</button> </td> </tr> </table> </c:otherwise> </c:choose> <!-- 내용입력, 저장버튼 --> </form> <div id="comcom"> <!-- 덧글 리스트 --> <ul class="media-list" id="comment_list"> </ul> </div> <div id="btn-sec"> <c:choose> <c:when test="${readListboard.mno == loginInfo.mno}"> <button class="btn btn-primary " id="ubtn" onclick="location.href='${pageContext.request.contextPath}/listboard/list_edit.do?listcate=${listcate}&listno=${readListboard.listno}'" style="margin-bottom: 20px;">수 정</button> <button class="btn btn-primary " id="cbtn" onclick="location.href='${pageContext.request.contextPath}/listboard/list_delete.do?listcate=${listcate}&listno=${readListboard.listno}'" style="margin-bottom: 20px;">삭 제</button> <button class="btn btn-info " id="lbtn" onclick="location.href='${pageContext.request.contextPath}/listboard/list_list.do?listcate=${listcate}'";> <span class="glyphicon glyphicon-list"> 목 록</span> </button> </c:when> <c:otherwise> <button class="btn btn-info " id="lbtn" onclick="location.href='${pageContext.request.contextPath}/listboard/list_list.do?listcate=${listcate}'";> <span class="glyphicon glyphicon-list"> 목 록</span> </button> </c:otherwise> </c:choose> </div> </section> <%@ include file="/WEB-INF/inc/footer.jsp"%> </div> <!-- 덧글 항목에 대한 템플릿 참조 --> <script id="tmpl_comment_item" type="text/x-handlebars-template"> <li class="media" style='border-top: 1px solid #ccc; padding-top: 15px' id="comment_{{id}}"> <div class="media-body" style='display: block;'> <h4 class="media-heading clearfix"> <!-- 작성자,작성일시 --> <div class='pull-left'> {{writerName}} <small> {{regDate}} </small> </div> <!-- 수정,삭제 버튼 --> <div class='pull-right'> <a href='${pageContext.request.contextPath}/listboard/list_comment_edit.do?comment_id={{id}}' data-toggle="modal" data-target="#comment_edit_modal" class='btn btn-info btn-xs'> <i class='glyphicon glyphicon-refresh'></i> </a> <a href='${pageContext.request.contextPath}/listboard/list_comment_delete.do?comment_id={{id}}' data-toggle="modal" data-target="#comment_delete_modal" class='btn btn-danger btn-xs'> <i class='glyphicon glyphicon-remove-circle'></i> </a> </div> </h4> <!-- 내용 --> <p>{{{content}}}</p> </div> </li> </script> <!-- 덧글 삭제시 사용될 Modal --> <div class="modal fade" id="comment_delete_modal"> <div class="modal-dialog modal-sm"> <div class="modal-content"> </div> </div> </div> <!-- 덧글 수정시 사용될 Modal --> <div class="modal fade" id="comment_edit_modal"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> </div> <script type="text/javascript"> $(function() { /** 페이지가 열리면서 동작하도록 이벤트 정의 없이 Ajax요청 */ $.get("${pageContext.request.contextPath}/listboard/list_comment_list.do", { listno: "${readListboard.listno}" }, function(json) { if (json.rt != "OK") { alert(json.rt); return false; } // 템플릿 HTML을 로드한다. var template = Handlebars.compile($("#tmpl_comment_item").html()); // JSON에 포함된 '&lt;br/&gt;'을 검색에서 <br/>로 변경함. // --> 정규표현식 /~~~/g는 문자열 전체의 의미. for (var i=0; i<json.item.length; i++) { json.item[i].content = json.item[i].content.replace(/&lt;br\/&gt;/g, "<br/>"); // 덧글 아이템 항목 하나를 템플릿과 결합한다. var html = template(json.item[i]); // 결합된 결과를 덧글 목록에 추가한다. $("#comment_list").append(html); } }); /** 덧글 작성 폼의 submit 이벤트 Ajax 구현 */ // <form>요소의 method, action속성과 <input>태그를 // Ajax요청으로 자동 구성한다. $("#comment_form").ajaxForm(function(json) { // json은 API에서 표시하는 전체 데이터 if (json.rt != "OK") { alert(json.rt); return false; } // 줄 바꿈에 대한 처리 // --> 정규표현식 /~~~/g는 문자열 전체의 의미. // --> JSON에 포함된 '&lt;br/&gt;'을 검색에서 <br/>로 변경함. json.item.content = json.item.content.replace( /&lt;br\/&gt;/g, "<br/>"); // 템플릿 HTML을 로드한다. var template = Handlebars.compile($( "#tmpl_comment_item").html()); // JSON에 포함된 작성 결과 데이터를 템플릿에 결합한다. var html = template(json.item); // 결합된 결과를 덧글 목록에 추가한다. $("#comment_list").append(html); // 폼 태그의 입력값을 초기화 하기 위해서 reset이벤트를 강제로 호출 $("#comment_form").trigger('reset'); }); /** 모든 모달창의 캐시 방지 처리 */ $('.modal').on('hidden.bs.modal', function (e) { // 모달창 내의 내용을 강제로 지움. $(this).removeData('bs.modal'); }); /** 동적으로 로드된 폼 안에서의 submit 이벤트 */ $(document).on('submit', "#comment_delete_form", function(e) { e.preventDefault(); // AjaxForm 플러그인의 강제 호출 $(this).ajaxSubmit(function(json) { if (json.rt != "OK") { alert(json.rt); return false; } alert("삭제되었습니다."); // modal 강제로 닫기 $("#comment_delete_modal").modal('hide'); // JSON 결과에 포함된 덧글일련번호를 사용하여 삭제할 <li>의 id값을 찾는다. var comment_id = json.commentId; $("#comment_" + comment_id).remove(); }); }); /** 동적으로 로드된 폼 안에서의 submit 이벤트 */ $(document).on('submit', "#comment_edit_form", function(e) { e.preventDefault(); // AjaxForm 플러그인의 강제 호출 $(this).ajaxSubmit(function(json) { if (json.rt != "OK") { alert(json.rt); return false; } // 줄 바꿈에 대한 처리 // --> 정규표현식 /~~~/g는 문자열 전체의 의미. // --> JSON에 포함된 '&lt;br/&gt;'을 검색에서 <br/>로 변경함. json.item.content = json.item.content.replace(/&lt;br\/&gt;/g, "<br/>"); // 템플릿 HTML을 로드한다. var template = Handlebars.compile($("#tmpl_comment_item").html()); // JSON에 포함된 작성 결과 데이터를 템플릿에 결합한다. var html = template(json.item); // 결합된 결과를 기존의 덧글 항목과 교체한다. $("#comment_" + json.item.id).replaceWith(html); // 덧글 수정 모달 강제로 닫기 $("#comment_edit_modal").modal('hide'); }); }); }); </script> </body> </html>
// main.dart import 'student.dart'; import 'teacher.dart'; void main() { // Create instances of Student and Teacher classes var student = Student("John Doe", 20, "123 Main St", 12345); student.courseScores = [90, 85, 82]; var teacher = Teacher("Mrs. Smith", 35, "456 Oak St", 67890); teacher.coursesTaught = ["Math", "English", "Bangle"]; // Display student information print("Student Information:"); student.displayRole(); print("Name: ${student.getName()}"); print("Age: ${student.getAge()}"); print("Address: ${student.getAddress()}"); print("Average Score: ${student.calculateAverageScore()}"); print("\n"); // Display teacher information print("Teacher Information:"); teacher.displayRole(); print("Name: ${teacher.getName()}"); print("Age: ${teacher.getAge()}"); print("Address: ${teacher.getAddress()}"); teacher.displayCoursesTaught(); }
import { filter, skipWhile, first, subscribeOn, observeOn, tap, map, take } from 'rxjs/operators'; import { animationFrameScheduler, asyncScheduler } from 'rxjs'; import { Router, NavigationEnd, NavigationStart } from '@angular/router'; /* eslint-disable @typescript-eslint/member-ordering */ import { Directive, ElementRef, Input, OnDestroy, OnInit, NgZone } from '@angular/core'; @Directive({ selector: '[appHero]' }) export class HeroDirective implements OnInit, OnDestroy { private static _heroMap = new Map<string, HeroDirective>(); private _appHeroDuration = 300; private _appHeroDelay = 0; @Input() appHero!: string; @Input() appHeroStyles?: { [key: string]: string | number }; @Input() public get appHeroDuration(): number { return this._appHeroDuration; } public set appHeroDuration(value: number | `${number}`) { this._appHeroDuration = typeof value === 'number' ? value : + value; } @Input() appHeroEaseing = 'linear'; @Input() public get appHeroDelay(): number { return this._appHeroDelay; } public set appHeroDelay(value: number | `${number}`) { this._appHeroDelay = typeof value === 'number' ? value : + value; } @Input() appHeroCssClass?: string; private _elementToHide: HTMLElement; private _destroyed = false; @Input() set elementToHide(element: HTMLElement | string) { if (typeof element === 'string') { if (!(typeof window === 'object' && typeof window.document === 'object')) { return; } const el = this._hostEl.nativeElement.closest(element); if (el instanceof HTMLElement) { this._elementToHide = el; } } else { this._elementToHide = element; } }; constructor(private _hostEl: ElementRef<HTMLElement>, private _router: Router, private _ngZone: NgZone) { this._elementToHide = _hostEl.nativeElement; if (!(typeof window === 'object' && typeof window.document === 'object')) { return; } if (!(_hostEl.nativeElement instanceof HTMLImageElement)) { throw new Error('[appHero] - appHero directive must by placed on image element'); } } ngOnInit(): void { if (HeroDirective._heroMap.has(this.appHero)) { throw new Error('[appHero] - duplicated id for appHero directive. This directive must have uniqe id per page'); } HeroDirective._heroMap.set(this.appHero, this); this._prepareTransition(); } ngOnDestroy(): void { HeroDirective._heroMap.delete(this.appHero); this._destroyed = true; } private _prepareTransition(): void { if (!(typeof window === 'object' && typeof window.document === 'object')) { return; } let sourceRect: DOMRect; this._ngZone.runOutsideAngular(() => { this._router.events.pipe( tap((ev) => { if (ev instanceof NavigationStart) { sourceRect = this._hostEl.nativeElement.getBoundingClientRect(); } }), filter((event) => event instanceof NavigationEnd), observeOn(animationFrameScheduler), skipWhile(() => !this._destroyed), take(1), subscribeOn(asyncScheduler) ).subscribe(() => { const targetHero = HeroDirective._heroMap.get(this.appHero); if (!targetHero) { return; } const targetEl = targetHero._hostEl.nativeElement; const sourceEl = this._hostEl.nativeElement; const targetElToHide = targetHero._elementToHide; const sourceElToHide = this._elementToHide; const tempEl = sourceEl.cloneNode() as HTMLElement; const targetRect = targetEl.getBoundingClientRect(); //Hiding targetElToHide.style.visibility = 'hidden'; sourceElToHide.style.visibility = 'hidden'; //InitialStyles if (this.appHeroStyles) { const heroStyles = this.appHeroStyles; Object.keys(heroStyles).forEach((key) => { if (key in tempEl.style) { tempEl.style[key as any] = typeof heroStyles[key] === 'string' ? heroStyles[key] as string : heroStyles[key].toString(); } }); } tempEl.style.position = 'absolute'; tempEl.style.width = `${Math.round(sourceEl.clientWidth)}px`; tempEl.style.height = `${Math.round(sourceEl.clientHeight)}px`; tempEl.style.top = `${Math.round(sourceRect.y + window.scrollY)}px`; tempEl.style.left = `${Math.round(sourceRect.x + window.scrollX)}px`; //prepering target styles let targetStyles: { [key: string]: string | number }; if (targetHero.appHeroStyles) { targetStyles = { ...targetHero.appHeroStyles, top: `${Math.round(targetRect.y + window.scrollY)}px`, left: `${Math.round(targetRect.x + window.scrollX)}px`, width: `${Math.round(targetEl.clientWidth)}px`, height: `${Math.round(targetEl.clientHeight)}px` }; } else { targetStyles = { top: `${Math.round(targetRect.y + window.scrollY)}px`, left: `${Math.round(targetRect.x + window.scrollX)}px`, width: `${Math.round(targetEl.clientWidth)}px`, height: `${Math.round(targetEl.clientHeight)}px` }; } //apply css class if (this.appHeroCssClass && this.appHeroCssClass.length > 1) { this.appHeroCssClass.split(' ').forEach((className) => { tempEl.classList.add(className); }); } //start animation document.body.appendChild(tempEl); const animation = tempEl.animate(targetStyles, { duration: this._appHeroDuration, easing: this.appHeroEaseing, delay: this._appHeroDelay }); animation.onfinish = () => { targetElToHide.style.visibility = ''; tempEl.remove(); }; animation.oncancel = () => { targetElToHide.style.visibility = ''; tempEl.remove(); }; }); }); } }
/*** * @Author OD79 * @Date 11/20/2014 * @Version 1.0 * @Version-comments : This is the initial version * @Description : This is responsible to create the import / export order item table which is a custom control. */ //Required libraries jQuery.sap.declare('mc.ccp.order.control.ImpExpOrderItemTable'); jQuery.sap.require("mc.ccp.control.McArrowTextField"); sap.ui.core.Control.extend('mc.ccp.order.control.ImpExpOrderItemTable', { metadata: { properties: { 'width': { type: 'sap.ui.core.CSSSize', group: 'Dimension', defaultValue: '100%' }, 'height': { type: 'sap.ui.core.CSSSize', group: 'Dimension', defaultValue: '210px' }, 'expand': { type: "boolean", defaultValue: false }, 'dirtyState': { type: "boolean", defaultValue: false }, 'readOnly': { type: "boolean", defaultValue: false }, 'forceRender': { type: "boolean", defaultValue: false }, 'readOnlyRole': { type: "boolean", defaultValue: false } }, aggregations: { skuLink: { type: "sap.ui.commons.Link", multiple: false, visibility: "public" }, orderedQuantity: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, expandCollapseImage: { type: "sap.ui.commons.Image", multiple: false, visibility: "public" }, //Aggregating forecast quantity from week 3 onwards, since forecast quantity for current week (week2) & current week -1 (week 1) are non editable. forecastQuantityWeek3: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek4: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek5: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek6: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek7: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek8: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek9: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek10: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek11: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek12: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, forecastQuantityWeek13: { type: "mc.ccp.control.McArrowTextField", multiple: false, visibility: "public" }, }, events: { 'change': {}, 'expand': {}, 'collapse': {}, 'press': {} } }, /** * Called when an ImpExpOrderItemTable control is instantiated. * It will bind the various oModel aggregation to this custom control. */ init: function() { //setting Aggregation for Ordered Quantity. var oOrderedQuantity = new mc.ccp.control.McArrowTextField(); //oOrderedQuantity.bindProperty("value", "ZCCP_ORD_CR_HEAD_ITM_NAV/results/12/OrderedQty"); oOrderedQuantity.bindProperty("pallet", "PalletValue"); oOrderedQuantity.bindProperty("readOnly", "readOnly"); this.setAggregation('orderedQuantity', oOrderedQuantity); oOrderedQuantity.getAggregation("textField").setMaxLength(16); //setting Aggregation for forecast Quantity from week 3 to week 13. var noOfWeeks = 13; for (var i = 2; i <= noOfWeeks - 1; i++) { //looping from week3 onwards since forecast quantity for current week (week2) & current week -1 (week 1) are non editable. var sForecastQuantityWeek = "forecastQuantityWeek" + (i + 1); var oForecastQuantity = new mc.ccp.control.McArrowTextField({ arrows: false }).bindProperty("value", "ZCCP_ORD_CR_HEAD_ITM_NAV/results/" + i + "/DistForecast"); //oForecastQuantity.bindProperty("readOnly", "readOnly"); oForecastQuantity.bindProperty("readOnly", "readOnlyRole"); this.setAggregation(sForecastQuantityWeek, oForecastQuantity); oForecastQuantity.getAggregation("textField").setMaxLength(16); } //setting Aggregation for SKU Link. var oSkuLink = new sap.ui.commons.Link({ arrows: false }).bindProperty("text", "SKU"); this.setAggregation('skuLink', oSkuLink); //setting Aggregation for ExpandCollapse Image in the header of each data row. var oExpandCollapseImage = new sap.ui.commons.Image({ src: 'image/expand.png' }); this.setAggregation('expandCollapseImage', oExpandCollapseImage); }, /*** * Is called before rendering the ImpExpOrderItemTable Control. * This method is used to detach the change and press events on the links and other controls of ImpExpOrderItemTable. */ onBeforeRendering: function() { //detaching change event for ordered quantity this.getAggregation('orderedQuantity').detachChange(this.handleChangeOrderQuantity, this); //detaching change event for forecast quantity from week3 onwards, since forecast quantity for current week (week2) & current week -1 (week 1) are non editable. var noOfWeeks = 13; for (var i = 2; i <= noOfWeeks - 1; i++) { this.getAggregation('forecastQuantityWeek' + (i + 1)).detachChange(this.handleChangeForecastQuantity, this); } //detaching press event for SKU Link this.getAggregation('skuLink').detachPress(this.handlePressSkuLink, this); //detaching press event for Expand Collapse Image this.getAggregation('expandCollapseImage').detachPress(this.handlePressExpandCollapse, this); }, /*** * Is called after rendering the ImpExpOrderItemTable Control. * This method is used to attach the change and press events on the links and other controls of ImpExpOrderItemTable. */ onAfterRendering: function() { //attaching change event for ordered quantity this.getAggregation('orderedQuantity').attachChange(this.handleChangeOrderQuantity, this); //attaching change event for forecast quantity from week3 onwards, since forecast quantity for current week (week2) & current week -1 (week 1) are non editable. var noOfWeeks = 13; for (var i = 2; i <= noOfWeeks - 1; i++) { this.getAggregation('forecastQuantityWeek' + (i + 1)).attachChange(this.handleChangeForecastQuantity, this); } //attaching press event for SKU Link this.getAggregation('skuLink').attachPress(this.handlePressSkuLink, this); //attaching press event for Expand Collapse Image this.getAggregation('expandCollapseImage').attachPress(this.handlePressExpandCollapse, this); if (this.getExpand()) { this.expand(); } else { this.collapse(); } }, /*** * Is called to render the Order Item Table control. * @param oRm * @param oControl */ renderer: function(oRm, oControl) { oRm.write("<div "); oRm.writeControlData(oControl); oRm.addStyle("width", oControl.getWidth()); oRm.writeStyles(); oRm.writeClasses(); oRm.write(">"); oRm.write("<table class='McCcpOrderItemTbl'>"); oRm.write("<tr class='McCcpOrderItemTblSpaceTr'><td colspan='10'></td></tr>"); //to render the header for each data set oControl._renderHeaderRow(oRm, oControl); //looped 5 times to render the Suggested, Ordered, Confirmed, Projected DOI, Target DOI rows for each record. var noOfRows = 5; for (var i = 1; i <= noOfRows; i++) { oControl._renderDataRows(oRm, oControl, i); } //to render the forecast row for each data set oControl._renderForecastRow(oRm, oControl); oRm.write("</table>"); oRm.write("</div>"); }, /*** * Is called to render the Header Row. Called with in renderer method. * @param oRm * @param oControl */ _renderHeaderRow: function(oRm, oControl) { oRm.write("<tr class='McCcpOrderItemTblHdrTr'>"); //creating image column. oRm.write("<td>"); oRm.renderControl(oControl.getAggregation('expandCollapseImage')); oRm.write("</td>"); //creating Dist SKU column. oRm.write("<td title ='"+ oControl.getModel().getProperty(oControl.getBindingContext().getPath()).Dist_SKU +"'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath()).Dist_SKU + "</td>"); //creating SKU column. oRm.write("<td>"); oRm.renderControl(oControl.getAggregation('skuLink')); oRm.write("</td>"); //creating Description column. oRm.write("<td title ='"+ oControl.getModel().getProperty(oControl.getBindingContext().getPath()).SKU_Desc +"' colspan=7>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath()).SKU_Desc + "</td>"); //creating Ship To column. oRm.write("<td title ='"+ oControl.getModel().getProperty(oControl.getBindingContext().getPath()).ShipToId +"'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath()).ShipToId + "</td>"); //creating Source column. oRm.write("<td title ='"+ oControl.getModel().getProperty(oControl.getBindingContext().getPath()).SourceId +"'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath()).SourceId + "</td>"); //creating Est Transit Days column. oRm.write("<td>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath()).EstdTransitDays + "</td>"); oRm.write("<td> </td>"); oRm.write("</tr>"); }, /*** * Is called to render the Forecast Row . Called with in renderer method. * @param oRm * @param oControl */ _renderForecastRow: function(oRm, oControl) { var sJsonProperty = 'DistForecast'; oRm.write("<tr id=" + (oControl.sId + '-forecast') + " class='McCcpImportOrderItemTblFrctTr'>"); //oRm.write("<tr id=" + (oControl.sId + '-forecast') + " >"); //creating DistForecast column. oRm.write("<td class='McCcpImportOrderItemTblLblCol'>" + this.getModel('i18n').getProperty('GBL_DIST_FORECAST') + "</td>"); //creating DistForecast week1 column. oRm.write("<td class='McCcpImportOrderItemTblDataCol'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/0/' + sJsonProperty) + "</td>"); //creating DistForecast week2 column. oRm.write("<td class='McCcpImportOrderItemTblDataCol'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/1/' + sJsonProperty) + "</td>"); //creating DistForecast week3 to week9 column(s). var noOfWeeks = 13; for (var i = 2; i <= noOfWeeks - 1; i++) { oRm.write("<td width='6.5%' height='30px' class = 'McCcpImportOrderItemTblStdHght'>"); oRm.renderControl(oControl.getAggregation('forecastQuantityWeek' + (i + 1))); oRm.write("</td>"); } oRm.write("</tr>"); }, /*** * Is called to render the rows. Called with in renderer method. * This will create the Suggested, Ordered, Confirmed, Projected DOI and Target DOI rows as per the case. * @param oRm * @param oControl */ _renderDataRows: function(oRm, oControl, index) { var sJsonProperty = ''; var sRowLabel = ''; var projectedDOIvalue; var targetDOIvalue; switch (index) { case 1: sJsonProperty = "SuggQty"; sRowLabel = this.getModel('i18n').getProperty('GBL_SUGGESTED'); break; case 2: sJsonProperty = "OrderedQty"; sRowLabel = this.getModel('i18n').getProperty('GBL_ORDERED'); break; case 3: sJsonProperty = "ConfirmQty"; sRowLabel = this.getModel('i18n').getProperty('GBL_CONFIRMED'); break; case 4: sJsonProperty = "ProjDOI"; sRowLabel = this.getModel('i18n').getProperty('GBL_PROJECTED_DOI'); break; case 5: sJsonProperty = "TargDOI"; sRowLabel = this.getModel('i18n').getProperty('GBL_TARGET_DOI'); break; } oRm.write("<tr id=" + (oControl.sId + sJsonProperty) + " class='McCcpImportOrderItemTblTr McCcpImportOrderItemTblStdHght'>"); oRm.write("<td class='McCcpImportOrderItemTblLblCol'>" + sRowLabel + "</td>"); var noOfWeeks = 13; for (var i = 0; i <= noOfWeeks - 1; i++) { var headerLevelWeekNo = oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/Week_No'); var itemLevelWeekNo = oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/Week_No'); if (index == 2) { if (oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/BlockPrdFlag') == 'X') { if (headerLevelWeekNo == itemLevelWeekNo) { oControl.getAggregation('orderedQuantity').setReadOnly(true); oRm.write("<td class='McCcpImportOrderItemTblDataCol McCcpImportOrderItemTblStdHght McCcpControlArrowTextFieldColor'>"); oControl.getAggregation('orderedQuantity').bindProperty("value", "ZCCP_ORD_CR_HEAD_ITM_NAV/results/" + i + "/OrderedQty"); oRm.renderControl(oControl.getAggregation('orderedQuantity')); oRm.write("</td>"); } else { oRm.write("<td class='McCcpImportOrderItemTblDataCol McCcpOrderItemTblCellProdBlock'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } } else { if (headerLevelWeekNo == itemLevelWeekNo) { oRm.write("<td class='McCcpImportOrderItemTblDataCol McCcpImportOrderItemTblStdHght McCcpImportOrderItemTblDataColColor' >"); oControl.getAggregation('orderedQuantity').bindProperty("value", "ZCCP_ORD_CR_HEAD_ITM_NAV/results/" + i + "/OrderedQty"); oRm.renderControl(oControl.getAggregation('orderedQuantity')); oRm.write("</td>"); } else { oRm.write("<td class='McCcpImportOrderItemTblDataCol'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } } } else { if (headerLevelWeekNo == itemLevelWeekNo) { if (index == 4) { projectedDOIvalue = oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty); targetDOIvalue = oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/TargDOI'); if (Math.abs(projectedDOIvalue - targetDOIvalue) > 5) { oRm.write("<td class='McCcpImportOrderItemTblDataColColor McCcpImportItemTableTextRed'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } else { oRm.write("<td class='McCcpImportOrderItemTblDataColColor'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } } else { oRm.write("<td class='McCcpImportOrderItemTblDataColColor'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } } else { if (index == 4) { projectedDOIvalue = oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty); targetDOIvalue = oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/TargDOI'); if (Math.abs(projectedDOIvalue - targetDOIvalue) > 5) { oRm.write("<td class='McCcpImportOrderItemTblDataCol McCcpImportItemTableTextRed'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } else { oRm.write("<td class='McCcpImportOrderItemTblDataCol'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } } else { oRm.write("<td class='McCcpImportOrderItemTblDataCol'>" + oControl.getModel().getProperty(oControl.getBindingContext().getPath() + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + i + '/' + sJsonProperty) + "</td>"); } } } } oRm.write("</tr>"); }, doRender : function(){ if(this.getForceRender() === true){ this.setForceRender(false); }else{ this.setForceRender(true); } } }); /*** * Is called on change of Order quantity. Setting the dirty state of changed record to true. * Also calculation of projected DOI would be done as per the new quantity entered by the user. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.handleChangeOrderQuantity = function(oEvent) { var editableWeek = this.getModel().getProperty(oEvent.getSource().getBindingContext().sPath + '/editableWeek'); var oChangedData = oEvent.getParameter('changed'); var oOriginalData; var oBackUpModel = this.getModel('backup') || this.getParent().getParent().getParent().getModel('backup'); oOriginalData = oBackUpModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + (editableWeek - 1) + '/OrderedQty'); this.setDirtyState(this._isDirty(editableWeek)); this.fireChange({ source: 'OrderQty', changedData: oChangedData, originalData: oOriginalData, dirtyState: this.getDirtyState() }); this._calculateProjectedDOI(); //this.rerender(); this.doRender(); }; /*** * Is called on press of SKU Link. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.handlePressSkuLink = function(oEvent) { this.firePress({ sku: oEvent.getSource().getProperty('text') }); }; /*** * Is called on change of forecast quantity. Setting the dirty state of changed record to true. * Also calculation of projected DOI would be done as per the quantity entered by the user. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.handleChangeForecastQuantity = function(oEvent) { var editableWeek = this.getModel().getProperty(oEvent.getSource().getBindingContext().sPath + '/editableWeek'); //Identify the Source control(which Forecast object) into Source var sSource = ''; for (var key in this.mAggregations) { if (this.mAggregations.hasOwnProperty(key)) { if (oEvent.getSource().sId == this.mAggregations[key].sId) { sSource = key; break; } } } var sRelativeContextPath = ''; switch (sSource) { case 'forecastQuantityWeek3': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/2/DistForecast"; break; case 'forecastQuantityWeek4': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/3/DistForecast"; break; case 'forecastQuantityWeek5': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/4/DistForecast"; break; case 'forecastQuantityWeek6': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/5/DistForecast"; break; case 'forecastQuantityWeek7': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/6/DistForecast"; break; case 'forecastQuantityWeek8': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/7/DistForecast"; break; case 'forecastQuantityWeek9': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/8/DistForecast"; break; case 'forecastQuantityWeek10': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/9/DistForecast"; break; case 'forecastQuantityWeek11': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/10/DistForecast"; break; case 'forecastQuantityWeek12': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/11/DistForecast"; break; case 'forecastQuantityWeek13': sRelativeContextPath = "/ZCCP_ORD_CR_HEAD_ITM_NAV/results/12/DistForecast"; break; } var oChangedData = oEvent.getParameter('changed'); var oOriginalData; var oBackUpModel = this.getModel('backup'); if (oBackUpModel) { oOriginalData = oBackUpModel.getProperty(this.getBindingContext().sPath + sRelativeContextPath); } else { oOriginalData = this.getParent().getParent().getParent().getModel('backup').getProperty(this.getBindingContext().sPath + sRelativeContextPath); } this.setDirtyState(this._isDirty(editableWeek)); this.fireChange({ source: sSource, changedData: oChangedData, originalData: oOriginalData, dirtyState: this.getDirtyState() }); this._calculateProjectedDOI(); //this.rerender(); this.doRender(); }; /*** * returns the dirty state of the record. */ mc.ccp.order.control.ImpExpOrderItemTable.prototype._isDirty = function(editableWeek) { editableWeek = editableWeek - 1; var oChangedModel = this.getModel(); var oOriginalModel = this.getModel('backup'); if (!oOriginalModel) { oOriginalModel = this.getParent().getParent().getParent().getModel('backup'); } if (oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + editableWeek + '/OrderedQty') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + editableWeek + '/OrderedQty') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/2/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/2/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/3/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/3/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/4/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/4/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/5/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/5/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/6/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/6/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/7/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/7/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/8/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/8/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/9/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/9/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/10/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/10/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/11/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/11/DistForecast') && oOriginalModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/12/DistForecast') == oChangedModel.getProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/12/DistForecast')) { return false; } else { return true; } }; /*** * Is called to set the expand collapse image on click of the expand/Collapse img link. * If user clicks on expand, forecast row would be displayed else its display would be hidden. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.handlePressExpandCollapse = function(oEvent) { if (this.getExpand()) { jQuery.sap.byId(this.getId()).find('tr#' + this.getId() + '-forecast').hide(); this.setExpand(false); this.getAggregation('expandCollapseImage').setSrc('image/expand.png'); this.fireCollapse(); } else { jQuery.sap.byId(this.getId()).find('tr#' + this.getId() + '-forecast').show(); this.setExpand(true); this.getAggregation('expandCollapseImage').setSrc('image/collapse.png'); this.fireExpand(); } }; /*** * Is a method to change the collapse image to expand image. Also it will display the forecast row. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.expand = function(oEvent) { jQuery.sap.byId(this.getId()).find('tr#' + this.getId() + '-forecast').show(); this.getAggregation('expandCollapseImage').setSrc('image/collapse.png'); this.setExpand(true); }; /*** * Is a method to change the expand image to collapse image. Also it will hide the forecast row from ImpExpOrderItemTable. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.collapse = function(oEvent) { jQuery.sap.byId(this.getId()).find('tr#' + this.getId() + '-forecast').hide(); this.getAggregation('expandCollapseImage').setSrc('image/expand.png'); this.setExpand(false); }; /*** * Is called implicitly by the framework to clean up the resource. * @param oEvent */ mc.ccp.order.control.ImpExpOrderItemTable.prototype.exit = function(oEvent) { //detaching attached non-default event handler //detaching change event for ordered quantity this.getAggregation('orderedQuantity').detachChange(this.handleChangeOrderQuantity, this); //detaching change event for forecast quantity from week3 onwards, since forecast quantity for current week (week2) & current week -1 (week 1) are non editable. var noOfWeeks = 13; for (var i = 2; i <= noOfWeeks - 1; i++) { this.getAggregation('forecastQuantityWeek' + (i + 1)).detachChange(this.handleChangeForecastQuantity, this); } //detaching press event for SKU Link this.getAggregation('skuLink').detachPress(this.handlePressSkuLink, this); //detaching press event for Expand Collapse Image this.getAggregation('expandCollapseImage').detachPress(this.handlePressExpandCollapse, this); }; /*** * Is called to calculate the projected DOI. */ mc.ccp.order.control.ImpExpOrderItemTable.prototype._calculateProjectedDOI = function() { // step 1: getting the row object which has been tapped on Order Create Screen var oCurrentRow = this.getModel().getProperty(this.getBindingContext().sPath); // step 2: creating on the fly object var oData = {"results" : []}; var numberOfWeeks = oCurrentRow.ZCCP_ORD_CR_HEAD_ITM_NAV.results.length; for(var i=0; i<numberOfWeeks; i++){ var oCurrentRowItem = oCurrentRow.ZCCP_ORD_CR_HEAD_ITM_NAV.results[i]; var beginningInv = 0; if(i === 0){ beginningInv = parseInt(oCurrentRow.BegINV); } oData.results.push({ beginningInventory :beginningInv, endingInventory : 0, projectedDOI : parseInt(oCurrentRowItem.ProjDOI), forecastQuantity : parseInt(oCurrentRowItem.DistForecast), arrivedQuantity : parseInt(oCurrentRowItem.ArrivedQty), intransitShipments : parseInt(oCurrentRowItem.TransitQty), plannedShipments : parseInt(oCurrentRowItem.PlannedQty), crQuantity : 0, currentOrderQuantity : 0, orderedQuantity : parseInt(oCurrentRowItem.OrderedQty), suggestedQuantity : parseInt(oCurrentRowItem.SuggQty), confirmedQuantity : parseInt(oCurrentRowItem.ConfirmQty), insOuts : 0 }); } // step 3: creating on the fly model var oOnTheFlyModel = new sap.ui.model.json.JSONModel(); oOnTheFlyModel.setData(oData); oOnTheFlyModel = MCAPP.projectedDOI(oOnTheFlyModel, numberOfWeeks); for (var k = 0; k < oOnTheFlyModel.getData().results.length; k++) { this.getModel().setProperty(this.getBindingContext().sPath + '/ZCCP_ORD_CR_HEAD_ITM_NAV/results/' + k + '/ProjDOI', oOnTheFlyModel.getProperty('/results/' + k + '/projectedDOI')); } };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Owen's Portfolio</title> <link rel="stylesheet" href="styles.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Space+Mono&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.2.1/css/fontawesome.min.css" integrity="sha384-QYIZto+st3yW+o8+5OHfT6S482Zsvz2WfOzpFSXMF9zqeLcFV0/wlZpMtyFcZALm" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"> <script src="https://kit.fontawesome.com/66ee73a1f5.js" crossorigin="anonymous"></script> <script src="script.js" defer></script> </head> <body> <header> <div class="tab"> <a href="index.html" id="logo"> <h1 id="tab-text"><span class="logo-brace">#</span>&nbsp;owenl.css</h1> </a> </div> <div class="vscode-controls"> <button class="icon-btn run-btn"><i class="fas fa-play"></i></button> <button class="icon-btn open-changes-btn"><i class="fas fa-code-branch"></i></button> <button class="icon-btn split-editor-btn"><i class="fas fa-columns"></i></button> <button class="icon-btn ellipsis-btn"><i class="fas fa-ellipsis-h"></i></button> </div> <div class="terminal-popup"> <div class="terminal-header"> <h4>TERMINAL</h4> <button class="terminal-close-btn">X</button> </div> <div class="terminal-content"> <p>C:\Website\Portfolio\owenl0000.github.io> Thanks for visiting!</p> </div> </div> </header> <div class="sub-header"> <span class="logo-brace">#</span> <span class="logo-text">owenl.css&nbsp;&nbsp;></span> <div class="dropdown"> <span class="dropbtn"> <i class="fa-solid fa-diagram-project"></i> <span class="current-section section-name">#welcome</span> </span> <div class="dropdown-content"> <a href="#welcome"><i class="fa-solid fa-diagram-project"></i> #welcome</a> <a href="#projects"><i class="fa-solid fa-diagram-project"></i> #projects</a> <a href="#skills"><i class="fa-solid fa-diagram-project"></i> #skills</a> <a href="#experience"><i class="fa-solid fa-diagram-project"></i> #experience</a> <a href="#contact"><i class="fa-solid fa-diagram-project"></i> #contact</a> </div> </div> </div> <div id="content-wrap"> <main id="main-content"> <section id="welcome"> <div class="css-format"> <h2 class="selector">#welcome</h2><span class="brace">&nbsp;{</span> <div class="properties"> <div class="property name-title">Name: <span class="value">Owen Liang</span>;</div> <div class="property student-title">Student: <span class="value">Computer Science</span>;</div> <div class="property about-me">Introduction: <span class="value"> Hey there! I am an undergrad student pursuing a bachelor's degree in Computer Science at Brooklyn College. I'm passionate about web development and software engineering. </span> </div> <div class="property comment">/* <span class="comment">I also enjoy playing the piano and learning a new language on my free time.</span>*/</div> </div> <span class="brace">}</span> </div> </section> <section id="projects" class="css-format"> <h2 class="selector">#projects</h2> <span class="brace">&nbsp;{</span> <div class="project-container"> <article class="project-box"> <a href="https://owenl0000.itch.io/procrastination" class="project-link" target="_blank"> <img src="Images/ProcrastinationGame.png" alt="Project Image 1" class="project-image"> </a> <h3>Procrastination: The Game</h3> <p>Game Design Group Project</p> <a href="https://github.com/9Mohamedismail/Procrastination-The-Game" class="github-link" target="_blank"><img src="Images/github-mark.png" alt="Github"></a> </article> <article class="project-box"> <a href="https://owenl0000.itch.io/blue-balloons" class="project-link" target="_blank"> <img src="Images/BlueBalloons.png" alt="Project Image 2" class="project-image"> </a> <h3>Blue Balloons</h3> <p>Game Design Project</p> <a href="https://github.com/owenl0000/CISC-3667-Lab-Game" class="github-link" target="_blank"><img src="Images/github-mark.png" alt="Github"></a> </article> <article class="project-box"> <a href="https://docs.google.com/spreadsheets/d/14Ax4QESKmpQlXzUP6imH_HkpntPouLxZiJi3DOe_zDs/edit?usp=sharing" class="project-link" target="_blank"> <img src="Images/Webscrape.png" alt="Project Image 3" class="project-image"> </a> <h3>Webscraping Project on Google Sheets</h3> <p>Design & Web Implementation Project</p> <a href="https://docs.google.com/document/d/1FOMAd9zbCAOD9Q0mJW5NaNyflD6YnsmA6L7lXBXHEeo/edit?usp=sharing" class="doc-link" target="_blank"> <img src="Images/docs.png" alt="Documentation" class="project-image"> </a> </article> <article class="project-box"> <a href="https://devpost.com/software/cartoonify-w2e8n3" class="project-link" target="_blank"> <img src="Images/CartoonifyImg.png" alt="Project Image 3" class="project-image"> </a> <h3>Cartoonify</h3> <p>CTP Hackathon Project</p> <a href="https://github.com/owenl0000/Cartoonify-Website" class="github-link" target="_blank"> <img src="Images/github-mark.png" alt="Documentation" class="project-image"> </a> </article> <article class="project-box"> <a href="https://kaja-app.vercel.app/" class="project-link" target="_blank"> <img src="Images/underconstruction.jpg" alt="Project Image 3" class="project-image"> </a> <h3>Kaja: Trip Planning Web App</h3> <p>CTP Group Project</p> <a href="https://github.com/owenl0000/kaja-app" class="github-link" target="_blank"> <img src="Images/github-mark.png" alt="Documentation" class="project-image"> </a> </article> <article class="project-box"> <a href="" class="project-link" target="_blank"> <img src="Images/underconstruction.jpg" alt="Project Image 3" class="project-image"> </a> <h3>Currently In Development</h3> <p>C++ Project</p> <a href="" class="github-link" target="_blank"> <img src="Images/github-mark.png" alt="Documentation" class="project-image"> </a> </article> </div> <span class="brace">}</span> </section> <section id="skills" class="css-format"> <h2 class="selector">#skills</h2> <span class="brace">&nbsp;{</span> <div class="skills-container"> <div class="skill-column"> <div class="skill html"> <img src="https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/file_type_html.svg" alt="HTML Icon" class="skill-icon"> <p class="skill-name" style="color: #e34f26;">HTML</p> <div class="progress html"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> </div> </div> <div class="skill css"> <img src="https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/file_type_css.svg" alt="CSS Icon" class="skill-icon"> <p class="skill-name" style="color: #1572b6;">CSS</p> <div class="progress css"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> </div> </div> <div class="skill javascript"> <img src="https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/file_type_js.svg" alt="JS Icon" class="skill-icon"> <p class="skill-name" style="color: #f7df1e;">JavaScript</p> <div class="progress javascript"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point"></div> </div> </div> </div> <div class="skill-column"> <div class="skill angular"> <img src="https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/file_type_angular.svg" alt="Angular Icon" class="skill-icon"> <p class="skill-name" style="color:#b52e31 ;">Angular</p> <div class="progress angular"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point"></div> <div class="point"></div> </div> </div> <div class="skill node"> <img src="https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/file_type_node.svg" alt="Node Icon" class="skill-icon"> <p class="skill-name" style="color: #8cc84b;">Node</p> <div class="progress node"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point"></div> </div> </div> <div class="skill react"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/react/react-original.svg" alt="React Icon" class="skill-icon"> <p class="skill-name" style="color: #61DAFB;">React</p> <div class="progress react"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point"></div> <div class="point"></div> </div> </div> </div> <div class="skill-column"> <!-- Java Skill --> <div class="skill java"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/java/java-original.svg" alt="Java Icon" class="skill-icon"> <p class="skill-name" style="color: #007396;">Java</p> <div class="progress java"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> </div> </div> <!-- C++ Skill --> <div class="skill cpp"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/cplusplus/cplusplus-original.svg" alt="C++ Icon" class="skill-icon"> <p class="skill-name" style="color: #F34B7D;">C++</p> <div class="progress cpp"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point"></div> <div class="point"></div> </div> </div> <!-- NextJS Skill --> <div class="skill nextjs"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/nextjs/nextjs-original.svg" alt="NextJS Icon" class="skill-icon"> <p class="skill-name" style="color: #000000;">NextJS</p> <div class="progress nextjs"> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point filled"></div> <div class="point"></div> </div> </div> </div> </div> <span class="brace">}</span> </section> <section id="experience" class="css-format"> <h2 class="selector">#experience</h2> <span class="brace">&nbsp;{</span> <div id="experience-box"> <h3>Web Development Fellow @ CUNY Tech Prep</h3> <p>June 2023 - Present</p> <a href="https://cunytechprep.org/about/program/" class="experience-link" target="_blank"> <img src="Images/CTP logo.png" alt="CTP logo" class="experience-pic"> </a> </div> <span class="brace">}</span> </section> <section id="contact" class="css-format"> <h2 class="selector">#contact</h2> <span class="brace">&nbsp;{</span> <div id="social-buttons"> <a href="mailto:owenliang3139@gmail.com" class="btn gmail"> <i class="fas fa-envelope"></i> <div class="btn-text"> <span>Email</span> <small>owenliang3139@gmail.com</small> </div> </a> <a href="https://github.com/owenl0000" target="_blank" class="btn github"> <i class="fab fa-github"></i> <div class="btn-text"> <span>GitHub</span> <small>github.com/owenl0000</small> </div> </a> <a href="https://linkedin.com/in/owenl0000" target="_blank" class="btn linkedin"> <i class="fab fa-linkedin"></i> <div class="btn-text"> <span>LinkedIn</span> <small>linkedin.com/in/owenl0000</small> </div> </a> </div> <span class="brace">}</span> </section> </main> <footer> <p>&copy; 2023 by Owen Liang. All rights reserved. Inspired by VSCode One Dark Pro</p> </footer> </div> </body> </html>
# plot decomposing variance explained in 26 traits alltraits=read.table("../data/vgprop_multi", header = F) colnames(alltraits)=c("vg1p", "vg2p", "vg3p", "vg4p", "vg", "nloci", "trait") # update trait name alltraits$trait=c("SkinPigmentation","Height","BMI","BirthWeight","SBP","DBP","PP","HDL","LDL","TG","TC","RBC","HGB","HCT","MCH","MCV","MCHC","RDW","WBC","NEU","LYM","MON","BAS","EOS","PLT","MPV") # reformat data for plot # Load the package library(tidyr) library(dplyr) # transform the format, get the order straight data_long <- gather(alltraits, Term, Percentage, vg1p:vg4p) %>% arrange(factor(trait, levels = c("SkinPigmentation","Height","BMI","BirthWeight","SBP","DBP","PP","HDL","LDL","TG","TC","RBC","HGB","HCT","MCH","MCV","MCHC","RDW","WBC","NEU","LYM","MON","BAS","EOS","PLT","MPV"))) %>% mutate(trait=factor(trait, levels=unique(trait))) # add group data_long$group=c(rep("Anthropometric", 4*4), rep("Blood Pressure", 3*4), rep("Lipids", 4*4), rep("Blood Cell", 15*4)) # change color # add nloci and vg info library(ggplot2) library(hrbrthemes) library(viridis) # update variance explained percent format pct_format = scales::percent_format(accuracy = .1) plt=ggplot(data_long, aes(fill=Term, y=Percentage, x=trait)) + geom_bar(position="stack", stat="identity") + theme_classic()+ ylab("Proportion of variance explained") + xlab("Trait") + scale_y_continuous(limits = c(-0.1, 1.1), breaks = seq(0, 1, .25)) + geom_hline(yintercept = 0, linetype = "dashed", color = "black") + geom_hline(yintercept = 1, linetype = "dashed", color = "black") + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) + geom_text( aes(label = sprintf( '%d \n %s', nloci, pct_format(vg))), y=-0.08, #angle = 50, colour = 'black', size = 2.5)+ facet_grid(~ factor(group, levels=c("Anthropometric", "Blood Pressure", "Lipids", "Blood Cell")), scales = "free_x", space = "free_x", switch = "x") + theme(panel.spacing = unit(0, units = "cm"), # removes space between panels #strip.placement = "outside", # moves the states down strip.text.x = element_text(size = 8), strip.background = element_rect(fill = NA) ) +# removes the background from the names guides(fill=guide_legend(title="Variance\nComponent")) + scale_fill_viridis(discrete=TRUE, labels=c('(1.1)', '(1.2)', '(1.3)', '(1.4)')) ggsave("../figs/traits_vgprop_multi.png", plot=plt, width = 10, height = 5.5, dpi = 300, units = "in", device='png')
"use client"; import { useEffect, useState } from "react"; import "./style.css"; import { useSpeechSynthesis } from "react-speech-kit"; import { MdAudiotrack } from "react-icons/md"; import { FaHeadset } from "react-icons/fa6"; import { HiOutlineSpeakerWave } from "react-icons/hi2"; import Link from "next/link"; import Navbar from "../Navbar/Navbar"; function Page() { /* ---------- Load All English Words ------------ */ const [commonWords, setCommonWords] = useState([]); useEffect(() => { fetch("https://wordbook-ten.vercel.app/words") .then((res) => res.json()) .then((data) => setCommonWords(data)); }, []); console.log(commonWords.map((word) => word.data.newRowData)); /* -------For Input Field Value------------- */ const [inputValue, setInputValue] = useState(""); const { speak } = useSpeechSynthesis(); const handleInputFieldClick = () => { speak({ text: inputValue }); }; /* -------For English Words form Table Row ------------- */ const handleWorldClick = (event) => { const word = event.target.textContent; speak({ text: word }); }; return ( <div className="max-w-[1800px] mx-auto "> <Navbar /> <div className=" w-full lg:w-10/12 mx-auto lg:mt-20 lg:py-20 text-center"> <div className="my-10"> <h1 className="text-center text-lg md:text-2xl lg:text-3xl font-semibold text-gray-700"> {commonWords.length} Most Common English Words </h1> <div className="overflow-x-auto w-11/12 lg:w-9/12 xl:w-7/12 mx-auto mt-3 md:mt-5 lg:mt-10 mb-20 rounded-md shadow-lg"> <table className="table text-[13px] md:text-[16px]"> {/*---------- head ------------ */} <thead className="text-lg text-white font-semibold"> <tr className="w-full text-[15px] md:text-[16px]"> {/* <th className="bg-blue-400 w-3/12">Rank</th> */} <th className="bg-purple-400 w-4/12" title="Word With Audio"> {" "} <span>English</span>{" "} <HiOutlineSpeakerWave className="inline text-xl md:text-2xl font-bold -mt-1" /> </th> <th className="bg-orange-400 w-5/12">Bengali Meaning</th> </tr> </thead> <tbody> {commonWords && commonWords.map((word) => { return ( <tr key={word?._id}> {/* <th className="bg-blue-100 ">{word?.rank}</th> */} <td title="Click to listen Pronunciation" onClick={handleWorldClick} className="bg-blue-100 hover:bg-blue-200 hover:cursor-pointer font-semibold text-gray-700" > {word?.data?.newRowData?.name} </td> <td className="bg-blue-100 text-gray-700 font-semibold"> {word?.data?.newRowData?.meaning} </td> </tr> ); })} </tbody> </table> </div> </div> {/* <h1 className=" text-xl md:text-2xl lg:text-4xl font-bold flex justify-center items-center text-gray-700"> <FaHeadset className="inline text-2xl md:text-3xl lg:text-6xl text-red-500 me-1 lg:me-2" /> <span>RedRose Audio Book</span>{" "} <MdAudiotrack className="inline text-2xl md:text-4xl lg:text-6xl text-red-500" /> </h1>*/} {/* <textarea placeholder="Write your text here." className=" w-11/12 md:w-8/12 lg:w-8/12 xl:w-6/12 mt-3 md:mt-8 border-2 lg:border-4 border-red-400 rounded-lg h-32 md:h-40 mx-auto p-2" onChange={(e) => { setInputValue(e.target.value); }} ></textarea> */} {/* <ul className="flex gap-4 justify-center btn my-4 text-xl"></ul> <br /> */} {/* <div className="flex justify-center items-center mt-1 md:mt-3 lg:mt-5"> <button onClick={() => { handleInputFieldClick(); }} class="btn-live btn-glow rounded-xl md:rounded-3xl flex items-center justify-between gap-1 px-5 py-2 md:py-3 " > {" "} <HiOutlineSpeakerWave className="inline text-xl md:text-2xl font-bold" />{" "} Listen{" "} </button> </div> */} </div> {/* ------- Word Table -----------*/} </div> ); } export default Page;
package com.basic.charstring; import static org.apache.commons.lang3.StringUtils.abbreviate; import static org.apache.commons.lang3.StringUtils.abbreviateMiddle; import static org.apache.commons.lang3.StringUtils.capitalize; import static org.apache.commons.lang3.StringUtils.chop; import static org.apache.commons.lang3.StringUtils.countMatches; import static org.apache.commons.lang3.StringUtils.defaultString; import static org.apache.commons.lang3.StringUtils.deleteWhitespace; import static org.apache.commons.lang3.StringUtils.difference; import static org.apache.commons.lang3.StringUtils.equalsAny; import static org.apache.commons.lang3.StringUtils.getCommonPrefix; import static org.apache.commons.lang3.StringUtils.indexOfDifference; import static org.apache.commons.lang3.StringUtils.isAllEmpty; import static org.apache.commons.lang3.StringUtils.isAnyEmpty; import static org.apache.commons.lang3.StringUtils.isNoneBlank; import static org.apache.commons.lang3.StringUtils.isNumeric; import static org.apache.commons.lang3.StringUtils.join; import static org.apache.commons.lang3.StringUtils.leftPad; import static org.apache.commons.lang3.StringUtils.normalizeSpace; import static org.apache.commons.lang3.StringUtils.overlay; import static org.apache.commons.lang3.StringUtils.remove; import static org.apache.commons.lang3.StringUtils.removeStart; import static org.apache.commons.lang3.StringUtils.repeat; import static org.apache.commons.lang3.StringUtils.replace; import static org.apache.commons.lang3.StringUtils.replaceEach; import static org.apache.commons.lang3.StringUtils.replaceOnce; import static org.apache.commons.lang3.StringUtils.reverse; import static org.apache.commons.lang3.StringUtils.reverseDelimited; import static org.apache.commons.lang3.StringUtils.rightPad; import static org.apache.commons.lang3.StringUtils.rotate; import static org.apache.commons.lang3.StringUtils.splitByCharacterType; import static org.apache.commons.lang3.StringUtils.splitByCharacterTypeCamelCase; import static org.apache.commons.lang3.StringUtils.splitByWholeSeparator; import static org.apache.commons.lang3.StringUtils.substringAfter; import static org.apache.commons.lang3.StringUtils.substringBefore; import static org.apache.commons.lang3.StringUtils.substringBetween; import static org.apache.commons.lang3.StringUtils.substringsBetween; import static org.apache.commons.lang3.StringUtils.uncapitalize; import java.util.Arrays; import org.apache.commons.lang3.StringUtils; /*- * - stripAccents(): Xóa dấu (vẫn còn xót "đ") * * - firstNonEmpty, firstNonBlank: Trả về phần tử đầu tiên khác empty hoặc blank * * - equals(): * - equalsIgnoreCase(): * * - indexOf(): * - indexOfAny(): * - lastIndexOf(): * * - contains(): * - containsAny(): * - containsIgnoreCase(): */ public class ApacheStringUtils { public static void splitByCharacter_Type() { String input = "Hello123! wo1412rld"; // Không tính khoảng trắng // String regex = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)|(?<=\\W)(?=\\w)|(?<=\\w)(?=\\W)"; // Kể cả khoảng trắng String regex = "(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)|(?<=\\W)(?=\\w)|(?<=\\w)(?=\\W)|(?<=\\s)(?=\\S)|(?<=\\S)(?=\\s)"; String[] result = input.split(regex); System.out.println("SplitByRegex: " + Arrays.toString(result)); // SplitByCharacterTypeCamelCase String[] splitByCharacterTypeCamelCase = splitByCharacterTypeCamelCase(input); System.out.println("SplitByCharacterTypeCamelCase: " + Arrays.toString(splitByCharacterTypeCamelCase)); // splitByCharacterType: Tách chuỗi dựa trên loại ký tự, phân biệt hoa & thường String[] splitByCharacterType = splitByCharacterType(input); System.out.println("SplitByCharacterType: " + Arrays.toString(splitByCharacterType)); } public static void method() { /** * isAnyEmpty: Có ít nhất 1 phần tử là empty */ boolean isAnyEmpty = isAnyEmpty("", "AA", null); System.out.println("IsAnyEmpty: " + isAnyEmpty + "\n"); /** * isNoneEmpty: Có ít nhất 1 phần tử là NOT empty */ boolean isNoneBlank = isNoneBlank("", "AA", null); System.out.println("IsNoneBlank: " + isNoneBlank + "\n"); /** * isAllEmpty: Tất cả các phần tử đều empty */ boolean isAllEmpty = isAllEmpty(null, "", "", null); System.out.println("IsNoneBlank: " + isAllEmpty + "\n"); /** * equalsAny: Kiểm tra giá trị có bằng với giá trị bất kỳ trong danh sách */ String input = "apple"; boolean isEqualsAny = equalsAny(input, "apple", "banana", "orange"); System.out.println("EqualsAny: " + isEqualsAny + "\n"); /** * substringBefore: */ input = "Hello, World"; String substringBefore = substringBefore(input, ","); System.out.println("SubstringBefore: " + input + " -> " + substringBefore); // Hello /** * substringAfter */ String substringAfter = substringAfter(input, ","); System.out.println("SubstringAfter: " + input + " -> " + substringAfter + "\n"); // World /** * substringBetween: Tìm chuỗi con (đầu tiên) nằm giữa 2 chuỗi */ input = "Hello [World]"; String substringBetween = substringBetween(input, "[", "]"); System.out.println("SubstringBetween: " + input + " -> " + substringBetween); /** * substringsBetween: Tìm tất cả các chuỗi con nằm giữa 2 chuỗi */ input = "[a][b][c]"; String[] substringsBetween = substringsBetween(input, "[", "]"); // -> [a, b, c] System.out.println("SubstringsBetween: " + input + " -> " + Arrays.toString(substringsBetween) + "\n"); /** * splitByWholeSeparator */ input = "Hello---World---Universe"; String[] splitByWholeSeparator = splitByWholeSeparator(input, "---"); // Hello, World, Universe String output = Arrays.toString(splitByWholeSeparator); System.out.println("SplitByWholeSeparator: " + input + " -> " + output + "\n"); /** * leftPad, rightPad: Thêm kí tự vào chuỗi cho đến khi bằng độ dài mong muốn */ input = "12345"; String leftPad = leftPad(input, 10, "0"); System.out.println("LeftPad: " + input + " -> " + leftPad); String rightPad = rightPad(input, 10, "0"); System.out.println("RightPad: " + input + " -> " + rightPad + "\n"); /** * join: Nối các phần tử thành chuỗi */ System.out.println("Join default: " + join("A", "B")); // default /** * Nối các phần tử với dấu phân cách separator (kiểu char) */ int[] A1 = { 1, 2, 3, 4 }; String[] A2 = { "apple", "banana", "orange" }; char separator = '-'; System.out.println("Join Primitive: " + join(A1, separator)); System.out.println("Join Object: " + join(A2, separator) + "\n"); /** * deleteWhitespace: Xóa khoảng trắng */ input = "abc d e "; System.out.println("DeleteWhitespace: " + deleteWhitespace(input) + "\n"); /** * remove: Loại bỏ chuỗi con khỏi chuỗi khác * * - Tương tự có removeIgnoreCase */ input = "Hello World"; System.out.println("Remove: " + remove(input, "o")); // Hell, Wrld /** * removeStart, removeStartIgnoreCase: Xóa một chuỗi khỏi đầu một chuỗi nếu nó * tồn tại * * - Tương tự có removeEnd, removeEndIgnoreCase */ input = "Hello World"; String prefix = "Hello "; System.out.println("RemoveStart: " + input + " -> " + removeStart(input, prefix) + "\n"); /** * replaceOnce: Thay thế lần đầu tiên xuất hiện của một chuỗi con trong chuỗi * nguồn * * - Tương tự có replaceOnceIgnoreCase */ input = "Hello, Hello, World!"; String searchString = "Hello"; String replacement = "Hi"; System.out.println("ReplaceOnce: " + input + " -> " + replaceOnce(input, searchString, replacement)); /** * - replace: Thay thế tối đa n lần */ input = "org.apache.commons.lang3.StringUtils"; String replace = replace(input, ".", "_", 3); System.out.println("Replace max: " + input + " -> " + replace); /** * - replaceEach: Thay thế một mảng các chuỗi con tương ứng bằng một mảng các * chuỗi khác */ input = "Hello World"; String[] searchList = { "Hello", "World" }; String[] replacementList = { "Hi", "Java" }; String result = replaceEach(input, searchList, replacementList); System.out.println("ReplaceEach: " + input + " -> " + result + "\n"); // Hi, Java /** * - overlay: Ghi đè 1 chuỗi lên chuỗi khác theo vị trí chỉ định */ input = "Hello World"; String overlay = "Awesome"; int start = 7; int end = 12; result = overlay(input, overlay, start, end); System.out.println("Overlay: " + input + " -> " + result + "\n"); // "Hello, Awesome" /** * - chop: Remove the last character from a String */ input = "Hello, World"; System.out.println("Chop: " + input + " -> " + chop(input) + "\n"); // "Hello, Worl" /** * - repeat: Lặp lại chuỗi n lần * * - repeat(String, String, int): Repeat với dấu phân cách */ System.out.println("Repeat: " + repeat("Hello", 3)); System.out.println("Repeat with separator: " + repeat("Hello", ",", 3) + "\n"); // Hello,Hello,Hello /** * - capitalize: Viết hoa chữ cái đầu tiên * * - uncapitalize: Ngược lại */ input = "hello wOrld"; String capitalize = capitalize(input); System.out.println("Capitalize: " + input + " -> " + capitalize); System.out.println("Uncapitalize: " + capitalize + " -> " + uncapitalize(capitalize)); /** * countMatches: Đếm số lần xuất hiện của một chuỗi */ input = "Hello, World, Hello abc Hello"; String sub = "Hello"; System.out.println("CountMatches: " + countMatches(input, sub) + "\n"); /** * - defaultString: Trả về một chuỗi mặc định nếu chuỗi đầu vào là null * * - Tương tự có: defaultIfEmpty, defaultIfBlank */ input = null; String defaultStr = "default value"; String defaultString = defaultString(input, defaultStr); System.out.println("DefaultString 1: " + defaultString); System.out.println("DefaultString 2: " + defaultString(input) + "\n"); // -> "" /** * - rotate: Xoay chuỗi */ input = "ABCDE"; int numberOfTimes = 2; System.out.println("Rotate 1: " + input + " -> " + rotate(input, numberOfTimes)); System.out.println("Rotate 2: " + input + " -> " + rotate(input, -numberOfTimes) + "\n"); /** * - reverse: Đảo chuỗi * * - reverseDelimited: Đảo chuỗi với dấu phân cách */ System.out.println("Reverse: " + input + " -> " + reverse(input)); input = "AB;CD;EF"; result = reverseDelimited(input, ';'); System.out.printf("ReverseDelimited: %s -> %s \n\n", input, result); /** * - abbreviate: Viết tắt 1 chuỗi dựa trên độ dài tối đa * * - abbreviateMiddle: Viết tắt ở giữa 1 chuỗi dựa trên độ dài tối đa */ input = "This is a long sentence that needs to be abbreviated"; int maxWidth = 20; result = abbreviate(input, maxWidth); System.out.printf("Abbreviate: %s -> %s \n", input, result); String middle = "..."; result = abbreviateMiddle(input, middle, maxWidth); System.out.printf("AbbreviateMiddle: %s -> %s \n\n", input, result); /** * - difference: Trả về phần tử khác nhau đầu tiên của hai chuỗi * * - indexOfDifference(s1, s2): Vị trí đầu tiên mà 2 chuỗi đầu vào khác nhau * * - indexOfDifference(s1, s2,...): Vị trí đầu tiên mà các chuỗi đầu vào khác * nhau */ String s1 = "Hello World"; String s2 = "Hello Java"; String difference = difference(s1, s2); int index = indexOfDifference(s1, s2); System.out.printf("Difference: (%s, %s) -> %s, Diff index = %d \n\n", s1, s2, difference, index); /** * - getCommonPrefix: Tìm tiền tố chung của một danh sách các chuỗi */ String[] strings = { "apple", "application", "applet", "app" }; String commonPrefix = getCommonPrefix(strings); System.out.println("Common Prefix: " + commonPrefix + "\n"); /** * - normalizeSpace: Xóa n > 1 khoảng trắng về còn 1 khoảng trắng */ input = " Hello World "; String normalized = normalizeSpace(input); System.out.printf("NormalizeSpace: '%s' -> '%s' \n\n", input, normalized); /** * - appendIfMissing: Thêm chuỗi con vào cuối một chuỗi nếu chuỗi chưa kết thúc * bằng chuỗi con đó. * * - Tương tự có prependIfMissing */ input = "Hello World"; String appended = StringUtils.appendIfMissing(input, "!"); System.out.printf("AppendIfMissing: %s -> %s\n\n", input, appended); input = "123"; System.out.printf("IsNumeric: %s -> %s\n", input, isNumeric(input)); input = "123a"; System.out.printf("IsNumeric: %s -> %s", input, isNumeric(input)); } public static void main(String[] args) { method(); // splitByCharacter_Type(); } }
CREATE TABLE animals ( class_id INT PRIMARY KEY AUTO_INCREMENT, description VARCHAR(15) NOT NULL ); INSERT INTO animals(description) VALUES ('Pets'), ('PackAnimals'); CREATE TABLE pets ( pet_id INT PRIMARY KEY AUTO_INCREMENT, description VARCHAR(15) NOT NULL ); INSERT INTO pets (description) VALUES ('Dogs'), ('Cats'), ('Hamsters'); ALTER TABLE pets ADD COLUMN class_id INT NOT NULL; UPDATE pets SET class_id = ( SELECT class_id FROM animals WHERE description = 'Pets' ) WHERE pet_id > 0; ALTER TABLE pets ADD CONSTRAINT fk_animal FOREIGN KEY (class_id) REFERENCES animals(class_id) ON UPDATE CASCADE ON DELETE CASCADE; CREATE TABLE packanimals ( pack_animal_id INT PRIMARY KEY AUTO_INCREMENT, description VARCHAR(15) NOT NULL ); INSERT INTO packanimals (description) VALUES ('Horses'), ('Camels'), ('Donkeys'); ALTER TABLE packanimals ADD COLUMN class_id INT NOT NULL; UPDATE packanimals SET class_id = ( SELECT class_id FROM animals WHERE description = 'PackAnimals' ) WHERE pack_animal_id > 0; ALTER TABLE packanimals ADD CONSTRAINT fk_animal_pa FOREIGN KEY (class_id) REFERENCES animals(class_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** CREATE TABLE dogs ( dog_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40) NOT NULL, birthdate DATE, commands VARCHAR(100) ); INSERT INTO dogs (name, birthdate, commands) VALUES ('Fido', '2020-01-01', 'Sit, Stay, Fetch'), ('Buddy', '2018-12-10', 'Sit, Paw, Bark'), ('Bella', '2019-11-11', 'Sit, Stay, Roll'); ALTER TABLE dogs ADD COLUMN pet_id INT NOT NULL; UPDATE dogs SET pet_id = ( SELECT pet_id FROM pets WHERE description = 'Dogs' ) WHERE dog_id > 0; ALTER TABLE dogs ADD CONSTRAINT fk_pets1 FOREIGN KEY (pet_id) REFERENCES pets(pet_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** CREATE TABLE cats ( cat_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40) NOT NULL, birthdate DATE, commands VARCHAR(100) ); INSERT INTO cats (name, birthdate, commands) VALUES ('Whiskers', '2019-05-15', 'Sit, Pounce'), ('Smudge', '2020-02-20', 'Sit, Pounce, Scratch'), ('Oliver', '2020-06-30', 'Meow, Scratch, Jump'); ALTER TABLE cats ADD COLUMN pet_id INT NOT NULL; UPDATE cats SET pet_id = ( SELECT pet_id FROM pets WHERE description = 'Cats' ) WHERE cat_id > 0; ALTER TABLE cats ADD CONSTRAINT fk_pets2 FOREIGN KEY (pet_id) REFERENCES pets(pet_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** CREATE TABLE hamsters ( hamster_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40) NOT NULL, birthdate DATE, commands VARCHAR(100) ); INSERT INTO hamsters (name, birthdate, commands) VALUES ('Hammy', '2021-03-10', 'Roll, Hide'), ('Peanut', '2021-08-01', 'Roll, Spin'); ALTER TABLE hamsters ADD COLUMN pet_id INT NOT NULL; UPDATE hamsters SET pet_id = ( SELECT pet_id FROM pets WHERE description = 'Hamsters' ) WHERE hamster_id > 0; ALTER TABLE hamsters ADD CONSTRAINT fk_pets3 FOREIGN KEY (pet_id) REFERENCES pets(pet_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** CREATE TABLE horses ( horse_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40) NOT NULL, birthdate DATE, commands VARCHAR(100) ); INSERT INTO horses (name, birthdate, commands) VALUES ('Thunder', '2015-07-21', 'Trot, Canter, Gallop'), ('Storm', '2014-05-05', 'Trot, Canter'), ('Blaze', '2016-02-29', 'Trot, Jump, Gallop'); ALTER TABLE horses ADD COLUMN pack_animal_id INT NOT NULL; UPDATE horses SET pack_animal_id = ( SELECT pack_animal_id FROM packanimals WHERE description = 'Horses' ) WHERE horse_id > 0; ALTER TABLE horses ADD CONSTRAINT fk_pets4 FOREIGN KEY (pack_animal_id) REFERENCES packanimals(pack_animal_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** CREATE TABLE camels ( camel_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40) NOT NULL, birthdate DATE, commands VARCHAR(100) ); INSERT INTO camels (name, birthdate, commands) VALUES ('Sandy', '2016-11-03', 'Walk, Carry Load'), ('Dune', '2018-12-12', 'Walk, Sit'), ('Sahara', '2015-08-14', 'Walk, Run'); ALTER TABLE camels ADD COLUMN pack_animal_id INT NOT NULL; UPDATE camels SET pack_animal_id = ( SELECT pack_animal_id FROM packanimals WHERE description = 'Camels' ) WHERE camel_id > 0; ALTER TABLE camels ADD CONSTRAINT fk_pets5 FOREIGN KEY (pack_animal_id) REFERENCES packanimals(pack_animal_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** CREATE TABLE donkeys ( donkey_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(40) NOT NULL, birthdate DATE, commands VARCHAR(100) ); INSERT INTO donkeys (name, birthdate, commands) VALUES ('Eeyore', '2017-09-18', 'Walk, Carry, Load, Bray'), ('Burro', '2019-01-23', 'Walk, Bray, Kick'); ALTER TABLE donkeys ADD COLUMN pack_animal_id INT NOT NULL; UPDATE donkeys SET pack_animal_id = ( SELECT pack_animal_id FROM packanimals WHERE description = 'Donkeys' ) WHERE donkey_id > 0; ALTER TABLE donkeys ADD CONSTRAINT fk_pets6 FOREIGN KEY (pack_animal_id) REFERENCES packanimals(pack_animal_id) ON UPDATE CASCADE ON DELETE CASCADE; # *** *** *** SELECT (@row_number:=@row_number + 1) AS id, name, type, birthdate, commands FROM ( SELECT d.name, p1.description as type, d.birthdate, d.commands FROM dogs d LEFT JOIN pets p1 ON p1.pet_id = d.pet_id UNION SELECT c.name, p2.description as type, c.birthdate, c.commands FROM cats c LEFT JOIN pets p2 ON p2.pet_id = c.pet_id UNION SELECT h.name, p3.description as type, h.birthdate, h.commands FROM hamsters h LEFT JOIN pets p3 ON p3.pet_id = h.pet_id ) AS subquery CROSS JOIN (SELECT @row_number:=0) AS rn; # *** *** *** SET @row_number := 0; WITH ds AS ( SELECT d.name, p1.description as type, d.birthdate, d.commands FROM dogs d LEFT JOIN pets p1 ON p1.pet_id = d.pet_id UNION SELECT c.name, p2.description as type, c.birthdate, c.commands FROM cats c LEFT JOIN pets p2 ON p2.pet_id = c.pet_id UNION SELECT h.name, p3.description as type, h.birthdate, h.commands FROM hamsters h LEFT JOIN pets p3 ON p3.pet_id = h.pet_id ) SELECT (@row_number := @row_number + 1) AS id, name, type, birthdate, commands FROM ds; # *** *** *** SELECT (@row_number:=@row_number + 1) AS id, name, type, birthdate, commands FROM ( SELECT h.name, p1.description as type, h.birthdate, h.commands FROM horses h LEFT JOIN packanimals p1 ON p1.pack_animal_id = h.pack_animal_id UNION SELECT c.name, p2.description as type, c.birthdate, c.commands FROM camels c LEFT JOIN packanimals p2 ON p2.pack_animal_id = c.pack_animal_id UNION SELECT d.name, p3.description as type, d.birthdate, d.commands FROM donkeys d LEFT JOIN packanimals p3 ON p3.pack_animal_id = d.pack_animal_id ) AS subquery CROSS JOIN (SELECT @row_number:=0) AS rn; # *** *** *** # Удалить записи о верблюдах и объединить таблицы лошадей и ослов. SELECT horse_id AS id, name, birthdate, commands, pack_animal_id FROM horses UNION SELECT donkey_id AS id, name, birthdate, commands, pack_animal_id FROM donkeys; # ИЛИ SELECT (@row_number:=@row_number + 1) AS id, name, type, birthdate, commands FROM ( SELECT h.name, p1.description as type, h.birthdate, h.commands FROM horses h LEFT JOIN packanimals p1 ON p1.pack_animal_id = h.pack_animal_id UNION SELECT d.name, p3.description as type, d.birthdate, d.commands FROM donkeys d LEFT JOIN packanimals p3 ON p3.pack_animal_id = d.pack_animal_id ) AS subquery CROSS JOIN (SELECT @row_number:=0) AS rn; # *** *** *** # Создать новую таблицу для животных в возрасте от 1 до 3 лет и вычислить их возраст с точностью до месяца. CREATE TABLE IF NOT EXISTS new_table ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40), type VARCHAR(15), birthdate DATE, age_months INT, commands VARCHAR(100) ); INSERT INTO new_table (name, type, birthdate, age_months, commands) SELECT name, type, birthdate, TIMESTAMPDIFF(MONTH, birthdate, CURRENT_DATE()) as age_months, commands FROM ( SELECT d.name, p1.description as type, d.birthdate, d.commands FROM dogs d LEFT JOIN pets p1 ON p1.pet_id = d.pet_id UNION SELECT c.name, p2.description as type, c.birthdate, c.commands FROM cats c LEFT JOIN pets p2 ON p2.pet_id = c.pet_id UNION SELECT h.name, p3.description as type, h.birthdate, h.commands FROM hamsters h LEFT JOIN pets p3 ON p3.pet_id = h.pet_id UNION SELECT h.name, p1.description as type, h.birthdate, h.commands FROM horses h LEFT JOIN packanimals p1 ON p1.pack_animal_id = h.pack_animal_id UNION SELECT c.name, p2.description as type, c.birthdate, c.commands FROM camels c LEFT JOIN packanimals p2 ON p2.pack_animal_id = c.pack_animal_id UNION SELECT d.name, p3.description as type, d.birthdate, d.commands FROM donkeys d LEFT JOIN packanimals p3 ON p3.pack_animal_id = d.pack_animal_id ) AS subquery WHERE TIMESTAMPDIFF(MONTH, birthdate, CURRENT_DATE()) > 12 AND TIMESTAMPDIFF(MONTH, birthdate, CURRENT_DATE()) <= 3 * 12; SELECT * FROM new_table; # *** *** *** # Объединить все созданные таблицы в одну, сохраняя информацию о принадлежности к исходным таблицам. SELECT an1.class_id AS animals_class_id, an1.description AS animals_description, p1.pet_id AS pets_id, p1.class_id AS pets_class_id, p1.description AS pets_description, d.dog_id AS type_id, d.pet_id AS type_pet_id, d.name AS type_name, d.birthdate AS type_birthdate, d.commands AS type_commands FROM dogs d LEFT JOIN pets p1 ON p1.pet_id = d.pet_id LEFT JOIN animals an1 ON an1.class_id = p1.class_id UNION SELECT an2.class_id AS animals_class_id, an2.description AS animals_description, p2.pet_id AS pets_id, p2.class_id AS pets_class_id, p2.description AS pets_description, c.cat_id AS type_id, c.pet_id AS type_pet_id, c.name AS type_name, c.birthdate AS type_birthdate, c.commands AS type_commands FROM cats c LEFT JOIN pets p2 ON p2.pet_id = c.pet_id LEFT JOIN animals an2 ON an2.class_id = p2.class_id UNION SELECT an3.class_id AS animals_class_id, an3.description AS animals_description, p3.pet_id AS pets_id, p3.class_id AS pets_class_id, p3.description AS pets_description, h.hamster_id AS type_id, h.pet_id AS type_pet_id, h.name AS type_name, h.birthdate AS type_birthdate, h.commands AS type_commands FROM hamsters h LEFT JOIN pets p3 ON p3.pet_id = h.pet_id LEFT JOIN animals an3 ON an3.class_id = p3.class_id UNION SELECT an4.class_id AS animals_class_id, an4.description AS animals_description, pk1.pack_animal_id AS pets_id, pk1.class_id AS pets_class_id, pk1.description AS pets_description, hr.horse_id AS type_id, hr.pack_animal_id AS type_pet_id, hr.name AS type_name, hr.birthdate AS type_birthdate, hr.commands AS type_commands FROM horses hr LEFT JOIN packanimals pk1 ON pk1.pack_animal_id = hr.pack_animal_id LEFT JOIN animals an4 ON an4.class_id = pk1.class_id UNION SELECT an5.class_id AS animals_class_id, an5.description AS animals_description, pk2.pack_animal_id AS pets_id, pk2.class_id AS pets_class_id, pk2.description AS pets_description, cm.camel_id AS type_id, cm.pack_animal_id AS type_pet_id, cm.name AS type_name, cm.birthdate AS type_birthdate, cm.commands AS type_commands FROM camels cm LEFT JOIN packanimals pk2 ON pk2.pack_animal_id = cm.pack_animal_id LEFT JOIN animals an5 ON an5.class_id = pk2.class_id UNION SELECT an6.class_id AS animals_class_id, an6.description AS animals_description, pk3.pack_animal_id AS pets_id, pk3.class_id AS pets_class_id, pk3.description AS pets_description, dn.donkey_id AS type_id, dn.pack_animal_id AS type_pet_id, dn.name AS type_name, dn.birthdate AS type_birthdate, dn.commands AS type_commands FROM donkeys dn LEFT JOIN packanimals pk3 ON pk3.pack_animal_id = dn.pack_animal_id LEFT JOIN animals an6 ON an6.class_id = pk3.class_id;
import numpy as np from numba.typed.typeddict import Dict import TidalPy TidalPy.test_mode() from TidalPy.toolbox.quick_tides import quick_tidal_dissipation, single_dissipation_from_dict_or_world_instance def test_quick_tidal_dissipation_fixedq_float(): """ This will test the quick tidal dissipation calculator - using all floats for fixed-q rheology """ orbital_period = 45. host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 rheology = 'cpl' dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=None, max_tidal_order_l=2, eccentricity_truncation_lvl=2, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) in [float, np.float64] assert type(dissipation_results['dUdM']) in [float, np.float64] assert type(dissipation_results['dUdw']) in [float, np.float64] assert type(dissipation_results['dUdO']) in [float, np.float64] assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 1 assert type(dissipation_results['love_number_by_orderl'][2]) in [complex, np.complex128] assert type(dissipation_results['negative_imk_by_orderl'][2]) in [float, np.float64] assert type(dissipation_results['effective_q_by_orderl'][2]) in [float, np.float64] def test_quick_tidal_dissipation_fixedq_orbital_array(): """ This will test the quick tidal dissipation calculator - using orbital array with the fixed-q rheology """ orbital_period = np.linspace(10., 40., 10) host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 rheology = 'cpl' dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=None, max_tidal_order_l=2, eccentricity_truncation_lvl=2, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 1 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray def test_quick_tidal_dissipation_fixedq_orbital_array_NSR(): """ This will test the quick tidal dissipation calculator - using orbital array with the fixed-q rheology - NSR """ orbital_period = np.linspace(10., 40., 10) spin_period = np.linspace(5., 10., 10) host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 rheology = 'cpl' dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, max_tidal_order_l=2, eccentricity_truncation_lvl=2, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 1 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray def test_quick_tidal_dissipation_maxwell_orbital_array_NSR(): """ This will test the quick tidal dissipation calculator - using orbital array with the Maxwell rheology - NSR """ orbital_period = np.linspace(10., 40., 10) spin_period = np.linspace(5., 10., 10) host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 viscosity = 1.e22 shear = 1.e10 rheology = 'maxwell' dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, viscosity=viscosity, shear_modulus=shear, max_tidal_order_l=2, eccentricity_truncation_lvl=2, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 1 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray def test_quick_tidal_dissipation_andrade_orbital_array_NSR(): """ This will test the quick tidal dissipation calculator - using orbital array with the Andrade rheology - NSR """ orbital_period = np.linspace(10., 40., 10) spin_period = np.linspace(5., 10., 10) host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 viscosity = 1.e22 shear = 1.e10 rheology = 'andrade' andrade_inputs = (0.2, 1.) dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, viscosity=viscosity, shear_modulus=shear, max_tidal_order_l=2, eccentricity_truncation_lvl=2, complex_compliance_inputs=andrade_inputs, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 1 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray def test_quick_tidal_dissipation_andrade_visco_array_NSR(): """ This will test the quick tidal dissipation calculator - using viscosity array with the Andrade rheology - NSR """ orbital_period = 40. spin_period = 10. host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 viscosity = np.logspace(10., 40., 10) shear = 1.e10 rheology = 'andrade' andrade_inputs = (0.2, 1.) dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, viscosity=viscosity, shear_modulus=shear, max_tidal_order_l=2, eccentricity_truncation_lvl=2, complex_compliance_inputs=andrade_inputs, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 1 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray def test_quick_tidal_dissipation_andrade_visco_array_higher_l(): """ This will test the quick tidal dissipation calculator - using viscosity array with the Andrade rheology Max l = 3, eccentricity trunc = 4 """ orbital_period = 40. spin_period = 10. host_mass = 1.e27 target_radius = 1.e6 target_mass = 1.e24 target_gravity = 10. target_density = 5000. target_moi = 1.e5 eccentricity = 0.1 obliquity = 0.1 viscosity = np.logspace(10., 40., 10) shear = 1.e10 rheology = 'andrade' andrade_inputs = (0.2, 1.) dissipation_results = \ quick_tidal_dissipation( host_mass, target_radius, target_mass, target_gravity, target_density, target_moi, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, viscosity=viscosity, shear_modulus=shear, max_tidal_order_l=3, eccentricity_truncation_lvl=4, complex_compliance_inputs=andrade_inputs, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 2 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray assert type(dissipation_results['love_number_by_orderl'][3]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][3]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][3]) == np.ndarray def test_quick_tidal_dissipation_andrade_visco_array_higher_l_from_dict(): """ This will test the quick tidal dissipation (parameters pulled from a dict) calculator - using viscosity array with the Andrade rheology. Max l = 3, eccentricity trunc = 4 """ host_dict = { 'mass': 1.e27 } secondary_dict = { 'radius' : 1.e6, 'mass' : 1.e24, 'gravity_surface': 10., 'density_bulk' : 5000., 'moi' : 1.e10 } orbital_period = 40. spin_period = 10. eccentricity = 0.1 obliquity = 0.1 viscosity = np.logspace(10., 40., 10) shear = 1.e10 rheology = 'andrade' andrade_inputs = (0.2, 1.) dissipation_results = \ single_dissipation_from_dict_or_world_instance( host_dict, secondary_dict, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, viscosity=viscosity, shear_modulus=shear, max_tidal_order_l=3, eccentricity_truncation_lvl=4, complex_compliance_inputs=andrade_inputs, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 2 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray assert type(dissipation_results['love_number_by_orderl'][3]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][3]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][3]) == np.ndarray def test_quick_tidal_dissipation_andrade_visco_array_higher_l_from_world_instance(): """ This will test the quick tidal dissipation (parameters pulled from a world instance) calculator - using viscosity array with the Andrade rheology. Max l = 3, eccentricity trunc = 4 """ from TidalPy import build_world jupiter = build_world('jupiter') io = build_world('io') orbital_period = 40. spin_period = 10. eccentricity = 0.1 obliquity = 0.1 viscosity = np.logspace(10., 40., 10) shear = 1.e10 rheology = 'andrade' andrade_inputs = (0.2, 1.) dissipation_results = \ single_dissipation_from_dict_or_world_instance( jupiter, io, rheology=rheology, eccentricity=eccentricity, obliquity=obliquity, orbital_period=orbital_period, spin_period=spin_period, viscosity=viscosity, shear_modulus=shear, max_tidal_order_l=3, eccentricity_truncation_lvl=4, complex_compliance_inputs=andrade_inputs, use_obliquity=True, tidal_scale=1., fixed_q=120. ) assert type(dissipation_results) == dict assert type(dissipation_results['tidal_heating']) == np.ndarray assert type(dissipation_results['dUdM']) == np.ndarray assert type(dissipation_results['dUdw']) == np.ndarray assert type(dissipation_results['dUdO']) == np.ndarray assert type(dissipation_results['love_number_by_orderl']) in [Dict, dict] assert type(dissipation_results['negative_imk_by_orderl']) in [Dict, dict] assert type(dissipation_results['effective_q_by_orderl']) in [Dict, dict] assert len(dissipation_results['effective_q_by_orderl']) == 2 assert type(dissipation_results['love_number_by_orderl'][2]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][2]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][2]) == np.ndarray assert type(dissipation_results['love_number_by_orderl'][3]) == np.ndarray assert type(dissipation_results['negative_imk_by_orderl'][3]) == np.ndarray assert type(dissipation_results['effective_q_by_orderl'][3]) == np.ndarray
--- title: Week 11 Lab Solutions layout: content mathjax: true --- $$ \newcommand{\tile}[2]{\left[\frac{\texttt{#1}}{\texttt{#2}}\right]} \newcommand{\desc}[1]{\langle #1 \rangle} $$ # Lab: Machine Behavior Undecidability ## Problem 1: Enter the Machine $$ \mathsf{USELESS} = \{\, \langle M \rangle \mid \text{\( M \) is a TM with at least one useless state} \,\}. $$ ## Problem 2: Mappings $f$ takes an input to $A_\mathsf{TM}$, a Turing machine $M$ and input $w$ to that Turing machine as input, and produces an input to $\mathsf{USELESS}$, a Turing machine $M'$, as output. ## Problem 3: The Condition $M$ accepts $w$ if and only if $M'$ has at least one useless state. ## Problem 4: The Construction ::: proof _Proof_. Assume for the sake of contradiction that $\mathsf{USELESS}$ is undecidable, so let $D$ decide it. Define a decider for $A_\mathsf{TM}$, $A$, as follows: $A$ = On input $\langle M, w \rangle$: * Define a Turing machine $M'$ that possesses a distinguished state $q_\mathsf{last}$ that can be only be reached from $q_\mathsf{start}$ and reading a special symbol $\omega$ that does not appear anywhere else in $M$ or $M'$. Define $M'$ as follows: + $M'$ = On input $x$: - If $x = \epsilon$, then visit every one of the states of $M'$ except for $q_\mathsf{last}$. Do so by writing a special symbol $@$ on the tape head that is not mentioned in any of the other transitions of $M'$. Then use this tape symbol to transition to every state (except for $q_\mathsf{last}$) in lexicographical order. - If $M$ accepts $w$, transition to $q_\mathsf{start}$, write an $\omega$ to the tape, and then use that to transition to $q_\mathsf{last}$. - Regardless of which branch we take, end by infinite looping anywhere on $M'$ - Run $D$ on $M'$ and do the opposite of what $D$ does. ::: Note that we must use a general reduction instead of a mapping reduction because the rejection and infinite loop cases require that $M'$ do positive behavior; they must transition to $q_\mathsf{last}$. Since we cannot get positive behavior out of the infinite loop, we instead use complementary behavior and negate the results of the assumed decider for $\mathsf{USELESS}$. ## Problem 5: The Proof of Correctness ::: proof Observe that $M'$ reaches all of its states on input $\epsilon$ except for $q_\mathsf{last}$. Thus, we only need to reason about whether a particular case reaches $q_\mathsf{last}$. + When $M$ accepts $w$, we transition to $q_\mathsf{last}$ explicitly so $M'$ has no useless states. Therefore, $D$ rejects $M'$ and $A$ (the assumed decider for $A_\mathsf{TM}$) accepts. + When $M$ rejects $w$, we do not reach $q_\mathsf{last}$. Therefore, $D$ accepts $M'$ and $A$ rejects. + When $M$ loops on $w$, we do not reach $q_\mathsf{last}$. Therefore, $D$ accepts $M'$ and $A$ rejects. ::: # Lab: PCP ## Problem: Honey Bunches of Oats An example match: $$ \tile{ab}{abab}, \tile{ab}{abab}, \tile{aba}{b}, \tile{b}{a}, \tile{b}{a}, \tile{aa}{a}, \tile{aa}{a}. $$ ::: proof _Proof_. Let $T$ be the set of tiles and for each tile $t \in T$, let $|t|$ be the difference of the number of $a$s on top of $t$ and the number of $a$s on the bottom of $t$. Then $T$ has a solution if and only if the following equation has a solution: $$ \sum_{t \in T} |t| \cdot x_t = 0. $$ Where each $x_t$ is a natural number denoting the number of occurrences of $t$ in a candidate solution. Such linear equations are always solvable, _e.g._, by Gaussian elimination, and thus this restricted version of PCP is decidable. ::: # Lab: Rice's Theorem ## Problem 1: Language Property Example $P$ is a machine property, not a language property! For example, let $M_1$ and $M_2$ be Turing machines that reject all strings so $L(M_1) = L(M_2) = \emptyset$. However, let $M_1$ write '\$' on the tape before rejecting whereas $M_2$ rejects immediately. Then $M_1 \in P$ and $M_2 \notin P$. ## Problem 2: Core Reduction :::proof Let $T$ be a TM such that $\desc{T} \in P$ and let $\desc{T_\emptyset} \notin P$. Define the mapping reduction $f(M, w) = M'$ where $M'$ is defined as follows: $M' =$ On input $x$: + Run $M$ on $w$. - If $M$ accepts $w$, run $T$ on $x$ and do what $T$ does. - If $M$ rejects $w$, reject $x$. Observe that if $M$ accepts $w$ when $M' \in P$ because $M'$ identically to $T$ which is assumed to be in $P$. If $M$ does not accept $w$, then $L(M') = \emptyset$ and thus it behaves identically to $T_\emptyset$ which is assumed to not be in $P$. Finally, note that since $P$ is a language property, membership of $P$ is determined entirely by the strings that $M'$ accepts, so any additional behavior of $M'$ beyond simulation of $T$ does not affect whether $M'$ is in $P$. ::: ## Problem 3: The First Constraint The non-trivial property allows us to posit the existence of a pair of Turing machines, one of which is in $P$ and the other not in $P$. ## Problem 4: The Final Fix-Up Assume that we have a decider for $\overline{P}$, call it $\overline{D}$. A decider for $P$, call it $D$ operates by running $\overline{D}$ and doing the opposite of what it does. Because $\overline{D}$ is a decider, we do not need to worry about whether $\overline{D}$ loops.
<template> <apexchart v-if="entries.length > 1" type="bar" height="200" :options="chartOptions" :series="series" ></apexchart> </template> ; <script lang="ts"> import { LeaderboardEntry } from 'src/models/Entries/entries'; import { formatTime } from 'src/utilities/time'; import { defineComponent, PropType } from 'vue'; import VueApexCharts from 'vue3-apexcharts'; export default defineComponent({ name: 'GroupDailyBarChart', props: { entries: { type: Array as PropType<LeaderboardEntry[]>, default: () => [], }, }, components: { apexchart: VueApexCharts, }, computed: { categories: function (): string[] { return this.entries.map((e) => e.user.name); }, series: function () { const data: number[] = this.entries.map((e) => e.time); return [ { name: 'Todays Times', data: data, }, ]; }, }, watch: { categories() { this.chartOptions.xaxis.categories = this.categories; }, }, data() { return { chartOptions: { colors: ['#3da8ff'], animations: { enabled: true, easing: 'easeinout', speed: 1000, }, grid: { show: false, strokeDashArray: 0, yaxis: { lines: { show: true, }, }, }, title: { text: 'Column', align: 'left', style: { color: '#FFF', }, }, dataLabels: { enabled: true, formatter: function (value: number) { return formatTime(value); }, }, stroke: { width: 0, }, xaxis: { type: 'category', categories: this.entries.map((e) => e.user.name), labels: { show: true, style: { fontsize: '12px', }, }, }, yaxis: { title: { text: '$ (thousands)', style: { color: '#FFF', }, }, labels: { style: { colors: '#fff', }, }, }, tooltip: { y: { formatter: function (timeInSeconds: number) { const mins = Math.floor(timeInSeconds / 60); const secs = timeInSeconds % 60; return `${mins}:${secs < 10 ? '0' : ''}${secs}`; }, }, }, chart: { toolbar: { show: false, }, offsetX: -25 }, }, }; }, }); </script> <style scoped></style>
<script lang="ts"> import { AppRoute } from '$lib/constants'; import Icon from '$lib/components/elements/icon.svelte'; import { goto } from '$app/navigation'; import { isSearchEnabled, preventRaceConditionSearchBar, savedSearchTerms } from '$lib/stores/search.store'; import { clickOutside } from '$lib/utils/click-outside'; import { mdiClose, mdiMagnify, mdiTune } from '@mdi/js'; import IconButton from '$lib/components/elements/buttons/icon-button.svelte'; import SearchHistoryBox from './search-history-box.svelte'; import SearchFilterBox from './search-filter-box.svelte'; import type { MetadataSearchDto, SmartSearchDto } from '@immich/sdk'; import { getMetadataSearchQuery } from '$lib/utils/metadata-search'; import { handlePromiseError } from '$lib/utils'; import { shortcut } from '$lib/utils/shortcut'; import { focusOutside } from '$lib/utils/focus-outside'; export let value = ''; export let grayTheme: boolean; export let searchQuery: MetadataSearchDto | SmartSearchDto = {}; let input: HTMLInputElement; let showHistory = false; let showFilter = false; $: showClearIcon = value.length > 0; const onSearch = async (payload: SmartSearchDto | MetadataSearchDto) => { const params = getMetadataSearchQuery(payload); showHistory = false; showFilter = false; $isSearchEnabled = false; await goto(`${AppRoute.SEARCH}?${params}`); }; const clearSearchTerm = (searchTerm: string) => { input.focus(); $savedSearchTerms = $savedSearchTerms.filter((item) => item !== searchTerm); }; const saveSearchTerm = (saveValue: string) => { $savedSearchTerms = [saveValue, ...$savedSearchTerms]; if ($savedSearchTerms.length > 5) { $savedSearchTerms = $savedSearchTerms.slice(0, 5); } }; const clearAllSearchTerms = () => { input.focus(); $savedSearchTerms = []; }; const onFocusIn = () => { showHistory = true; $isSearchEnabled = true; }; const onFocusOut = () => { if ($isSearchEnabled) { $preventRaceConditionSearchBar = true; } showHistory = false; $isSearchEnabled = false; showFilter = false; }; const onHistoryTermClick = async (searchTerm: string) => { const searchPayload = { query: searchTerm }; await onSearch(searchPayload); }; const onFilterClick = () => { showFilter = !showFilter; value = ''; if (showFilter) { showHistory = false; } }; const onSubmit = () => { handlePromiseError(onSearch({ query: value })); saveSearchTerm(value); }; </script> <svelte:window use:shortcut={{ shortcut: { key: 'Escape' }, onShortcut: () => { onFocusOut(); }, }} /> <div class="w-full relative" use:clickOutside={{ onOutclick: onFocusOut }} use:focusOutside={{ onFocusOut }}> <form draggable="false" autocomplete="off" class="select-text text-sm" action={AppRoute.SEARCH} on:reset={() => (value = '')} on:submit|preventDefault={onSubmit} > <label> <div class="absolute inset-y-0 left-0 flex items-center pl-6"> <div class="dark:text-immich-dark-fg/75"> <button class="flex items-center"> <Icon ariaLabel="search" path={mdiMagnify} size="1.5em" /> </button> </div> </div> <input type="text" name="q" class="w-full {grayTheme ? 'dark:bg-immich-dark-gray' : 'dark:bg-immich-dark-bg'} px-14 py-4 text-immich-fg/75 dark:text-immich-dark-fg {(showHistory && $savedSearchTerms.length > 0) || showFilter ? 'rounded-t-3xl border border-gray-200 bg-white dark:border-gray-800' : 'rounded-3xl border border-transparent bg-gray-200'}" placeholder="Search your photos" required pattern="^(?!m:$).*$" bind:value bind:this={input} on:click={onFocusIn} on:focus={onFocusIn} disabled={showFilter} use:shortcut={{ shortcut: { key: 'Escape' }, onShortcut: () => { onFocusOut(); }, }} /> <div class="absolute inset-y-0 {showClearIcon ? 'right-14' : 'right-5'} flex items-center pl-6 transition-all"> <div class="dark:text-immich-dark-fg/75"> <IconButton on:click={onFilterClick} title="Show search options"> <Icon path={mdiTune} size="1.5em" /> </IconButton> </div> </div> </label> {#if showClearIcon} <div class="absolute inset-y-0 right-0 flex items-center pr-4"> <button type="reset" class="rounded-full p-2 hover:bg-immich-primary/5 active:bg-immich-primary/10 dark:text-immich-dark-fg/75 dark:hover:bg-immich-dark-primary/25 dark:active:bg-immich-dark-primary/[.35]" > <Icon ariaLabel="clear" path={mdiClose} size="1.5em" /> </button> </div> {/if} <!-- SEARCH HISTORY BOX --> {#if showHistory && $savedSearchTerms.length > 0} <SearchHistoryBox on:clearAllSearchTerms={clearAllSearchTerms} on:clearSearchTerm={({ detail: searchTerm }) => clearSearchTerm(searchTerm)} on:selectSearchTerm={({ detail: searchTerm }) => handlePromiseError(onHistoryTermClick(searchTerm))} /> {/if} </form> {#if showFilter} <SearchFilterBox {searchQuery} on:search={({ detail }) => onSearch(detail)} /> {/if} </div>
package collections; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; class Snow { } class Powder extends Snow { } class Light extends Powder { } class Heavy extends Powder { } class Crusty extends Snow { } class Slush extends Snow { } public class AsListInterface { public static void main(String[] args) { List<Snow> snow1 = Arrays.asList(new Crusty(), new Slush(), new Powder()); //- snow1.add(new Heavy()); // Exception List<Snow> snow2 = Arrays.asList(new Light(), new Heavy()); //- snow2.add(new Slush()); // Exception List<Snow> snow3 = new ArrayList<>(); Collections.addAll(snow3, new Light(), new Heavy(), new Powder()); snow3.add(new Crusty()); // Hint with explicit type argument specification: List<Snow> snow4 = Arrays.<Snow>asList(new Light(), new Heavy(), new Slush()); //- snow4.add(new Powder()); // Exception } }
<template> <div class="row"> <div class="col-12 col-md-4 col-lg-4"> <input-form name="internal_order_number" id="txt_internal_order_number" label="Número de Pedido Interno" pattern="^[a-zA-Z0-9-]{3,20}$" errorMsg="Ingrese un número de pedido interno válido" requiredMsg="El número pedido interno es obligatorio" :modelo.sync="purchase_order.internal_order_number" :msgServer.sync="errors.internal_order_number" :required="true" @keyup="changeInternalNumber" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txtCustomerOrderNumber" name="customer_order_number" label="Número de Pedido Cliente" pattern="^[\w -]{3,}$" errorMsg="Ingrese un número de pedido cliente válido" requiredMsg="El número pedido cliente es obligatorio" :modelo.sync="purchase_order.customer_order_number" :msgServer.sync="errors.customer_order_number" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txtInvoiceNumber" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar cliente', taggable: false, label: 'name', options: customers, 'custom-label': (customer) => customer.business_name, }" :modelo.sync="purchase_order.customer" :msgServer.sync="errors.customer" name="cliente" label="Cliente" pattern="all" errorMsg="Cliente no seleccionado" requiredMsg="El cliente es obligatorio" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_invoice" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar factura', taggable: false, label: 'name', options: invoices, 'custom-label': (invoice) => invoice.invoice_number, }" :modelo.sync="purchase_order.invoice" :msgServer.sync="errors.invoice" name="factura" label="Factura" pattern="all" errorMsg="Factura no seleccionada" requiredMsg="La factura es obligatoria" :required="false" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txtFinalUser" name="final_user" label="Usuario Final" pattern="all" errorMsg="Ingrese un usuario final válido" requiredMsg="El usuario final es obligatorio" :modelo.sync="purchase_order.final_user" :msgServer.sync="errors.final_user" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_order_type" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar tipo', taggable: false, label: 'name', 'track-by': 'id', options: order_types, 'custom-label': (order_type) => order_type.name, }" :modelo.sync="purchase_order.order_type" :msgServer.sync="errors.order_type" name="order_type" label="Tipo" pattern="all" errorMsg="Tipo no seleccionado" requiredMsg="El tipo es obligatorio" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_zone" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar zona', taggable: false, label: 'name', options: zones, 'custom-label': (zone) => zone.name, }" :modelo.sync="purchase_order.zone" :msgServer.sync="errors.zone" name="zone" label="Zona" pattern="all" errorMsg="Zona no seleccionada" requiredMsg="La zona es obligatoria" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_seller" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar vendedor', taggable: false, label: 'name', options: sellers, 'track-by': 'id', 'custom-label': (seller) => seller.user.name, }" :modelo.sync="purchase_order.seller" :msgServer.sync="errors.seller" name="seller" label="Vendedor" pattern="all" errorMsg="Vendedor no seleccionado" requiredMsg="El vendedor es obligatorio" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_house" name="house" label="Casa" pattern="^.{3,}$" errorMsg="Ingrese una casa válida" requiredMsg="La casa es obligatoria" :modelo.sync="purchase_order.house" :msgServer.sync="errors.house" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="date" id="txt_order_receipt_date" name="order_receipt_date" label="Fecha de recibo de la orden" pattern="all" errorMsg="Ingrese una fecha válida" requiredMsg="La fecha de recibo es obligatoria" :modelo.sync="purchase_order.order_receipt_date" :msgServer.sync="errors.order_receipt_date" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="date" id="txt_offer_delivery_date" name="offer_delivery_date" label="Fecha de entrega ofertada" pattern="all" errorMsg="Ingrese una fecha válida" requiredMsg="La fecha ofertada es obligatoria" :modelo.sync="purchase_order.offer_delivery_date" :msgServer.sync="errors.offer_delivery_date" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="date" id="txt_delivery_date_required_customer" name="delivery_date_required_customer" label="Fecha de entrega requerida por el cliente" pattern="all" errorMsg="Ingrese una fecha válida" requiredMsg="La fecha requerida por el cliente es obligatoria" :modelo.sync="purchase_order.delivery_date_required_customer" :msgServer.sync="errors.delivery_date_required_customer" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="textarea" id="txt_description" name="description" label="Aplicación" pattern="^.{3,}$" errorMsg="Ingrese una aplicación válida" requiredMsg="La aplicación es obligatoria" :modelo.sync="purchase_order.description" :msgServer.sync="errors.description" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_currency" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar tipo de moneda', taggable: false, label: 'type_moneda', options: type_currencies, 'custom-label': (currency) => currency.code, }" :modelo.sync="purchase_order.currency" :msgServer.sync="errors.currency" name="currency" label="Tipo de Moneda" pattern="all" errorMsg="Tipo de moneda no seleccionado" requiredMsg="El tipo de moneda es obligatorio" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="date" id="txt_expected_dispatch_date" name="expected_dispatch_date" label="Fecha esperada de despacho de la orden" pattern="all" errorMsg="Ingrese una fecha válida" requiredMsg="La fecha de despacho esperada es obligatoria" :modelo.sync="purchase_order.expected_dispatch_date" :msgServer.sync="errors.expected_dispatch_date" :required="false" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="money" label="TRM" id="txt_trm" pattern="all" errorMsg="Ingrese un trm válido" requiredMsg="El trm es obligatorio" :required="true" :modelo.sync="purchase_order.trm" :msgServer.sync="errors.trm" :money="{ decimal: '.', thousands: ',', prefix: '$ ', suffix: 'COP', precision: 0, }" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form type="money" label="Valor Total" id="txt_total_value" pattern="all" errorMsg="Ingrese un valor válido" requiredMsg="El valor total es obligatorio" :required="true" :modelo.sync="purchase_order.total_value" :msgServer.sync="errors.total_value" :money="moneyConfig" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_internal_quote_number" name="internal_quote_number" label="Número de cotización interna" pattern="^[a-zA-Z0-9-]{3,20}$" errorMsg="Ingrese un número de cotización válido" requiredMsg="El número de cotización interno es obligatorio" :modelo.sync="purchase_order.internal_quote_number" :msgServer.sync="errors.internal_quote_number" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_manufacturer_house_quotation_number" name="manufacturer_house_quotation_number" label="Numero de cotización casa fabricante" pattern="^[\w -]{3,}$" errorMsg="Ingrese un número de cotización válido" requiredMsg="El número de cotización del fabricante es obligatorio" :modelo.sync="purchase_order.manufacturer_house_quotation_number" :msgServer.sync="errors.manufacturer_house_quotation_number" :required="false" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <input-form id="txt_payment" type="multiselect" :multiselect="{ selectLabel: 'Seleccionar', selectedLabel: 'Seleccionado', deselectLabel: 'Desmarcar', placeholder: 'Seleccionar forma de pago', taggable: false, label: 'name', options: payments, 'custom-label': (payment) => payment.name, }" :modelo.sync="purchase_order.payment" :msgServer.sync="errors.payment" name="payment" label="Forma de Pago" pattern="all" errorMsg="Forma de pago no seleccionado" requiredMsg="La forma de pago es obligatoria" :required="true" ></input-form> </div> <div class="col-12 col-md-4 col-lg-4"> <div class="form-group txt_contact_number"> <label for="txt_contact_number" class="form-control-label" ><span>Número de Contacto</span> <span class="text-danger asterisco">*</span> </label> <celular-component v-model="purchase_order.contact_number" :required="true" /> </div> </div> </div> </template> <script> export default { name: "HeaderPurchaseOrder", props: { purchase_order: { type: Object, require: true, }, customers: { type: Array, default: function () { return []; }, }, order_types: { type: Array, default: function () { return []; }, }, zones: { type: Array, default: function () { return []; }, }, sellers: { type: Array, default: function () { return []; }, }, type_currencies: { type: Array, default: function () { return []; }, }, payments: { type: Array, default: function () { return []; }, }, }, data() { return { invoices: [], errors: {}, }; }, computed: { moneyConfig() { const id = this.purchase_order.currency ? this.purchase_order.currency.id : 1; switch (id) { case 1: return { decimal: ".", thousands: ",", prefix: "$ ", suffix: "USD", precision: 0, }; case 2: return { decimal: ".", thousands: ",", prefix: "$ ", suffix: "COP", precision: 0, }; case 3: return { decimal: ",", thousands: ".", prefix: "$ ", suffix: "", precision: 0, }; } }, }, created() { axios.get("/api/all-invoices-list").then((response) => { this.invoices = response.data; }); this.timeoutCheck = null; }, methods: { changeInternalNumber() { if (!this.purchase_order || !this.purchase_order.internal_order_number) { return; } clearTimeout(this.timeoutCheck); this.timeoutCheck = setTimeout(() => { const code = this.purchase_order.internal_order_number; axios .post("/api/check-purchase-internal-order", { internal_order_number: code, }) .then((response) => { // console.log(response); this.errors.internal_order_number = null; if (response.data && !response.data.length) { this.errors = Object.assign(response.data); } }); }, 300); }, }, }; </script>
import PySimpleGUI as sg import json from employee import Employee from quicksort import Quicksort as qs import re import sys #Load contents of json file into employee_list. #If file doesn't exist, create it. def load_json(): try: with open('employees.json', 'r') as openfile: json_object = json.load(openfile) except FileNotFoundError: with open('employees.json', 'w') as outfile: json.dump([], outfile) json_object = [] except Exception as e: sg.popup_error('ERROR', f'[{e}]', keep_on_top=True) sys.exit() return json_object #Update what is displayed in the window's Listbox. def update(window, employee_list): msg = [] if len(employee_list) > 0: for emp in employee_list: n = emp["name"] i = emp["id"] t = emp["title"] h = emp["hire_date"] msg.append(f'Name: {n} | ID Number: {i} | Job Title: {t} | Hire Date: {h}') window['-DIS-'].update(msg, set_to_index=[0]) #Employees are sorted by their data fields. def sort(values, employee_list): if values['-S_NAME-']: qs.quicksort(employee_list, 'name', 0, len(employee_list)-1) elif values['-S_ID-']: qs.quicksort(employee_list, 'id', 0, len(employee_list)-1) elif values['-S_TITLE-']: qs.quicksort(employee_list, 'title', 0, len(employee_list)-1) elif values['-S_DATE-']: qs.quicksort(employee_list, 'date', 0, len(employee_list)-1) #Make sure information entered by the user is properly formatted. def check_format(name, date): #Check for valid name format. found = name.find(', ') name = name.replace(', ', '') matches = name.isalpha() name_valid = False if found > 0 and matches: name_valid = True #Check for valid date format. r = re.compile('.{2}/.{2}/.{4}') date_valid = False if len(date) == 10 and r.match(date): date_valid = True return name_valid, date_valid def main(): search_layout = [ [sg.Text('Name Format: Last, First | Hire Date Format: XX/XX/XXXX (month/date/year)', size =(60, 1))], [sg.Text('Employee Name:', size =(15, 1)), sg.InputText('', size=30, key='-NAME-')], [sg.Text('Employee ID:', size =(15, 1)), sg.InputText('', size=30, key='-ID-')], [sg.Text('Employee Title:', size =(15, 1)), sg.InputText('', size=30, key='-TITLE-')], [sg.Text('Employee Hire Date:', size =(15, 1)), sg.InputText('', size=30, key='-DATE-')], [sg.Button('Add Employee')], [sg.Text('_____' * 30, size=(124, 1))], [sg.Radio('Sort By Name', 'RADIO1', default=True, key='-S_NAME-')], [sg.Radio('Sort By ID', 'RADIO1', default=False, key='-S_ID-')], [sg.Radio('Sort By Title', 'RADIO1', default=False, key='-S_TITLE-')], [sg.Radio('Sort By Hire Date', 'RADIO1', default=False, key='-S_DATE-')], [sg.Button('Sort Employees')], [sg.Text('_____' * 30, size=(124, 1))], [sg.Listbox('', size=(200, 10), key='-DIS-')], [sg.Button('Delete Selected'), sg.Button('Exit')] ] window = sg.Window('Company Employees', search_layout, size=(600, 650), finalize=True) employee_list = load_json() update(window, employee_list) while True: event, values = window.read() if event in (sg.WIN_CLOSED, 'Exit'): #Exit window break if event in ('Add Employee',): id = values['-ID-'] invalid_id = False for emp in employee_list: if emp["id"] == id: invalid_id = True break name = values['-NAME-'] date = values['-DATE-'] valid_input = check_format(name, date) if invalid_id: sg.popup_error('ERROR', 'Employee ID must be unique.') elif not valid_input[0] and not valid_input[1]: sg.popup_error('ERROR', 'Name and hire date do not conform to format.') elif not valid_input[0]: sg.popup_error('ERROR', 'Name does not conform to format.') elif not valid_input[1]: sg.popup_error('ERROR', 'Hire date does not conform to format.') else: employee = Employee(name, id, values['-TITLE-'], date) employee = employee.create() if employee is not None: employee_list.append(employee) with open('employees.json', 'w') as outfile: json.dump(employee_list, outfile, indent=4) window['-NAME-'].update('') window['-ID-'].update('') window['-TITLE-'].update('') window['-DATE-'].update('') update(window, employee_list) if event in ('Sort Employees',) and len(employee_list) > 0: sort(values, employee_list) update(window, employee_list) with open('employees.json', 'w') as outfile: json.dump(employee_list, outfile, indent=4) if event in ('Delete Selected',) and len(employee_list) > 0: emp = values['-DIS-'][0] start_index = emp.find('ID Number: ')+11 end_index = emp.find(' ', start_index) id_num = emp[start_index:end_index] for emp in employee_list: if emp["id"] == id_num: employee_list.remove(emp) if employee_list: update(window, employee_list) else: window['-DIS-'].update(employee_list) with open('employees.json', 'w') as outfile: json.dump(employee_list, outfile, indent=4) window.close() if __name__ == "__main__": main()
def recursive_dynamic_fibonacci(): """ RECOMMENDED RECURSIVE SOLUTION """ cache = {} def computation(N): if N < 2: return N else: if N in cache: result = cache[N] else: result = computation(N - 1) + computation(N - 2) cache[N] = result return result return computation def recursive_fibonacci(N): """ NOT RECOMMENDED """ if N < 2: return N else: return recursive_fibonacci(N - 1) + recursive_fibonacci(N - 2) def iterative_fibonacci(N): """ RECOMMENDED """ first = 0 second = 1 for i in range(1, N, 1): sum = first + second first, second = second, sum return sum
// Copyright (c) Christian Prochnow and Contributors. All rights reserved. // Licensed under the Apache-2.0 license. See LICENSE file in the project root for full license information. /* NOTE: This file is derived from https://github.com/kubernetes-client/ licensed under the Apache-2.0 license. */ using System; using System.Numerics; using System.Text.Json.Serialization; using Fractions; using YamlDotNet.Serialization; namespace Kubernetes.Models; /// <content> /// Provides methods to convert between <see cref="ResourceQuantityValue"/> and <see cref="ResourceQuantity"/>. /// </content> public partial class ResourceQuantity { /// <summary> /// Gets the maximum value. /// </summary> public static readonly decimal MaxValue = (decimal)BigInteger.Pow(2, 63) - 1; internal static readonly char[] SuffixChars = "eEinumkKMGTP".ToCharArray(); private ResourceQuantityValue? _value; /// <summary> /// Gets the format of the resource quantity. /// </summary> [JsonIgnore] [YamlIgnore] public ResourceQuantityFormat Format => GetValue().Format; private ResourceQuantity(decimal n, int exp, ResourceQuantityFormat format) { _value = new ResourceQuantityValue(null, format, Fraction.FromDecimal(n) * Fraction.Pow(10, exp)); } private ResourceQuantityValue GetValue() { if (_value == null || !string.Equals(Value, _value.Value, StringComparison.InvariantCulture)) _value = ResourceQuantityValue.Parse(Value); return _value; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <param name="format">Specifies the format of the formatted value.</param> /// <returns>The <see cref="ResourceQuantity"/> formatted as a string.</returns> public string ToString(ResourceQuantityFormat format) { return GetValue().CanonicalizeString(format); } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <remarks> /// The string is formatted using the <see cref="ResourceQuantityFormat"/> of the <see cref="ResourceQuantity"/>. /// </remarks> /// <returns>The <see cref="ResourceQuantity"/> formatted as a string.</returns> public override string ToString() { return GetValue().CanonicalizeString(); } /// <summary> /// Converts the value of this instance to an <see cref="int"/>. /// </summary> /// <returns>The value of this instance converted to an <see cref="int"/>.</returns> public int ToInt32() { return GetValue().RationalValue.ToInt32(); } /// <summary> /// Converts the value of this instance to an <see cref="long"/>. /// </summary> /// <returns>The value of this instance converted to an <see cref="long"/>.</returns> public long ToInt64() { return GetValue().RationalValue.ToInt64(); } /// <summary> /// Converts the value of this instance to an <see cref="uint"/>. /// </summary> /// <returns>The value of this instance converted to an <see cref="uint"/>.</returns> public uint ToUInt32() { return GetValue().RationalValue.ToUInt32(); } /// <summary> /// Converts the value of this instance to an <see cref="ulong"/>. /// </summary> /// <returns>The value of this instance converted to an <see cref="ulong"/>.</returns> public ulong ToUInt64() { return GetValue().RationalValue.ToUInt64(); } /// <summary> /// Converts the value of this instance to an <see cref="BigInteger"/>. /// </summary> /// <returns>The value of this instance converted to an <see cref="BigInteger"/>.</returns> public BigInteger ToBigInteger() { return GetValue().RationalValue.ToBigInteger(); } /// <summary> /// Converts the value of this instance to a <see cref="decimal"/>. /// </summary> /// <returns>The value of this instance converted to a <see cref="decimal"/>.</returns> public decimal ToDecimal() { return GetValue().RationalValue.ToDecimal(); } /// <summary> /// Converts the value of this instance to a <see cref="double"/>. /// </summary> /// <returns>The value of this instance converted to a <see cref="double"/>.</returns> public double ToDouble() { return GetValue().RationalValue.ToDouble(); } /// <summary> /// Implicit conversion from <see cref="ResourceQuantity"/> to <see cref="decimal"/>. /// </summary> /// <param name="v">The <see cref="ResourceQuantity"/> to convert.</param> /// <returns>The converted <see cref="decimal"/> value.</returns> public static implicit operator decimal(ResourceQuantity? v) { return v?.ToDecimal() ?? 0; } /// <summary> /// Implicit conversion from <see cref="decimal"/> to <see cref="ResourceQuantity"/> using /// <see cref="ResourceQuantityFormat.DecimalExponent"/>. /// </summary> /// <param name="v">The <see cref="decimal"/> to convert.</param> /// <returns>The converted <see cref="ResourceQuantity"/> value.</returns> public static implicit operator ResourceQuantity(decimal v) { return new ResourceQuantity(v, 0, ResourceQuantityFormat.DecimalExponent); } /// <summary> /// Gets the hash code for this instance. /// </summary> /// <returns>The hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { unchecked { ResourceQuantityValue value = GetValue(); return ((int)value.Format * 397) ^ value.RationalValue.GetHashCode(); } } /// <summary> /// Determines whether the specified <see cref="ResourceQuantity"/> is equal to this instance. /// </summary> /// <param name="other">The <see cref="ResourceQuantity"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="ResourceQuantity"/> is equal to this instance; otherwise, <c>false</c>.</returns> protected bool Equals(ResourceQuantity? other) { ResourceQuantityValue value = GetValue(); ResourceQuantityValue? otherValue = other?.GetValue(); return value.Format == otherValue?.Format && value.RationalValue.Equals(otherValue.RationalValue); } /// <summary> /// Determines whether the specified <see cref="object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((ResourceQuantity)obj); } }
import React from 'react' import Heading from '../ui/Heading' import { Stareicon, groupicon, educationicon } from '../../assets' const Values = () => { const Valuecard = ({icon, title, description, className}) => { return ( <div className={`p-4 border-[#262626] rounded-2xl ${className}`}> <div className='flex gap-4 mb-4'> <div className='rounded-full p-3 border border-[#703BF7] h-fit'><img src={icon} alt="icons" /></div> <h2 className='h2'>{title}</h2> </div> <div> <p className='p'>{description}</p> </div> </div> ) } return ( <div className='mt-32 mx-auto flex flex-col xl:flex-row gap-8'> <div className='my-auto basis-4/12'> <Heading heading="Our Values" description="Our story is one of continuous growth and evolution. We started as a small team with big dreams, determined to create a real estate platform that transcended the ordinary." className={'gap-4'} /> </div> <div className='p-4 grid md:grid-cols-2 grid-cols-1 basis-8/12 border-[#262626] border shadow-[0px_0px_0px_10px_#191919] rounded-xl'> <Valuecard icon={Stareicon} title="Trust" description="Trust is the cornerstone of every successful real estate transaction." className='border-r-2 border-b-2 ' /> <Valuecard icon={educationicon} title="Education" description="We set the bar high for ourselves. From the properties we list to the services we provide." className='border-b-2 border-l-2' /> <Valuecard icon={groupicon} title="Client-Centric" description="Your dreams and needs are at the center of our universe. We listen, understand." className='border-r-2 border-b-2 md:border-b-0' /> <Valuecard icon={Stareicon} title="Our Commitment" description="We are dedicated to providing you with the highest level of service, professionalism, and support." className='border-l-2 border-b-2 md:border-b-0' /> </div> </div> ) } export default Values
<template> <div class="container"> <el-row type="flex" class="main" justify="space-between"> <!-- logo --> <div class="logo"> <img src="http://157.122.54.189:9093/images/logo.jpg" alt=""> </div> <el-row type="flex" class="navs"> <!-- nuxt-link的作用和使用方式和router-link --> <nuxt-link to="/">首页</nuxt-link> <nuxt-link to="/post"> 旅游攻略</nuxt-link> <nuxt-link to="/hotel"> 酒店</nuxt-link> <nuxt-link to="/air"> 国内机票</nuxt-link> </el-row> <!-- 登录跳转 --> <div v-if="!$store.state.user.userInfo.token"> <nuxt-link to="/user/login">登录 / 注册</nuxt-link> </div> <div v-else> <el-dropdown> <span class="el-dropdown-link"> <!-- 头像,昵称 --> <img :src="` ${$axios.defaults.baseURL}${$store.state.user.userInfo.user.defaultAvatar} `"> <span>{{$store.state.user.userInfo.user.nickname}}</span> <i class="el-icon-arrow-down el-icon--right"></i> </span> <el-dropdown-menu slot="dropdown"> <el-dropdown-item>个人中心</el-dropdown-item> <!-- click.native 给第三方组件添加事件需要加上native --> <el-dropdown-item @click.native="handleLogout">退出</el-dropdown-item> </el-dropdown-menu> </el-dropdown> </div> </el-row> </div> </template> <script> export default { methods: { // 用户退出 handleLogout() { // 清除登录信息 this.$store.commit("user/clearUserInfo"); this.$message({ type: "success", message: "成功退出" }); } }, // 加载组件 mounted() { // console.log(this.$store.state.user.userInfo.token); // this.$emit("click") } }; </script> <style scoped lang="less"> .container { width: 100%; height: 60px; line-height: 60px; border-bottom: 1px #ddd solid; box-shadow: 0 2px 2px #ddd; } .main { width: 1000px; margin: 0 auto; } .navs { flex: 1; margin-left: 10px; a { display: block; height: 60px; padding: 0 20px; box-sizing: border-box; &:hover { color: #409eff; border-bottom: 5px #409eff solid; } } // 该class是nuxt会去自动匹配nuxt-link的to的值,如果url和to的值相等会自动加上下面的class .nuxt-link-exact-active { background: #409eff; color: #fff; &:hover { color: #fff; } } } .logo { padding-top: 9px; img { width: 156px; height: 42px; display: block; } } // 头像样式 .el-dropdown-link img { width: 36px; height: 36px; border-radius: 50%; vertical-align: middle; box-sizing: border-box; border: 2px #fff solid; &:hover { border: 2px #409eff solid; } } </style>
import React, { useReducer, useContext, useState } from "react"; import { Store } from "../../states/store"; // import { getError } from "../../utils/error"; import { reducer } from "../../states/reducers"; // import { ToastContainer, toast } from "react-toastify"; import { Card, Col, Container, Row } from "react-bootstrap"; import { LoadingBox } from "../../components"; import { MessageBox } from "../../components"; import UpdateProfileModel from "./UpdateProfile"; // import axiosInstance from "../../utils/axiosUtil"; import { motion } from "framer-motion"; import { FaEdit } from "react-icons/fa"; import Skeleton from "react-loading-skeleton"; const ViewProfile = () => { const { state } = useContext(Store); const { userInfo } = state; const [modalShow, setModalShow] = useState(false); const [{ loading, error }] = useReducer(reducer, { loading: false, error: "", }); // useEffect(() => { // const fetchData = async () => { // try { // dispatch({ type: "FETCH_REQUEST" }); // const { data } = await axiosInstance.get(`/api/user/user-profile`, { // headers: { Authorization: token }, // }); // // console.log(data); // dispatch({ type: "FETCH_SUCCESS", payload: data }); // } catch (err) { // dispatch({ // type: "FETCH_FAIL", // payload: getError(err), // }); // toast.error(getError(err), { // position: toast.POSITION.BOTTOM_CENTER, // }); // } // }; // fetchData(); // }, [token]); const getDateTime = (dt) => { const dT = dt.split(".")[0].split("T"); return `${dT[0]} ${dT[1]}`; }; // console.log(userInfo); return ( <motion.div initial={{ x: "100%" }} animate={{ x: "0%" }} transition={{ duration: 0.75, ease: "easeInOut" }} exit={{ x: "100%" }} > <Container fluid className="py-3"> {loading ? ( <LoadingBox></LoadingBox> ) : error ? ( <MessageBox variant="danger">{error}</MessageBox> ) : ( <> <Card> <Card.Header> <Card.Title> {loading ? <Skeleton /> : `Admin Profile`} </Card.Title> <div className="card-tools"> <FaEdit style={{ color: "blue" }} onClick={() => setModalShow(true)} /> </div> </Card.Header> <Card.Body> <Row> <Col md={4}> {loading ? ( <Skeleton height={200} /> ) : ( <img style={{ borderRadius: "5px", }} src={userInfo.avatar} alt="" className="img-fluid" width={"200px"} height={"200px"} /> )} </Col> </Row> <Row> <Col md={4}> <p className="mb-0"> <strong>User Name</strong> </p> <p>{loading ? <Skeleton /> : userInfo.username}</p> </Col> <Col md={4}> <p className="mb-0"> <strong>Email</strong> </p> <p>{loading ? <Skeleton /> : userInfo.email}</p> </Col> <Col md={4}> <p className="mb-0"> <strong>Mobile</strong> </p> <p>{loading ? <Skeleton /> : userInfo.mobile_no}</p> </Col> {/* <Col md={4}> <p className="mb-0"> <strong>Fax</strong> </p> <p>{user.fax}</p> </Col> */} <Col md={4}> <p className="mb-0"> <strong>Role</strong> </p> <p>{loading ? <Skeleton /> : userInfo.role}</p> </Col> <Col md={4}> <p className="mb-0"> <strong>Gender</strong> </p> <p>{loading ? <Skeleton /> : userInfo.gender}</p> </Col> {userInfo.dob !== null && ( <Col md={4}> <p className="mb-0"> <strong>Date of Birth</strong> </p> <p> {loading ? <Skeleton /> : userInfo.dob.split("T")[0]} </p> </Col> )} <Col md={4}> <p className="mb-0"> <strong>Country</strong> </p> <p>{loading ? <Skeleton /> : userInfo.country}</p> </Col> <Col md={4}> <p className="mb-0"> <strong>Created At</strong> </p> <p> {loading ? <Skeleton /> : getDateTime(userInfo.createdAt)} </p> </Col> <Col md={4}> <p className="mb-0"> <strong>Last Update</strong> </p> <p> {loading ? <Skeleton /> : getDateTime(userInfo.updatedAt)} </p> </Col> </Row> </Card.Body> </Card> <UpdateProfileModel show={modalShow} onHide={() => setModalShow(false)} /> {/* <ToastContainer /> */} </> )} </Container> </motion.div> ); }; export default ViewProfile;
import { NextFunction, Request, Response } from "express"; import HttpError from "../httpError"; function errorMiddleware( error: HttpError, _request: Request, response: Response, _next: NextFunction ) { let status = error.status || 500; // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status let message = error.message || "Something went wrong"; // 1. Error is already logged // 2. Generalize response message - discreet, polite and protective against malign attackers // status >= 100 - Information responses // status >= 200 - Successful responses // status >= 300 - Redirection messages // Client error - https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses if (error.status === 400 || error.status === 401 || error.status === 403) { // status 400 message are allowed to pass through (ex.: "Email needs to be confirmed in order to enable login") status = error.status; message = error.message; } if (error.status > 400 && error.status !== 401 && error.status !== 403) { status = 400; // BadRequestError - The server could not understand the request due to invalid syntax message = "Expired or invalid input"; // e.g.: deleted/outdated uuid } // Server error - https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses if (error.status >= 500) { status = 500; // InternalServerError message = "Something went wrong"; } response.status(status).send(message); } export default errorMiddleware;
// importing all module--------> const express = require("express"); const { connection } = require("./config/db"); const { userRouter } = require("./routes/user.routes"); require("dotenv").config(); const cors = require("cors"); const { userProductRouter } = require("./routes/user.product.routes"); const { sellerProductRouter } = require("./routes/seller.product.routes"); const { cartRouter } = require("./routes/cart.routes"); const { orderRouter } = require("./routes/order.routes"); const { authMiddleware } = require("./middleware/auth.middleware"); const { rateLimiter } = require("./middleware/rateLimiter.middleware"); const { swaggerSpec } = require("./swagger"); const swaggerUI = require("swagger-ui-express"); // creating an express app instance--------> const app = express(); // middlewares------> app.use(express.json()); app.use(cors()); app.use("/api-docs", swaggerUI.serve, swaggerUI.setup(swaggerSpec)); // Home route--------> app.get("/",(req,res)=>{ res.status(200).send({msg:"Welcome To Triveous Ecommerce Api Backend"}) }) // other routes-----> app.use(rateLimiter); app.use("/user",userRouter); app.use("/user/products",userProductRouter); app.use(authMiddleware); app.use("/seller/products",sellerProductRouter); app.use("/cart",cartRouter); app.use("/order",orderRouter); // app listing and connection to db-------> app.listen(process.env.PORT,async()=>{ try { await connection; console.log("Connected to db!"); } catch (error) { console.log("Unable to connect db!"); console.log(error.message); } console.log(`Server is Running on PORT ${process.env.PORT}!`) })
--- title: 剑指 Offer 06 - 从尾到头打印链表 date: 2022-09-23 14:45:29 permalink: /pages/95a77e/ --- ## 📃 题目描述 题目链接:[剑指 Offer 06. 从尾到头打印链表](https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/) 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 **示例 1:** ``` 输入:head = [1,3,2] 输出:[2,3,1] ``` ## 🔔 解题思路 ```java /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public int[] reversePrint(ListNode head) { Stack<ListNode> stack = new Stack<>(); while (head != null) { stack.push(head); head = head.next; } List<Integer> list = new ArrayList<>(); while (!stack.isEmpty()) { list.add(stack.pop().val); } return list.stream().mapToInt(Integer::intValue).toArray(); } } ``` ## 💥 复杂度分析 - 空间复杂度: - 时间复杂度:
<div align="center"> ![Logo Metodologie di Programmazione](https://static.wikia.nocookie.net/logopedia/images/a/aa/Minecraft-java-logo.png/revision/latest?cb=20190316052713) # Metodologie di Programmazione </div> ## About 🔎 Il corso di Metodologie di Programmazione mira all'apprendimento dei concetti della programmazione orientata agli oggetti mediante il linguaggio di programmazione Java. In linea di massima, verranno affrontati i seguenti argomenti - I concetti fondamentali della programmazione orientata agli oggetti (SOLID) - classi e oggetti - incapsulamento - ereditarietà - polimorfismo - binding statico e dinamico - i design pattern - La programmazione funzionale ## Materiale 📚 - [Slide del corso](https://classroom.google.com/u/1/c/NTkzNzA4NTg3MDU5?cjc=j3msarm) ## Esercizi 📝 Una volta alla settimana viene svolta un'attività di laboratorio, in cui vengono proposti degli esercizi da svolgere in autonomia. <details closed> <summary> <strong> Esercizi </strong> </summary> - <details closed> <summary> Esercizi Capitolo 2</summary> - [Esercizio 1](./Esercizi/Esercizi%20Capitolo%202/Esercizio_1) - [Esercizio 2](./Esercizi/Esercizi%20Capitolo%202/Esercizio_2) - [Esercizio 3](./Esercizi/Esercizi%20Capitolo%202/Esercizio_3) - [Esercizio 4](./Esercizi/Esercizi%20Capitolo%202/Esercizio_4) - [Esercizio 5](./Esercizi/Esercizi%20Capitolo%202/Esercizio_5) - [Esercizio 6](./Esercizi/Esercizi%20Capitolo%202/Esercizio_6) - [Esercizio 7](./Esercizi/Esercizi%20Capitolo%202/Esercizio_7) - [Esercizio 8](./Esercizi/Esercizi%20Capitolo%202/Esercizio_8) - [Esercizio 9](./Esercizi/Esercizi%20Capitolo%202/Esercizio_9) - [Esercizio 10](./Esercizi/Esercizi%20Capitolo%202/Esercizio_10) - [Esercizio 11](./Esercizi/Esercizi%20Capitolo%202/Esercizio_11) - [Esercizio 12](./Esercizi/Esercizi%20Capitolo%202/Esercizio_12) - [Esercizio 13](./Esercizi/Esercizi%20Capitolo%202/Esercizio_13) - [Esercizio 14](./Esercizi/Esercizi%20Capitolo%202/Esercizio_14) - [Esercizio 15](./Esercizi/Esercizi%20Capitolo%202/Esercizio_15) - [Esercizio 16](./Esercizi/Esercizi%20Capitolo%202/Esercizio_16) - [Esercizio 17](./Esercizi/Esercizi%20Capitolo%202/Esercizio_17) - [Esercizio 18](./Esercizi/Esercizi%20Capitolo%202/Esercizio_18) - [Esercizio 19](./Esercizi/Esercizi%20Capitolo%202/Esercizio_19) </details> - <details closed> <summary> Esercizi Capitolo 3</summary> - [Esercizio 1](./Esercizi/Esercizi%20Capitolo%203/Esercizio_1) - [Esercizio 2](./Esercizi/Esercizi%20Capitolo%203/Esercizio_2) - [Esercizio 3](./Esercizi/Esercizi%20Capitolo%203/Esercizio_3) - [Esercizio 4](./Esercizi/Esercizi%20Capitolo%203/Esercizio_4) - [Esercizio 5](./Esercizi/Esercizi%20Capitolo%203/Esercizio_5) - [Esercizio 6](./Esercizi/Esercizi%20Capitolo%203/Esercizio_6) - [Esercizio 7](./Esercizi/Esercizi%20Capitolo%203/Esercizio_7) - [Esercizio 8](./Esercizi/Esercizi%20Capitolo%203/Esercizio_8) - [Esercizio 9](./Esercizi/Esercizi%20Capitolo%203/Esercizio_9) - [Esercizio 10](./Esercizi/Esercizi%20Capitolo%203/Esercizio_10) - [Esercizio 11](./Esercizi/Esercizi%20Capitolo%203/Esercizio_11) - [Esercizio 12](./Esercizi/Esercizi%20Capitolo%203/Esercizio_12) - [Esercizio 13](./Esercizi/Esercizi%20Capitolo%203/Esercizio_13) - [Esercizio 14](./Esercizi/Esercizi%20Capitolo%203/Esercizio_14) - [Esercizio 15](./Esercizi/Esercizi%20Capitolo%203/Esercizio_15) - [Esercizio 16](./Esercizi/Esercizi%20Capitolo%203/Esercizio_16) - [Esercizio 17](./Esercizi/Esercizi%20Capitolo%203/Esercizio_17) - [Esercizio 18](./Esercizi/Esercizi%20Capitolo%203/Esercizio_18) - [Esercizio 19](./Esercizi/Esercizi%20Capitolo%203/Esercizio_19) - [Esercizio 20](./Esercizi/Esercizi%20Capitolo%203/Esercizio_20) </details> </details> Di seguito sono riportati dei piccoli walkthrough di alcune prove scritte precedenti realizzati al fine di rafforzare le soluzioni già presenti o andare a colmare la dove non siano presenti. <details closed> <summary> <strong> Esami Precedenti </strong> </summary> - <details closed> <summary> 2021 </summary> - <details closed> <summary> Maggio </summary> - [Walkthrough Esame 19 Maggio 2021](./Esami%20precedenti/2021/Maggio/Esame%2019%20Maggio%202021) </details> </details> - <details closed> <summary> 2023 </summary> - <details closed> <summary> Maggio </summary> - [Walkthrough Esame 17 Maggio 2023](./Esami%20precedenti/2023/Maggio/Esame%2017%20Maggio%202023) </details> - <details closed> <summary> Giugno </summary> - [Walkthrough Esame 13 Giugno 2023](./Esami%20precedenti/2023/Giugno/Esame%2013%20Giugno%202023) </details> - <details closed> <summary> Luglio </summary> - [Walkthrough Esame 13 Luglio 2023](./Esami%20precedenti/2023/Luglio/Esame%2013%20Luglio%202023) </details> </details> </details> <div align="center"> [***Torna alla Home***](../../../) </div>
using System; class Program {// Главный класс для управления книгой контактов в консольном приложении. static ContactBook contactBook = new ContactBook(); static void Main(string[] args) { while (true) {// Выводим меню действий пользователю. Console.WriteLine("\nChoose an option:"); Console.WriteLine("1: Add Contact"); Console.WriteLine("2: Search Contacts"); Console.WriteLine("3: Edit Contact"); Console.WriteLine("4: Delete Contact"); Console.WriteLine("5: List All Contacts"); Console.WriteLine("6: Exit"); Console.Write("Enter option: "); string option = Console.ReadLine(); switch (option) { case "1": AddContact(); break; case "2": SearchContacts(); break; case "3": EditContact(); break; case "4": DeleteContact(); break; case "5": ListAllContacts(); break; case "6": Console.WriteLine("Exiting..."); return; default: Console.WriteLine("Invalid option. Please try again."); break; } } } // Собирает информацию от пользователя и добавляет новый контакт. static void AddContact() { Console.Write("Enter first name: "); string firstName = Console.ReadLine(); Console.Write("Enter last name: "); string lastName = Console.ReadLine(); Console.Write("Enter phone number: "); string phoneNumber = Console.ReadLine(); Console.Write("Enter email: "); string email = Console.ReadLine(); // Добавляем контакт используя введенные данные. contactBook.AddContact(firstName, lastName, phoneNumber, email); } // Поиск контактов на основе запроса пользователя. static void SearchContacts() { Console.Write("Enter search query: "); string query = Console.ReadLine(); var foundContacts = contactBook.SearchContacts(query); Console.WriteLine("Found contacts:"); foreach (var contact in foundContacts) { Console.WriteLine(contact); } } // Редактирует существующий контакт, идентифицированный по ID. static void EditContact() { Console.Write("Enter the ID of the contact to edit: "); if (int.TryParse(Console.ReadLine(), out int id)) { Console.Write("Enter new first name: "); string firstName = Console.ReadLine(); Console.Write("Enter new last name: "); string lastName = Console.ReadLine(); Console.Write("Enter new phone number: "); string phoneNumber = Console.ReadLine(); Console.Write("Enter new email: "); string email = Console.ReadLine(); contactBook.EditContact(id, firstName, lastName, phoneNumber, email); } else { Console.WriteLine("Invalid ID format."); } } // Удаляет контакт по ID, предоставленному пользователем. static void DeleteContact() { Console.Write("Enter the ID of the contact to delete: "); if (int.TryParse(Console.ReadLine(), out int id)) { contactBook.DeleteContact(id); } else { Console.WriteLine("Invalid ID format."); } } static void ListAllContacts() { contactBook.ListAllContacts(); } }
import { NumberTreeNode, TreeNode } from "../../helpers/tree-node"; import { TestCases } from "../../../types"; import { lca } from "."; describe("235 - lowest common ancestor", () => { const testCases: TestCases<[Array<number | null>, number, number], number> = [ { input: [[6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], 2, 4], output: 2, }, { input: [[6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], 2, 8], output: 6, }, { input: [[2, 1], 2, 1], output: 2, }, ]; for (const tc of testCases) { const [inputArray, p, q] = tc.input; const tree = TreeNode.buildCompleteBinaryTreeFromArray(inputArray); expect(tree).not.toBeNull(); let pNode: NumberTreeNode, qNode: NumberTreeNode; tree!.inOrderTraversal((v) => { if (v.val === p) { pNode = v; } else if (v!.val === q) { qNode = v; } }); expect(pNode!).not.toBeNull(); expect(qNode!).not.toBeNull(); const ancestor = lca(tree!, pNode!, qNode!); expect(ancestor?.val).toEqual(tc.output); } });
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using RepoistoryPatternWith.Core.consts; namespace RepositoryPattern.Controllers { [Route("api/[controller]")] [ApiController] public class BookController : ControllerBase { private readonly IBaseRepository<Book> _bookRepository; public BookController(IBaseRepository<Book> bookRepository) { _bookRepository = bookRepository; } [HttpGet] public async Task<IActionResult> GetById(int id) { var book = await _bookRepository.GetById(id); if(book == null) { return NotFound(); } return Ok(book); } [HttpGet("GetAll")] public async Task<IActionResult> GetAll() { var allBook= await _bookRepository.GetAll(); return Ok(allBook); } [HttpGet("GetbyName")] public IActionResult GetbyName() { var findBook = _bookRepository.Find(e=>e.Title=="action"); if(findBook == null) { return NotFound(); } return Ok(findBook); } [HttpGet("GetbyNameInclude")] public IActionResult GetbyNameInclude() { var findBook = _bookRepository.Find(e => e.Title == "action",new [] {"Author"}); if (findBook == null) { return NotFound(); } return Ok(findBook); } [HttpGet("GetbyAll")] public IActionResult GetbyAll() { var findBook = _bookRepository.FindAll(e => e.Title == "action", new[] { "Author" }); if (findBook == null) { return NotFound(); } return Ok(findBook); } [HttpGet("GetbyOrder")] public IActionResult GetbyOrder() { var findBook = _bookRepository.FindAll(e => e.AuthorId==1, null,null,b=>b.Id,OrderBy.Descending); if (findBook == null) { return NotFound(); } return Ok(findBook); } [HttpPost("Addone")] public IActionResult Addone() { var res = _bookRepository.Add(new Book { Title = "test", AuthorId = 2 }); return Ok(res); } } }
import React, { Component } from 'react'; import Style from './style.module.scss'; import Input from '../../common/Input'; import { connect } from 'react-redux'; import { v4 as uuidv4 } from 'uuid'; import PropTypes from 'prop-types'; import SubscriptionsActions from '../../actions/subscriptionsActions'; import SelectInput from '../../common/SelectInput'; import Button from '../../common/Button/index'; class AddSubscriptionForm extends Component { constructor(props) { super(props); this.serviceOptions = [ { value: 'NFLX', displayName: 'Netflix', }, { value: 'DIS', displayName: 'Disney+', }, { value: 'SPOT', displayName: 'Spotify', }, { value: 'others', displayName: 'Others', }, ]; this.billingCycle = [ { value: 'm', displayName: 'Monthly (30 days)', }, { value: 'y', displayName: 'Yearly (365 days)', }, ]; this.initialValues = { servicename: this.serviceOptions[0].value, customServiceName: '', startdate: '', cycle: this.billingCycle[0].value, amount: '', showCustomServiceInput: false, isValidForm: false, errors: {}, }; this.state = { servicename: this.serviceOptions[0].value, customServiceName: '', startdate: '', cycle: this.billingCycle[0].value, amount: '', showCustomServiceInput: false, isValidForm: false, errors: {}, fromDate: new Date().toISOString().substr(0, 10), }; } handleChange = (e) => { this.setState( { [e.target.name]: e.target.value, }, () => { this.validate(); } ); }; handleServiceChange = (e) => { const v = e.target.value; this.setState({ servicename: v }, () => { let showCustomService = false; this.state.servicename === 'others' ? (showCustomService = true) : (showCustomService = false); this.setState({ ...this.initialValues, servicename: v, showCustomServiceInput: showCustomService, }); }); }; validate = () => { const { startdate, amount, customServiceName, showCustomServiceInput, } = this.state; if ( startdate === '' || amount <= 0 || (showCustomServiceInput && customServiceName === '') ) { this.setState({ isValidForm: false }); let err = { bottomText: 'All fields are mandatory and amount shall be greater than 0', }; this.setState({ errors: err }); } else { this.setState({ isValidForm: true }); this.setState({ errors: {} }); } }; handleSaveButtonClick = () => { const serviceObject = this.serviceOptions.find( (so) => so.value === this.state.servicename ); const { amount, cycle, startdate, customServiceName } = this.state; const savedSubscriptionInfo = { serviceName: serviceObject.displayName, amount, startdate, cycle, id: uuidv4(), }; if (this.state.servicename === 'others') { savedSubscriptionInfo.serviceName = customServiceName; } const { addSubscription } = this.props; addSubscription(savedSubscriptionInfo); this.props.onCancel(); }; render() { const { onCancel } = this.props; const { servicename, cycle, startdate, amount, customServiceName, showCustomServiceInput, isValidForm, errors, fromDate, } = this.state; return ( <form className={Style.formDiv}> <SelectInput name="servicename" label="Service Name" options={this.serviceOptions} onChange={this.handleServiceChange} value={servicename} /> {showCustomServiceInput && ( <Input type="input" label="Enter service name" name="customServiceName" onChange={this.handleChange} value={customServiceName} /> )} <Input type="date" label="Start Date" name="startdate" onChange={this.handleChange} value={startdate} maxValue={fromDate} /> <SelectInput name="cycle" label="Cycle" options={this.billingCycle} onChange={this.handleChange} value={cycle} /> <Input type="number" label="Amount (in Indian Rupees)" name="amount" onChange={this.handleChange} value={amount} /> {!isValidForm && <div className={Style.error}>{errors.bottomText}</div>} <div className={Style.cancelSaveButtonWrapper}> <Button type="button" text="Cancel" customButtonStyle={Style.customButtonStyle} onClick={() => onCancel()} /> <Button type="button" text="Save" customButtonStyle={Style.customButtonStyle} onClick={this.handleSaveButtonClick} disabled={!isValidForm} /> </div> </form> ); } } const mapDispatchToProps = (dispatch) => { return { addSubscription: (subscription) => dispatch(SubscriptionsActions.setSubscription(subscription)), }; }; AddSubscriptionForm.propTypes = { addSubscription: PropTypes.func, onCancel: PropTypes.func, }; export default connect(null, mapDispatchToProps)(AddSubscriptionForm);
import 'package:example/core/remote/dummy_api_client.dart'; import 'package:example/core/remote/model/product.dart'; import 'package:flosha/base/logic/base_object_logic.dart'; import 'package:flosha/base/state/base_object_state.dart'; class ProductDetailLogic extends BaseObjectLogic<Product> { final int? id; ProductDetailLogic(this.id) : super(const BaseObjectState()); double get discountedPrice { final double discountedPrice = (data?.price ?? 0) - ((data?.price ?? 0) * ((data?.discountPercentage ?? 0) / 100)); return discountedPrice; } @override Product? get deserializeFromJson => cache == null ? null : Product.fromJson(cache ?? {}); @override bool get loadFromCache => true; @override void refreshData() { loadData(); } @override Future<void> loadData() async { try { loading(); final result = await DummyApiClient.instance().getSingleProduct(id ?? 0); success(result); } catch (e) { error(errorTitle: "Something went wrong", errorMessage: e.toString()); } } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ import * as t from 'io-ts'; import { CoreSetup, kibanaResponseFactory } from '@kbn/core/server'; import { loggerMock } from '@kbn/logging-mocks'; import { registerRoutes } from './register_routes'; import { routeValidationObject } from './route_validation_object'; import { NEVER } from 'rxjs'; describe('registerRoutes', () => { const get = jest.fn(); const getAddVersion = jest.fn(); const getWithVersion = jest.fn((_options) => { return { addVersion: getAddVersion, }; }); const createRouter = jest.fn().mockReturnValue({ get, versioned: { get: getWithVersion, }, }); const internalOptions = { internal: true, }; const publicOptions = { public: true, }; const internalHandler = jest.fn().mockResolvedValue('internal'); const publicHandler = jest .fn() .mockResolvedValue( kibanaResponseFactory.custom({ statusCode: 201, body: { message: 'public' } }) ); const errorHandler = jest.fn().mockRejectedValue(new Error('error')); const mockLogger = loggerMock.create(); const mockService = jest.fn(); const mockContext = {}; const mockRequest = { body: { bodyParam: 'body', }, query: { queryParam: 'query', }, params: { pathParam: 'path', }, events: { aborted$: NEVER, }, }; beforeEach(() => { jest.clearAllMocks(); const coreSetup = { http: { createRouter, }, } as unknown as CoreSetup; const paramsRt = t.type({ body: t.type({ bodyParam: t.string, }), query: t.type({ queryParam: t.string, }), path: t.type({ pathParam: t.string, }), }); registerRoutes({ core: coreSetup, repository: { internal: { endpoint: 'GET /internal/app/feature', handler: internalHandler, params: paramsRt, options: internalOptions, }, public: { endpoint: 'GET /api/app/feature version', handler: publicHandler, params: paramsRt, options: publicOptions, }, error: { endpoint: 'GET /internal/app/feature/error', handler: errorHandler, params: paramsRt, options: internalOptions, }, }, dependencies: { aService: mockService, }, logger: mockLogger, }); }); it('creates a router and defines the routes', () => { expect(createRouter).toHaveBeenCalledTimes(1); expect(get).toHaveBeenCalledTimes(2); const [internalRoute] = get.mock.calls[0]; expect(internalRoute.path).toEqual('/internal/app/feature'); expect(internalRoute.options).toEqual(internalOptions); expect(internalRoute.validate).toEqual(routeValidationObject); const [errorRoute] = get.mock.calls[1]; expect(errorRoute.path).toEqual('/internal/app/feature/error'); expect(errorRoute.options).toEqual(internalOptions); expect(errorRoute.validate).toEqual(routeValidationObject); expect(getWithVersion).toHaveBeenCalledTimes(1); const [publicRoute] = getWithVersion.mock.calls[0]; expect(publicRoute.path).toEqual('/api/app/feature'); expect(publicRoute.options).toEqual(publicOptions); expect(publicRoute.access).toEqual('public'); expect(getAddVersion).toHaveBeenCalledTimes(1); const [versionedRoute] = getAddVersion.mock.calls[0]; expect(versionedRoute.version).toEqual('version'); expect(versionedRoute.validate).toEqual({ request: routeValidationObject, }); }); it('calls the route handler with all dependencies', async () => { const [_, internalRouteHandler] = get.mock.calls[0]; await internalRouteHandler(mockContext, mockRequest, kibanaResponseFactory); const [args] = internalHandler.mock.calls[0]; expect(Object.keys(args).sort()).toEqual( ['aService', 'request', 'response', 'context', 'params', 'logger'].sort() ); const { params, logger, aService, request, response, context } = args; expect(params).toEqual({ body: { bodyParam: 'body', }, query: { queryParam: 'query', }, path: { pathParam: 'path', }, }); expect(request).toBe(mockRequest); expect(response).toBe(kibanaResponseFactory); expect(context).toBe(mockContext); expect(aService).toBe(mockService); expect(logger).toBe(mockLogger); }); it('wraps a plain route handler result into a response', async () => { const [_, internalRouteHandler] = get.mock.calls[0]; const internalResult = await internalRouteHandler( mockContext, mockRequest, kibanaResponseFactory ); expect(internalHandler).toHaveBeenCalledTimes(1); expect(internalResult).toEqual({ status: 200, payload: 'internal', options: { body: 'internal' }, }); }); it('allows for route handlers to define a custom response', async () => { const [_, publicRouteHandler] = getAddVersion.mock.calls[0]; const publicResult = await publicRouteHandler(mockContext, mockRequest, kibanaResponseFactory); expect(publicHandler).toHaveBeenCalledTimes(1); expect(publicResult).toEqual({ status: 201, payload: { message: 'public' }, options: {} }); }); it('translates errors thrown in a route handler to an error response', async () => { const [_, errorRouteHandler] = get.mock.calls[1]; const errorResult = await errorRouteHandler(mockContext, mockRequest, kibanaResponseFactory); expect(errorHandler).toHaveBeenCalledTimes(1); expect(errorResult).toEqual({ status: 500, payload: { message: 'error', attributes: { data: {} } }, options: {}, }); }); });
import { inject, injectable } from "tsyringe"; import { ISalasRepository } from "../../repositories/interfaces/ISalasRepository"; import { Salas } from "../../entities/Salas"; import { AppError } from "../../../../shared/errors/AppError"; @injectable() class FindSalasByIdUseCase { constructor( @inject("SalasRepository") private salasRepository: ISalasRepository ){} async execute(idSala: number): Promise<Salas> { const salaFound = await this.salasRepository.findById(idSala); if(!salaFound) { throw new AppError("Sala não encontradaa"); } return salaFound; } } export { FindSalasByIdUseCase };
import React, { useState } from 'react'; import { RecipeModel } from '../../models/RecipeModel'; import './SearchForm.css'; interface SearchFormProps { onFormSubmit: (formData: RecipeModel[]) => void; setSearchSuccess: React.Dispatch<React.SetStateAction<boolean>>; } const SearchForm: React.FC<SearchFormProps> = ({ onFormSubmit, setSearchSuccess, }) => { const [query, setQuery] = useState('salad'); const [selectedRecipe, setSelectedRecipe] = useState<RecipeModel | null>( null ); const searchRecipes = async () => { const apiUrl = 'http://localhost:8080/recipes/complexSearch'; const params = { query, limit: '20', instructionsRequired: 'true', addRecipeInformation: 'true', }; const queryString = new URLSearchParams(params).toString(); const url = `${apiUrl}?${queryString}`; console.log(url); try { const response = await fetch(url); const data = await response.json(); console.log(data); const searchResults = data.results || []; console.log(searchResults); onFormSubmit(searchResults); setSearchSuccess(true); } catch (error) { console.error('Error fetching recipes:', error); } }; const handleFormSubmit = (e: React.FormEvent) => { e.preventDefault(); searchRecipes(); }; const handleRecipeClick = (recipe: RecipeModel) => { setSelectedRecipe(recipe); }; return ( <div> <div className="d-flex justify-content-center"> <form onSubmit={handleFormSubmit} className="mb-5 search-bar"> <div className="input-group"> <input type="text" className="form-control" value={query === 'salad' ? '' : query} onChange={(e) => setQuery(e.target.value)} placeholder="Search for recipes..." /> <div className="input-group-append"> <button type="submit" className="btn main-color text-white ml-2" style={{ marginLeft: '10px', }} > Search </button> </div> </div> </form> </div> </div> ); }; export default SearchForm;
"use client"; import React from "react"; import { Tab, TabList, TabPanel, Tabs } from "react-tabs"; import "./AdvanceSearch.css"; import { MdOutlineLocationOn } from "react-icons/md"; import { usePathname } from "next/navigation"; const AdvancedSearch = ({ onclick, className }) => { const pathname = usePathname(); return ( <div className={` relative z-20 ${ pathname === "/car-details" || pathname === "/driver-details" || pathname === "/booking-details" || pathname === "/booking-checkout" ? "lg:-mt-12 " : "lg:-mt-72" } lg:mx-auto text-white lg:p-6 background-search lg:max-w-[860px] lg:h-[278px] ${className} `} > <div className="grid grid-cols-1 lg:grid-cols-3 sm:bg-for-form relative"> <div> {" "} <span className="w-fit ">CHOOSE CATEGORY</span> </div> <div className=""> <Tabs className={""}> <div className=" -translate-y-24 lg:translate-y-0 "> <TabList className={ "flex w-full justify-center gap-4 lg:gap-2 mt-3 bg-[#fff] lg:w-[359px] mb-4 text-white font-medium p-[1px] lg:-translate-x-16 " } > <Tab className={ "bg-[#008080] px-2 lg:px-[23px] py-2 rounded-[5px]" } > {" "} car </Tab> <Tab className={ "bg-[#008080] px-4 lg:px-[23px] py-2 rounded-[5px]" } > Flight </Tab> <Tab className={ "bg-[#008080] px-4 lg:px-[23px] py-2 rounded-[5px]" } > Hotel </Tab> <Tab className={ "bg-[#008080] px-4 lg:px-[23px] py-2 rounded-[5px]" } > Boat </Tab> </TabList> </div> <div className=""> <TabPanel className={"flex justify-center"}> <div className="w-full relative lg:absolute left-0 p-3"> {/* div one */} <div className=" grid grid-cols-2 gap-4 space-y-2 lg:grid-cols-3 "> <div className="relative"> <span className="mb-4 inline-block">From</span> <input type="text" placeholder="Your loacation" className="input input-bordered w-full text-black px-10 max-w-xs " /> <MdOutlineLocationOn className="absolute text-xl text-black top-2/4 left-4" /> </div> <div className="relative"> <span className="mb-2 inline-block">To</span> <input type="text" placeholder="Your loacation" className="input text-black input-bordered w-full px-10 max-w-xs " /> <MdOutlineLocationOn className="absolute text-xl text-black top-2/4 left-4" /> </div> <div className="relative col-span-2 lg:col-span-1"> <span className="mb-2 inline-block">Choose Your Car</span> <input type="text" placeholder="Your loacation" className="input text-black input-bordered w-full md:px-10 " /> <MdOutlineLocationOn className="absolute text-xl text-black top-2/4 left-4" /> </div> </div> {/*======== 2nd div========= */} <div className="grid grid-cols-2 lg:grid-cols-6 gap-3"> <div> <span className="block "> No of Luggage</span> <input type="text" placeholder="Type here" className="input text-black input-bordered w-full max-w-xs" /> </div> <div> <span className="block "> Pick-Up Date</span> <input type="text" placeholder="Type here" className="input text-black input-bordered w-full max-w-xs" /> </div> <div className=""> <span className="block "> Passenger</span> <input type="text" placeholder="Type here" className="input text-black input-bordered w-full max-w-xs" /> </div> <div> <span className="block "> Passenger</span> <select className="select select-bordered text-black w-full max-w-xs"> <option disabled selected> Who shot first? </option> <option>Han Solo</option> <option>Greedo</option> </select> </div> <div className="flex gap-2 pt-7"> <button onClick={onclick} className="btn bg-[#008080] hover:bg-green-600 btn-md z-10 px-10 py-3 text-white btn-outline" > Book Now </button> <button onClick={onclick} className="btn bg-[#008080] hover:bg-green-600 btn-md z-10 px-0 py-3 w-[95px] text-white btn-outline" > Search Now </button> </div> </div> </div> </TabPanel> <TabPanel> <h2>Any content 2</h2> </TabPanel> <TabPanel> <h2>Any content 1</h2> </TabPanel> <TabPanel> <h2>Any content 2</h2> </TabPanel> </div> </Tabs> </div> {/* raido butoon */} <div className="flex flex-col gap-1 pl-12 lg:flex-row "> <div className="form-control"> <label className="label cursor-pointer"> <span className="label-text text-white">One way</span> <input type="radio" name="radio-10" className="radio checked:bg-red-500" checked /> </label> </div> <div className="form-control "> <label className="label cursor-pointer"> <span className="label-text text-white">Round Tip</span> <input type="radio" name="radio-10" className="radio checked:bg-red-500" checked /> </label> </div> </div> </div> </div> ); }; export default AdvancedSearch;
/* ** Copyright 2012-2021 Double Precision, Inc. ** See COPYING for distribution information. */ #ifndef x_yaml_parserobj_H #define x_yaml_parserobj_H #include <x/namespace.h> #include <x/exception.H> #include <x/yaml/document.H> #include <iterator> #include <iostream> #include <list> namespace LIBCXX_NAMESPACE::yaml { #if 0 } #endif //! Parse a YAML document. class parserObj : virtual public obj { public: //! Base class for implementing read handler callback from libyaml. //! \internal class read_handler_base { public: //! Implement the read request. virtual int read(unsigned char *buffer, size_t size, size_t *size_read)=0; //! An exception was caught bool caught_exception_flag; //! An exception that got caught inside the C callback from yaml gets rethrown here exception caught_exception; //! Constructor read_handler_base() : caught_exception_flag(false) {} }; private: //! Read handler callback, read from an input iterator sequence template<typename iter_type> class read_handler : public read_handler_base { public: //! Current iterator iter_type b; //! Ending iterator value iter_type e; //! Constructor read_handler(const iter_type &bArg, const iter_type &eArg) : b(bArg), e(eArg) { } //! Implement the callback from libyaml int read(unsigned char *buffer, size_t size, size_t *size_read) override { *size_read=0; try { while (b != e && size) { *buffer++ = *b; ++b; --size; ++*size_read; } } catch (const x::exception &e) { caught_exception=e; caught_exception_flag=true; } return 1; } }; public: //! The constructor puts parsed documents here. std::list<document> documents; //! Constructor, parse a YAML file from an arbitrary input sequence. template<typename iter_type> parserObj(iter_type b, iter_type e) { read_handler<iter_type> handler(b, e); parse(handler); } //! Destructor ~parserObj(); private: //! Internal parser implementation void parse(read_handler_base &b); //! Internal parser implementation //! \internal void parse(read_handler_base &b, yaml_parser_t &parser) LIBCXX_INTERNAL; }; //! Specialized implementation that uses the const_iterator-based implemenation template<> parserObj::parserObj(std::string::iterator, std::string::iterator); #ifndef DOXYGEN extern template class parserObj::read_handler<std::string::const_iterator>; extern template class parserObj::read_handler<std::istreambuf_iterator<char> >; extern template parserObj::parserObj(std::string::const_iterator, std::string::const_iterator); extern template parserObj::parserObj(std::istreambuf_iterator<char>, std::istreambuf_iterator<char>); #endif #if 0 { #endif } #endif
using System.Buffers.Binary; using System.Runtime.CompilerServices; namespace Nasdaq.MarketDepth { /// <summary> /// New Reference Number Delta: The new reference number delta associated with the new order. /// </summary> public struct NewReferenceNumberDelta { /// <summary> /// Size of New Reference Number Delta in bytes /// </summary> public const int Size = 4; /// <summary> /// New Reference Number Delta value /// </summary> public readonly uint Value => Decode(); /// <summary> /// Read New Reference Number Delta /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly uint Decode() => BinaryPrimitives.ReverseEndianness(Underlying); /// <summary> /// Write New Reference Number Delta /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Encode(uint value) => Underlying = BinaryPrimitives.ReverseEndianness(value); /// <summary> /// Set New Reference Number Delta to unused /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() => Encode(NoValue); /// <summary> /// New Reference Number Delta as string /// </summary> public readonly override string ToString() => $"{Value}"; /// <summary> /// Underlying bytes /// </summary> internal uint Underlying; } }
# 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 2 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. # # Author: Jeffersson Abreu (ctw6av) from structures.input import InputEvent from events.interfaces import Observer from typing import AnyStr, Dict, List import networking.communication import constants.globals import devices.physical import constants.ecodes import configparser import asyncio import os class EventSender(Observer): """ Send all events that occurs to the client in focus at the moment. """ def __init__(self, *args, **kwargs): Observer.__init__(self, *args, **kwargs) # Networking events handler self.events = networking.communication.Events() self._identification = None self._transport = None def run(self) -> None: while True: data = self.queue.get() who, event = data.values() if who == 'PhysicalDevice': if self._identification is not 'StrinoServer' and self._identification is not None: evt = self.events.generate("DEVICE_EVENT", event) self._transport.write(evt) if who == 'FocusEvents': self._identification = event.get('identification') self._transport = event.get('transport') class ShortcutListener(Observer): """ Listen to events and try to match the keyboard shortcuts and notify all observers attached """ def __init__(self, *args, **kwargs): Observer.__init__(self, *args, **kwargs) # Open shortcuts settings and load all of then self.path = os.path.join(constants.globals.BASE_DIR, 'etc/shortcuts.ini') shortcuts = configparser.ConfigParser() shortcuts.read(self.path) # Get all modifiers and map all shortcuts self.modifiers = self.get_all_modifiers(shortcuts) self.shortcuts = self.map(shortcuts) self.event = None self.modifier = 0 @staticmethod def get_all_modifiers(shortcuts): """ Get all modifiers in shortcuts :param shortcuts: Shortcuts read with configparser :return: A set containing modifiers keys """ modifiers = set() for name in shortcuts: if name is not "DEFAULT": event = shortcuts[name] modifier = event.getint('modifier') modifiers.add(modifier) return modifiers @staticmethod def map(shortcuts) -> dict: """ Map all shortcuts and generalize then to be readable as events. The default shortcut in shortcuts.ini sims like: [SHORTCUT_NAME] modifier = 29 left = 105 This functions map the shortcuts to something like: '29 105': 'SHORTCUT_NAME' :param shortcuts: Shortcuts read with configparser :return: dict of mapped shortcuts """ events = dict() for name in shortcuts: if name is not "DEFAULT": shortcut = shortcuts[name] event = ' '.join(shortcut.get(key) for key in shortcut) events[event] = name return events def run(self) -> None: while True: data = self.queue.get() who, event = data.values() if who == "PhysicalDevice": data = event.get('data') for evt in data: ie = InputEvent.from_buffer_copy(evt) if ie.type == constants.ecodes.EV_KEY: # In case of the key pressed is an modifier if ie.code in self.modifiers: if ie.value: # Pressing self.modifier = ie.code continue # Releasing self.modifier = 0 # We just propagate the shortcut event # when the modifier key is released to # prevent bug that stuck devices if self.event: event = self.event self.notify(event) self.event = None continue if self.modifier: # A modifier is pressed if not ie.value: # The key is being released # Generate a key name as in "map" function defined above keys = [str(self.modifier), str(ie.code)] shortcut = ' '.join(keys) # Check if shortcut name is in # mapped shortcuts list if shortcut in self.shortcuts: # Set the shortcut event to be sent on modifier key release self.event = {'name': self.shortcuts[shortcut]} class FocusEvents(Observer): """ Keep references of clients and notify all observers attached about changes """ def __init__(self, *args, **kwargs): Observer.__init__(self, *args, **kwargs) # Define the clients data type self._clients: Dict[AnyStr, asyncio.BaseTransport] = {} # Generate the default identification and # pass it as default to the _client self.default_identification = "StrinoServer" self._focus = self.default_identification # Register the default identification key and transport self._clients[self.default_identification] = asyncio.BaseTransport() constants.globals.logger.info(f"Added {self.default_identification} as default focus") def register(self, name: AnyStr, transport: asyncio.BaseTransport): """ Register a client to send events """ self._clients[name] = transport constants.globals.logger.info(f"Added {name} to sender list") def forget(self, name: AnyStr): """ Remove a client from list of clients """ if name in self._clients: constants.globals.logger.info(f"Removing {name} from sender list") self._clients.pop(name) self.to_last_client() def to_last_client(self): """ Change the focus to the last client """ if len(self._clients): identifications = list(self._clients.keys()) identification = identifications[-1] self._focus = identification constants.globals.logger.info(f"Focus moved to {self._focus}") self.notify({ 'identification': self._focus, 'transport': self._clients.get(self._focus) }) def to_left(self): """ Change the focus to left """ names = list(self._clients.keys()) position = names.index(self._focus) - 1 if position >= 0: try: self._focus = names[position] constants.globals.logger.info(f"Focus moved to {self._focus}") self.notify({ 'identification': self._focus, 'transport': self._clients.get(self._focus) }) except (ValueError, IndexError): pass def to_right(self): """ Change the focus to left """ names = list(self._clients.keys()) position = names.index(self._focus) + 1 if position <= len(self._focus): try: self._focus = names[position] constants.globals.logger.info(f"Focus moved to {self._focus}") self.notify({ 'identification': self._focus, 'transport': self._clients.get(self._focus) }) except (ValueError, IndexError): pass def run(self) -> None: while True: data = self.queue.get() who, event = data.values() if who == "ShortcutListener": shortcut = event.get('name') if shortcut == "FOCUS_SWITCH_RIGHT": self.to_right() if shortcut == "FOCUS_SWITCH_LEFT": self.to_left() class Grabber(Observer): """ Grab devices based on focus """ def __init__(self, *args, **kwargs): Observer.__init__(self, *args, **kwargs) self._devices: List[devices.physical.PhysicalDevice] = [] def get_devices(self) -> List[devices.physical.PhysicalDevice]: """ Return a list of devices we are watching for grab """ return self._devices def add_device(self, device: devices.physical.PhysicalDevice) -> None: """ Add devices to internal devices list :param device: PhysicalDevice instance :return: None """ self._devices.append(device) return None def release_all(self): """ Release all devices in internal list """ constants.globals.logger.info("Releasing all devices") for device in self._devices: if device.is_grabbed: device.release() def grab_all(self): """ Grab all devices in internal list """ constants.globals.logger.info("Grabbing all devices") for device in self._devices: if not device.is_grabbed: device.grab() def run(self) -> None: while True: data = self.queue.get() who, event = data.values() if who == 'FocusEvents': if event.get('identification') == 'StrinoServer': self.release_all() continue self.grab_all()
// // PushingNewViewsOntoStackUsingNavigationLink.swift // Moonshot // // Created by Brandon Johns on 11/30/23. // import SwiftUI struct PushingNewViewsOntoStackUsingNavigationLink: View { var body: some View { NavigationStack { NavigationLink { Text("Detail View") } label: { VStack { Text("This is the label") Text("so is this") Image(systemName: "face.smiling") } .font(.largeTitle) } List(0..<100){ row in NavigationLink("Row \(row)") { Text("Detail \(row)") } } .navigationTitle("SwiftUI") } } } #Preview { PushingNewViewsOntoStackUsingNavigationLink() }
// ignore_for_file: prefer_function_declarations_over_variables import 'package:flutter/widgets.dart'; import 'package:go_router/go_router.dart'; import 'package:poloniex_app/features/auth/presentation/screens/auth_screen.dart'; import 'package:poloniex_app/features/bootup/splash_screen.dart'; import 'package:poloniex_app/features/trade/presentation/screens/trade_screen.dart'; /// An abstract interface class representing a route. abstract interface class _Route { final String path; final String name; final Widget Function(BuildContext context, GoRouterState state) builder; _Route(this.path, this.name, this.builder); } /// A class representing an splash route. class SplashRoute implements _Route { @override final Widget Function(BuildContext context, GoRouterState state) builder = (context, state) => const SplashScreen(); @override final String name = 'splash'; @override final String path = '/'; /// Returns the path of the splash route. String get splashRoutePath => path; /// Returns the name of the splash route. String get splashRouteName => name; /// Returns the builder function for the splash route. Widget Function(BuildContext context, GoRouterState state) get splashRouteBuilder => builder; } /// A class representing an authentication route. class AuthRoute implements _Route { @override final Widget Function(BuildContext context, GoRouterState state) builder = (context, state) => const AuthScreen(); @override final String name = 'auth'; @override final String path = '/auth'; /// Returns the path of the authentication route. String get authRoutePath => path; /// Returns the name of the authentication route. String get authRouteName => name; /// Returns the builder function for the authentication route. Widget Function(BuildContext context, GoRouterState state) get authRouteBuilder => builder; } /// A class representing a home route. class HomeRoute implements _Route { @override final Widget Function(BuildContext context, GoRouterState state) builder = (context, state) => const TradeScreen(); @override final String name = 'home'; @override final String path = '/home'; /// Returns the path of the home route. String get homeRoutePath => path; /// Returns the name of the home route. String get homeRouteName => name; /// Returns the builder function for the home route. Widget Function(BuildContext context, GoRouterState state) get homeRouteBuilder => builder; }
<!-- Sidebar start --> Step 1 Your info Step 2 Select plan Step 3 Add-ons Step 4 Summary <!-- Sidebar end --> <!-- Step 1 start --> Personal info Please provide your name, email address, and phone number. Name e.g. Stephen King Email Address e.g. stephenking@lorem.com Phone Number e.g. +1 234 567 890 Next Step <!-- Step 1 end --> <!-- Step 2 start --> Select your plan You have the option of monthly or yearly billing. Arcade $9/mo Advanced $12/mo Pro $15/mo Monthly Yearly Go Back Next Step <!-- Step 2 end --> <!-- Step 3 start --> Pick add-ons Add-ons help enhance your gaming experience. Online service Access to multiplayer games +$1/mo Larger storage Extra 1TB of cloud save +$2/mo Customizable Profile Custom theme on your profile +$2/mo Go Back Next Step <!-- Step 3 end --> <!-- Step 4 start --> Finishing up Double-check everything looks OK before confirming. <!-- Dynamically add subscription and add-on selections here --> Total (per month/year) Go Back Confirm <!-- Step 4 end --> <!-- Step 5 start --> Thank you! Thanks for confirming your subscription! We hope you have fun using our platform. If you ever need support, please feel free to email us at support@loremgaming.com. <!-- Step 5 end --> <div id="root" class="personal"> <label for="name">Name</label> <input type="text" id="name" placeholder="e.g. Stephen King" > <label for="email">Email Address</label> <input type="email" name="email" id="email" placeholder="e,g, stephenking@lorem.com"> <label for="phone--number">Phone Number</label> <input type="tel" name="tel" id="phone--number" placeholder="e.g. +1 234 567 890"> </div> <div id="root" class="plan--choice"> <div class="plan arcade" onclick="choosePlan(0)"> <img src="./assets/images/icon-arcade.svg" alt=""> <div class="plan--info"> <p class="plan--name">Arcade</p> <p class="cost">$9/mo</p> </div> </div> <div class="plan advanced" onclick="choosePlan(1)"> <img src="./assets/images/icon-advanced.svg" alt=""> <div class="plan--info"> <p class="plan--name">Advanced</p> <p class="cost">$12/mo</p> </div> </div> <div class="plan pro" onclick="choosePlan(2)"> <img src="./assets/images/icon-pro.svg" alt=""> <div class="plan--info"> <p class="plan--name">Pro</p> <p class="cost">$15/mo</p> </div> </div> <div class="monYear"> <p class="choseTime">Monthly</p> <div class="toggle" onclick="handleDurationChange()"> <div class="toggleBar"></div> </div> <p>Yearly</p> </div> </div> <div id="root" class="add--ons"> <div class="online--service" onclick="choseAddon(0)"> <div class="addon--checkbox"> <input type="checkbox"> <span class="checkmark"></span> </div> <div class="add--ons--info"> <p class="addon--name">Online Service</p> <p class="addon--desc">Access to multiplayer games</p> </div> <p class="addon--cost">+1$/mo</p> </div> <div class="larger--storage" onclick="choseAddon(1)"> <div class="addon--checkbox"> <input type="checkbox"> <span class="checkmark"></span> </div> <div class="add--ons--info"> <p class="addon--name">Larger Storage</p> <p class="addon--desc">Extra 1TB of cloud save</p> </div> <p class="addon--cost">+2$/mo</p> </div> <div class="custom--profile" onclick="choseAddon(2)"> <div class="addon--checkbox"> <input type="checkbox"> <span class="checkmark"></span> </div> <div class="add--ons--info"> <p class="addon--name">Customizable Profile</p> <p class="addon--desc">Custom theme on your profile</p> </div> <p class="addon--cost">+2$/mo</p> </div> </div> <div id="root" class="summary"> <div class="choice--preview"> <div class="choice--list"> <div class="choice"> <p class="type--name">Arcade (Monthly)</p> <p class="change">Change</p> </div> <p class="cost">$9/mo</p> </div> <hr> <div class="choice--list"> <p class="addon--service">Online service</p> <p class="cost">$1/mo</p> </div> <div class="choice--list"> <p class="addon--service">Larger Storage</p> <p class="cost">$2/mo</p> </div> </div> <div class="total"> <p class="total--name">Total (Per Month)</p> <p class="cost">$12/mo</p> </div> </div> <form action="#"> <h1>Personal info</h1> <p id="form--desc">Please provide your name, email address, and phone number.</p> <div class="nav--button"> <button onclick="pageChange(-1)" class="go--back">Go Back</button> <button onclick="pageChange(1)" class="next--step">Next Step</button> <button type="submit" onclick="handleSubmit()">Confirm</button> </div> </form> <div class="thanks"> <img src="./assets/images/icon-thank-you.svg" alt=""> <p class="thank--you">Thank you!</p> <p class="thank--desc">Thanks for confirming your subscription! We hope you have fun using our platform. If you ever need support, please feel free to email us at support@loremgaming.com.</p> </div>
import Head from "next/head"; import Image from "next/image"; import { useState, useEffect, useContext } from "react"; import classes from "@/styles/Home.module.scss"; import TechStackList from "@/components/techStackList/TechStackList"; import { techStackList } from "@/pages/api/projectList"; import LanguageContext from "@/context/LangContext"; function HomePage() { const { selectedLanguage } = useContext(LanguageContext); const [isAnimated, setIsAnimated] = useState(false); const [techDescText, setTechDescText] = useState(""); const homePageLanguage = selectedLanguage.homePage; useEffect(() => { setIsAnimated(true); }, []); return ( <> <Head> <title>Portfolio - Hubert Paprocki</title> </Head> <main className={classes.main}> <div className={classes.mainWrapper}> <section className={`${classes.left} ${ isAnimated && classes.animationSlideFromLeft }`} > <h1 className={classes.heading}> <em> {homePageLanguage.title[0]}{" "} <span className={classes.headingSpan}> Hubert<span className={classes.headingSpanAfter}>Hubert</span> </span> {homePageLanguage.title[1]} </em> </h1> </section> <div className={classes.imgWrapper}> <Image src="/images/me.jpg" fill alt="me, the dev" className={`${classes.img} ${ isAnimated && classes.animationSlideFromLeft }`} /> </div> </div> <section> <TechStackList animation={isAnimated} techStack={techStackList} setTechDescText={setTechDescText} small /> {techDescText && ( <p className={classes.techStackDesc}>{techDescText}</p> )} </section> </main> </> ); } export default HomePage;
import { createSlice } from '@reduxjs/toolkit'; export const applicationSlice = createSlice({ name: 'application', initialState: { name: '', email: '', level: '', department: '', image: '', schoolId: '', bio: '', experience: '', availability: '', courses: [], additionalInfo: '', isSubmitting: false, submitError: null, submitSucessState: false, }, reducers: { setField: (state, action) => { state[action.payload.field] = action.payload.value; }, startSubmitting: (state) => { state.isSubmitting = true; state.submitError = null; }, submitSuccess: (state) => { state.isSubmitting = false; state.submitSucessState = true; // Reset form fields state.name = ''; state.email = ''; state.level = ''; state.department = ''; state.image = ''; state.schoolId = ''; state.bio = ''; state.experience = ''; state.availability = ''; state.courses = []; state.additionalInfo = ''; }, submitError: (state, action) => { state.isSubmitting = false; state.submitError = action.payload; }, }, }); export const { setField, startSubmitting, submitSuccess, submitError } = applicationSlice.actions; export default applicationSlice.reducer;
<?php namespace App\Http\Controllers; use App\Models\Post; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Http\Requests\CreatePostRequest; use App\Http\Services\PostService; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $posts = Post::all(); return view("pages/ui/index",compact('posts')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CreatePostRequest $request, PostService $service) { $service->store($request->all()); return redirect()->back()->with('success', 'Post created successfully.'); } /** * Display the specified resource. * * @param \App\Models\Post $post * @return \Illuminate\Http\Response */ public function show($id) { $post = Post::find($id); return view("pages/ui/view",compact('post')); } /** * Show the form for editing the specified resource. * * @param \App\Models\Post $post * @return \Illuminate\Http\Response */ public function edit($id) { $post = Post::find($id); return view("pages/ui/edit",compact('post')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Post $post * @return \Illuminate\Http\Response */ public function update(Request $request, PostService $service) { $posts = $service->update($request); return view("pages/ui/index",compact('posts')); } /** * Remove the specified resource from storage. * * @param \App\Models\Post $post * @return \Illuminate\Http\Response */ public function destroy(Request $request,PostService $service) { $posts = $service->delete($request); return view("pages/ui/index",compact('posts')); } }
import styled from "@emotion/styled"; import React from "react"; import SizedBox from "@components/SizedBox"; import TokenInput from "@components/TokenInput"; import SwapDetailRow from "@components/SwapDetailRow"; import Divider from "@src/components/Divider"; import Card from "@components/Card"; import { Observer } from "mobx-react-lite"; import SwitchTokensButton from "@screens/TradeInterface/SwitchTokensButton"; import SwapButton from "@screens/TradeInterface/SwapButton"; import { ReactComponent as ArrowIcon } from "@src/assets/icons/arrowRightBorderless.svg"; import Layout from "@components/Layout"; import { TradeVMProvider, useTradeVM } from "@screens/TradeInterface/TradeVM"; import { useNavigate } from "react-router-dom"; import { Row } from "@components/Flex"; import Text from "@components/Text"; import Tooltip from "@components/Tooltip"; import { ReactComponent as InfoIcon } from "@src/assets/icons/info.svg"; import { ReactComponent as ShowMoreIcon } from "@src/assets/icons/showMore.svg"; import RoutingModal from "@screens/TradeInterface/RoutingModal"; import Details from "./Details"; import TooltipFeeInfo from "@screens/TradeInterface/TooltipFeeInfo"; import { useStores } from "@stores"; const Root = styled.div` display: flex; flex-direction: column; align-items: center; justify-content: center; box-sizing: border-box; padding: 0 16px; min-width: 100%; min-height: 100%; margin-bottom: 24px; margin-top: 40px; @media (min-width: 880px) { margin-top: 56px; } `; const TradeInterfaceImpl: React.FC = () => { const { notificationStore } = useStores(); const vm = useTradeVM(); const navigate = useNavigate(); const handleSetAssetId0 = (assetId: string) => { if (assetId === vm.assetId1) { notificationStore.notify("You can't choose same assets", { type: "error", title: "Warning", }); return; } const urlSearchParams = new URLSearchParams(window.location.search); urlSearchParams.set("asset0", assetId); navigate({ pathname: window.location.pathname, search: `?${urlSearchParams.toString()}`, }); vm.setAssetId0(assetId); }; const handleSetAssetId1 = (assetId: string) => { if (assetId === vm.assetId0) { notificationStore.notify("You can't choose same assets", { type: "error", title: "Warning", }); return; } const urlSearchParams = new URLSearchParams(window.location.search); urlSearchParams.set("asset1", assetId); navigate({ pathname: window.location.pathname, search: `?${urlSearchParams.toString()}`, }); vm.setAssetId1(assetId); }; return ( <Layout> <Observer> {() => ( <Root> <Card paddingDesktop="32px" maxWidth={560}> <TokenInput decimals={vm.token0.decimals} amount={vm.amount0} setAmount={vm.setAmount0} assetId={vm.assetId0} setAssetId={handleSetAssetId0} balances={vm.balances} onMaxClick={vm.amount0MaxClickFunc} selectable /> <SwitchTokensButton /> <TokenInput decimals={vm.token1.decimals} amount={vm.amount1} assetId={vm.assetId1} setAssetId={handleSetAssetId1} balances={vm.balances} selectable /> <SizedBox height={24} /> <SwapButton /> <SizedBox height={16} /> <SwapDetailRow title="Route"> <Row alignItems="center" mainAxisSize="fit-content" justifyContent="flex-end" style={{ cursor: "pointer" }} onClick={() => vm.setRoutingModalState(true)} > {vm.simpleRoute != null ? vm.simpleRoute.map((symbol, i) => ( <React.Fragment key={i}> <Text style={{ lineHeight: 0 }}>{symbol}&nbsp;</Text> {i !== vm.simpleRoute!.length - 1 && ( <ArrowIcon style={{ minWidth: 16 }} /> )} </React.Fragment> )) : "—"} &nbsp; <ShowMoreIcon style={{ minWidth: 16, cursor: "pointer" }} /> </Row> </SwapDetailRow> <Divider /> <SwapDetailRow title="Price impact"> <Row alignItems="center" mainAxisSize="fit-content" justifyContent="flex-end" > {vm.priceImpact && ( <Text>~{vm.priceImpact.toFormat(4)}%&nbsp;</Text> )} {vm.token0 && !vm.amount0.isNaN() && ( <Tooltip content={<TooltipFeeInfo />} config={{ placement: "top", trigger: "click" }} > <InfoIcon /> </Tooltip> )} </Row> </SwapDetailRow> </Card> <SizedBox height={16} /> <Details /> <RoutingModal visible={vm.routingModalOpened} onClose={() => vm.setRoutingModalState(false)} /> </Root> )} </Observer> </Layout> ); }; const TradeInterface: React.FC = () => ( <TradeVMProvider> <TradeInterfaceImpl /> </TradeVMProvider> ); export default TradeInterface;
import React,{Suspense, lazy} from 'react'; import {Route, Link, Switch} from 'react-router-dom'; import ErrorBoundary from '../components/ErrorBoundary'; /** * difference between router component pros and reder pros: * component prop: component create new instance of the component and it will go through the * lifecycle constructor, componentWillmount, componentDidMount. * So if we goto next and prev it will mounted, unmounted and again mounted. * Ex:<Route path="/:locale/store"> <Store /> //calling as new component. </Route> * render prop: it will call as function and it did not create any new instances * of component. if component instance already created then it will just return that * comopnent. EX. * <Route path="/:locale/store"> {Store()}//calling as function </Route> */ const DynamicRouters = () => { const Home = lazy(() => import('../containers/Home')); const LiveChart = lazy(() => import('../containers/LiveChart')); const PageNotFound = lazy(() => import('../components/PageNotFound')); const routes = <div className='router-container'> <ul> <li> <Link to='/'>Home/Overview</Link> </li> <li> <Link to='/livechart'>Live Chart</Link> </li> </ul> <ErrorBoundary> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route exact path='/' component={Home}/> <Route exact path='/livechart' component={LiveChart}/> <Route component={PageNotFound}/> </Switch> </Suspense> </ErrorBoundary> </div> return(routes) } export default DynamicRouters
import logging import re import yaml class FrontmatterApi: def __init__(self, fs_api): self._fs_api = fs_api self._yaml_frontmatter_regex = r"^---([\s\S]+?)---" def get_yaml_frontmatter(self, file): file_content = self._fs_api.read_file(file) matches = re.findall(self._yaml_frontmatter_regex, file_content) if matches: yaml_string = matches[0] metadata = yaml.safe_load(yaml_string) if "tags" in metadata and isinstance(metadata["tags"], str): metadata["tags"] = metadata["tags"].split() return metadata def write_yaml_frontmatter(self, file, yaml_dict): file_content = self._fs_api.read_file(file) new_yaml_string = yaml.safe_dump(yaml_dict).strip() matches = re.findall(self._yaml_frontmatter_regex, file_content) if matches: yaml_string = matches[0].strip() new_content = file_content.replace(yaml_string, new_yaml_string) else: new_content = f"---\n{new_yaml_string}\n---\n{file_content}" self._fs_api.write_file(file, new_content) def update_yaml_frontmatter(self, file, attr, value): logging.info(f"Updating {attr} in frontmatter of {file} to {value}") yaml_frontmatter = self.get_yaml_frontmatter(file) yaml_frontmatter[attr] = value self.write_yaml_frontmatter(file, yaml_frontmatter) def get_yaml_value_from_str(self, yaml_str): return yaml.safe_load(yaml_str) def remove_yaml_attr(self, file, attr): yaml_frontmatter = self.get_yaml_frontmatter(file) if attr in yaml_frontmatter: del yaml_frontmatter[attr] self.write_yaml_frontmatter(file, yaml_frontmatter) else: logging.warning(f"Attribute {attr} not found in frontmatter of {file}")
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { Router, ActivatedRoute } from '@angular/router'; import { MatSnackBar } from '@angular/material'; import { FormBuilder } from '@angular/forms'; import { of } from 'rxjs'; import { TextMaskModule } from 'angular2-text-mask'; import { AuthSharedModule } from '../../../../../shared/auth-shared.module'; import { DeliveryRouteDetailComponent } from './delivery-route-detail.component'; import { AlertService } from '../../../../../shared/services/alert.service'; import { DataApiService } from '../../../services/data-api.service'; describe('DeliveryRouteDetailComponent', () => { const testRoute = { id: '1000', description: 'test Route', driverName: 'Test Driver', driverPhone: '1111111111' }; let component: DeliveryRouteDetailComponent; let fixture: ComponentFixture<DeliveryRouteDetailComponent>; beforeEach(async(() => { const route = ({ data: of({ route: testRoute} ), snapshot: {} } as any) as ActivatedRoute; TestBed.configureTestingModule({ declarations: [ DeliveryRouteDetailComponent ], imports: [ NoopAnimationsModule, AuthSharedModule, RouterTestingModule, TextMaskModule], providers: [ { provide: ActivatedRoute, useValue: route }, FormBuilder, { provide: MatSnackBar, useValue: jasmine.createSpyObj('MatSnackBar', ['open']) }, { provide: DataApiService, useValue: jasmine.createSpyObj('DataApiService', ['upsert', 'destroyById']) }, { provide: AlertService, useValue: jasmine.createSpyObj('AlertService', ['confirm', 'alertSuccess']) } ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DeliveryRouteDetailComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
import PropTypes from 'prop-types'; // material import { visuallyHidden } from '@material-ui/utils'; import { Box, TableRow, TableCell, TableHead, TableSortLabel } from '@material-ui/core'; // ---------------------------------------------------------------------- UserListHead.propTypes = { order: PropTypes.oneOf(['asc', 'desc']), orderBy: PropTypes.string, headLabel: PropTypes.array, onRequestSort: PropTypes.func }; export default function UserListHead({ order, orderBy, headLabel, onRequestSort }) { const createSortHandler = (event) => { onRequestSort(event); }; return ( <TableHead> <TableRow> {headLabel.map((headCell) => ( <TableCell key={headCell.id} align={headCell.alignRight ? 'right' : 'center'} sortDirection={headCell.id === 'createdAt' ? order : false} > <TableSortLabel hideSortIcon={headCell.id !== 'createdAt'} active={headCell.id === 'createdAt'} direction={headCell.id === 'createdAt' ? order : 'asc'} onClick={() => (headCell.id === 'createdAt' ? createSortHandler(headCell.id) : '')} > {headCell.label} {orderBy === headCell.id ? ( <Box sx={{ ...visuallyHidden }}> {order === 'desc' ? 'sorted descending' : 'sorted ascending'} </Box> ) : null} </TableSortLabel> </TableCell> ))} </TableRow> </TableHead> ); }
import { Injectable } from '@angular/core'; export interface Growl { message: string; type: string; } export interface GrowlHandler { handle(growl: Growl): void } @Injectable({ providedIn: 'root' }) export class GrowlService { handlers: Function[] = []; constructor() { } subscribe(handler: Function): void { this.handlers.push(handler); } notify(growl: Growl): void { this.handlers.forEach(handler => handler(growl)); } }
const mongoose = require('mongoose'); const express = require('express'); const cors = require('cors'); const dotenv = require("dotenv"); const promMid = require("express-prometheus-middleware"); dotenv.config(); const app = express(); // CORS options const corsOptions = { credentials: true, origin: ['https://inote.hirentimbadiya.me', 'http://localhost:3000'] }; app.use(cors(corsOptions)); app.options('*', cors(corsOptions)); app.use(express.json()); const mongoURI = process.env.MONGODB_URI; mongoose.set("strictQuery", false); mongoose.connect(mongoURI).then(() => { console.log("Database Connected!"); }).catch((error) => { console.log("Error connecting to database: ", error); }); app.use( promMid({ metricsPath: "/metrics", collectDefaultMetrics: true, requestDurationBuckets: [0.1, 0.5, 1, 1.5], requestLengthBuckets: [512, 1024, 5120, 10240, 51200, 102400], responseLengthBuckets: [512, 1024, 5120, 10240, 51200, 102400], }) ); app.get('/', (req, res) => { res.send('Server is Up and Running!') }); app.use('/api/auth', require('./routes/auth')); app.use('/api/notes', require('./routes/notes')); const port = process.env.PORT || 3001; app.listen(port, () => { console.log(`iNotebook Backend listening on port ${port}`) });
import { useState, useContext } from "react"; import "../SignUp/index.css"; import { Link } from "react-router-dom"; import { AuthContext } from "../../contexts/auth"; export default function SignIn() { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const { signIn, loadingAuth } = useContext(AuthContext); async function handleSignIn(e) { e.preventDefault(); if (email !== "" && password !== "") { await signIn(email, password); } } return ( <div className="body"> <form onSubmit={handleSignIn} id="form"> <h1 className="title">Entrar</h1> <label>Email</label> <input className="input" type="text" placeholder="email@email.com" value={email} onChange={(e) => setEmail(e.target.value)} /> <label>Password</label> <input className="input" type="password" placeholder="********" value={password} onChange={(e) => setPassword(e.target.value)} /> <button type="submit" id="btn"> {loadingAuth ? "Carregando..." : "Acessar"} </button> <Link to="/register" className="link"> Criar uma conta </Link> </form> </div> ); }
import { FC } from 'react' import { addProduct, subProduct } from '@/slices/cartSlice' import { useAppDispatch } from '@/hooks' import { IProduct } from '@/services' import { Button, Container, CounterDisplay } from './styles' interface ICounterProps { product: IProduct quantity: number } export const CounterControl: FC<ICounterProps> = ({ product, quantity }) => { const dispatch = useAppDispatch() const isSubButtonDisabled = quantity <= 1 const handleAddProduct = () => { dispatch(addProduct(product)) } const handleSubProduct = () => { if (!isSubButtonDisabled) { dispatch(subProduct(product.id)) } } return ( <Container> <Button onClick={handleSubProduct} disabled={isSubButtonDisabled}> - </Button> <CounterDisplay data-testid="quantity-id">{quantity}</CounterDisplay> <Button onClick={handleAddProduct}>+</Button> </Container> ) }
use crate::checks::check_bond_authority; use crate::error::ErrorCode; use crate::events::{bond::ConfigureBondEvent, PubkeyValueChange, U64ValueChange}; use crate::instructions::verify_max_stake_wanted; use crate::state::bond::Bond; use crate::state::config::Config; use anchor_lang::prelude::*; use anchor_lang::solana_program::vote::program::ID as vote_program_id; #[derive(AnchorDeserialize, AnchorSerialize)] pub struct ConfigureBondArgs { /// New bond authority that can manage the bond account. pub bond_authority: Option<Pubkey>, /// New `cpmpe` value (cost per mille per epoch). /// It defines the bid for the validator to get delegated up to `max_stake_wanted` lamports. pub cpmpe: Option<u64>, /// New `max_stake_wanted` value that the vote account owner declares /// as the maximum delegated stake desired. pub max_stake_wanted: Option<u64>, } /// Change parameters of validator bond account #[event_cpi] #[derive(Accounts)] pub struct ConfigureBond<'info> { pub config: Account<'info, Config>, #[account( mut, has_one = vote_account @ ErrorCode::VoteAccountMismatch, has_one = config @ ErrorCode::ConfigAccountMismatch, seeds = [ b"bond_account", config.key().as_ref(), vote_account.key().as_ref(), ], bump = bond.bump, )] pub bond: Account<'info, Bond>, /// validator vote account validator identity or bond authority may change the account pub authority: Signer<'info>, /// CHECK: check&deserialize the vote account in the code #[account( owner = vote_program_id @ ErrorCode::InvalidVoteAccountProgramId, )] pub vote_account: UncheckedAccount<'info>, } impl<'info> ConfigureBond<'info> { pub fn process( ctx: Context<ConfigureBond>, configure_bond_args: ConfigureBondArgs, ) -> Result<()> { require!(!ctx.accounts.config.paused, ErrorCode::ProgramIsPaused); require!( check_bond_authority( &ctx.accounts.authority.key(), &ctx.accounts.bond, &ctx.accounts.vote_account ), ErrorCode::BondChangeNotPermitted ); let ConfigureBondChanges { bond_authority_change, cpmpe_change, max_stake_wanted_change, } = configure_bond( &mut ctx.accounts.bond, ctx.accounts.config.min_bond_max_stake_wanted, configure_bond_args, )?; emit_cpi!(ConfigureBondEvent { bond_authority: bond_authority_change, cpmpe: cpmpe_change, max_stake_wanted: max_stake_wanted_change, }); Ok(()) } } pub struct ConfigureBondChanges { pub bond_authority_change: Option<PubkeyValueChange>, pub cpmpe_change: Option<U64ValueChange>, pub max_stake_wanted_change: Option<U64ValueChange>, } pub(crate) fn configure_bond( bond: &mut Bond, min_bond_max_stake_wanted: u64, configure_args: ConfigureBondArgs, ) -> Result<ConfigureBondChanges> { let bond_authority_change = configure_args.bond_authority.map(|authority| { let old = bond.authority; bond.authority = authority; PubkeyValueChange { old, new: authority, } }); let cpmpe_change = configure_args.cpmpe.map(|new_cpmpe| { let old = bond.cpmpe; bond.cpmpe = new_cpmpe; U64ValueChange { old, new: new_cpmpe, } }); let max_stake_wanted_change = configure_args.max_stake_wanted.map(|new_max_stake_wanted| { let old = bond.max_stake_wanted; bond.max_stake_wanted = new_max_stake_wanted; U64ValueChange { old, new: new_max_stake_wanted, } }); verify_max_stake_wanted(bond.max_stake_wanted, min_bond_max_stake_wanted)?; Ok(ConfigureBondChanges { bond_authority_change, cpmpe_change, max_stake_wanted_change, }) }
--- title: 11779 최소비용구하기 2 author: 신성일 date: 2021-08-07 21:00:00 +0900 categories: [알고리즘, beackjoon] tags: [] --- ## 알고리즘 - 일반적인 다익스트라로 푸는데, 풀면서 이전에 어디서 왔는지를 기록한다. - 다익스트라가 끝나고, 끝에서부터 왔던길을 되돌아가며 경로를 찾아낸다. ## 코드 ```c++ #include <iostream> #include <queue> #include <vector> #include <cstring> #define INF 2000000000000 typedef long long ll; using namespace std; int n, m, s, e, path[1001]; vector<int> p; vector<pair<int, int>> to[1001]; priority_queue<pair<ll, int>> q; ll cost[1001]; void dijkstra(); void checkPath(); int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin >> n >> m; while (m--) { int a, b, c; cin >> a >> b >> c; to[a].push_back({ b, c }); } cin >> s >> e; dijkstra(); checkPath(); cout << cost[e] << "\n"; cout << p.size() << "\n"; for (int i = p.size()-1; i >= 0; i--) cout << p[i] << " "; } void dijkstra() { for (int i = 0; i <= n; i++) cost[i] = INF; cost[s] = 0; path[s] = -1; q.push({ 0, s }); while (!q.empty()) { ll c = -q.top().first; int cur = q.top().second; q.pop(); if (c > cost[cur]) continue; for (int i = 0; i < to[cur].size(); i++) { ll nc = c + to[cur][i].second; int ncur = to[cur][i].first; if (nc < cost[ncur]) { cost[ncur] = nc; path[ncur] = cur; q.push({ -nc, ncur }); } } } return; } void checkPath() { int cur = e; while (path[cur] != -1) { p.push_back(cur); cur = path[cur]; } p.push_back(cur); } ```
use std::{ fmt::{self, Display, Formatter}, num::NonZero, ops::Mul, }; use rust_decimal::Decimal; use static_assertions::const_assert; use thiserror::Error; use crate::{AverageMass, Charge, Count, Mass, MonoisotopicMass}; impl Count { const BITS: u32 = NonZero::<u32>::BITS; pub fn new(n: u32) -> Option<Self> { NonZero::new(n).map(Self) } } impl From<Count> for u32 { fn from(value: Count) -> Self { value.0.get() } } #[derive(Clone, Debug, Error)] #[error("`Count` values must be non-zero")] pub struct Zero; impl TryFrom<u32> for Count { type Error = Zero; fn try_from(value: u32) -> Result<Self, Self::Error> { Self::new(value).ok_or(Zero) } } // NOTE: Since this will only panic on 16-bit platforms, I couldn't test a `TryFrom` impl if I wanted to — I don't want // to add an entire error-handling code path that could never possibly be run. #[allow(clippy::fallible_impl_from)] impl From<Count> for usize { fn from(value: Count) -> Self { const_assert!(usize::BITS >= Count::BITS); // SAFETY: The above assertion prevents compilation on platforms with fewer bits than the type used to // represent `Count`. If this code compiles, then this `.unwrap()` will never panic. Self::try_from(value.0.get()).unwrap() } } macro_rules! mass_mul_impls { // NOTE: `$mass_type` is a `tt` since it actually has to play the role of both a type (`ty`) and expression (`expr`) // in this impl, and `tt` appears to be the only way to pull off that sort of "metavariable polymorphism" ($($mass_type:tt),+ $(,)?) => { $( impl Mul<$mass_type> for Count { type Output = $mass_type; fn mul(self, rhs: $mass_type) -> Self::Output { $mass_type(Decimal::from(self.0.get()) * rhs.0) } } )+ }; } mass_mul_impls!(Mass, MonoisotopicMass, AverageMass); impl Mul<Charge> for Count { type Output = Charge; fn mul(self, rhs: Charge) -> Self::Output { Charge(i64::from(self.0.get()) * rhs.0) } } impl Display for Count { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let count = self.0.get(); if count > 1 { write!(f, "{count}")?; } Ok(()) } } impl Default for Count { fn default() -> Self { Self::new(1).unwrap() } }
#pragma once #include <Source/AutoGen/UserRegistry.AutoComponent.h> #include <Components/Interfaces/UserRegistryBus.h> namespace metapulseWorld { /* * Component used to read the information from the userregistry network * component, and perform client side operations like sending data * to clients. */ class UserRegistry : public UserRegistryBase , public UserRegistryGettersBus::Handler { public: AZ_MULTIPLAYER_COMPONENT(metapulseWorld::UserRegistry, s_userRegistryConcreteUuid, metapulseWorld::UserRegistryBase); static void Reflect(AZ::ReflectContext* context); void OnInit() override; void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; /* * Get the entityId of the first player that is connected, in string form. */ AZStd::string BusGetPlayer1() override; /* * Get the entityId if the second player connected, in string form. */ AZStd::string BusGetPlayer2() override; protected: }; /* * Controller for the user registry multiplayer component. This controller is the one * that sets the user entityIds serverside so that they can be replicated to the clients */ class UserRegistryController : public UserRegistryControllerBase , public UserRegistryBus::Handler { public: explicit UserRegistryController(UserRegistry& parent); void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; /* * Registers a user. At most, it can register 2 users. */ void RegisterUser(const AZ::EntityId& entityId) override; /* * Removes a user's EntityId from the user Registry. */ void UnregisterUser(const AZStd::string& entityId) override; protected: }; }
from pulp import LpVariable, LpProblem, LpMaximize, value import time # Объявление переменных x1 = LpVariable("x1", lowBound=0, cat="Integer") x2 = LpVariable("x2", lowBound=0, cat="Integer") # Добавление целевой функции problem = LpProblem("0", LpMaximize) problem += 6 * x1 + 8 * x2, "Целевая функция" # Добавление ограничений problem += 2 * x1 + x2 <= 400, "1" problem += x1 + 3 * x2 <= 600, "2" problem += 4 * x1 + 5 * x2 <= 1238, "3" # Решаем задачу и замеряем время start = time.time() problem.solve() stop = time.time() print("Прибыль:") print(value(problem.objective), "\n") print("Результат:") for variable in problem.variables(): print(variable.name, "=", int(variable.varValue)) print() print("Время :") print(1000 * (stop - start), "мс")
import { ShipClass, ShipType } from "@fh/utils"; import { MasterAttrRule, MasterData, MasterShip, ShipAttr, SpeedGroup, } from "fleethub-core"; import { MstPlayerShip, MstShip } from "kc-tools"; import set from "lodash/set"; import { SpreadsheetTable } from "./SpreadsheetTable"; import { ExprParser } from "./parser"; import { toCellString } from "./utils"; const SUFFIXES = [ "甲", "乙", "丙", "丁", "戊", "特", "改二", "改II", "乙改", "丁改", "改", "航", "母", "護", " zwei", " drei", " due", " andra", " два", " Mod.2", " Mk.II", "後期型II", "後期型", " バカンスmode", " 夏季上陸mode", " 夏mode", "-壊", ]; const SUFFIX_RE = RegExp(`(${SUFFIXES.join("|")})+$`); const isPlayerShip = (ship: MstShip): ship is MstPlayerShip => "api_houg" in ship; const getDefaultSpeedGroup = ({ name, yomi, stype, ctype, speed, }: MasterShip): SpeedGroup => { const isFastAV = (stype as ShipType) == ShipType.AV && speed == 10; if ( isFastAV || [ShipType.SS, ShipType.SSV].includes(stype) || ["夕張", "夕張改"].includes(name) || [ ShipClass.KagaClass, ShipClass.R1, ShipClass.RepairShip, ShipClass.RevisedKazahayaClass, ].includes(ctype || 0) ) { return "C"; } if ( [ ShipClass.ShimakazeClass, ShipClass.TashkentClass, ShipClass.TaihouClass, ShipClass.ShoukakuClass, ShipClass.ToneClass, ShipClass.MogamiClass, ].includes(ctype || 0) ) { return "A"; } if ( [ ShipClass.AganoClass, ShipClass.SouryuuClass, ShipClass.HiryuuClass, ShipClass.KongouClass, ShipClass.YamatoClass, ShipClass.IowaClass, ].includes(ctype || 0) ) { return "B1"; } const isAmatsukaze = yomi === "あまつかぜ"; const isUnryuu = yomi === "うんりゅう"; const isAmagi = yomi === "あまぎ"; const isNagatoKai2 = name === "長門改二"; if (isAmatsukaze || isUnryuu || isAmagi || isNagatoKai2) { return "B1"; } return "B2"; }; const getConvertibleShips = (ships: MasterShip[]) => { const findNextShip = ({ next_id }: MasterShip) => next_id ? ships.find((s) => s.ship_id === next_id) : undefined; const convertibleShips: MasterShip[] = []; const irreversibleShips: MasterShip[] = []; const isConvertible = (base: MasterShip): boolean => { if (!base.next_id || irreversibleShips.includes(base)) return false; if (convertibleShips.includes(base)) return true; const remodelList: MasterShip[] = []; const setRemodelList = (current: MasterShip): MasterShip | undefined => { remodelList.push(current); const next = findNextShip(current); if (!next) return current; const index = remodelList.findIndex((s) => s === next); if (index < 0) { return setRemodelList(next); } convertibleShips.push(...remodelList.slice(index)); irreversibleShips.push(...remodelList.slice(0, index)); return; }; setRemodelList(base); return convertibleShips.includes(base); }; return ships.filter(isConvertible); }; function createShips( parser: ExprParser, table: SpreadsheetTable, ): MasterShip[] { const { start2, nationalityMap } = parser; const { headerValues, rows } = table; const createShip = (mst: MstShip): MasterShip => { const row = rows.find((row) => Number(row.ship_id) === mst.api_id); const base: MasterShip = { ship_id: mst.api_id, name: mst.api_name, yomi: mst.api_yomi, sort_id: mst.api_sort_id, stype: mst.api_stype, ctype: mst.api_ctype, slotnum: mst.api_slot_num, speed: mst.api_soku, max_hp: [null, null], firepower: [null, null], armor: [null, null], torpedo: [null, null], evasion: [null, null], anti_air: [null, null], asw: [null, null], los: [null, null], luck: [null, null], slots: [], stock: [], }; if (row) { headerValues.forEach((h) => { const value = row[h]; if (value !== "" && value !== undefined && value !== false) { set(base, h, value); } }); } if (isPlayerShip(mst)) { const { api_aftershipid, api_afterlv } = mst; const ship: MasterShip = { nationality: nationalityMap.getByCtype(mst.api_ctype), speed_group: getDefaultSpeedGroup(base), ...base, max_hp: mst.api_taik, firepower: mst.api_houg, torpedo: mst.api_raig, anti_air: mst.api_tyku, armor: mst.api_souk, luck: mst.api_luck, range: mst.api_leng, fuel: mst.api_fuel_max, ammo: mst.api_bull_max, }; const next_id = Number(api_aftershipid); const next_level = api_afterlv; if (next_id) { ship.next_id = next_id; } if (next_level) { ship.next_level = next_level; } return ship; } else { const baseName = mst.api_name.replace(SUFFIX_RE, ""); const abyssal_ctype = start2.api_mst_ship.find( (s) => s.api_name === baseName, )?.api_id; return { ...base, ctype: abyssal_ctype || 0, }; } }; const ships = start2.api_mst_ship.map((ship) => createShip(ship)); getConvertibleShips(ships).forEach((ship) => { ship.useful = true; }); return ships; } const createShipAttrs = (parser: ExprParser, table: SpreadsheetTable) => { const attrs: MasterAttrRule<ShipAttr>[] = []; table.rows.forEach((row) => { const str = toCellString(row.expr); const expr = parser.parseShip(str); attrs.push({ tag: toCellString(row.tag) as ShipAttr, name: toCellString(row.name), expr, }); }); return attrs; }; export function createShipData( parser: ExprParser, tables: Record<"ships" | "ship_attrs" | "nationalities", SpreadsheetTable>, ): Pick<MasterData, "ships" | "ship_attrs"> { const ships = createShips(parser, tables.ships); const ship_attrs = createShipAttrs(parser, tables.ship_attrs); return { ships, ship_attrs, }; }
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import toast from "react-hot-toast"; import axiosInstance from "../../Helpers/axiosInstance"; const initialState = { courseData: [], } // make asynce thunk for get courses export const getAllCourses = createAsyncThunk("/course/get", async ()=>{ try { const response = axiosInstance.get("/courses") toast.promise(response, { loading:"Loading courses data...", success: "courses loaded successfully!", error: "Failed to load all courses" }) return (await response).data.courses; } catch (error) { toast.error(error?.response?.data?.message) } }); // course create thunk export const createNewCourse = createAsyncThunk("/course/create", async (data)=> { try { // make form data const formData = new FormData(); formData.append("title", data?.title) formData.append("category", data?.category) formData.append("createdBy", data?.createdBy) formData.append("description", data?.description) formData.append("thumbnail", data?.thumbnail) // put a axios request const res = axiosInstance.post("/courses", formData); toast.promise(res, { loading: "Wait! Creating new course", success: "Course created successfully", error: "Failed to create course" }) return (await res).data } catch (error) { toast.error(error?.response?.data?.message) } }) const courseSlice = createSlice({ name: "courses", initialState, reducers: {}, extraReducers: (builder)=>{ builder.addCase(getAllCourses.fulfilled, (state, action)=> { if(action?.payload){ console.log(action.payload); //action.payload me courses ka data hoga (sare course array me destructure ho jayenge) state.courseData = [...action.payload]; } }) } }); export default courseSlice.reducer;
package com.emarket.terminal import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.nfc.NfcAdapter import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.emarket.terminal.NetworkService.Companion.makeRequest import com.google.zxing.integration.android.IntentIntegrator import com.google.zxing.integration.android.IntentResult import java.nio.charset.StandardCharsets import kotlin.concurrent.thread const val READER_FLAGS = NfcAdapter.FLAG_READER_NFC_A or NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK class MainActivity : AppCompatActivity() { companion object { private const val REQUEST_CAMERA_PERMISSION = 1 } private val nfc by lazy { NfcAdapter.getDefaultAdapter(this) } private val paymentReader by lazy { PaymentReader(::paymentListener) } private val scanBtn by lazy { findViewById<Button>(R.id.scan_btn) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) scanBtn.setOnClickListener { requestCameraPermissionAndStartScan() } } override fun onResume() { super.onResume() nfc?.enableReaderMode(this, paymentReader, READER_FLAGS, null) } override fun onPause() { super.onPause() nfc?.disableReaderMode(this) } private fun paymentListener(payment: ByteArray) { nfc?.disableReaderMode(this) processPayment(payment) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.activity_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId) { R.id.mn_scanner -> requestCameraPermissionAndStartScan() } return true } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when(requestCode) { REQUEST_CAMERA_PERMISSION -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) startScan() } } } private fun requestCameraPermissionAndStartScan() { val permission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) if (permission == PackageManager.PERMISSION_GRANTED) { startScan() } else { val requests = arrayOf(Manifest.permission.CAMERA) ActivityCompat.requestPermissions(this, requests, REQUEST_CAMERA_PERMISSION) } } private fun startScan() { val intentIntegrator = IntentIntegrator(this).apply { setPrompt(getString(R.string.scanner_prompt)) setOrientationLocked(false) } readQRCode.launch(intentIntegrator.createScanIntent()) } private val readQRCode = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { val intentResult : IntentResult? = IntentIntegrator.parseActivityResult(it.resultCode, it.data) if (intentResult?.contents != null) { val data = intentResult.contents.toByteArray(StandardCharsets.ISO_8859_1) processPayment(data) } } private fun processPayment(data : ByteArray) { thread(start = true) { val res = makeRequest( Constants.SERVER_URL + Constants.CHECKOUT_ENDPOINT, data) runOnUiThread { intent = Intent(this, ResultActivity::class.java) intent.putExtra("RESULT", res) startActivity(intent) } } } }
<template> <app-layout title="Dashboard"> <template #header> <h2 class="h4 font-weight-bold">Create</h2> </template> <div class="container mt-5 text-gray-300 "> <form @submit.prevent="storePost" enctype="multipart/form-data"> <input type="hidden" name="region77" id="region77" :value=this.region11> <!-- 지역값 --> <div class="form-group"> <label for="title">title</label> <input type="text" id="title" class="form-control" v-model="this.form.title" /> </div> <div class="form-group text-gray-300"> <label for="content">content</label> <div> <textarea type="text" id="content" class="form-control" v-model="this.form.content" > </textarea> </div> </div> <br /> <br /> <div class="form-group"> <label for="image">image</label> <input type="file" id="image" @input="this.form.image = $event.target.files[0]" /> </div> <br /> <br /> <br /> <br /> <br /> <div> <button type="submit" style="color: lavender" class="btn btn-secondary" > 완료 </button> &nbsp; &nbsp; </div> </form> </div> </app-layout> </template> <script> import AppLayout from "@/Layouts/AppLayout.vue"; import { useForm } from "@inertiajs/inertia-vue3"; export default { props:['region1'], components: { AppLayout, }, setup(){ const form = useForm({ title: '', image: null, content: '', region: '', }) //form 을 이용하여 post 요청. axios 필요 x function storePost() { if (this.form.processing) { return false } form.post('/post/store',{ preserveScroll: true, onSuccess: () => this.form.reset()}); } return { form, storePost } }, data(){ return{ region11:'???', } }, mounted(){ this.region11 = this.region1; console.log(this.region11);// this.form.region = this.region11; }, methods:{ } }; </script>
import { Reservation } from "./schemas.ts"; import { BusinessHour } from "../businessHours/schemas.ts"; import { daysOfWeek } from "../restaurant/businessHours/const.ts"; export const filterReservationsByDate = ( reservations: Reservation[], date: Date ) => reservations.filter((reservation) => { const reservationDate = new Date(reservation.startDateTime); return ( reservationDate.getUTCFullYear() === date.getUTCFullYear() && reservationDate.getUTCMonth() === date.getUTCMonth() && reservationDate.getUTCDate() === date.getUTCDate() ); }); type Slot = { startDateTime: string; endDateTime: string; }; export const getFreeSlots = ( reservations: Reservation[], openingHours: BusinessHour[], date: Date ): Slot[] => { const freeSlots: Slot[] = []; const inputDayOfWeek = daysOfWeek[(date.getUTCDay() + 6) % 7]; const hours = openingHours.find((hour) => hour.dayOfWeek === inputDayOfWeek); if (!hours) { return freeSlots; } let openTime = hours.openingTime; const closeTime = hours.closingTime; if (reservations.length === 0) { freeSlots.push({ startDateTime: openTime, endDateTime: closeTime }); return freeSlots; } reservations.forEach((reservation, index) => { const reservationStart = reservation.startDateTime.split("T")[1]; const reservationEnd = reservation.endDateTime.split("T")[1]; if (openTime < reservationStart) { freeSlots.push({ startDateTime: openTime, endDateTime: reservationStart, }); } openTime = reservationEnd; if (index === reservations.length - 1 && openTime < closeTime) { freeSlots.push({ startDateTime: openTime, endDateTime: closeTime }); } }); return freeSlots; };
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!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"> <meta name="description" content=""> <meta name="author" content=""> <c:set var="k" value="${sessionScope.user}"/> <c:set var="s" value="${subscription}"/> <c:set var="c" value="${subscriptionPlans}"/> <title>Library</title> <!-- Bootstrap Core CSS --> <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> <!-- Custom CSS --> <link href="<c:url value="/resources/css/shop-homepage.css" />" rel="stylesheet"> <link href="<c:url value="/resources/css/bootstrap.icon-large.css" />" rel="stylesheet"> <link href="<c:url value="/resources/css/bootstrap.icon-large.min.css" />" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <c:url value="/j_spring_security_logout" var="logoutUrl" /> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <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="<c:url value="/userhomepage"/>">Hello ${k.firstName}</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">${k.firstName} <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="<c:url value="/userprofilepage"/>">Profile </a> </li> <li> <a href="${logoutUrl}">Logout</a> </li> </ul> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Page Content --> <div class="container"> <!-- Search bar --> <div class="row"> <div class="col-md-12"> <h1 class="page-header">User Profile</h1> <ol class="breadcrumb"> <li class="active"><h4>User Details</h4></li> </ol> </div> </div> <div class="row"> <div class="col-md-2"> <a href="portfolio-item.html"> <img class="img-responsive img-hover" src="<c:url value="/resources/images/user.jpg"/>"> </a> </div> <div class="col-md-10"> <br/> <p ><b style="font-size:large;">Name: </b>${k.firstName} ${k.lastName}</p> <p><b style="font-size:large;">Address: </b>${k.permanentAddress}</p> <p><b style="font-size:large;">Phone Number: </b>${k.phoneNo}</p> <p><b style="font-size:large;">Email ID: </b>${k.userEmailId}</p> <p><b style="font-size:large;">Language Preference: </b>${k.language}</p> </div> </div> <!-- /.row --> <hr> <div class="row"> <div class="col-md-12"> <ol class="breadcrumb"> <li class="active"><h4>Current Subscription Plan</h4></li> </ol> </div> </div> <div class="row"> <div class="col-md-12"> <c:if test="${s.subscriptionPlan ==null}"><p>Currently No Plan is Activated.</p></c:if> <c:if test="${s.subscriptionPlan !=null}"> <p><b style="font-size:large;">Subscription Plan: </b>${s.subscriptionPlan}</p> <p><b style="font-size:large;">Valid From: </b>${s.startDate}</p> <p><b style="font-size:large;">Valid Till: </b>${s.endDate}</p> <p><b style="font-size:large;">No. of Books(Max): </b>${s.noOfBooks}</p> </c:if> <div class="row"> <div class="col-md-12"> <div class="text-right"> <button id="editPlan" class="btn btn-warning" onclick="changePlan('${s.endDate}','${subscriptionPlans}');"><span class="glyphicon glyphicon-pencil" ></span> Switch to New Plan</button> </div> </div> </div> </div> </div> <hr> <div id ="newPlans" style="display: none;"> <div class="row"> <div class="col-md-12"> <ol class="breadcrumb"> <li class="active"><h4>Currently Available Subscription Plans (Choose)</h4></li> </ol> </div> </div> <div class="row"> <form action="<c:url value="/userswitchToNewPlan"/>" method="post"> <c:forEach var="p" items="${subscriptionPlans}"> <div class="col-md-4"> <div class="panel panel-primary text-center"> <div class="panel-heading"> <h3 class="panel-title"><input type="radio" name="subscription_plan" value="${p.subscriptionPlan}"> Subscription Plan:${p.subscriptionPlan}</h3> </div> <ul class="list-group"> <li class="list-group-item">Period: <strong>${p.period} <c:if test="${p.period==1}">Year</c:if><c:if test="${p.period !=1}">Years</c:if></strong></li> <li class="list-group-item">Amount: <strong>Rs ${p.amount}</strong></li> <li class="list-group-item">No. of books(Can be issued): <strong>${p.noOfBooks}</strong></li> </ul> </div> </div> </c:forEach> <div class="row"> <div class="col-md-11"> <button type="submit" class="btn btn-success active" id="submit" onClick="alert('Your New Subscription Plan is Activated!!');"><span class="glyphicon glyphicon-pencil" ></span> Switch to New Plan</button> </div> </div> </form> </div> <hr> </div> </div> <!-- jQuery Version 1.11.0 --> <script src="<c:url value="/resources/js/jquery-1.11.0.js" />"></script> <!-- Bootstrap Core JavaScript --> <script src="<c:url value="/resources/js/bootstrap.min.js" />"></script> <script type="text/javascript"> function changePlan(end_date){ date1=new Date().getTime(); date2=new Date(end_date).getTime(); if (date2>date1){ alert("Your Current Plan is Active!! You Can't Switch to a New Plan."); } else{ $('#newPlans').slideDown(500); } } </script> </body> </html>
import QtQuick 1.1 import com.nokia.meego 1.0 import "../js/UIConstants.js" as UIConstants import "../js/constants.js" as ExtrasConstants Item { id: headerItem property alias text: title.text property alias subtext: subtitle.text property bool loading: false property bool showindicator: true signal clicked clip: true anchors { left: parent.left; right: parent.right } height: screen.currentOrientation === Screen.Portrait ? UIConstants.HEADER_DEFAULT_HEIGHT_PORTRAIT : UIConstants.HEADER_DEFAULT_HEIGHT_LANDSCAPE + (UIConstants.DEFAULT_MARGIN * 2) Image { id: headerBackground anchors.fill: parent source: "image://theme/color2-meegotouch-view-header-fixed" // + (theme.inverted ? "-inverted" : "") } Column { anchors { left: parent.left leftMargin: UIConstants.DEFAULT_MARGIN right: parent.right verticalCenter: parent.verticalCenter } Text { id: title verticalAlignment: Text.AlignVCenter font.pixelSize: UIConstants.FONT_XLARGE font.family: UIConstants.FONT_FAMILY color: !theme.inverted ? UIConstants.COLOR_FOREGROUND : UIConstants.COLOR_INVERTED_FOREGROUND width: parent.width wrapMode: Text.WordWrap } Text { id: subtitle font.pixelSize: UIConstants.FONT_SMALL font.family: UIConstants.FONT_FAMILY_LIGHT color: theme.inverted ? Settings.getValue("LIST_SUBTITLE_COLOR_INVERTED") : Settings.getValue("LIST_SUBTITLE_COLOR"); verticalAlignment: Text.AlignVCenter width: parent.width wrapMode: Text.WordWrap visible: subtitle.text } } Item { id: loaderItem visible: showindicator anchors { right: parent.right verticalCenter: parent.verticalCenter margins: UIConstants.DEFAULT_MARGIN } width: 46; height: 46; Loader { id: loader anchors { right: parent.right verticalCenter: parent.verticalCenter } sourceComponent: loading ? busyIndicator : refreshIcon } Component { id: refreshIcon Image { source: "image://theme/icon-m-toolbar-refresh" + (theme.inverted ? "-white" : "") } } Component { id: busyIndicator BusyIndicator { running: loading; platformStyle: BusyIndicatorStyle { inverted: false size: "medium" } } } MouseArea { id: mouseArea anchors.fill: parent onClicked: { header.clicked(); } } } }
import axios from 'axios'; import React, { useState, useEffect } from 'react'; import { StatusBar, StyleSheet, TouchableOpacity, View, } from 'react-native'; import { Button, Text, TextInput,ActivityIndicator } from 'react-native-paper'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { useNetInfo } from '@react-native-community/netinfo'; import MidLoad from './MidLoadScreen'; import Reloading from './ReloadingScreen'; const SignUpScreen = (props) => { const baseUrl = 'https://fliptradebackend.onrender.com'; //const baseUrl = 'http://192.168.0.103:3000'; const [email, setEmail] = useState(''); const [password, setPassword] = useState('') const [exist, setExist] = useState('') const [isloading, setIsloading] = useState(false) const onboardClick = async () => { if (netInfo.isConnected === false) return; const url = `${baseUrl}/signup`; try { if (email.length < 3 ) { setExist('* Name too short'); return; } if (email.length >10) { setExist('* Name too long'); return; } if (password.length < 8) { setExist('* Passsword too short'); return; } setIsloading(true) const resToken = await axios.post(url, { email, password }); if (resToken.data.message === 'user exist') { setExist('* Please try to login user already exist'); return; } await AsyncStorage.setItem('token', resToken.data.token); setIsloading(false) props.navigation.replace('Home'); } catch (error) { console.log('Error occurred:', error); } }; const netInfo = useNetInfo(); const [isConnected, setIsConnected] = useState(false); useEffect(() => { if (netInfo.isConnected !== null) { setIsConnected(netInfo.isConnected); } }, [netInfo.isConnected]); if (netInfo.isConnected === null) { return <MidLoad /> } else if (!isConnected) { return <Reloading /> } else { return ( <View style={{ backgroundColor: '#EAE4F1', flex: 1 }}> <StatusBar backgroundColor="#50BDD2" barStyle="light-content" /> <View> <View style={styles.headerView}> <Text style={styles.headerTxt}>Welcome</Text> <ActivityIndicator animating={isloading} color="#000000" size={18} /> </View> <TextInput autoCapitalize='none' label={'Name'} style={styles.container} value={email} onChangeText={(text) => setEmail(text)} /> <TextInput autoCapitalize='none' label={'Password'} style={styles.container} value={password} onChangeText={(text) => setPassword(text)} secureTextEntry={true} /> <Text style={styles.hidetxt}>{exist}</Text> <Button mode="contained" style={styles.btn} onPress={onboardClick}> Onboard </Button> <TouchableOpacity onPress={() => props.navigation.navigate('Signin')}> <Text style={styles.general}>already have an account ?</Text> </TouchableOpacity> </View> </View> ); } } const styles = StyleSheet.create({ headerView:{ flexDirection: 'row', marginBottom: 1, marginTop: 120, }, hidetxt: { color: 'red', fontSize: 15, textAlign: 'center' }, container: { margin: 20, marginBottom: 5, backgroundColor: '#BAE5F3', }, headerTxt: { fontSize: 30, fontWeight: 'bold', margin: 20, marginRight: 15, color: '#000000', }, general: { color: '#000000', marginLeft: 40, marginTop: 15, }, btn: { margin: 30, marginBottom: 5, backgroundColor: '#000000', } }) export default SignUpScreen;
<?php namespace App\Repository; use App\Entity\Personnage; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @extends ServiceEntityRepository<Personnage> * * @method Personnage|null find($id, $lockMode = null, $lockVersion = null) * @method Personnage|null findOneBy(array $criteria, array $orderBy = null) * @method Personnage[] findAll() * @method Personnage[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PersonnageRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Personnage::class); } /** * Permet d'obtenir le nombre de personnages (dans la base de données) */ public function countCharacters(): int{ /* Query qui permet d'obtenir le nombre de personnages total dans la base de données */ $totalCharacters = $this->createQueryBuilder('p') // Création d'un query builder avec un alias pour identifier l'entité actuel ->select('COUNT(p.id)') // Sélection du nombre d'id des personnages ->getQuery() // Obtention de la query construite ->getSingleScalarResult(); // Execution de la query et obtention du résultat sous forme d'un nombre return $totalCharacters; } // /** // * @return Personnage[] Returns an array of Personnage objects // */ // public function findByExampleField($value): array // { // return $this->createQueryBuilder('p') // ->andWhere('p.exampleField = :val') // ->setParameter('val', $value) // ->orderBy('p.id', 'ASC') // ->setMaxResults(10) // ->getQuery() // ->getResult() // ; // } // public function findOneBySomeField($value): ?Personnage // { // return $this->createQueryBuilder('p') // ->andWhere('p.exampleField = :val') // ->setParameter('val', $value) // ->getQuery() // ->getOneOrNullResult() // ; // } }
import { RouterModule } from "@angular/router"; import { NgModule, Component } from "@angular/core"; import { HomeComponent } from "./home.component"; import { AboutComponent } from "./about.component"; @Component({ selector: "app-root", template: ` <ul> <li><a routerLink="/home">Home</a></li> <li><a routerLink="/about">About</a></li> </ul> <router-outlet></router-outlet> `, }) export class AppComponent {} @NgModule({ imports: [ RouterModule.forRoot([ { path: "home", component: HomeComponent }, { path: "about", component: AboutComponent }, ]), ], declarations: [AppComponent, HomeComponent, AboutComponent], bootstrap: [AppComponent], }) export class AppModule {}
import React from "react"; import { useState } from "react"; import { useForm } from "../../hooks/useForm"; import { Peticion } from "../../helpers/Peticion"; import { Global } from "../../helpers/Global"; export const Crear = () => { const { formulario, enviado, cambiado } = useForm({}); const [resultado, setResultado] = useState("no_enviado"); const guardarArticulo = async (e) => { e.preventDefault(); //Recoger datos formulario let nuevoArticulo = formulario; //Guardar articulo en el backend const { datos } = await Peticion( Global.url + "crear", "POST", nuevoArticulo ); console.log(datos.status); if (datos.status === "success") { setResultado("guardado"); } else { setResultado("error"); } //Subir imagen const fileInput = document.querySelector("#file"); if (datos.status === "success" && fileInput.files[0]) { setResultado("guardado"); const formData = new FormData(); formData.append("file0", fileInput.files[0]); const subida = await Peticion( Global.url + "subir-imagen/" + datos.articulo._id, "POST", formData, true ); console.log(subida.datos.status); if (subida.datos.status === "sucsess") { setResultado("guardado"); } else { setResultado("error"); } } console.log(resultado); }; return ( <div className="jumbo"> <h1>Crear articulo</h1> <p>Formulario para crear un articulo</p> {/* <pre>{JSON.stringify(formulario)}</pre> */} <strong> {resultado == "error" ? "Los datos proporcionados son incorrectos " : ""} </strong> <strong> {resultado == "guardado" ? "Articulo guardado con exito !!" : ""} </strong> {/* montar formulario*/} <form className="formulario" onSubmit={guardarArticulo}> <div className="form-group"> <label htmlFor="titulo">Titulo</label> <input type="text" name="titulo" onChange={cambiado} /> </div> <div className="form-group"> <label htmlFor="contenido">Contenido</label> <textarea type="text" name="contenido" onChange={cambiado} /> </div> <div className="form-group"> <label htmlFor="file0">Imagen</label> <input type="file" name="file0" id="file" /> </div> <input type="submit" value="Guardar" className="btn btn-success" /> </form> </div> ); };
class Sword: total_swords = 0 def __init__(self, name, damage): self.name = name self.damage = damage Sword.total_swords += 1 @staticmethod def get_total_swords(): return Sword.total_swords def __str__(self): return f"Имя меча: {self.name}, Урон меча: {self.damage}" class Katana(Sword): def __init__(self, name, damage, rarity): super().__init__(name, damage) self.rarity = rarity def __str__(self): return f"Имя меча: {self.name}, Урон меча: {self.damage}, Редкость: {self.rarity}" class Sabre(Katana): def __init__(self, name, damage, rarity): super().__init__(name, damage, rarity) def __str__(self): return f"Имя меча: {self.name}, Урон меча: {self.damage}, Редкость: {self.rarity}" sword1 = Sword("Клинок Тьмы", 45) sword2 = Sword("Острие Справедливости", 190) sword3 = Sabre("Пронзающий Небеса", 470, "Эпический") sword4 = Katana("Жнец Вечной Пустоты", 780, "Легендарный") print(sword1) print(sword2) print(sword3) print(sword4) print(f"Общее количество мечей: {Sword.get_total_swords()}")
import Foundation import Utils // TODO: Make this a protocol and add roles/members properties public struct Guild { public let id: GuildID public let ownerId: UserID? public let region: String? public let large: Bool public let name: String public let joinedAt: Date? public let splash: String public let unavailable: Bool public let description: String public let mfaLevel: Int? public let verificationLevel: Int? public let widgetEnabled: Bool public let widgetChannelId: ChannelID? public let icon: String? public let members: [UserID: Member] public let roles: [RoleID: Role] public let presences: [UserID: Presence] public let voiceStates: [UserID: VoiceState] public let emojis: [EmojiID: Emoji] public let channels: [ChannelID: Channel] public let threads: [ChannelID: Channel] /// Fetches the guild's channels and threads as a tree. public var channelTree: [ChannelTreeNode] { let treeNodes = channels .merging(threads, uniquingKeysWith: { k, _ in k }) .mapValues { ChannelTreeNode(channel: $0) } for treeNode in treeNodes.values { if let parentId = treeNode.channel.parentId, let parent = treeNodes[parentId] { parent.childs.append(treeNode) } } for treeNode in treeNodes.values { treeNode.childs.sort(by: ascendingComparator(comparing: \.channel.type, then: \.channel.position)) } return treeNodes.values .sorted(by: ascendingComparator(comparing: \.channel.type, then: \.channel.position)) .filter { $0.channel.parentId == nil } } /// Fetches the channels, correctly ordered. Since this requires /// building a channel tree, it is generally considered an expensive /// property to compute. public var channelsInOrder: [Channel] { channelTree.flatMap(\.traversed) } public init( id: GuildID = GuildID(""), ownerId: UserID? = nil, region: String? = nil, large: Bool = false, name: String = "", joinedAt: Date? = nil, splash: String = "", unavailable: Bool = false, description: String = "", mfaLevel: Int? = nil, verificationLevel: Int? = nil, widgetEnabled: Bool = false, widgetChannelId: ChannelID? = nil, icon: String? = nil, members: [UserID: Member] = [:], roles: [RoleID: Role] = [:], presences: [UserID: Presence] = [:], voiceStates: [UserID: VoiceState] = [:], emojis: [EmojiID: Emoji] = [:], channels: [ChannelID: Channel] = [:], threads: [ChannelID: Channel] = [:] ) { self.id = id self.ownerId = ownerId self.region = region self.large = large self.name = name self.joinedAt = joinedAt self.splash = splash self.unavailable = unavailable self.description = description self.mfaLevel = mfaLevel self.verificationLevel = verificationLevel self.widgetEnabled = widgetEnabled self.widgetChannelId = widgetChannelId self.icon = icon self.members = members self.roles = roles self.presences = presences self.voiceStates = voiceStates self.emojis = emojis self.channels = channels self.threads = threads } public func roles(for member: Member) -> [Role] { member.roleIds.compactMap { roles[$0] } } public class ChannelTreeNode { public let channel: Channel public fileprivate(set) var childs: [ChannelTreeNode] = [] public var traversed: [Channel] { [channel] + childs.flatMap(\.traversed) } fileprivate init(channel: Channel) { self.channel = channel } public func traversedWithDepth(_ depth: Int = 0) -> [(channel: Channel, depth: Int)] { [(channel: channel, depth: depth)] + childs.flatMap { $0.traversedWithDepth(depth + 1) } } } public struct Member { public let guildId: GuildID public let joinedAt: Date public let user: User public let deaf: Bool public let mute: Bool public let nick: String? public let roleIds: [RoleID] public init( guildId: GuildID, joinedAt: Date = Date(), user: User, deaf: Bool = false, mute: Bool = false, nick: String? = nil, roleIds: [RoleID] = [] ) { self.guildId = guildId self.joinedAt = joinedAt self.user = user self.deaf = deaf self.mute = mute self.nick = nick self.roleIds = roleIds } } }
import { useOpenState, useRectInfo, type OriginType } from "@/modules/hooks"; import { RectElement } from "../use-element-info/use-element-info"; export type AlignValuesType = "center" | "start" | "end"; export type SideValuesType = "top" | "right" | "bottom" | "left"; export type IntrinsicUseDialog = { defaultOpen?: boolean; open?: boolean; setOpen?: (value: boolean) => void; clickOutsideToClose?: boolean; }; export type DestructureUseDialog = { align?: AlignValuesType; side?: SideValuesType; sideOffset?: number; info?: Partial<RectElement>; }; export interface UseDialogType<T> extends IntrinsicUseDialog, DestructureUseDialog { ref?: React.MutableRefObject<T | null>; } export interface DialogContextProps<T> extends UseDialogType<T> { refs: Partial<Record<OriginType, React.MutableRefObject<T | null>>>; render: boolean; setOpen: (value: boolean) => void; attrData: (as: OriginType) => { [key: string]: string }; styles: (as: OriginType) => { [key: string]: string }; } export function useDialog<T extends HTMLElement>(Dialog: UseDialogType<T> = {}) { const { side = "bottom", align = "center", open: externalOpen, setOpen: externalSetOpen, sideOffset = 0 } = Dialog; const { refs, render, dataState, open, setOpen } = useOpenState<T>({ open: externalOpen, setOpen: externalSetOpen, ...Dialog, }); const triggerInfo = useRectInfo<T>(refs?.trigger?.current); const contentInfo = useRectInfo<T>(refs?.content?.current); const attrData = (as: OriginType): { [key: string]: string } => ({ "data-state": dataState, "data-side": side, "data-align": align, "data-origin": as, }); const styles = (as: OriginType): { [key: string]: string } => { const vars: { [key: string]: string } = {}; const setVars = (as: OriginType, info?: RectElement) => { if (info) { vars[`--${as}-h`] = `${info.height}px`; vars[`--${as}-w`] = `${info.width}px`; vars[`--${as}-x`] = `${info.x}px`; vars[`--${as}-y`] = `${info.y}px`; } }; switch (as) { case "root": vars["--offset"] = String(`${sideOffset}px`); setVars("trigger", triggerInfo); setVars("content", contentInfo); break; case "trigger": setVars(as, triggerInfo); break; case "content": setVars(as, contentInfo); break; } return vars; }; return { refs, styles, triggerInfo, attrData, render, side, align, open, setOpen }; }
<template> <b-tabs vertical content-class="col-12 col-md-9 mt-1 mt-md-0" pills nav-wrapper-class="col-md-3 col-12" nav-class="nav-left" > <!-- general tab --> <b-tab active> <!-- title --> <template #title> <feather-icon icon="UserIcon" size="18" class="mr-50" /> <span class="font-weight-bold">General</span> </template> <account-setting-general v-if="options" :general-data="options" /> </b-tab> <!--/ general tab --> <!-- change password tab --> <b-tab> <!-- title --> <template #title> <feather-icon icon="LockIcon" size="18" class="mr-50" /> <span class="font-weight-bold">Change Password</span> </template> <account-setting-password /> </b-tab> <!--/ change password tab --> <!-- notification --> <b-tab> <!-- title --> <template #title> <feather-icon icon="BellIcon" size="18" class="mr-50" /> <span class="font-weight-bold">Notifications</span> </template> <account-setting-notification v-if="options" :notification-data="options" /> </b-tab> </b-tabs> </template> <script> import { BTabs, BTab } from 'bootstrap-vue' import AccountSettingGeneral from './AccountSettingGeneral.vue' import AccountSettingPassword from './AccountSettingPassword.vue' import AccountSettingNotification from './AccountSettingNotification.vue' export default { components: { BTabs, BTab, AccountSettingGeneral, AccountSettingPassword, AccountSettingNotification, }, data() { return { options: {}, } }, beforeCreate() { this.options = JSON.parse(localStorage.getItem('userData')) // this.$http.get('/account-setting/data').then(res => { this.options = res.data }) }, } </script>
<mat-sidenav-container class="sidenav-container"> <mat-sidenav #drawer class="sidenav" fixedInViewport="true" [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'" [mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="!(isHandset$ | async)"> <mat-toolbar>OrdenApp</mat-toolbar> <mat-nav-list> <a mat-list-item routeLink="/dashboard"><mat-icon>today</mat-icon>Órdenes</a> <a mat-list-item routeLink="reports"><mat-icon>dashboard</mat-icon>Reportes</a> <a mat-list-item (click)="authService.logout()"><mat-icon>exit_to_app</mat-icon>Salir</a> </mat-nav-list> </mat-sidenav> <mat-sidenav-content> <mat-toolbar color="primary"> <button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()" *ngIf="isHandset$ | async"> <mat-icon aria-label="Side nav toggle icon">menu</mat-icon> </button> <span>Administración de órdenes recibidas</span> <span class="spacer"></span> <span class="display-name">{{authService.getDisplayName()}}</span> <img [src]="authService.getProfileImg()" alt="" class="avatar"> <button mat-icon-button [matMenuTriggerFor]="menu"> <mat-icon>more_vert</mat-icon> </button> <mat-menu #menu="matMenu"> <button mat-menu-item> <mat-icon>notifications_off</mat-icon> <span>Disable alerts</span> </button> <button mat-menu-item (click)="authService.logout()"> <mat-icon>logout</mat-icon> <span>Logout</span> </button> </mat-menu> </mat-toolbar> <!-- Add Content Here --> <app-data-table></app-data-table> </mat-sidenav-content> </mat-sidenav-container>
using AutoMapper; using Microsoft.EntityFrameworkCore; using Npgsql; using TopicArticleService.Application.Dtos; using TopicArticleService.Application.Queries; using TopicArticleService.Application.Queries.Handlers; using TopicArticleService.Infrastructure.EntityFramework.Contexts; namespace TopicArticleService.Infrastructure.Queries.Handlers { internal sealed class GetParentTopicWithChildrenHandler : IQueryHandler<GetParentTopicWithChildrenQuery, TopicDto> { private readonly ReadDbContext _readDbContext; private readonly IMapper _mapper; public GetParentTopicWithChildrenHandler(ReadDbContext readDbContext, IMapper mapper) { _readDbContext = readDbContext; _mapper = mapper; } public async Task<TopicDto> HandleAsync(GetParentTopicWithChildrenQuery query) { //Find all parents for topic with id: TopicId and select ONLY the root parent topic. //This is recursive function, that will be executed in the database. //The table and column names are written with double quotes, becouse there names must be interpreted by postgresql literally. //CAUTION: If the table and column names are written without double quotes there names will be lower cased by postgresql and the query will NOT be valid. var parentTopicReadModel = await _readDbContext.Topics .FromSqlRaw("WITH RECURSIVE ancestors AS (" + " SELECT t.\"TopicId\", t.\"TopicName\", t.\"ParentTopicId\", t.\"Version\"\t\n" + " FROM \"topic-article-service\".\"Topic\" AS t" + " WHERE t.\"TopicId\" = @topicId" + " UNION ALL" + " SELECT t.\"TopicId\", t.\"TopicName\", t.\"ParentTopicId\", t.\"Version\"" + " FROM \"topic-article-service\".\"Topic\" AS t" + " JOIN ancestors ON t.\"TopicId\" = ancestors.\"ParentTopicId\"" + " )" + " SELECT * FROM ancestors", new NpgsqlParameter("@topicId", query.TopicId)) //Include the TopicId. The documentation specifies that this is safer than $"{}". .Where(x => x.Parent == null) //Include ONLY the root parent topic. .FirstOrDefaultAsync(); //Find all topics and include their children. var alltopics = _readDbContext.Topics .Include(x => x.Children) .ThenInclude(x => x.Children); //Find the topic, that has id equal to the id of the parent topic (parentTopicReadModel). var topicReadModel = await alltopics?.Where(x => x.TopicId == parentTopicReadModel.TopicId).FirstOrDefaultAsync(); return _mapper.Map<TopicDto>(topicReadModel); } } }
import torch from copy import deepcopy from torch.nn.functional import one_hot from sklearn import metrics import numpy as np from tqdm import tqdm from random import random, randint from utils import EarlyStopping class DKT_plus_trainer(): def __init__( self, model, optimizer, n_epochs, device, num_q, crit, lambda_r, lambda_w1, lambda_w2, max_seq_len, grad_acc=False, grad_acc_iter=4 ): self.model = model self.optimizer = optimizer self.n_epochs = n_epochs self.device = device self.num_q = num_q self.crit = crit self.lambda_r = lambda_r self.lambda_w1 = lambda_w1 self.lambda_w2 = lambda_w2 self.max_seq_len = max_seq_len self.grad_acc=grad_acc self.grad_acc_iter=grad_acc_iter def _train(self, train_loader, metric_name): auc_score = 0 y_trues, y_scores = [], [] loss_list = [] for idx, data in enumerate(tqdm(train_loader)): self.model.train() q_seqs, r_seqs, qshft_seqs, rshft_seqs, mask_seqs = data #collate에 정의된 데이터가 나옴 q_seqs = q_seqs.to(self.device) #|q_seqs| = (bs, sq) -> [[58., 58., 58., -0., -0., -0., -0., ...], [58., 58., 58., -0., -0., -0., -0., ...]...] r_seqs = r_seqs.to(self.device) #|r_seqs| = (bs, sq) -> [[1., 1., 0., -0., -0., -0., -0., ...], [1., 1., 0., -0., -0., -0., -0., ...]...] qshft_seqs = qshft_seqs.to(self.device) #|qshft_seqs| = (bs, sq) -> [[58., 58., 58., -0., -0., -0., -0., ...], [58., 58., 58., -0., -0., -0., -0., ...]...] rshft_seqs = rshft_seqs.to(self.device) #|rshft_seqs| = (bs, sq) -> [[1., 1., 0., -0., -0., -0., -0., ...], [1., 1., 0., -0., -0., -0., -0., ...]...] mask_seqs = mask_seqs.to(self.device) #|mask_seqs| = (bs, sq) -> [[True, True, True, ..., False, False, False], [True, True, True, ..., False, False, False]..] y_hat = self.model( q_seqs.long(), r_seqs.long() ) #|y_hat| = (bs, sq, self.num_q) -> tensor([[[0.6938, 0.7605, ..., 0.7821], [0.8366, 0.6598, ..., 0.8514],..) #=> 각 sq별로 문항의 확률값들이 담긴 벡터들이 나오게 됨 y_hat = self.model( q_seqs.long(), r_seqs.long() ) #|y_hat| = (bs, sq, self.num_q) -> tensor([[[0.6938, 0.7605, ..., 0.7821], [0.8366, 0.6598, ..., 0.8514],..) #=> 각 sq별로 문항의 확률값들이 담긴 벡터들이 나오게 됨 #|one_hot_vectors| = (bs, sq, self.num_q) y_curr = ( y_hat * one_hot(q_seqs.long(), self.num_q) ).sum(-1) #|y_curr| = (bs, sq) -> 현재 값에 대한 확률, 각 sq에는 그 문항에 해당하는 확률값만 담기게 됨 y_next = ( y_hat * one_hot(qshft_seqs.long(), self.num_q) ).sum(-1) #|y_next| = (bs, sq) -> 다음 값에 대한 확률, 각 sq에는 그 문항에 해당하는 확률값만 담기게 됨 y_curr = torch.masked_select(y_curr, mask_seqs) #|y_curr| = () -> 현재 확률값 y_next = torch.masked_select(y_next, mask_seqs) #|y_curr| = () -> 다음 확률값, 원래 DKT는 이것만 봄 correct = torch.masked_select(r_seqs, mask_seqs) #|correct| = () -> 현재 정답값 correct_shft = torch.masked_select(rshft_seqs, mask_seqs) #|correct_shft| = () -> 다음 정답값 loss_w1 = torch.masked_select( torch.norm(y_hat[:, 1:] - y_hat[:, :-1], p = 1, dim = -1), mask_seqs[:, 1:] ) loss_w2 = torch.masked_select( (torch.norm(y_hat[:, 1:] - y_hat[:, :-1], p = 2, dim = -1) ** 2), mask_seqs[:, 1:] ) loss = \ self.crit(y_next, correct_shft) + \ self.lambda_r * self.crit(y_curr, correct) + \ self.lambda_w1 * loss_w1.mean() / self.num_q + \ self.lambda_w2 * loss_w2.mean() / self.num_q #grad_accumulation if self.grad_acc == True: loss.backward() if (idx + 1) % self.grad_acc_iter == 0: self.optimizer.step() self.optimizer.zero_grad() else: self.optimizer.zero_grad() loss.backward() self.optimizer.step() y_trues.append(correct) y_scores.append(y_hat) loss_list.append(loss) y_trues = torch.cat(y_trues).detach().cpu().numpy() #|y_tures| = () -> [0. 0. 0. ... 1. 1. 1.] y_scores = torch.cat(y_scores).detach().cpu().numpy() #|y_scores| = () -> tensor(0.5552) auc_score += metrics.roc_auc_score( y_trues, y_scores ) #|metrics.roc_auc_score( y_trues, y_scores )| = () -> 0.6203433289463159 loss_result = torch.mean(torch.Tensor(loss_list)).detach().cpu().numpy() if metric_name == "AUC": return auc_score elif metric_name == "RMSE": return loss_result def _validate(self, valid_loader, metric_name): auc_score = 0 y_trues, y_scores = [], [] loss_list = [] with torch.no_grad(): for data in tqdm(valid_loader): self.model.eval() q_seqs, r_seqs, qshft_seqs, rshft_seqs, mask_seqs = data #collate에 정의된 데이터가 나옴 q_seqs = q_seqs.to(self.device) r_seqs = r_seqs.to(self.device) qshft_seqs = qshft_seqs.to(self.device) rshft_seqs = rshft_seqs.to(self.device) mask_seqs = mask_seqs.to(self.device) y_hat = self.model( q_seqs.long(), r_seqs.long() ) #|y_hat| = (bs, sq, self.num_q) -> tensor([[[0.6938, 0.7605, ..., 0.7821], [0.8366, 0.6598, ..., 0.8514],..) #=> 각 sq별로 문항의 확률값들이 담긴 벡터들이 나오게 됨 y_curr = ( y_hat * one_hot(q_seqs.long(), self.num_q) ).sum(-1) #|y_curr| = (bs, sq) -> 현재 값에 대한 확률, 각 sq에는 그 문항에 해당하는 확률값만 담기게 됨 y_next = ( y_hat * one_hot(qshft_seqs.long(), self.num_q) ).sum(-1) #|y_next| = (bs, sq) -> 다음 값에 대한 확률, 각 sq에는 그 문항에 해당하는 확률값만 담기게 됨 y_curr = torch.masked_select(y_curr, mask_seqs) #|y_curr| = () -> 현재 확률값 y_next = torch.masked_select(y_next, mask_seqs) #|y_curr| = () -> 다음 확률값, 원래 DKT는 이것만 봄 correct = torch.masked_select(r_seqs, mask_seqs) #|correct| = () -> 현재 정답값 correct_shft = torch.masked_select(rshft_seqs, mask_seqs) #|correct_shft| = () -> 다음 정답값 loss_w1 = torch.masked_select( torch.norm(y_hat[:, 1:] - y_hat[:, :-1], p = 1, dim = -1), mask_seqs[:, 1:] ) loss_w2 = torch.masked_select( (torch.norm(y_hat[:, 1:] - y_hat[:, :-1], p = 2, dim = -1) ** 2), mask_seqs[:, 1:] ) loss = \ self.crit(y_next, correct_shft) + \ self.lambda_r * self.crit(y_curr, correct) + \ self.lambda_w1 * loss_w1.mean() / self.num_q + \ self.lambda_w2 * loss_w2.mean() / self.num_q y_trues.append(correct_shft) y_scores.append(y_next) loss_list.append(loss) y_trues = torch.cat(y_trues).detach().cpu().numpy() y_scores = torch.cat(y_scores).detach().cpu().numpy() auc_score += metrics.roc_auc_score( y_trues, y_scores ) loss_result = torch.mean(torch.Tensor(loss_list)).detach().cpu().numpy() if metric_name == "AUC": return auc_score elif metric_name == "RMSE": return loss_result def _test(self, test_loader, metric_name): auc_score = 0 y_trues, y_scores = [], [] loss_list = [] with torch.no_grad(): for data in tqdm(test_loader): self.model.eval() q_seqs, r_seqs, qshft_seqs, rshft_seqs, mask_seqs = data #collate에 정의된 데이터가 나옴 q_seqs = q_seqs.to(self.device) r_seqs = r_seqs.to(self.device) qshft_seqs = qshft_seqs.to(self.device) rshft_seqs = rshft_seqs.to(self.device) mask_seqs = mask_seqs.to(self.device) y_hat = self.model( q_seqs.long(), r_seqs.long() ) #|y_hat| = (bs, sq, self.num_q) -> tensor([[[0.6938, 0.7605, ..., 0.7821], [0.8366, 0.6598, ..., 0.8514],..) #=> 각 sq별로 문항의 확률값들이 담긴 벡터들이 나오게 됨 y_curr = ( y_hat * one_hot(q_seqs.long(), self.num_q) ).sum(-1) #|y_curr| = (bs, sq) -> 현재 값에 대한 확률, 각 sq에는 그 문항에 해당하는 확률값만 담기게 됨 y_next = ( y_hat * one_hot(qshft_seqs.long(), self.num_q) ).sum(-1) #|y_next| = (bs, sq) -> 다음 값에 대한 확률, 각 sq에는 그 문항에 해당하는 확률값만 담기게 됨 y_curr = torch.masked_select(y_curr, mask_seqs) #|y_curr| = () -> 현재 확률값 y_next = torch.masked_select(y_next, mask_seqs) #|y_curr| = () -> 다음 확률값, 원래 DKT는 이것만 봄 correct = torch.masked_select(r_seqs, mask_seqs) #|correct| = () -> 현재 정답값 correct_shft = torch.masked_select(rshft_seqs, mask_seqs) #|correct_shft| = () -> 다음 정답값 loss_w1 = torch.masked_select( torch.norm(y_hat[:, 1:] - y_hat[:, :-1], p = 1, dim = -1), mask_seqs[:, 1:] ) loss_w2 = torch.masked_select( (torch.norm(y_hat[:, 1:] - y_hat[:, :-1], p = 2, dim = -1) ** 2), mask_seqs[:, 1:] ) loss = \ self.crit(y_next, correct_shft) + \ self.lambda_r * self.crit(y_curr, correct) + \ self.lambda_w1 * loss_w1.mean() / self.num_q + \ self.lambda_w2 * loss_w2.mean() / self.num_q y_trues.append(correct_shft) y_scores.append(y_next) loss_list.append(loss) y_trues = torch.cat(y_trues).detach().cpu().numpy() y_scores = torch.cat(y_scores).detach().cpu().numpy() auc_score += metrics.roc_auc_score( y_trues, y_scores ) loss_result = torch.mean(torch.Tensor(loss_list)).detach().cpu().numpy() if metric_name == "AUC": return auc_score elif metric_name == "RMSE": return loss_result #auc용으로 train def train(self, train_loader, valid_loader, test_loader, config): if config.crit == "binary_cross_entropy": best_valid_score = 0 best_test_score = 0 metric_name = "AUC" elif config.crit == "rmse": best_valid_score = float('inf') best_test_score = float('inf') metric_name = "RMSE" #출력을 위한 기록용 train_scores = [] valid_scores = [] test_scores = [] #best_model = None # early_stopping 선언 early_stopping = EarlyStopping(metric_name=metric_name, best_score=best_valid_score) # Train and Valid Session for epoch_index in range(self.n_epochs): print("Epoch(%d/%d) start" % ( epoch_index + 1, self.n_epochs )) # Training Session train_score = self._train(train_loader, metric_name) valid_score = self._validate(valid_loader, metric_name) test_score = self._test(test_loader, metric_name) # train, test record 저장 train_scores.append(train_score) valid_scores.append(valid_score) test_scores.append(test_score) # early stop train_scores_avg = np.average(train_scores) valid_scores_avg = np.average(valid_scores) early_stopping(valid_scores_avg, self.model) if early_stopping.early_stop: print("Early stopping") break if config.crit == "binary_cross_entropy": if test_score >= best_test_score: best_test_score = test_score #best_model = deepcopy(self.model.state_dict()) elif config.crit == "rmse": if test_score <= best_test_score: best_test_score = test_score #best_model = deepcopy(self.model.state_dict()) print("Epoch(%d/%d) result: train_score=%.4f valid_score=%.4f test_score=%.4f best_test_score=%.4f" % ( epoch_index + 1, self.n_epochs, train_score, valid_score, test_score, best_test_score, )) print("\n") print("The Best Test Score(" + metric_name + ") in Testing Session is %.4f" % ( best_test_score, )) print("\n") # 가장 최고의 모델 복구 #self.model.load_state_dict(best_model) self.model.load_state_dict(torch.load("../checkpoints/checkpoint.pt")) return train_scores, valid_scores, \ best_valid_score, best_test_score
import {createTypedArray} from './createTypedArray'; import {createVertexObjectPrototype} from './createVertexObjectPrototype'; import {TypedArray, VertexAttributeDataType, VertexAttributeUsageType, VertexObjectBuffersData} from './types'; import {VertexObjectDescriptor} from './VertexObjectDescriptor'; interface BufferAttribute { bufferName: string; attributeName: string; offset: number; } interface Buffer { bufferName: string; itemSize: number; dataType: VertexAttributeDataType; usageType: VertexAttributeUsageType; typedArray: TypedArray; // serial? // needsUpdate? // autoTouch // THREE->bufferAttribute? } export class VertexObjectBuffer { readonly descriptor: VertexObjectDescriptor; readonly capacity: number; /** the names are always sorted the same way */ readonly attributeNames: readonly string[]; readonly buffers: Map<string, Buffer>; readonly bufferAttributes: Map<string, BufferAttribute>; /** buffer name -> list of buffer attributes */ readonly bufferNameAttributes: Map<string, BufferAttribute[]>; constructor(source: VertexObjectDescriptor | VertexObjectBuffer, capacityOrBuffersData: number | VertexObjectBuffersData) { let buffersData: VertexObjectBuffersData | undefined; if (typeof capacityOrBuffersData === 'number') { this.capacity = capacityOrBuffersData; } else { buffersData = capacityOrBuffersData; this.capacity = buffersData.capacity; } if (source instanceof VertexObjectBuffer) { this.descriptor = source.descriptor; this.attributeNames = source.attributeNames; this.bufferAttributes = source.bufferAttributes; this.bufferNameAttributes = source.bufferNameAttributes; this.buffers = new Map(); for (const [bufferName, buffer] of source.buffers) { this.buffers.set(bufferName, { bufferName, itemSize: buffer.itemSize, dataType: buffer.dataType, usageType: buffer.usageType, typedArray: createTypedArray(buffer.dataType, this.capacity * this.descriptor.vertexCount * buffer.itemSize), }); } } else { this.descriptor = source; this.buffers = new Map(); this.bufferAttributes = new Map(); this.attributeNames = Object.freeze(Array.from(this.descriptor.attributeNames).sort()); for (const attributeName of this.attributeNames) { const attribute = this.descriptor.getAttribute(attributeName)!; const {bufferName} = attribute; let offset = 0; if (this.buffers.has(bufferName)) { const buffer = this.buffers.get(bufferName)!; offset = buffer.itemSize; buffer.itemSize += attribute.size; } else { this.buffers.set(bufferName, { bufferName, itemSize: attribute.size, dataType: attribute.dataType, usageType: attribute.usageType, // @ts-ignore typedArray: undefined, }); } this.bufferAttributes.set(attributeName, { bufferName, attributeName, offset, }); } for (const buffer of this.buffers.values()) { buffer.typedArray = buffersData?.buffers[buffer.bufferName] ?? createTypedArray(buffer.dataType, this.capacity * this.descriptor.vertexCount * buffer.itemSize); } this.bufferNameAttributes = new Map(); for (const bufAttr of this.bufferAttributes.values()) { const {bufferName} = bufAttr; if (this.bufferNameAttributes.has(bufferName)) { this.bufferNameAttributes.get(bufferName)!.push(bufAttr); } else { this.bufferNameAttributes.set(bufferName, [bufAttr]); } } } if (!this.descriptor.voPrototype) { this.descriptor.voPrototype = createVertexObjectPrototype( this, this.descriptor.basePrototype as object | undefined, this.descriptor.methods as object | undefined, ); } } copy(otherVob: VertexObjectBuffer, objectOffset = 0): void { const {vertexCount} = this.descriptor; for (const {bufferName, typedArray, itemSize} of this.buffers.values()) { typedArray.set(otherVob.buffers.get(bufferName)!.typedArray, objectOffset * vertexCount * itemSize); } } clone(): VertexObjectBuffer { const clone = new VertexObjectBuffer(this, this.capacity); clone.copy(this); return clone; } copyArray(source: TypedArray, bufferName: string, objectOffset = 0): void { const {vertexCount} = this.descriptor; const {typedArray, itemSize} = this.buffers.get(bufferName)!; typedArray.set(source, objectOffset * vertexCount * itemSize); } copyWithin(target: number, start: number, end = this.capacity): void { const {vertexCount} = this.descriptor; for (const {typedArray, itemSize} of this.buffers.values()) { typedArray.copyWithin(target * vertexCount * itemSize, start * vertexCount * itemSize, end * vertexCount * itemSize); } } copyAttributes(attributes: Record<string, ArrayLike<number>>, objectOffset = 0): number { let copiedObjCount = 0; for (const [attrName, data] of Object.entries(attributes)) { const attr = this.bufferAttributes.get(attrName); if (attr) { let attrObjCount = 0; const buffer = this.buffers.get(attr.bufferName)!; const {vertexCount} = this.descriptor; const attrSize = this.descriptor.getAttribute(attrName)!.size; let idx = 0; let bufIdx = objectOffset * vertexCount * buffer.itemSize; while (idx < data.length && attrObjCount + objectOffset < this.capacity) { for (let i = 0; i < vertexCount; i++) { buffer.typedArray.set(Array.prototype.slice.call(data, idx, idx + attrSize), bufIdx + attr.offset); idx += attrSize; bufIdx += buffer.itemSize; } ++attrObjCount; } if (attrObjCount > copiedObjCount) { copiedObjCount = attrObjCount; } } } return copiedObjCount; } toAttributeArrays(attributeNames: string[], start = 0, end = this.capacity): Record<string, TypedArray> { return Object.fromEntries( attributeNames.map((attrName) => { const attr = this.bufferAttributes.get(attrName); if (attr) { const buffer = this.buffers.get(attr.bufferName)!; const {vertexCount} = this.descriptor; const attrSize = this.descriptor.getAttribute(attrName)!.size; const targetArray = createTypedArray(buffer.dataType, (end - start) * vertexCount * attrSize); let targetIdx = 0; let bufferIdx = start * vertexCount * buffer.itemSize + attr.offset; for (let objIdx = start; objIdx < end; objIdx++) { for (let i = 0; i < vertexCount; i++) { targetArray.set(buffer.typedArray.subarray(bufferIdx, bufferIdx + attrSize), targetIdx); targetIdx += attrSize; bufferIdx += buffer.itemSize; } } return [attrName, targetArray]; } return [attrName]; }), ); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Page</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="login-container"> <div class="user-type"> <label><input type="radio" name="userType" value="admin" onclick="showLoginForm('admin')" checked> Admin</label> <label><input type="radio" name="userType" value="student" onclick="showLoginForm('student')"> Student</label> </div> <!-- Admin Form --> <form class="login-form" id="admin-form" onsubmit="return validateForm('admin')"> <h2>Admin Login</h2> <div class="input-group"> <label for="admin-username">Username</label> <input type="text" id="admin-username" name="username" required> </div> <div class="input-group"> <label for="admin-password">Password</label> <input type="password" id="admin-password" name="password" required> </div> <button type="submit" class="login-button">Login</button> </form> <!-- Student Form --> <form class="login-form" id="student-form" onsubmit="return validateForm('student')" style="display:none;"> <h2>Student Login</h2> <div class="input-group"> <label for="student-username">Username</label> <input type="text" id="student-username" name="username" required> </div> <div class="input-group"> <label for="student-password">Password</label> <input type="password" id="student-password" name="password" required> </div> <button type="submit" class="login-button">Login</button> </form> </div> <script> function showLoginForm(userType) { document.getElementById('admin-form').style.display = userType === 'admin' ? 'block' : 'none'; document.getElementById('student-form').style.display = userType === 'student' ? 'block' : 'none'; } function validateForm(formType) { let username = document.getElementById(formType + '-username').value; let password = document.getElementById(formType + '-password').value; if (username === '1RN21CD015' && password === '12345678') { // Redirect to another page if credentials are correct window.location.href = 'student.html'; // Replace 'welcome.html' with the actual page you want to redirect to return false; // Prevent default form submission } else { alert('Invalid Username or Password'); return false; // Prevent form submission } } </script> </body> </html>