text
stringlengths
184
4.48M
import 'package:autoclub_frontend/browser/used_dealer/used_dealer_homepage.dart'; import 'package:autoclub_frontend/browser/used_dealer/used_dealer_listing.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class UsedDealerListingEntry extends StatelessWidget { final Map<String, dynamic> listing; final Function(UsedDealerPage, Map<String, dynamic>) updateDealerPage; const UsedDealerListingEntry({Key? key, required this.listing, required this.updateDealerPage}) : super(key: key); @override Widget build(BuildContext context) { // Define a fixed height for the image or use MediaQuery to make it responsive double imageHeight = 180; // Example fixed height return GestureDetector( onTap: () { updateDealerPage(UsedDealerPage.listing, listing); }, child: Column( mainAxisSize: MainAxisSize.min, // Make the column take up only needed space crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: imageHeight, // Apply fixed height to control image size child: Stack( children: [ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image.network(listing["thumbnailLink"], fit: BoxFit.cover), ), Positioned( bottom: 10, left: 10, child: Container( width: 120, height: 30, decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(15) ), child: Align( alignment: Alignment.center, child: Text( "\$ ${NumberFormat("#,##0", "en_US").format(listing["salePrice"])}", style: Theme.of(context).primaryTextTheme.displaySmall, ), ), ), ), ] ), ), const SizedBox(height: 15,), Text( listing["carObject"].fullName(), style: Theme.of(context).primaryTextTheme.displayLarge, ), const SizedBox(height: 8,), Text( listing["titleDescription"], style: Theme.of(context).primaryTextTheme.displayMedium, ), Text( "${NumberFormat("#,##0", "en_US").format(listing["carObject"].mileage)} km", style: Theme.of(context).primaryTextTheme.displayMedium, ) ], ), ); } }
import React, { useState, useEffect } from 'react'; import Papa, { ParseResult } from 'papaparse'; import { useFormContext } from 'react-hook-form'; import { MessageDescriptor } from 'react-intl'; import { FileReaderFile } from '~utils/fileReader/types'; import { InputStatus } from '~shared/Fields'; import { isEqual, isNil } from '~utils/lodash'; import { DefaultPlaceholder, SingleFileUpload } from '../FileUpload'; import CSVUploaderItem from './CSVUploaderItem'; interface Props { name: string; processingData: boolean; setProcessingData: React.Dispatch<React.SetStateAction<boolean>>; status?: string | MessageDescriptor; error?: string | MessageDescriptor; setHasFile?: React.Dispatch<React.SetStateAction<boolean>>; } const MIME_TYPES = { 'text/csv': [], }; const CSVUploader = ({ name, error, status, processingData, setProcessingData, setHasFile, }: Props) => { const [CSVFile, setCSVFile] = useState<FileReaderFile | null>(null); const [parsedCSV, setParsedCSV] = useState<ParseResult<unknown> | null>(null); const { setValue, watch, trigger, formState: { touchedFields }, } = useFormContext(); const uploaderValue = watch(name); const handleUploadError = async () => { if (isNil(uploaderValue?.parsedData)) { setValue(name, { ...CSVFile, parsedData: [] }); } }; useEffect(() => { if (CSVFile && !parsedCSV) { Papa.parse(CSVFile.file, { complete: setParsedCSV, header: true, }); if (setHasFile) setHasFile(true); } else if (!CSVFile && parsedCSV) { setParsedCSV(null); setValue(name, null, { shouldValidate: true }); if (setHasFile) setHasFile(false); } }, [setHasFile, CSVFile, parsedCSV, name, setValue]); useEffect(() => { if (CSVFile && parsedCSV && isNil(uploaderValue?.parsedData)) { let validAddresses: string[] = []; if (parsedCSV.meta.fields?.length === 1) { validAddresses = parsedCSV.data.flatMap( (CSVRow: Record<string, any>) => { const potentialAddress: string = CSVRow[Object.keys(CSVRow)[0]]; return potentialAddress ? [potentialAddress] : []; }, ); } if (!isEqual(validAddresses, uploaderValue?.parsedData)) { setValue( name, { ...CSVFile, parsedData: validAddresses }, { shouldTouch: true }, ); trigger(name); } } if (processingData) { setProcessingData(false); } }, [ trigger, parsedCSV, uploaderValue, setValue, processingData, setProcessingData, name, CSVFile, ]); const getPlaceholder = () => { if (!CSVFile) { return <DefaultPlaceholder />; } return ( <CSVUploaderItem error={error} name={name} upload={(file: FileReaderFile | null) => setCSVFile(file)} processingData={processingData} handleProcessingData={setProcessingData} /> ); }; return ( <> <SingleFileUpload handleFileAccept={setCSVFile} dropzoneOptions={{ accept: MIME_TYPES, }} handleFileReject={handleUploadError} placeholder={getPlaceholder()} /> <InputStatus appearance={{ theme: 'fat', textSpace: 'wrap' }} status={status} error={error} touched={touchedFields[name]} /> </> ); }; CSVUploader.displayName = 'CSVUploader'; export default CSVUploader;
package com.kite.mvc.domain; //DB와 상관없으므로 이 패키지 사용 import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"id", "message", "creationTime"}) //이름은 엘리먼트의 이름으로 바로 들어가게 함. //속성의 구성 public class GuestMessage { private int id; private String message; private Date creationTime; public GuestMessage(int id, String message, Date creationTime) { super(); this.id = id; this.message = message; this.creationTime = creationTime; } public GuestMessage() { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Date getCreationTime() { return creationTime; } public void setCreationTime(Date creationTime) { this.creationTime = creationTime; } @Override public String toString() { return "GuestMessage [id=" + id + ", message=" + message + ", creationTime=" + creationTime + "]"; } }
export interface ILoginMethod { name: string target?: string href?: string } export interface IRuntimeConfig { baseUrl: string loginMethods: ILoginMethod[] } export const config: IRuntimeConfig = { baseUrl: window.location.pathname, loginMethods: [ { name: 'Password', target: '/login/password' } // More login methods here ] } export function getUrl(path: string) { let base = config.baseUrl if (base.endsWith('/')) base = base.slice(0, -1) if (path.startsWith('/')) path = path.slice(1) return base + '/' + path } try { const resp = await fetch('config.json') const data = await resp.json() Object.assign(config, data) } catch (err) { console.log(err) }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * 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. See accompanying * LICENSE file. */ package target; import hydra.blackboard.Blackboard; public class TargetBB extends Blackboard{ static String BB_NAME = "TargetTest_BlackBoard"; static String BB_TYPE = "RMI"; public static long NumCreates = 0; private static TargetBB bbInstance = null; /* Creates a black board with a name and the transport type * */ private TargetBB(String name, String type) { super(name, type, TargetBB.class); } public TargetBB() { // TODO Auto-generated constructor stub } /** Returns the singleton instance of the TargetBB * */ public static TargetBB getBB() { if (bbInstance == null) { synchronized (TargetBB.class) { if (bbInstance == null) { bbInstance = new TargetBB(BB_NAME, BB_TYPE); } } } return bbInstance; } }
import {FC} from "react"; import {SubmitHandler, useForm} from "react-hook-form"; import {ICommentDto} from "@/types/comment.interface"; import {commentApi} from "@/store/api/comment.api"; import styles from './../../../layout/header/authForm/AuthForm.module.scss' import Field from "@/components/UI/field/Field"; import {MdSend} from "react-icons/md"; const AddComment: FC<{ filmId: number | undefined }> = ({filmId}) => { const {register, formState: {errors}, handleSubmit, reset} = useForm<ICommentDto>({ mode: 'onChange' }) const [writeComment, {isLoading}] = commentApi.useCreateCommentMutation() const onSubmit: SubmitHandler<ICommentDto> = async data =>{ writeComment({...data, filmId}).unwrap().then(() => reset()) } return ( <form className={styles.form} onSubmit={handleSubmit(onSubmit)}> <div className={'relative'}> <Field {...register('message', { required: 'Сообщение обязательно' })} placeholder={'Введите комментарий'} error={errors.message}/> <button className={'text-xl absolute right-2 top-1.5 text-white'} disabled={isLoading}> <MdSend/> </button> </div> </form> ) } export default AddComment;
<template> <view class="container"> <view class="wallet-header"> <view class="header-container"> <view class="netWorth"> <view> <text>净资产</text> <text @tap="eyesTab" class="iconfont eye-item-img {{ eyeImageClass }}" > </text> </view> <view>{{ hiddenMoney ? '****' : netWorth }}</view> </view> <view class="asset-and-debt"> <text>总资产 {{ hiddenMoney ? '****' : totalAssets }}</text> <text>|</text> <text>总负债 {{ hiddenMoney ? '****' : totalDebt }}</text> </view> </view> </view> <view id="all-assets"> <view class="asset" wx:for="{{ wallets }}"> <view class="asset-header"> <text class="fs12">{{ item.name }}</text> <text class="fs12">{{ hiddenMoney ? '****' : item.amount }}</text> </view> <view class="column" wx:for="{{ item.childs }}" bindtap="showAsset('{{ item.id }}')"> <view class="icon pull-left"> <image class="icon-small-size" src="{{ item.icon_path }}"></image> </view> <view class="money pull-right">{{ hiddenMoney ? '****' : item.amount }}</view> <view class="title">{{ item.name }}</view> </view> </view> </view> </view> </template> <script> import wepy from 'wepy' import Session from '@/utils/session' import wxRequest from '@/utils/wxRequest' export default class Wallet extends wepy.page { config = { navigationBarTitleText: '资产总览', "usingComponents": { "i-spin": "../public/iview/spin/index" } } data = { wallets: [], netWorth: '0.00', totalAssets: '0.00', totalDebt: '0.00', yesterdayAmount: '0.00', seventAmount: '0.00', monthAmount: '0.00', } methods = { showAsset (id) { wx.navigateTo({ url: `/pages/assets/asset_detail?id=${id}` }) }, async eyesTab () { this.$parent.globalData.user.hidden_asset_money = !this.$parent.globalData.user.hidden_asset_money await wxRequest.Put('users/update_user', { user: { hidden_asset_money: this.$parent.globalData.user.hidden_asset_money ? 1 : 0 } }) } } onShow () { if (Session.get('@asset_list_load_cache@')) { this.wallets = Session.get('@asset_list_load_cache@') this.$apply() } this.getAssets() } computed = { hiddenMoney () { return this.$parent.globalData.user.hidden_asset_money }, eyeImageClass () { return this.hiddenMoney ? 'jz-icon-yanjing-zheng' : 'jz-icon-yanjing-bi' } } async getAssets() { const data = await wxRequest.Get('wallet'); let list = data.list let header = data.header this.netWorth = header.net_worth, this.totalAssets = header.total_asset, this.totalDebt = header.total_liability, this.yesterdayAmount = header.yesterday_balance, this.seventAmount = header.sevent_day_consumption, this.monthAmount = header.last_month_consumption, this.wallets = list Session.set('@asset_list_load_cache@', this.wallets) this.$apply() } } </script> <style lang="scss" src="../public/styles/asset.scss"></style>
"use client"; import { Button } from "@/app/_components/ui/button"; import { useEffect, useMemo, useState } from "react"; import type { CreditNoteFile, InvoiceFile, ParseError } from "@/lib/invoice.parser"; import { useFilePicker } from "use-file-picker"; import { getInvoiceTaxTotal, parseTributaryFile } from "@/lib/invoice.parser"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/app/_components/ui/card"; import { Tooltip, TooltipContent, TooltipTrigger, } from "@/app/_components/ui/tooltip"; import InvoicePreview from "@/app/_components/invoice-preview"; import CreditNotePreview from "@/app/_components/creditnote-preview"; import { type ImpuestosClass } from "@/lib/invoice.parser.types"; import moment from "moment"; import ExpensesGraph from "@/app/_components/expenses-graph"; const ImportPage: React.FC = () => { const [invoices, setInvoices] = useState<InvoiceFile[]>([]); const [creditNotes, setCreditNotes] = useState<CreditNoteFile[]>([]); const [parseErrors, setParseErrors] = useState<ParseError[]>([]); const { openFilePicker, filesContent, loading } = useFilePicker({ accept: ".xml", multiple: true, readAs: "ArrayBuffer", readFilesContent: true, }); useEffect(() => { if (filesContent.length > 0) { const docs: [InvoiceFile[], CreditNoteFile[], ParseError[]] = filesContent.reduce( (p, f) => { const [invoice, creditnote, parseError] = parseTributaryFile( f.name, Buffer.from(f.content), ); if (invoice) { p[0].push(invoice); return p; } if (creditnote) { p[1].push(creditnote); return p; } if (parseError) { p[2].push(parseError); return p; } p[2].push({ fileName: f.name, error: "Unknown error" }); return p; }, [[], [], []] as [InvoiceFile[], CreditNoteFile[], ParseError[]], ); setInvoices(docs[0]); setCreditNotes(docs[1]); setParseErrors(docs[2]); } }, [filesContent]); const USDollar = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }); const businessInvoices = useMemo(() => { return invoices.filter((v) => v.content.infoFactura.identificacionComprador.endsWith("001"), ); }, [invoices]); const business1SInvoices = useMemo(() => { return businessInvoices.filter((v) => { const date = moment(v.content.infoFactura.fechaEmision, 'DD/MM/YYYY'); return date.get('month') <= 5; }); }, [businessInvoices]); const business2SInvoices = useMemo(() => { return businessInvoices.filter((v) => { const date = moment(v.content.infoFactura.fechaEmision, 'DD/MM/YYYY'); if (date.get('year') <= 2020) { console.error("Invalid date", date, v.content.infoFactura.fechaEmision); } return date.get('month') > 5; }); }, [businessInvoices]); const businessCreditNotes = useMemo(() => { return creditNotes.filter((v) => v.content.infoNotaCredito.identificacionComprador.endsWith("001"), ); }, [creditNotes]); const business1SCreditNotes = useMemo(() => { return businessCreditNotes.filter((v) => { const date = moment(v.content.infoNotaCredito.fechaEmision, 'DD/MM/YYYY'); return date.get('month') <= 5; }); }, [businessCreditNotes]); const business2SCreditNotes = useMemo(() => { return businessCreditNotes.filter((v) => { const date = moment(v.content.infoNotaCredito.fechaEmision, 'DD/MM/YYYY'); return date.get('month') > 5; }); }, [businessCreditNotes]); const personalInvoices = useMemo(() => { return invoices.filter( (v) => !v.content.infoFactura.identificacionComprador.endsWith("001"), ); }, [invoices]); // const personalCreditNotes = useMemo(() => { // return creditNotes.filter( // (v) => !v.content.infoNotaCredito.identificacionComprador.endsWith("001"), // ); // }, [creditNotes]); const invoicesTotal = useMemo(() => { return invoices.reduce((p, c) => { return p + c.content.infoFactura.importeTotal; }, 0); }, [invoices]); const [invoicesAverage, businessInvoicesAverage, personalInvoicesAverage] = useMemo(() => { const total = invoices.reduce((p, c) => { return p + c.content.infoFactura.importeTotal; }, 0); const businessTotal = businessInvoices.reduce((p, c) => { return p + c.content.infoFactura.importeTotal; }, 0); const personalTotal = personalInvoices.reduce((p, c) => { return p + c.content.infoFactura.importeTotal; }, 0); return [total / invoices.length, businessTotal / businessInvoices.length, personalTotal / personalInvoices.length]; }, [invoices, businessInvoices, personalInvoices]); const taxesTypes = useMemo(() => { return invoices .reduce((p, c) => { return [ ...p, ...c.content.detalles.detalle.reduce((p, c) => { return [ ...p, ...c.impuestos.impuesto.map((v) => { return v.tarifa; }), ]; }, [] as number[]), ]; }, [] as number[]) .filter((v, i, a) => a.indexOf(v) === i) .sort((a, b) => a - b); }, [invoices]); // const reasonTypes = useMemo(() => { // return creditNotes // .reduce((p, c) => { // return [...p, c.content.infoNotaCredito.motivo]; // }, [] as string[]) // .filter((v, i, a) => a.indexOf(v) === i); // }, [creditNotes]); return ( <main className="flex-1 space-y-4 p-8 pt-6"> <section className="flex items-center justify-between space-y-2"> <h2 className="text-3xl font-bold tracking-tight">Import</h2> <div className="flex items-center space-x-2"> <Button onClick={openFilePicker} disabled={loading}> Load Files </Button> </div> </section> {parseErrors.length > 0 ? <section> <h3 className="text-2xl font-bold tracking-tight">Errors</h3> <ul> {parseErrors.map((error, index) => ( <li key={index}> <h4 className="text-xl font-bold tracking-tight"> {error.fileName} </h4> <p>{error.error}</p> </li> ))} </ul> </section> : null} <section className="grid grid-cols-2 gap-2"> <Card> <CardHeader> <CardTitle>Summary</CardTitle> <CardDescription> Total {USDollar.format(invoicesTotal)} </CardDescription> </CardHeader> <CardContent> <div className="grid grid-cols-3 gap-1"> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {invoices.length + creditNotes.length} </h5> <p className="text-xs font-medium">files imported</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( businessInvoices.reduce((p, c) => { return p + c.content.infoFactura.importeTotal; }, 0), )} </h5> <p className="text-xs font-medium">Business expenses</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( personalInvoices.reduce((p, c) => { return p + c.content.infoFactura.importeTotal; }, 0), )} </h5> <p className="text-xs font-medium">Personal expenses</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format(invoicesAverage)} </h5> <p className="text-xs font-medium">Average expense</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format(businessInvoicesAverage)} </h5> <p className="text-xs font-medium">Avg business expense</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format(personalInvoicesAverage)} </h5> <p className="text-xs font-medium">Avg personal expense</p> </div> </div> </CardContent> </Card> <Card> <CardHeader> <CardTitle>Taxes</CardTitle> <CardDescription>Overview of generated taxes</CardDescription> </CardHeader> <CardContent> <div className="grid grid-cols-3 gap-1"> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( businessInvoices.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { return ( p + c.impuestos.impuesto.reduce((p, c) => { return p + c.valor; }, 0) ); }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">Business taxes</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( personalInvoices.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { return ( p + c.impuestos.impuesto.reduce((p, c) => { return p + c.valor; }, 0) ); }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">Personal taxes</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( invoices.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { return ( p + c.impuestos.impuesto.reduce((p, c) => { return p + c.valor; }, 0) ); }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">Total taxes</p> </div> {taxesTypes.map((tax, index) => ( <div key={index} className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> <Tooltip> <TooltipContent>Personal</TooltipContent> <TooltipTrigger> {USDollar.format( personalInvoices.reduce( (p, c) => p + getInvoiceTaxTotal(c, tax), 0, ), )} </TooltipTrigger> </Tooltip> / <Tooltip> <TooltipContent>Business</TooltipContent> <TooltipTrigger> {USDollar.format( businessInvoices.reduce( (p, c) => p + getInvoiceTaxTotal(c, tax), 0, ), )} </TooltipTrigger> </Tooltip> </h5> <p className="text-xs font-medium">{tax}%</p> </div> ))} </div> </CardContent> </Card> <Card> <CardHeader> <CardTitle>Semesters (Business)</CardTitle> <CardDescription>Subtotals invoices ({businessInvoices.length})</CardDescription> </CardHeader> <CardContent> <div className="grid grid-cols-3 gap-1"> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( business1SInvoices.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { return ( p + c.impuestos.impuesto.reduce((p, c) => { return p + c.baseImponible; }, 0) ); }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">1st semester({business1SInvoices.length})</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( business2SInvoices.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { return ( p + c.impuestos.impuesto.reduce((p, c) => { return p + c.baseImponible; }, 0) ); }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">2nd semester({business2SInvoices.length})</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( businessInvoices.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { return ( p + c.impuestos.impuesto.reduce((p, c) => { return p + c.baseImponible; }, 0) ); }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">Total subtotal({businessInvoices.length})</p> </div> {taxesTypes.map((tax, index) => ( <div key={index} className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> <Tooltip> <TooltipContent>1st semester</TooltipContent> <TooltipTrigger> {USDollar.format( business1SInvoices.reduce( (p, c) => p + c.content.detalles.detalle.reduce( (p2, c2) => p2 + c2.impuestos.impuesto .filter((v) => v.tarifa === tax) .reduce((p3, c3) => p3 + c3.baseImponible, 0), 0, ), 0, ), )} </TooltipTrigger> </Tooltip> / <Tooltip> <TooltipContent>2nd semester</TooltipContent> <TooltipTrigger> {USDollar.format( business2SInvoices.reduce( (p, c) => p + getInvoiceTaxTotal(c, tax), 0, ), )} </TooltipTrigger> </Tooltip> </h5> <p className="text-xs font-medium">{tax}%</p> </div> ))} </div> </CardContent> </Card> <Card> <CardHeader> <CardTitle>Semesters (Business)</CardTitle> <CardDescription>Subtotals credit notes</CardDescription> </CardHeader> <CardContent> <div className="grid grid-cols-3 gap-1"> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( business1SCreditNotes.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { if (!(c.impuestos as string[]).length) { return ( p + (c.impuestos as ImpuestosClass).impuesto.reduce( (p, c) => { return p + c.baseImponible; }, 0, ) ); } return p; }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">1st semester</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( business2SCreditNotes.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { if (!(c.impuestos as string[]).length) { return ( p + (c.impuestos as ImpuestosClass).impuesto.reduce( (p, c) => { return p + c.baseImponible; }, 0, ) ); } return p; }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">2nd semester</p> </div> <div className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> {USDollar.format( businessCreditNotes.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { if (!(c.impuestos as string[]).length) { return ( p + (c.impuestos as ImpuestosClass).impuesto.reduce( (p, c) => { return p + c.baseImponible; }, 0, ) ); } return p; }, 0) ); }, 0), )} </h5> <p className="text-xs font-medium">Total subtotal</p> </div> {taxesTypes.map((tax, index) => ( <div key={index} className="flex flex-col text-center"> <h5 className="text-xl font-bold tracking-tight"> <Tooltip> <TooltipContent>1st semester</TooltipContent> <TooltipTrigger> {USDollar.format( business1SCreditNotes.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { if (!(c.impuestos as string[]).length) { return ( p + (c.impuestos as ImpuestosClass).impuesto .filter((v) => v.tarifa === tax) .reduce((p, c) => { return p + c.baseImponible; }, 0) ); } return p; }, 0) ); }, 0), )} </TooltipTrigger> </Tooltip> / <Tooltip> <TooltipContent>2nd semester</TooltipContent> <TooltipTrigger> {USDollar.format( business2SCreditNotes.reduce((p, c) => { return ( p + c.content.detalles.detalle.reduce((p, c) => { if (!(c.impuestos as string[]).length) { return ( p + (c.impuestos as ImpuestosClass).impuesto .filter((v) => v.tarifa === tax) .reduce((p, c) => { return p + c.baseImponible; }, 0) ); } return p; }, 0) ); }, 0), )} </TooltipTrigger> </Tooltip> </h5> <p className="text-xs font-medium">{tax}%</p> </div> ))} </div> </CardContent> </Card> </section> <h3 className="text-2xl font-bold tracking-tight">Expenses (Business)</h3> <ExpensesGraph invoices={businessInvoices} taxesType={taxesTypes} /> <h3 className="text-2xl font-bold tracking-tight">Credit notes (Business)</h3> <h4 className="text-1xl font-bold tracking-tight">1st Semester</h4> <section className="grid grid-cols-4 gap-2"> {business1SCreditNotes.map((creditNote, index) => ( <CreditNotePreview taxesTypes={taxesTypes} creditNote={creditNote} key={index} /> ))} {!business1SCreditNotes.length && (<p>No credit notes found</p>)} </section> <h4 className="text-1xl font-bold tracking-tight">2nd Semester</h4> <section className="grid grid-cols-4 gap-2"> {business2SCreditNotes.map((creditNote) => ( <CreditNotePreview taxesTypes={taxesTypes} creditNote={creditNote} key={creditNote.fileName} /> ))} {!business2SCreditNotes.length && (<p>No credit notes found</p>)} </section> <h3 className="text-2xl font-bold tracking-tight">Invoices</h3> <section className="grid grid-cols-4 gap-2"> {invoices.map((file) => ( <InvoicePreview invoice={file} key={file.fileName} taxesTypes={taxesTypes} /> ))} </section> </main> ); }; export default ImportPage;
/**************************************************************************** FileName [ cirMgr.h ] PackageName [ cir ] Synopsis [ Define circuit manager ] Author [ Chung-Yang (Ric) Huang ] Copyright [ Copyleft(c) 2008-2014 LaDs(III), GIEE, NTU, Taiwan ] ****************************************************************************/ #ifndef CIR_MGR_H #define CIR_MGR_H #include <vector> #include <string> #include <fstream> #include <iostream> #include <map> #include <set> #include "myHashMap.h" #include "cirGate.h" #include <mutex> #include <thread> #include <condition_variable> using namespace std; // TODO: Feel free to define your own classes, variables, or functions. #include "cirDef.h" extern CirMgr *cirMgr; class fraigTask { public: fraigTask(unsigned p, unsigned m, bool i): parent(p), merge(m), invert(i){} unsigned parent; unsigned merge; bool invert; }; class fecEraser { public: set<unsigned> toRemove; bool operator () (unsigned g) const { return toRemove.find(g) == toRemove.end(); } }; class CirMgr { public: CirMgr() { simulate = false; _simLog = 0; satSolver = 0; fecGroupList = 0; gates = 0; fecHashMap = 0; } ~CirMgr() { CirGate * gate; if(gates==0) return; for(unsigned i =0;i<M+O+1;i++) { gate = getGate(i); if(gate !=0) delete gate; } delete gates; delete fecGroupList; if(fecHashMap != 0) delete fecHashMap; } // Access functions // return '0' if "gid" corresponds to an undefined gate. CirGate* getGate(unsigned gid) const { if(gid >= (M+O+1)) { return 0; } return gates[gid]; } // My Custom Function string getGateName(unsigned gid) const { map<unsigned,string>::const_iterator itr = nameTable.find(gid); if(itr == nameTable.end()) return ""; else return (*itr).second; } // Member functions about circuit construction bool readCircuit(const string&); // Member functions about circuit optimization void sweep(); void optimize(); // Member functions about simulation void randomSim(); void fileSim(ifstream&); void setSimLog(ofstream *logFile) { _simLog = logFile; } // Member functions about fraig void strash(); void printFEC() const; void fraig(); // Member functions about circuit reporting void printSummary() const; void printNetlist() const; void printPIs() const; void printPOs() const; void printFloatGates() const; void printFECPairs() const; void writeAag(ostream&) const; private: ofstream *_simLog; typedef map<unsigned,CirGate*> cirDict; unsigned int M; unsigned int I; unsigned int L; unsigned int O; unsigned int A; CirGate** gates; vector<unsigned> PIs; vector<unsigned> POs; //vector<unsigned> Ls; //vector<unsigned> As; set<unsigned> unDefs;//change name (floatFanInID) set<unsigned> gatesWithFloatFanin; vector<unsigned> dfsList; //set<unsigned> reachableID; map<unsigned,string> nameTable; void buildfanout(); void buildDFSList(); CirGate** cirGateBegin() {return gates;} CirGate** cirOutputGateBegin() {return gates + (M+1);} CirGate** cirGateEnd() {return gates + (M+O+1);} void merge(CirGate* a, CirGate* b, bool invert ,string why); void checkhealth(); void removeGate(unsigned gid); //for simulation map<unsigned,vector<uint32_t> > patternPool; grouplist* fecGroupList; HashMap<CirGate::PatternKey,grouplist::iterator>* fecHashMap; bool simulate; unsigned nSim; void gateSim(unsigned gid, unsigned &round, bool skipPISim = false); void roundSim(unsigned &round, unsigned bitPerRound = 32); void resetSim(); void randomAddPattern(); void fecGroupInit(); bool fecGroupUpdate(); void fecGroupPushToGate(); static bool fecGroupListEraser(const IdList &i) { return i.size()==1; } //for fraig grouplist::iterator currentFECGroup; vector<fraigTask> task; bool taskFinish; void initFECTask() { currentFECGroup = fecGroupList->begin(); taskFinish = false; return; } mutex cirMutex; bool getFECTask(grouplist::iterator &itr) { lock_guard<mutex> mLock(cirMutex); if(taskFinish) return false; if(currentFECGroup == fecGroupList->end()) { taskFinish = true; return false; } itr = currentFECGroup; currentFECGroup ++; return true; } void setFraigTask(unsigned &parent, unsigned &merge, bool &invert) { lock_guard<mutex> mLock(cirMutex); task.push_back(fraigTask(parent, merge, invert)); } void fraigTaskMerge() { for(vector<fraigTask>::iterator itr = task.begin(); itr != task.end(); itr++) { merge(getGate(itr->merge), getGate(itr->parent), itr->invert,"Fraig"); } task.clear(); } SatSolver* satSolver; void satInitialize(); bool solveBySat(unsigned gid1, unsigned gid2, bool &invert); bool readForSim[4]; bool ready; std::condition_variable simCon; std::mutex simMutex; class fecSolver { public: fecSolver() { varArray = 0; solver = 0; } ~fecSolver() { if(varArray != 0) delete [] varArray; if(solver != 0) delete solver; } unsigned id; unsigned counter; Var* varArray; SatSolver* solver; unsigned gid1, gid2; bool invert, result; fecEraser eraser; grouplist::iterator itr; void init(); void solve(); void operator () (); }; }; #endif
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Newsletter Signup</title> </head> <body> <h1>Newletter Signup</h1> <p id="feedback"></p> <form> <div> <label for="name">Name</label ><input type="text" id="name" name="name" /> </div> <div> <label for="email">Email</label ><input type="text" id="email" name="email" /> </div> <div> <button type="submit">Signup</button> </div> </form> <script> let form = document.querySelector("form"); let name = document.querySelector("#name"); let email = document.querySelector("#email"); let feedback = document.querySelector("#feedback"); form.addEventListener("submit", (e) => { e.preventDefault(); feedback.textContent = ""; fetch("/newsletter_signup", { method: "POST", body: JSON.stringify({ name: name.value, email: email.value }), }) .then((res) => res.json()) .then((data) => { name.value = ""; email.value = ""; feedback.textContent = data.msg; }) .catch((err) => { console.error(err); feedback.textContent = "Failed to signup :/"; }); }); </script> </body> </html>
<template> <div class="list-page"> <pullUpBox class="wrapper" :data="goodListData" @loadMore="loadData"> <ul class="list"> <li class="item" :key="index" v-for="(item ,index) in goodListData "> <span class="hot" v-show="item.is_fire==1"></span> <img v-lazy="item.goods_img"> <h6 class="title-6">{{item.goods_name}}</h6> <a href="javascript:;" v-if="item.stock_num_total>0" @click="submitOrder(item)" class="btn literary-btn" >{{item.goods_wealth}} 财气</a> <a href="javascript:;" v-else class="btn literary-btn" :class="{active:true}" >已兑完</a> </li> </ul> </pullUpBox> <!-- 这里时信息提示区域 --> <msgBox :msgTxt="msgTxt"></msgBox> <!-- 这里显示收获地址列表 --> <addressCheck @submitAddress="selectedAddress" :addressShow="addressShow"></addressCheck> <!-- 确定是否选择这个地址 --> <prompt :promptObj="promptObj"></prompt> <!-- 规格选择 --> <skuCheck :skuShow="skuShow" :data="goodsItem" @submitSku="submitSku"></skuCheck> </div> </template> <script> import pullUpBox from "@/components/pullUpBox"; import msgBox from "./msgBox"; import addressCheck from "./addressCheck"; import prompt from "@/components/prompt"; import skuCheck from "@/components/skuCheck"; import { goodsDetail, secondGoodsDetail } from "./../assets/js/api.js"; import { bindAddAddress, goodList, exchange_goods } from "./../assets/js/api.js"; export default { name: "list", data() { return { msgTxt: "", addressData: [], addressShow: false, promptObj: { show: false, tittle: "请确认您的收货地址", ptmTxt: "", success: this.submieSuccess }, isAddDone: false, skuShow: false, skuType: {}, goodsItem: {}, //存放商品规则信息 spec_id: "", // 我的规格id goods_id: "", // 商品id address_id: "", // 地址id goodListData: [], // 存放数据列表 wealth: "", //用户当前财气值, next_page: 0, // 下一页编号,为0时表示无下一页 page: 1, isLoadData: true //是否加载数据 }; }, created() { this.getGoodList(); }, methods: { submitOrder(item) { let _this = this; _this.goods_id =item.goods_id; if (_this.wealth < item.goods_wealth) { _this.msgTxt = "财气值不足,赶快去积攒吧~"; } else { if (item.have_more_spec == 0) { _this.spec_id = item.spec[0].specId; _this.addressShow = true; } else { _this.goodsItem = item; _this.goodsItem.img320url = item.goods_img; _this.skuShow = true; } } }, // 获取用户当前选择的地址 selectedAddress(selectAddress) { this.promptObj.ptmTxt = selectAddress.addrTxt; this.address_id = selectAddress.id; this.promptObj.show = true; }, // 获取商品列表 getGoodList() { let _this = this; let params = { page: this.page }; this.$http.get(goodList, { params }).then(res => { if (res.data.result == 1) { let data = res.data; _this.wealth = data.wealth; _this.next_page = data.next_page; this.isLoadData = false; if (_this.next_page != 0) { this.page++; } else { this.isLoadData = true; } _this.goodListData = _this.goodListData.concat(data.data); } else { } }); }, loadData() { if (!this.isLoadData) { this.isLoadData = true; this.getGoodList(); } }, // 最终用户兑换商品 submieSuccess() { let _this = this; let params = { goods_id: _this.goods_id, spec_id: _this.spec_id, address_id: _this.address_id }; this.$http .get(exchange_goods, { params }) .then( res => { this.addressShow = false; if (res.data.result == 1) { this.msgTxt = " 订单已创建,平台将在48小时内安排发货"; _this.isAddDone = true; _this.page= 1; _this.goodListData=[]; _this.getGoodList(); } else { this.msgTxt = res.data.message || " 兑换失败请联系客服"; } }, err => { this.msgTxt = res.data.message || " 发生未知错误请刷新重试"; } ) .catch(err => { this.msgTxt = " 后台服务器发生未知错误 请稍后重试"; }); }, // 接收选中的skuid submitSku(obj) { this.spec_id = obj.id; this.skuShow = !this.skuShow; this.addressShow = true; } }, mounted() {}, components: { msgBox, addressCheck, prompt, skuCheck, pullUpBox } }; </script> <style lang="scss" scoped> .clearfix:before, .clearfix:after { content: " "; display: table; } .msgBox { min-width: 209px; } .list-page { background: #f8f8f8; padding: 15px 15px 0; .list { display: flex; flex-flow: row wrap; justify-content: space-between; .item { position: relative; background: #fff; width: 165px; margin-bottom: 15px; border-radius: 0 0 .25rem .25rem; img { width: 100%; height: 130px; border-radius: 4px 4px 0 0; } .hot { position: absolute; top: 0; left: 0; width: 61px; height: 22px; background: url("../assets/images/icon_rmdh@2x.png"); background-size: cover; } .title-6 { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; font-size: 13px; color: #333333; letter-spacing: 0; padding: 0 10px; margin: 10px 0; height: 30px; } .literary-btn { display: block; width: 128px; height: 30px; line-height: 30px; text-align: center; margin: 0 auto; background-image: linear-gradient( -180deg, #ff5d4d 0%, #ff3429 98% ); box-shadow: 0 4px 8px 0 rgba(237, 55, 45, 0.25); border-radius: 15px; font-size: 15px; color: #ffffff; letter-spacing: 0; margin-bottom: 15px; &.active { background-image: linear-gradient( -180deg, #eaeaea 6%, #d0d0d0 93% ); box-shadow: 0 3px 6px 0 rgba(74, 60, 59, 0.1); } } } } } </style>
package com.example.roomdb import com.example.roomdb.busInfo.TimingApiResponse import com.example.roomdb.entities.Timing import org.junit.Test import org.junit.Assert.* class BusTimingsDataTest { @Test fun `TimingApiResponse should have correct properties`() { val timingList = listOf( Timing(1, "101", "10:00"), Timing(2, "102", "11:30"), Timing(3, "103", "01:00") ) val timingApiResponse = TimingApiResponse( status = "success", body = timingList ) assertEquals("success", timingApiResponse.status) assertEquals(timingList, timingApiResponse.body) } @Test fun `TimingApiResponse instances with the same properties should be equal`() { val timingList1 = listOf( Timing(1, "101", "10:00"), Timing(2, "102", "11:30"), Timing(3, "103", "01:00") ) val timingApiResponse1 = TimingApiResponse( status = "success", body = timingList1 ) val timingList2 = listOf( Timing(1, "101", "10:00"), Timing(2, "102", "11:30"), Timing(3, "103", "01:00") ) val timingApiResponse2 = TimingApiResponse( status = "success", body = timingList2 ) assertEquals(timingApiResponse1, timingApiResponse2) } @Test fun `TimingApiResponse instances with different properties should not be equal`() { val timingList1 = listOf( Timing(1, "101", "10:00"), Timing(2, "102", "11:30"), Timing(3, "103", "01:00") ) val timingApiResponse1 = TimingApiResponse( status = "success", body = timingList1 ) val timingList2 = listOf( Timing(4, "104", "02:30"), Timing(5, "105", "04:00") ) val timingApiResponse2 = TimingApiResponse( status = "failure", body = timingList2 ) assertNotEquals(timingApiResponse1, timingApiResponse2) } }
/** * Licensed Materials - Property of HCL Technologies Limited. * (C) Copyright HCL Technologies Limited 2023. */ import { getSettings, Settings } from '@/data/Settings'; import { ID } from '@/data/types/Basic'; import { CategoryType } from '@/data/types/Category'; import { extractContentsArray } from '@/data/utils/extractContentsArray'; import { unstable_serialize as unstableSerialize } from 'swr'; import { queryV2CategoryResource } from 'integration/generated/query'; import { GetServerSidePropsContext } from 'next'; import { RequestParams } from 'integration/generated/query/http-client'; import { Cache } from '@/data/types/Cache'; import { constructRequestParamsWithPreviewToken } from '@/data/utils/constructRequestParams'; import { getContractIdParamFromContext } from '@/data/utils/getContractIdParamFromContext'; import { getUser } from '@/data/User'; import { UserContext } from '@/data/types/UserContext'; export const DATA_KEY = 'Category'; export const fetcher = (pub: boolean) => /** * The data fetcher for Category * @param query The request query. * @param params The RequestParams, it contains all the info that a request needed except for 'body' | 'method' | 'query' | 'path'. * we are using it to send cookie header. * @returns Fetched Category data. */ async ( query: { storeId: string; [key: string]: string | boolean | ID | ID[]; }, params: RequestParams ): Promise<CategoryType[] | undefined> => { try { return extractContentsArray( await queryV2CategoryResource(pub).getV2CategoryResources(query, params) ); } catch (error) { console.log(error); return undefined; } }; /** * Invoke category API based on input lookup parameters * @param cache * @param lookupParams * @param context * @returns */ export const getCategoryExtended = async ( cache: Cache, lookupParams: Record<string, ID | ID[]>, context: GetServerSidePropsContext ) => { const settings = await getSettings(cache, context); const user = await getUser(cache, context); const key = getCategoryCacheKey(lookupParams, settings, user.context); const query = getCategoryFetchPayload(lookupParams, settings, user.context); const params = constructRequestParamsWithPreviewToken({ context }); const value = cache.get(key) ?? fetcher(false)(query, params); cache.set(key, value); return (await value) as CategoryType[] | undefined; }; /** * Fetching one category * @param cache * @param id * @returns */ export const getCategory = async (cache: Cache, id: ID, context: GetServerSidePropsContext) => { const value = await getCategoryExtended(cache, { id }, context); return value?.at(0); }; export const parseChildCategoryId = (category: CategoryType | undefined) => category?.links?.children ?.map((childLink: string) => childLink.split('&').at(-1)?.split('=').at(-1) ?? '') .filter(Boolean) ?? []; /** * Cache and put category by id query into SWR fallback * @param map C * @param categories * @returns */ export const cacheCategories = ( cache: Cache, categories: CategoryType[] | undefined, settings: Settings, userContext: UserContext | undefined ) => { const recursively = [...(categories ?? [])]; // we want to avoid blowing up the stack, so we iterate instead of recursing // note: this still doesn't necessarily prevent a heap blowup // eslint-disable-next-line functional/no-loop-statement for (const category of recursively) { const key = getCategoryCacheKey({ id: category.uniqueID }, settings, userContext); cache.set(key, Promise.resolve([category])); if (category.children?.length) { recursively.push(...category.children); } } }; export const getCategoryFetchPayload = ( params: Record<string, ID | ID[]>, settings: Settings, userCtx: UserContext | undefined ) => ({ storeId: settings.storeId, ...params, ...getContractIdParamFromContext(userCtx), langId: settings?.defaultLanguage, }); const getCategoryCacheKey = ( params: Record<string, ID | ID[]>, settings: Settings, userCtx: UserContext | undefined ) => unstableSerialize([getCategoryFetchPayload(params, settings, userCtx), DATA_KEY]);
function List(){ const fruits = [ {id: 1, name:'apple', calories: 95}, {id: 2, name:'orange', calories: 45}, {id: 3, name:'banana', calories: 105}, {id: 4, name:'coconut', calories: 159}, {id: 5, name:'pineapple', calories: 37} ]; // fruits.sort((a, b) => a.name.localeCompare(b.name)); // alphabetical // fruits.sort((a,b) => b.name.localeCompare(a.name)) // reverse alpha // fruits.sort((a,b) => a.calories - b.calories) // numerical // fruits.sort((a,b) => b.calories - a.calories) // reverse numerical const lowCalFruits = fruits.filter((fruit) => fruit.calories < 100) // filter numerical const listItems = lowCalFruits.map(fruit => <li key={fruit.id}> {fruit.name}: <b>{fruit.calories}</b> </li>); return(<ol>{listItems}</ol>); } export default List;
import { Dialog, DialogTitle, Stepper, Step, StepButton, DialogContent, Grid, Card, CardContent, Typography, DialogActions, } from '@mui/material'; import IconCancel from '@mui/icons-material/Cancel'; import { Button, Form, RecordContextProvider, SaveButton } from 'react-admin'; import React from 'react'; import { BuilderBlocks } from '@algocount/shared/types'; interface BuilderDialogProps { onClose: () => void; open: boolean; dialogForm: string | undefined; activeStep: number; handleStep: (index: number) => void; setDialogForm: (item: string | undefined) => void; content?: any; updateItem: (content: any) => void; builderBlocks: BuilderBlocks; } export const BuilderDialog = (props: BuilderDialogProps) => { const steps = ['Select component', 'Configure']; const { open, onClose, dialogForm, activeStep, handleStep, setDialogForm, content, updateItem, builderBlocks, } = props; const onSubmit = (values: any) => { let newValues = values; if (typeof builderBlocks[dialogForm!].form.getSaveContent !== 'undefined') { newValues = builderBlocks[dialogForm!].form.getSaveContent!(values); } updateItem(newValues); }; const getContent = () => { if ( typeof builderBlocks[dialogForm!].form.getInitialContent !== 'undefined' ) { return builderBlocks[dialogForm!].form.getInitialContent!(content); } return content; }; const renderPossibleComponents = () => { return Object.keys(builderBlocks).map((blocKey) => { const builderBlock = builderBlocks[blocKey]; return ( <Grid key={blocKey} item onClick={() => { setDialogForm(blocKey); handleStep(1); }} > <Card> <CardContent> <Typography>{builderBlock.description}</Typography> </CardContent> </Card> </Grid> ); }); }; return ( <Dialog disableEnforceFocus={true} onClose={onClose} open={open} fullWidth maxWidth="xl" > <DialogTitle> <Stepper alternativeLabel nonLinear activeStep={activeStep}> {steps.map((label, index) => { return ( <Step disabled={index === 1 && !dialogForm} key={label}> <StepButton onClick={() => handleStep(index)}> {label} </StepButton> </Step> ); })} </Stepper> </DialogTitle> {activeStep === 0 && ( <> <DialogContent> <Grid container spacing={2} alignItems="center"> {renderPossibleComponents()} </Grid> </DialogContent> <DialogActions> <Button label="ra.action.cancel" onClick={onClose}> <IconCancel /> </Button> </DialogActions> </> )} {activeStep === 1 && ( <RecordContextProvider value={getContent()}> <Form onSubmit={onSubmit}> <DialogContent> {React.cloneElement(builderBlocks[dialogForm!].form.component, { ...builderBlocks[dialogForm!].form.component.props, })} </DialogContent> <DialogActions> <SaveButton /> </DialogActions> </Form> </RecordContextProvider> )} </Dialog> ); };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sistema de Chaveamento Marcial</title> <style> body { font-family: 'Arial', sans-serif; margin: 0; padding: 0; background-color: #f4f4f4; color: #333; } header { background-color: #3498db; color: #fff; padding: 20px; text-align: center; display: flex; justify-content: space-between; align-items: center; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } header h1 { margin: 0; font-size: 36px; letter-spacing: 2px; } .auth-buttons { display: flex; align-items: center; } .auth-buttons a, .user-info button { margin-left: 20px; padding: 10px 15px; border-radius: 5px; background-color: #fff; color: #3498db; border: 1px solid #3498db; text-decoration: none; transition: background-color 0.3s, color 0.3s; } .auth-buttons a:hover, .user-info button:hover { background-color: #3498db; color: #fff; } .user-info { display: flex; align-items: center; } .user-info span { margin-right: 10px; color: #fff; } form { max-width: 400px; width: 100%; padding: 20px; border-radius: 5px; margin: 20px auto; border: 2px solid #3498db; /* Adiciona borda */ } h2 { text-align: center; color: #3498db; } label { display: block; margin-bottom: 8px; color: #333; } label.required::after { content: " *"; color: #e74c3c; } input, select { width: 100%; padding: 8px; margin-bottom: 16px; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; } button { width: 100%; padding: 10px; border: none; border-radius: 5px; background-color: #3498db; color: #fff; cursor: pointer; } button:hover { background-color: #3498db; color: #fff; } </style> </head> <body> <header class="header"> <h1>Sistema de Chaveamento Marcial</h1> {% if user.is_authenticated %} <div class="user-info"> <span>Olá, {{ user.username }}!</span> <form action="{% url 'logout' %}" method="post"> {% csrf_token %} <button type="submit" >Sair</button> </form> </div> {% else %} <div class="auth-buttons"> <a href="{% url 'login' %}" style="color: #007bff;">Login</a> <a href="{% url 'register' %}" style="color: #007bff;">Cadastro</a> </div> {% endif %} </header> <form action="{% url 'sucessoCadastro' %}" method="post" style="margin-top: 40px;"> {% csrf_token %} <h2>Inscrição</h2> <div id="error-messages"> {% if messages %} {% for message in messages %} <p class="error-message">{{ message }}</p> {% endfor %} {% endif %} </div> <label for="tipo" class="required">Escolha o Tipo:</label> <select id="tipo" name="tipo" required> <option value="lutador" selected>Lutador</option> <option value="mestre">Mestre</option> </select> <label for="categoria" class="required">Categoria:</label> <select id="categoria" name="categoria" required> <option value="peso_pena">Peso Pena</option> <option value="peso_medio">Peso Médio</option> <option value="peso_pesado">Peso Pesado</option> </select> <label for="nome" class="required">Nome:</label> <input type="text" id="nome" name="nome" required> <label for="genero" class="required">Gênero:</label> <select id="genero" name="genero" required> <option value="masculino">Masculino</option> <option value="feminino">Feminino</option> <option value="Indefinido">Desejo Não Declarar</option> </select> <label for="data_nascimento" class="required">Data de Nascimento:</label> <input type="date" id="data_nascimento" name="data_nascimento" required> <label for="email" class="required">Email:</label> <input type="email" id="email" name="email" required> <label for="telefone" class="required">Telefone:</label> <small>Exemplo: (XX)XXXXX-XXXX / Apenas números</small> <input type="tel" id="telefone" name="telefone" pattern="\d{10,11}" required> <label for="endereco" class="required">Endereço:</label> <small>Formato: Rua, Número, Bairro</small> <input type="text" id="endereco" name="endereco" required> <label for="faixa" class="required">Faixa:</label> <select id="faixa" name="faixa" style="display: block"> <option value="Branca">Branca</option> <option value="Amarela">Amarela</option> <option value="Laranja">Laranja</option> <option value="Verde">Verde</option> <option value="Azul">Azul</option> <option value="Roxa">Roxa</option> <option value="Marrom">Marrom</option> <option value="Preta">Preta</option> </select> <select id="faixa_mestre" name="faixa_mestre" style="display: none"> <option value="Coral">Coral (Vermelho e preto - Mestre)</option> <option value="Vermelha">Vermelha (Grande Mestre)</option> </select> <!-- Campos específicos para Mestre --> <div id="certificado_fields" style="display: none;"> <label for="certificado" class="required">Certificado:</label> <input type="text" id="certificado" name="certificado"> </div> <label for="senha" class="required">Senha:</label> <input type="password" id="senha" name="senha" required> <div id="error-messages"> {% if messages %} {% for message in messages %} {% if 'Senha incorreta' in message %} <p class="error-message">{{ message }}</p> {% endif %} {% endfor %} {% endif %} </div> <button type="submit">Cadastrar</button> </form> <script> // Adiciona lógica para exibir campos específicos para Mestre quando a opção é selecionada document.getElementById('tipo').addEventListener('change', function() { var certificadoFields = document.getElementById('certificado_fields'); var faixaLutador = document.getElementById('faixa'); var faixaMestre = document.getElementById('faixa_mestre'); var certificadoInput = document.getElementById('certificado'); if (this.value === 'mestre') { certificadoFields.style.display = 'block'; faixaLutador.style.display = 'none'; faixaMestre.style.display = 'block'; certificadoInput.setAttribute('required', 'required'); } else { certificadoFields.style.display = 'none'; faixaLutador.style.display = 'block'; faixaMestre.style.display = 'none'; certificadoInput.removeAttribute('required'); } }); </script> </body> </html>
# SSH Port Forwarding ## basic link - The SSH basic command is: ```bash ssh username@hostname ``` ```mermaid graph LR Host_A -->|pw or key| Host_B ``` > username > : username on Host_B logined > hostname > : device, domain name or IP address on Host_B which located on Internet ## Local Forwarding - [ appliction client ] access quest ~~[ A --> C/Z ]~~ - [ Host_A port_X --> Host_B ] - [ Host_B --> Host_C port_Z ] [ application server ] the port forwarding command: ```bash ssh -L Host_A/port_X : Host_C: Host_C/port_Z username@hostname ssh -L [ receive interface: ] receive port: target host: target port username@hostname ssh -p port_X hostname_C@localhost # visit A:X into C:Z ``` After the local forwarding command, we execute the visit proposal command **ssh -p** ```mermaid flowchart TB subgraph Host_A subgraph client ac[application client] end li[local interface] -->sc[(SSH Client)] end subgraph Host_B ss[(SSH Server)] end subgraph Host_C as[application server] end ac --> li sc -->|port X SSH| ss ss -->|port Z direct visit| as client -->|no direct access| Host_C ``` ```mermaid graph LR rp[repuest port] -->|SSH| tp[target port] -->|direct visit| th[target host] ``` C provide [ application server ] on one port, while Host_A can't visit C or the port. With SSH: A-->B and B can directly visit port on C. The local forwarding matters. Access quest occurs from Host_A, which can be A itself or any device linked to A visiting the port from A to B. > -L > : select [local forwarding] >
\usepackage[utf8]{inputenc} \usepackage{amsmath} \usepackage{amssymb} \usepackage{multicol} \usepackage{blindtext} \usepackage{geometry} \geometry{a4paper, left=5mm, right=5mm, top=5mm, bottom=12mm} \setlength{\parindent}{0pt} \setlength{\columnsep}{0.4cm} \setlength{\columnseprule}{0.5pt} \usepackage{enumitem} \usepackage{svg} \usepackage{dsfont} \usepackage{hyperref} \hypersetup { pdfauthor={https://github.com/EladSharony}, } \usepackage{xcolor} \definecolor{myblue}{cmyk}{1,.72,0,.38} \definecolor{mygreen}{RGB}{78, 153, 67} % A vibrant green \definecolor{myred}{RGB}{220, 53, 69} % A bright red \definecolor{myyellow}{cmyk}{0,0,1,0} % Pure yellow \definecolor{mydarkblue}{cmyk}{1,.6,0,.4} % A darker shade of blue \definecolor{mypurple}{RGB}{104, 33, 122} % A deep purple \definecolor{myorange}{RGB}{253, 126, 20} % A bright orange \definecolor{mygray}{gray}{0.6} % A medium gray, 0 is black, 1 is white \definecolor{myteal}{RGB}{0,128,128} % A teal color % TikZ settings for diagrams \usepackage{tikz} \usetikzlibrary{shapes,positioning,arrows,fit,calc,graphs,graphs.standard} % Font and typography settings \usepackage[T1]{fontenc} \usepackage[nosf]{kpfonts} % Keeping kpfonts for mathematical symbols \usepackage{sourcesanspro} % Sans-serif font for clarity % Microtype for improved typography \usepackage{microtype} % Apply color to all math environments % \everymath{\color{myblue}} % \everydisplay{\color{myblue}} % Customized spacing and no page numbering \renewcommand{\baselinestretch}{.8} \pagestyle{empty} % Remove page numbers % Layer declaration for TikZ drawings \pgfdeclarelayer{background} \pgfsetlayers{background,main} \usepackage{titlesec} % For customizing section titles % Redefining section titles for a more compact look \titleformat{\section} {\normalfont\large\sffamily\bfseries\color{myblue}} {\thesection}{1em}{} \titleformat{\subsection} {\normalfont\normalsize\sffamily\bfseries\color{mygreen}} {\thesubsection}{1em}{} \titleformat{\subsubsection} {\normalfont\normalsize\sffamily\bfseries\color{mypurple}} {\thesubsubsection}{1em}{} % Adjust spacing before and after section titles \titlespacing*{\section}{0pt}{1ex plus 1ex minus .2ex}{0.5ex plus .2ex} \titlespacing*{\subsection}{0pt}{1ex plus 1ex minus .2ex}{0.5ex plus .2ex} \titlespacing*{\subsubsection}{0pt}{1ex plus 1ex minus .2ex}{0.5ex plus .2ex} \usepackage{enumitem} % Ensure this is in your def.tex if not already included % Adjust spacing for enumerate environment to make it more compact \setlist[enumerate]{ topsep=0pt, % Space between the first item and the preceding paragraph partopsep=0pt, % Extra space added to topsep when environment starts a new paragraph parsep=0pt, % Space between paragraphs within an item itemsep=1pt, % Space between items leftmargin=* % Adjusts the left margin to align with the surrounding text } \setlist[itemize]{ topsep=0pt, % Space between the first item and the preceding paragraph partopsep=0pt, % Extra space added to topsep when environment starts a new paragraph parsep=0pt, % Space between paragraphs within an item itemsep=1pt, % Space between items leftmargin=* % Adjusts the left margin to align with the surrounding text } % Reduce spacing around all display math, affecting align environments \AtBeginDocument{ \setlength{\abovedisplayskip}{0pt} % Space above display math \setlength{\abovedisplayshortskip}{0pt} % Space above display math when preceding text line is short \setlength{\belowdisplayskip}{0pt} % Space below display math \setlength{\belowdisplayshortskip}{0pt} % Space below display math when following text line is short }
/* * ThinkingRock, a project management tool for Personal Computers. * Copyright (C) 2006 Avente Pty Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package au.com.trgtd.tr.view.cal; import au.com.trgtd.tr.appl.Constants; import au.com.trgtd.tr.cal.ctlr.DateCtlr; import au.com.trgtd.tr.cal.ctlr.DayPanelCtlr; import au.com.trgtd.tr.cal.view.DateChangePanel; import au.com.trgtd.tr.cal.view.DatePanel; import au.com.trgtd.tr.cal.view.DayOfMonthChooserPanel; import au.com.trgtd.tr.cal.view.DayPanel; import au.com.trgtd.tr.cal.view.Period; import au.com.trgtd.tr.view.ViewUtils; import au.com.trgtd.tr.view.cal.tree.RootNode; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.beans.PropertyChangeEvent; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JToggleButton; import javax.swing.border.Border; import javax.swing.text.DefaultEditorKit; import net.miginfocom.swing.MigLayout; import org.openide.explorer.ExplorerManager; import org.openide.explorer.ExplorerUtils; import org.openide.explorer.view.BeanTreeView; import org.openide.util.ImageUtilities; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; /** * Calendar day view top component. */ public final class DayTopComponent extends TopComponent implements ExplorerManager.Provider, Lookup.Provider, LookupListener { private final static String ICON_PATH = "au/com/trgtd/tr/view/cal/resource/day.png"; private final ExplorerManager manager = new ExplorerManager(); private final DateCtlr dateCtlr = DateCtlr.DEFAULT; private BeanTreeView treeView; private ShowHideDoneAction showDoneAction; /** * Creates a new instance. */ public DayTopComponent() { setName(NbBundle.getMessage(DayTopComponent.class, "CTL_DayTopComponent")); setIcon(ImageUtilities.loadImage(ICON_PATH, true)); putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE); putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE); putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE); putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE); this.initComponents(); } private void initComponents() { CalModelImp calModel = new CalModelImp(); showDoneAction = new ShowHideDoneAction(calModel, dateCtlr); RootNode rootNode = new RootNode(dateCtlr, calModel); manager.setRootContext(rootNode); treeView = new BeanTreeView(); treeView.setRootVisible(false); treeView.setBackground(Color.WHITE); dateCtlr.addPropertyChangeListener((PropertyChangeEvent pce) -> { treeView.expandAll(); }); ActionMap map = getActionMap(); map.put(DefaultEditorKit.copyAction, ExplorerUtils.actionCopy(manager)); map.put(DefaultEditorKit.cutAction, ExplorerUtils.actionCut(manager)); map.put(DefaultEditorKit.pasteAction, ExplorerUtils.actionPaste(manager)); map.put("delete", ExplorerUtils.actionDelete(manager, true)); try { associateLookup(ExplorerUtils.createLookup(manager, map)); } catch (IllegalStateException ex) { // already associated - ignore } JPanel treePanel = new JPanel(new BorderLayout()); Color COLOR_BORDER = new Color(8 * 26, 8 * 26, 8 * 26); Border treePanelBorder = BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(1, 1, 1, 1, COLOR_BORDER), BorderFactory.createEmptyBorder(6, 0, 0, 0)); treePanel.setBorder(treePanelBorder); treePanel.setBackground(ViewUtils.COLOR_PANEL_BG); treePanel.add(treeView, BorderLayout.CENTER); DayPanelCtlr dayPanelCtlr = new DayPanelCtlr(calModel, dateCtlr, 0, 23); DayPanel dayPanel = dayPanelCtlr.getPanel(); DatePanel dateDisplayPanel = new DatePanel(dateCtlr); dateDisplayPanel.setBackground(ViewUtils.COLOR_PANEL_BG); DayOfMonthChooserPanel dayOfMonthPanel = new DayOfMonthChooserPanel(dateCtlr); dayOfMonthPanel.setBackground(ViewUtils.COLOR_PANEL_BG); DateChangePanel dateChangerPanel = new DateChangePanel(dateCtlr, Period.Day); dateChangerPanel.setBackground(ViewUtils.COLOR_PANEL_BG); JPanel leftPanel = new JPanel(new MigLayout("fill", "6[grow]6[]20", "8[]0[grow]6")); leftPanel.add(dateDisplayPanel, "alignx left, aligny top, growx"); leftPanel.add(dayOfMonthPanel, "alignx right, wrap"); leftPanel.add(treePanel, "spanx, spany, growx, growy, wrap"); leftPanel.setBackground(ViewUtils.COLOR_PANEL_BG); JPanel rightNorthPanel = new JPanel(new MigLayout("", "0[grow]6[]0", "0[]0")); rightNorthPanel.add(getShowDoneButton(), "alignx right"); rightNorthPanel.add(dateChangerPanel, "alignx right, wrap"); rightNorthPanel.setBackground(ViewUtils.COLOR_PANEL_BG); JPanel rightPanel = new JPanel(new BorderLayout()); rightPanel.add(rightNorthPanel, BorderLayout.NORTH); rightPanel.add(dayPanel, BorderLayout.CENTER); rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 6, 6)); rightPanel.setBackground(ViewUtils.COLOR_PANEL_BG); setLayout(new GridLayout(1, 2)); add(leftPanel); add(rightPanel); setBackground(ViewUtils.COLOR_PANEL_BG); } private Component getShowDoneButton() { JToggleButton button = new JToggleButton(showDoneAction); Dimension buttonSize = Constants.TOOLBAR_BUTTON_SIZE; button.setPreferredSize(buttonSize); button.setMinimumSize(buttonSize); button.setMaximumSize(buttonSize); button.setText(""); button.setFocusable(false); button.doClick(); return button; } @Override protected void componentOpened() { dateCtlr.fireChange(); } @Override public ExplorerManager getExplorerManager() { return manager; } @Override public void resultChanged(LookupEvent ev) { } @Override public int getPersistenceType() { return TopComponent.PERSISTENCE_NEVER; } @Override protected String preferredID() { return "DayTopComponent"; } }
/* Copyright 2023 zhiwei@youya.org. 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 main import ( "os" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. "github.com/chenzhiwei/k8s-storage-webhook/pkg/validator" _ "k8s.io/client-go/plugin/pkg/client/auth" corev1 "k8s.io/api/core/v1" "sigs.k8s.io/controller-runtime/pkg/builder" "sigs.k8s.io/controller-runtime/pkg/client/config" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/manager/signals" //+kubebuilder:scaffold:imports ) func init() { logf.SetLogger(zap.New()) //+kubebuilder:scaffold:scheme } func main() { log := logf.Log.WithName("storage-webhook") // Setup a Manager log.Info("setting up manager") mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{ Port: 8443, }) if err != nil { log.Error(err, "unable to start manager") os.Exit(1) } // Setup Webhook log.Info("setting up webhook") if err := builder.WebhookManagedBy(mgr). For(&corev1.PersistentVolumeClaim{}). WithValidator(&validator.PersistentVolumeClaimValidator{Client: mgr.GetClient()}). Complete(); err != nil { log.Error(err, "unable to create webhook", "webhook", "PersistentVolumeClaim") os.Exit(1) } log.Info("starting manager") if err := mgr.Start(signals.SetupSignalHandler()); err != nil { log.Error(err, "problem running manager") os.Exit(1) } }
import React from 'react' import ReactDOM from 'react-dom/client' import './index.css' import { Provider } from 'react-redux' import { createBrowserRouter, createRoutesFromElements, Outlet, Route, RouterProvider, } from 'react-router-dom' import AdminNavbar from './components/AdminNavbar' import HomePage from './pages/HomePage' import SurveryCreatePage from './pages/SurveryCreatePage' import SurveyListPage from './pages/SurveyListPage' import { store } from './redux/store' import SingleComponentTestPage from './pages/SingleComponentTestPage' import { fetchSurveyWithId } from './redux/surveyAction' import Login from './components/Auth/Login' import ForgotPassword from './components/Auth/ForgotPassword' import ResetPassword from './components/Auth/ResetPassword' import ManageUsers from './components/AdminPanel/ManageUsers' import Earnings from './components/AdminPanel/Earnings' import ShowModal from './components/AdminPanel/ShowModal' const router = createBrowserRouter( createRoutesFromElements( <> <Route path="/test" element={<SingleComponentTestPage />} /> <Route path="/homepage" element={<HomePage />} /> <Route path="/" element={<Login />} /> <Route path='/forgot/password' element= {<ForgotPassword/>}/> <Route path='/reset/password/passwordreset/:uidb64/:token' element= {<ResetPassword/>}/> <Route path='/company/users' element={<ManageUsers/>}/> <Route path='/company/account' element={<Earnings/>}/> <Route path="/survey" element={ <> <AdminNavbar to="/survey" title="Survey Dashboard" /> <Outlet /> </> } > <Route index element={<SurveyListPage />}></Route> <Route path="/survey/create" element={<SurveryCreatePage />} /> </Route> </> ) ) ReactDOM.createRoot(document.getElementById('root')).render( <Provider store={store}> <RouterProvider router={router} /> </Provider> ) // ReactDOM.createPortal( // <Provider store={store}> // <RouterProvider router={router} /> // </Provider>, // document.getElementById('myPortalDiv') // ); // const root = ReactDOM.createRoot(document.getElementById('root')); // root.render( // <Provider store={store}> // <RouterProvider router={router} /> // </Provider> // ); const portalRoot = ReactDOM.createRoot(document.getElementById('myPortalModalDiv')[0]); portalRoot.render( <div> {<ShowModal/>} </div> );
import React, {Fragment, useState, useEffect} from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import MetaData from '../layout/MetaData'; import Sidebar from './Sidebar' import { useAlert } from 'react-alert'; import { useDispatch, useSelector } from 'react-redux'; import { updateUser, getUserDetails, clearErrors } from '../../actions/userActions'; import { UPDATE_USER_RESET } from '../../constants/userConstants'; const UpdateUser = () => { const [name,setName] = useState(''); const [email,setEmail] = useState(''); const [role, setRole] = useState(''); const alert = useAlert(); const match = { params: useParams() }; const navigate = useNavigate(); const dispatch = useDispatch(); const { error, isUpdated } = useSelector(state => state.user); const { user } = useSelector(state => state.userDetails); const userId = match.params.id; useEffect(()=>{ if(user && user._id !== userId){ dispatch(getUserDetails(userId)) }else{ setName(user.name); setEmail(user.email); setRole(user.role); } if(error){ alert.error(error); dispatch(clearErrors()); } if(isUpdated){ alert.success('user updated successfully'); navigate('/admin/users'); dispatch({ type: UPDATE_USER_RESET }); } },[dispatch, alert, error, user, navigate, isUpdated,userId]) const submitHandler = (e) => { e.preventDefault(); const formData = new FormData(); formData.set('name', name); formData.set('email', email); formData.set('role', role); dispatch(updateUser(user._id,formData)); } const isAdmin = user && user.role === 'admin' ? true : false ; return ( <Fragment> <MetaData title={`Update User`}/> <div className='row'> <div className='col-12 col-md-2 '> <Sidebar/> </div> <div className='col-12 col-md-10'> <div className="row wrapper"> <div className="col-10 col-lg-5"> <form className="shadow-lg" onSubmit={submitHandler}> <h1 className="mt-2 mb-5">Update User</h1> <div className="form-group"> <label htmlFor="name_field">Name</label> <input type="name" id="name_field" className="form-control" name='name' value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="email_field">Email</label> <input type="email" id="email_field" className="form-control" name='email' value={email} onChange={(e) => setEmail(e.target.value)} /> </div> {!isAdmin && ( <div className="form-group"> <label htmlFor="role_field">Role</label> <select id="role_field" className="form-control" name='role' value={role} onChange={(e) => setRole(e.target.value)} > <option value="user">user</option> <option value="admin">admin</option> </select> </div> )} <button type="submit" className="btn update-btn btn-block mt-4 mb-3" >Update</button> </form> </div> </div> </div> </div> </Fragment> ) } export default UpdateUser
'use client'; import { DevTool } from '@hookform/devtools'; import { SubmitHandler, useForm } from 'react-hook-form'; import * as Model from '@/lib/model'; import { Form } from '@/components/ui/form'; import { Separator } from '@/components/ui/separator'; import CustomSettingsFields from './CustomSettingsFields'; import ModeField from './ModeField'; import PresetFields from './PresetFields'; import SettingsFormResetButton from './SettingsFormResetButton'; const SETTINGS_FORM_ID = 'settings-form'; type SettingsMode = 'preset' | 'custom'; interface SettingsFormValues { mode: SettingsMode; dataNameKey: Model.DataNameKey; collectionKey: Model.CollectionKey; yearKey: Model.YearKey; seasonKey: Model.SeasonKey; monthKey: Model.MonthKey; } type SettingsFormSubmitHandler = SubmitHandler<SettingsFormValues>; interface SettingsFormProps { defaultValues: SettingsFormValues; onSubmit: SettingsFormSubmitHandler; devTool?: boolean; } function SettingsForm({ defaultValues, onSubmit, devTool = false, }: SettingsFormProps) { const settingsForm = useForm<SettingsFormValues>({ mode: 'onSubmit', reValidateMode: 'onSubmit', shouldUseNativeValidation: false, defaultValues, }); return ( <> <Form {...settingsForm}> <form id={SETTINGS_FORM_ID} className="space-y-5 py-4" noValidate autoComplete="off" onSubmit={settingsForm.handleSubmit(onSubmit)} > <div className="flex justify-between gap-2"> <ModeField /> <SettingsFormResetButton /> </div> <Separator /> <PresetFields /> <CustomSettingsFields /> </form> </Form> {devTool && <DevTool control={settingsForm.control} />} </> ); } export { SETTINGS_FORM_ID }; export type { SettingsMode, SettingsFormValues, SettingsFormSubmitHandler }; export default SettingsForm;
import { Field, Float, ID, InputType, Int, PartialType } from '@nestjs/graphql'; @InputType() export class CreateBookInput{ @Field({ nullable: false }) title: string @Field({ nullable: false }) description: string @Field(() => Float, { nullable: false }) price: number @Field(() => Int, { nullable: false }) quantity: number @Field(() => ID, { nullable: true }) authorId: number } @InputType() export class UpdateBookInput extends PartialType(CreateBookInput){}
import {createSlice} from "@reduxjs/toolkit"; const initialState: IState = { auth: { username: "", token: "" }, profile: undefined, isLoading: false, error: "", tab: 0 } export const mainSlice = createSlice({ name: 'mainSlice', initialState, reducers: { setLoading(state, action) { state.isLoading = action.payload; }, setError(state, action) { state.error = action.payload; }, ackError(state, action) { state.error = ""; }, setTab(state, action) { state.tab = action.payload; }, setAuthAction(state: IState, action: { payload: IAuth, type: string }) { state.auth = action.payload; console.log("auth: " + action.payload.token); }, setProfileAction(state: IState, action: { payload: IProfile, type: string }) { state.profile = action.payload; console.log("profile: " + action.payload.username); } } }) export const {setAuthAction, setProfileAction, setLoading, setError, ackError, setTab} = mainSlice.actions;
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rules\Password; class StoreUserRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return auth()->user()->hasRole('admin'); } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string> */ public function rules(): array { return [ 'name' => ['required', 'max:255'], 'phone' => ['required', 'unique:users,phone', 'numeric', 'min_digits:11', 'max_digits:13'], 'email' => ['required', 'email:rfc,dns', 'unique:users'], 'password' => ['required', 'confirmed', Password::min(8)], ]; } }
import React, {useEffect,useState} from 'react' import useSound from 'use-sound'; import HelpIcon from '@material-ui/icons/Help'; import IconButton from '@material-ui/core/IconButton'; import email from '../../Resources/sound/yt1s.com - BLOOP SOUND EFFECT.mp3'; import password from '../../Resources/sound/yt1s.com - MV 가호 시작 이태원클라쓰 OST Part2 ITAEWON CLASS OST Part2.mp3' export function ForEmailUsername ({available,setAvailable,data}) { const [play, { stop, isPlaying }] = useSound( (data === "email" ? email : password)); const [isClicked, setIsClicked] = useState(false); useEffect(() => { if (available && isClicked){ play(); }else{ stop(); setIsClicked(false); } }, [available]) return ( <IconButton edge="end" onClick={() => { setIsClicked(!isClicked); setAvailable(!available); } } > <HelpIcon style={{fontSize:'25px'}}/> </IconButton> ); } export function ForPassword ({available,setAvailable}) { const [play, { stop }] = useSound( password, {interrupt: false} ); const [isClicked, setIsClicked] = React.useState(false); React.useEffect(() => { if (available && isClicked){ play(); }else{ stop(); setIsClicked(false); } }, [available]) return ( <IconButton edge="end" onClick={() => { setIsClicked(!isClicked) setAvailable(!available); } } > <HelpIcon style={{fontSize:'25px'}}/> </IconButton> ); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.com.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; /** * * @author jpatarroyo */ @Entity @NamedQueries({ @NamedQuery(name = "Person.findPeople", query = "SELECT p FROM Persona p ORDER BY p.id") }) public class Persona implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_persona") private int id; @Column(name = "nombre") private String name; @Column(name = "apellido") private String surname; @Column(name = "segundo_apellido") private String lastSurname; private String email; @Column(name = "telefono") private Long phone; public Persona() { } public Persona(int id) { this.id = id; } public Persona(int id, String name, String surname, String lastSurname, String email, Long phone) { this.id = id; this.name = name; this.surname = surname; this.lastSurname = lastSurname; this.email = email; this.phone = phone; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getLastSurname() { return lastSurname; } public void setLastSurname(String lastSurname) { this.lastSurname = lastSurname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getPhone() { return phone; } public void setPhone(Long phone) { this.phone = phone; } @Override public String toString() { return "Person{" + "id=" + id + ", name=" + name + ", surname=" + surname + ", lastSurname=" + lastSurname + ", email=" + email + ", phone=" + phone + '}'; } }
#define F_CPU 8000000 #include <avr/interrupt.h> #include <avr/io.h> #include <util/delay.h> const uint8_t ZERO_POURCENT = 255; // 255, car tourne un peu a 0 const uint8_t VINGT_CINQ_POURCENT = 64; // 255, car tourne un peu a 0 const uint8_t CINQUANTE_POURCENT = 128; // 255, car tourne un peu a 0 const uint8_t SOIXANTE_QUINZE_POURCENT = 192; // 255, car tourne un peu a 0 const uint8_t CENT_POURCENT = 254; // 255, car tourne un peu a 0 void initialisation() { // cli est une routine qui bloque toutes les interruptions. // Il serait bien mauvais d'être interrompu alors que // le microcontrôleur n'est pas prêt... cli(); // configurer et choisir les ports pour les entrées // et les sorties. DDRx... Initialisez bien vos variables DDRD |= (1 << DDD4) | (1 << DDD5); sei(); } void ajustementPwm(uint8_t thresholdPwm1, uint8_t thresholdPwm2) { // mise à un des sorties OC1A et OC1B sur comparaison // réussie en mode PWM 8 bits, phase correcte // et valeur de TOP fixe à 0xFF (mode #1 de la table 16-5 // page 130 de la description technique du ATmega324PA) OCR1A = thresholdPwm1; OCR1B = thresholdPwm2; // division d'horloge par 8 - implique une fréquence de PWM fixe TCCR1A |= (1 << COM1A1) | (1 << COM1B1) | (1 << WGM10); TCCR1B |= (1 << CS11); TCCR1C = 0; } int main() { initialisation(); ajustementPwm(ZERO_POURCENT, ZERO_POURCENT); _delay_ms(2000); ajustementPwm(VINGT_CINQ_POURCENT, VINGT_CINQ_POURCENT); _delay_ms(2000); ajustementPwm(CINQUANTE_POURCENT, CINQUANTE_POURCENT); _delay_ms(2000); ajustementPwm(SOIXANTE_QUINZE_POURCENT, SOIXANTE_QUINZE_POURCENT); _delay_ms(2000); ajustementPwm(CENT_POURCENT, CENT_POURCENT); _delay_ms(2000); ajustementPwm(CENT_POURCENT, CENT_POURCENT); _delay_ms(2000); ajustementPwm(SOIXANTE_QUINZE_POURCENT, SOIXANTE_QUINZE_POURCENT); _delay_ms(2000); ajustementPwm(CINQUANTE_POURCENT, CINQUANTE_POURCENT); _delay_ms(2000); ajustementPwm(VINGT_CINQ_POURCENT, VINGT_CINQ_POURCENT); _delay_ms(2000); ajustementPwm(ZERO_POURCENT, ZERO_POURCENT); return 0; }
let cardstorage=new LocalStorage() @Entry(cardstorage) @Component struct WebShopCard { @LocalStorageProp('topTitle') tt: string = '666'; @LocalStorageProp('bottomTitle') bt: string = '777'; @LocalStorageProp('topMovieImage') ti: Resource = ($r('app.media.ic_logo')); @LocalStorageProp('bottomMovieImage') bi: Resource=($r('app.media.ic_logo')); @LocalStorageProp('bottomUrl') burl: string = ''; @LocalStorageProp('topUrl') turl: string = ''; /* * The title. */ /* * The action type. */ readonly ACTION_TYPE: string = 'router'; /* * The ability name. */ readonly ABILITY_NAME: string = 'EntryShopAbility'; /* * The message. */ readonly MESSAGE: string = 'add detail'; /* * The with percentage setting. */ readonly FULL_WIDTH_PERCENT: string = '100%'; /* * The height percentage setting. */ readonly FULL_HEIGHT_PERCENT: string = '100%'; readonly HALF_HEIGHT_PERCENT: string = '50%'; readonly TARGET_TEXT_OPACITY: number = 0.6; build() { Column() { Row() { Image(this.ti) .objectFit(ImageFit.Cover) .height(this.FULL_HEIGHT_PERCENT) .width($r("app.float.introduction_image_width")) .padding({ top: $r('app.float.agency_row_padding'), bottom: $r('app.float.agency_row_padding'), left: $r('app.float.card_padding'), right: $r('app.float.card_padding') }) .borderRadius(10) Column() { Text(this.tt) .fontSize(14) .fontColor($r("app.color.start_window_background")) .fontWeight(500) .width(this.FULL_WIDTH_PERCENT) .textOverflow({ overflow: TextOverflow.Ellipsis }) .maxLines(1) .lineHeight(19) .margin({left: '10vp', top: '10vp' }) Text(('立即购票')) .fontWeight(FontWeight.Bolder) .fontSize($r("app.float.see_button_size")) .textAlign(TextAlign.Center) .fontColor(Color.White) .borderRadius($r("app.float.see_button_radius")) .alignSelf(ItemAlign.Start) .backgroundColor(Color.Pink) .width('45%') .height($r("app.float.see_button_height")) .margin({top: '10vp', right: '10vp', left: '10vp' }) .textAlign(TextAlign.Center) .onClick(() => { postCardAction(this, { "action": this.ACTION_TYPE, "abilityName": this.ABILITY_NAME, "params": { "index": this.turl } }); }) } } .height(this.HALF_HEIGHT_PERCENT) Row() { Image(this.bi) .width($r("app.float.introduction_image_width")) .height($r("app.float.introduction_image_height")) .objectFit(ImageFit.Cover) .height(this.FULL_HEIGHT_PERCENT) .padding({ top: $r('app.float.agency_row_padding'), bottom: $r('app.float.agency_row_padding'), left: $r('app.float.card_padding'), right: $r('app.float.card_padding') }) .borderRadius(10) Column() { Text(this.bt) .fontSize(14) .fontColor($r("app.color.start_window_background")) .fontWeight(500) .width(this.FULL_WIDTH_PERCENT) .textOverflow({ overflow: TextOverflow.Ellipsis }) .maxLines(1) .lineHeight(19) .margin({left: '10vp', top: '10vp' }) Text(('立即购票')) .fontWeight(FontWeight.Bolder) .fontSize($r("app.float.see_button_size")) .textAlign(TextAlign.Center) .fontColor(Color.White) .borderRadius($r("app.float.see_button_radius")) .alignSelf(ItemAlign.Start) .backgroundColor(Color.Pink) .width('45%') .height($r("app.float.see_button_height")) .textAlign(TextAlign.Center) .margin({top: '10vp', right: '10vp', left: '10vp' }) .onClick(() => { postCardAction(this, { "action": this.ACTION_TYPE, "abilityName": this.ABILITY_NAME, "params": { "index": this.burl } }); }) } } .height(this.HALF_HEIGHT_PERCENT) } .backgroundColor($r("app.color.card_background")) .height(this.FULL_HEIGHT_PERCENT) } }
import React from "react"; import { Tabs, TabList, TabPanels, Tab, TabPanel, TabIndicator, Box, Container, } from "@chakra-ui/react"; import Features from "./TabPanels/Features"; import ProductDetails from "./TabPanels/ProductDetails"; const TabNavigation = () => { return ( <React.Fragment> <Box backgroundColor={"#f8f8f8"} p={10}> <Container maxW={"8xl"}> <Tabs position="relative" variant="unstyled"> <TabList> <Tab>Features</Tab> <Tab>Product Details</Tab> </TabList> <TabIndicator mt="-1.5px" height="2px" bg="blue.500" borderRadius="1px" /> <TabPanels pt={8}> <TabPanel> <Features /> </TabPanel> <TabPanel> <ProductDetails /> </TabPanel> </TabPanels> </Tabs> </Container> </Box> </React.Fragment> ); }; export default TabNavigation;
<!DOCTYPE html> <!-- Template: Agatha - Photography Portfolio Website Template Author: Themetorium URL: https://themetorium.net --> <html lang="en"> <head> <!-- Title --> <title>Agatha - Photography Portfolio Website Template</title> <!-- Meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="HTML5 Photography Portfolio Website Template by Themetorium"> <meta name="keywords" content="HTML5, CSS3, JavaScript, Bootsrtrap, Responsive, Photography, Portfolio, Template, Theme, Website, Themetorium" /> <meta name="author" content="themetorium.net"> <!-- Mobile Metas --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Favicon (http://www.favicon-generator.org/) --> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> <link rel="icon" href="favicon.ico" type="image/x-icon"> <!-- Google font (https://www.google.com/fonts) --> <link href='https://fonts.googleapis.com/css?family=Roboto+Mono:400,300,500,700,100' rel='stylesheet' type='text/css'> <!-- Bootstrap CSS (http://getbootstrap.com) --> <link rel="stylesheet" href="assets/vendor/bootstrap/css/bootstrap.min.css"> <!-- bootstrap CSS (http://getbootstrap.com) --> <!-- Libs and Plugins CSS --> <link rel="stylesheet" href="assets/vendor/fontawesome/css/all.min.css"> <!-- Font Icons CSS (https://fontawesome.com) Free version! --> <link rel="stylesheet" href="assets/vendor/lightgallery/css/lightgallery.min.css"> <!-- lightGallery CSS (http://sachinchoolur.github.io/lightGallery) --> <link rel="stylesheet" href="assets/vendor/justifiedgallery/css/justifiedGallery.min.css"> <!-- Justified Gallery CSS (http://miromannino.github.io/Justified-Gallery/) --> <link rel="stylesheet" href="assets/vendor/ytplayer/css/jquery.mb.YTPlayer.min.css"> <!-- YTPlayer CSS (more info: https://github.com/pupunzi/jquery.mb.YTPlayer) --> <link rel="stylesheet" href="assets/vendor/owl-carousel/css/owl.carousel.min.css"> <!-- Owl Carousel CSS (https://owlcarousel2.github.io/OwlCarousel2/) --> <link rel="stylesheet" href="assets/vendor/owl-carousel/css/owl.theme.default.min.css"> <!-- Owl Carousel default theme CSS (https://owlcarousel2.github.io/OwlCarousel2/) --> <link rel="stylesheet" href="assets/vendor/animate.min.css"> <!-- Animate libs CSS (http://daneden.me/animate) --> <!-- Template master CSS --> <link rel="stylesheet" href="assets/css/theme.css"> <link rel="stylesheet" href="assets/css/helper.css"> <!-- Template dark style CSS (comment or uncomment below line to enable/disable template dark style) --> <!-- <link rel="stylesheet" href="assets/css/dark-style.css"> --> <!-- 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/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> ///// Begin body ///// <body id="body"> <!-- Begin page preloader --> <div id="preloader"> <div class="pulse bg-main"></div> </div> <!-- End page preloader --> ///// Begin header ///// * Use class "show-hide-on-scroll" to hide header on scroll down and show on scroll up. * Use class "fixed-top" to set header to fixed position. --> <header id="header" class="fixed-top"> <div class="header-inner"> <!-- Begin logo --> <div id="logo"> <a href="index.html" class="logo-dark"><img src="assets/img/logo-dark.png" alt="logo"></a> <a href="index.html" class="logo-light"><img src="assets/img/logo-light.png" alt="logo"></a> </div> <!-- End logo --> <!-- Begin menu (Bootstrap navbar) * Use class "navbar-default" or "navbar-border-bottom" for navbar style. --> <nav class="navbar navbar-default"> <div class="navbar-inner"> <!-- Toggle for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- /.navbar-header --> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <!-- Begin dropdown * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-right" to right align the dropdown menu. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-hover active"> <a href="#0" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Home <span class="caret-2"><i class=""></i></span></a> </li> <!-- End dropdown --> <!-- Begin dropdown * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-right" to right align the dropdown menu. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-hover"> <a href="#0" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Gallery <span class="caret-2"><i class=""></i></span></a> <ul class="dropdown-menu"> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-submenu dropdown-hover"> <ul class="dropdown-menu"> </ul> </li> <!-- End dropdown --> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> </ul> </li> <!-- End dropdown --> <!-- Begin dropdown * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-right" to right align the dropdown menu. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-hover"> <a href="album-list-masonry-3col.html" aria-haspopup="true" aria-expanded="false">Portfolio <span class="caret-2"><i class="fas fa-chevron-down"></i></span></a> <ul class="dropdown-menu"> <li><a href="album-single-masonry-3col.html">NATURE</a></li> <li><a href="album-single-masonry-3col.html">FASHION</a></li> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-submenu dropdown-hover"> <a href="album-single-masonry-3col.html" class="dropdown-toggle keep-inside-screen" aria-haspopup="true" aria-expanded="false">BRIDAL<span class="caret-2"><i class=""></i></span></a> <!-- End dropdown --> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-submenu dropdown-hover"> <a href="album-single-masonry-3col.html" class="dropdown-toggle keep-inside-screen" aria-haspopup="true" aria-expanded="false">OUTDOOR <span class="caret-2"><i class=""></i></span></a> </li> <!-- End dropdown --> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-submenu dropdown-hover"> <a href="album-single-masonry-3col.html" class="dropdown-toggle keep-inside-screen" aria-haspopup="true" aria-expanded="false">potrait Single <span class="caret-2"><i class=""></i></span></a> </li> <!-- End dropdown --> </ul> </li> <!-- End dropdown --> <!-- Begin dropdown * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-right" to right align the dropdown menu. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-hover"> <a href="#0" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Blog <span class="caret-2"><i class=""></i></span></a> <ul class="dropdown-menu"> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <!-- End dropdown --> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-submenu dropdown-hover"> </li> <!-- End dropdown --> </ul> </li> <!-- End dropdown --> <!-- Begin dropdown * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-right" to right align the dropdown menu. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-hover"> <a href="#0" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">About <span class="caret-2"><i class="fas fa-chevron-down"></i></span></a> <ul class="dropdown-menu"> <li><a href="page-about-me.html">About Me</a></li> <li><a href="page-about-us.html">About Us</a></li> <li><a href="page-faq.html">FAQ</a></li> <!-- Begin dropdown (submenu) * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-submenu dropdown-hover"> </li> <!-- End dropdown --> </ul> </li> <!-- End dropdown --> <!-- Begin dropdown * Use class "dropdown-hover" to make navigation toggle on desktop hover. * Use class "dropdown-menu-right" to right align the dropdown menu. * Use class "dropdown-menu-dark" to enable dark dropdown menu. --> <li class="dropdown dropdown-hover dropdown-menu-right"> <a href="#0" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Contact <span class="caret-2"><i ></i></span></a> </li> <!-- End dropdown --> </ul> <!-- /.nav --> </div> <!-- /.navbar-collapse --> </div> <!-- /.navbar-inner --> </nav> <!-- End menu --> </div> <!-- /.header-inner --> </header> <!-- End header --> ///// Begin off-canvas menu (more info: http://codyhouse.co/gem/secondary-expandable-navigation/) ///// <nav id="cd-lateral-nav"> <div class="nav-inner"> <!-- Menu header --> <div class="menu-header">Extra Stuff</div> <!-- Begin nav content box --> <div class="cd-content-box margin-top-20"> <form id="cd-search-form"> <div class="form-group"> <input type="text" class="form-control" id="cd-search" name="search" placeholder="Search"> <button type="submit"><i class="fas fa-search"></i></button> </div> </form> </div> <!-- End nav content box --> <!-- Begin nav links <ul class="cd-navigation"> <li><a class="link" href="page-about-us.html">About Us</a></li> <li><a class="link" href="album-list-grid-5col.html">Photo Gallery</a></li> <li><a class="link" href="portfolio-list-grid-5col.html">Portfolio</a></li> <li><a class="link" href="blog-list-sidebar-right.html">Articles</a></li> <li><a class="link" href="page-contact.html">Contact</a></li> <!-- Begin submenu --> <li class="item-has-children"> <a href="#0">Submenu<span class="caret-2"><i class="fas fa-chevron-down"></i></span></a> <ul class="sub-menu"> <li><a class="link" href="#">Sub Link 1</a></li> <li><a class="link" href="#">Sub Link 2</a></li> <li><a class="link" href="#">Sub Link 3</a></li> </ul> </li> <!-- End submenu --> <li class="cd-menu-separator"></li> </ul> <!-- End nav links --> <!-- Begin nav content box --> <div class="cd-content-box"> <h2 class="cd-menu-heading">Instagram:</h2> <!-- Begin thumbnail list * Use class "col-2", "col-3", "col-4" "col-5" or "col-6" for thumbnail list columns. * Use class "gutter-1", "gutter-2", "gutter-3", "gutter-4" or "gutter-5" to add more space between items. --> <ul class="thumb-list col-3 gutter-3"> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-1.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-2.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-3.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-4.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-5.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-6.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-7.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-8.jpg);"></a></li> <li><a target="_blank" href="https://www.instagram.com" class="thumb-list-item bg-image" style="background-image: url(assets/img/album-list/small/img-9.jpg);"></a></li> </ul> <!-- End thumbnail list --> </div> <!-- End nav content box --> <!-- Begin nav content box --> <div class="cd-content-box margin-top-20"> <a target="_blank" href="http://themeforest.net/item/agatha-photography-portfolio-website-template/15349868?ref=Themetorium" class="link btn btn-primary btn-rounded-5x btn-sm btn-block">Buy This Template</a> <p class="margin-top-15 small">Enimat illum atera ates expedita obcaecati atque.</p> </div> <!-- End nav content box --> </div> <!-- /.nav-inner --> </nav> <!-- End off-canvas menu --> /////// Begin body content /////// <div id="body-content"> ///// Begin page header section ///// <section id="page-header-secion" class="alter-heading"> <!-- Begin page header image * Use class "parallax" to enable parallax effect. --> <div class="page-header-image parallax bg-image" style="background-image: url(assets/img/headings/heading-12.jpg); background-position: 50% 50%;"></div> <!-- End page header image --> <!-- Element cover --> <div class="cover page-header-cover"></div> <!-- Begin page header info --> <div class="container page-header-content no-padding max-width-800 text-center"> <div class="row"> <div class="col-lg-12"> <h1 class="album-title">FAQ</h1> <ol class="breadcrumb"> <li><a href="index.html">Home</a></li> <li class="active">Page - FAQ</li> </ol> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- End page header info --> </section> <!-- End page header section --> /////// Begin content section /////// <section id="content-section" class="page"> <div class="container"> <div class="row"> <div class="col-md-12"> <!-- Begin content wrap --> <div class="content-wrap"> <div class="row"> <div class="col-md-12"> <!-- Left column --> <div class="col-md-4 col-md-push-8"> <!-- Begin sidebar <div class="sidebar sidebar-right margin-bottom-50"> <h3 class="sidebar-heading">Info</h3> <hr class="hr-short"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Provident nemo odit cupiditate nam maiores, accusantium quis doloribus expedita sapiente. Voluptatibus unde explicabo?</p> <h3 class="sidebar-heading margin-top-60">Useful Links</h3> <hr class="hr-short"> <ul class="list-unstyled"> <li> - <a href="#" target="_blank">Labore Wes Anderson</a></li> <li> - <a href="#" target="_blank">Menda Shoreditch</a></li> <li> - <a href="#" target="_blank">Vice Lomo</a></li> <li> - <a href="#" target="_blank">Keffiyeh Helvetica</a></li> <li> - <a href="#" target="_blank">Moon Tempor</a></li> </ul> <a href="page-contact.html" class="btn btn-primary btn-rounded-5x margin-top-40">Ask a Question</a> </div> <!-- End sidebar --> </div> <!-- /.col --> <!-- Right column --> <div class="col-md-8 col-md-pull-4"> <!-- Begin accordion --> <div class="panel-group accordion-wrap" id="accordion-76845678" role="tablist" aria-multiselectable="true"> <h3>General Help:</h3> <hr class="hr-short margin-bottom-30"> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-1"> <h4 class="panel-title"> <a class="bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-1" aria-expanded="true" aria-controls="acc-76845678-collapse-1"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What is a short/long term goal of yours? </a> </h4> </div> <div id="acc-76845678-collapse-1" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="acc-76845678-head-1"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-2"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-2" aria-expanded="false" aria-controls="acc-76845678-collapse-2"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What is the longest that you've stayed awake for? </a> </h4> </div> <div id="acc-76845678-collapse-2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-2"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-3"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-3" aria-expanded="false" aria-controls="acc-76845678-collapse-3"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> How would you know if you were in love? </a> </h4> </div> <div id="acc-76845678-collapse-3" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-3"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-4"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-4" aria-expanded="false" aria-controls="acc-76845678-collapse-4"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> Do you have any pets? </a> </h4> </div> <div id="acc-76845678-collapse-4" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-4"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-5"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-5" aria-expanded="false" aria-controls="acc-76845678-collapse-5"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What is your least favorite chore? </a> </h4> </div> <div id="acc-76845678-collapse-5" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-5"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <h3 class="margin-top-60">Pre-Sale Questions:</h3> <hr class="hr-short margin-bottom-30"> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-6"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-6" aria-expanded="true" aria-controls="acc-76845678-collapse-6"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What was your favorite cartoon? </a> </h4> </div> <div id="acc-76845678-collapse-6" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-6"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-7"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-7" aria-expanded="false" aria-controls="acc-76845678-collapse-7"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What is your favorite holiday? </a> </h4> </div> <div id="acc-76845678-collapse-7" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-7"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-8"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-8" aria-expanded="false" aria-controls="acc-76845678-collapse-8"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> If you could invent a holiday, what would it be? </a> </h4> </div> <div id="acc-76845678-collapse-8" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-8"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-9"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-9" aria-expanded="false" aria-controls="acc-76845678-collapse-9"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What is your favorite hangout spot? </a> </h4> </div> <div id="acc-76845678-collapse-9" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-9"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> <div class="panel panel-default no-border"> <div class="panel-heading" role="tab" id="acc-76845678-head-10"> <h4 class="panel-title"> <a class="collapsed bg-gray-3" role="button" data-toggle="collapse" data-parent="#accordion-76845678" href="#acc-76845678-collapse-10" aria-expanded="false" aria-controls="acc-76845678-collapse-10"><span class="acc-arrow"><i class="fas fa-chevron-up"></i></span> What position do you usually sleep in? </a> </h4> </div> <div id="acc-76845678-collapse-10" class="panel-collapse collapse" role="tabpanel" aria-labelledby="acc-76845678-head-10"> <div class="panel-body no-border-top"> Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS. </div> </div> </div> </div> <!-- End accordion --> </div> <!-- /.col --> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- End content wrap --> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.container --> </section> <!-- End content section --> <!-- Begin footer --> <footer id="footer"> <div class="footer-inner"> <div class="container-fluid"> <div class="row"> <div class="col-sm-6"> <div class="copyright"> &copy; Agatha / All rights reserved </div> </div> <!-- /.col --> <div class="col-sm-6"> <div class="social-icons"> <ul> <li><a target="_blank" href="https://www.facebook.com" title="Follow us on Facebook"><i class="fab fa-facebook-f"></i></a></li> <li><a target="_blank" href="https://twitter.com/" title="Follow us on Twitter"><i class="fab fa-twitter"></i></a></li> <li><a target="_blank" href="https://www.pinterest.com" title="Follow us on Pinterest"><i class="fab fa-pinterest-p"></i></a></li> <li><a target="_blank" href="https://www.instagram.com" title="Follow us on Instagram"><i class="fab fa-instagram"></i></a></li> <!-- shange "your@email.com" to your email --> <li><a target="_blank" href="mailto:your@email.com" title="Contact Us"><i class="fas fa-envelope"></i></a></li> </ul> </div> </div> <!-- /.col --> </div> <!-- /.row --> </div> <!-- /.container --> </div> <!-- /.footer-inner --> </footer> <!-- End footer --> </div> <!-- End body content --> <!-- Scroll to top button --> <a href="#body" class="scrolltotop sm-scroll"><i class="fas fa-chevron-up"></i></a> ///// Scripts below ///// <!-- Core JS --> <script src="assets/vendor/jquery/jquery.min.js"></script> <!-- jquery JS (https://jquery.com) --> <script src="assets/vendor/bootstrap/js/bootstrap.min.js"></script> <!-- bootstrap JS (http://getbootstrap.com) --> <!-- Libs and Plugins JS --> <script src="assets/vendor/lightgallery/js/lightgallery-all.min.js"></script> <!-- lightGallery JS (http://sachinchoolur.github.io/lightGallery) --> <script src="assets/vendor/jquery.mousewheel.min.js"></script> <!-- A jQuery plugin that adds cross browser mouse wheel support --> <script src="assets/vendor/jquery.easing.min.js"></script> <!-- Easing JS (http://gsgd.co.uk/sandbox/jquery/easing/) --> <script src="assets/vendor/isotope.pkgd.min.js"></script> <!-- Isotope JS (http://isotope.metafizzy.co) --> <script src="assets/vendor/imagesloaded.pkgd.min.js"></script> <!-- ImagesLoaded JS (https://github.com/desandro/imagesloaded) --> <script src="assets/vendor/justifiedgallery/js/jquery.justifiedGallery.min.js"></script> <!-- Justified Gallery JS (http://miromannino.github.io/Justified-Gallery/) --> <script src="assets/vendor/ytplayer/js/jquery.mb.YTPlayer.min.js"></script> <!-- YTPlayer JS (more info: https://github.com/pupunzi/jquery.mb.YTPlayer) --> <script src="assets/vendor/owl-carousel/js/owl.carousel.min.js"></script> <!-- Owl Carousel JS (https://owlcarousel2.github.io/OwlCarousel2/) --> <!-- Theme master JS --> <script src="assets/js/theme.js"></script> ///// Begin Google Analytics ///// <!-- Paste your Google Analytics code here. Go to http://www.google.com/analytics/ for more information. --> ///// End Google Analytics ///// </body> <!-- End body --> </html>
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User ekle</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-3"> <h1 th:if="${user.id==null}">Add User</h1> <h1 th:if="${user.id!=null}">Edit User</h1> <a th:href="@{/users}">User Listesine Dön</a> </div> <div class="col-6"> <form method="post" th:action="${user.id == null} ? @{/users/new} : @{/users/edit/{id}(id=${user.id})}" th:object="${user}"> <div class="row mt-2"><input type="text" class="form-control" placeholder="Username" name="username" th:field="*{username}"></div> <div class="row mt-2"><input type="text" class="form-control" placeholder="E-Mail" name="email" th:field="*{email}"></div> <div class="row mt-2"> <select class="form-control" name="role" th:field="*{role}"> <option value="">Seçiniz</option> <option value="ADMIN">Admin</option> <option value="USER">Kullanıcı</option> </select> </div> <div class="row mt-2"><input type="password" class="form-control" placeholder="Password" name="password" th:field="*{password}"></div> <div class="row mt-2"><input type="submit" class="btn btn-primary"></div> </form> </div> </div> </div> </body> </html>
import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:get/get.dart'; import 'package:logger/logger.dart'; import 'package:smg/controller/profile_controller.dart'; import 'package:smg/helper/logger.dart'; import 'package:smg/model/notices_model.dart'; import 'package:smg/services/api_check.dart'; import 'package:smg/services/api_client.dart'; import 'package:smg/services/api_constant.dart'; final log = Logger(); class HomeController extends GetxController { late ScrollController scrollController; final _profileController = Get.find<ProfileController>(); int page = 1; var isFirstLoadRunning = false.obs; var hasNextPage = true.obs; var isLoadMoreRunning = false.obs; // var noticeList = <NoticeData>[].obs; RxList<NoticeModel> noticeList = List<NoticeModel>.empty(growable: true).obs; List sliderImage=[ "https://img.freepik.com/free-vector/dark-blue-banner-with-arrow-style-yellow-shapes_1017-32328.jpg?w=2000", "https://img.freepik.com/free-vector/abstract-yellow-blue-geometric-banner-half-tone-design_1017-39620.jpg?w=2000", "https://media.istockphoto.com/id/1430537202/vector/modern-abstract-blue-yellow-orange-banner-background-design-abstract-geometric-background.jpg?s=170667a&w=0&k=20&c=UBGh1gKIcffbjPC85FqanmvA-h99kXo8f7wHP0aqoWc=" ]; var dotPosition=0.obs; @override void onInit() { fastLoad(); scrollController = ScrollController(); scrollController.addListener(() { if (scrollController.position.pixels == scrollController.position.maxScrollExtent) { loadMore(); } }); super.onInit(); } refreshData()async{ page=1; Response response = await ApiClient.getData(ApiConstant.noticeApi +page.toString()); if (response.statusCode == 200) { noticeList.value = noticeModelFromJson(response.body['data']['notices']['data']); hasNextPage = true.obs; noticeList.refresh(); } else { ApiChecker.checkApi(response); } } fastLoad()async { isFirstLoadRunning(true); Response response = await ApiClient.getData(ApiConstant.noticeApi + page.toString()); if (response.statusCode == 200) { noticeList.value = noticeModelFromJson(response.body['data']['notices']['data']); } else { ApiChecker.checkApi(response); } isFirstLoadRunning(false); } loadMore() async { print("load more"); if (hasNextPage.value == true && isFirstLoadRunning.value == false && isLoadMoreRunning.value == false) { isLoadMoreRunning(true); page += 1; Response response = await ApiClient.getData(ApiConstant.noticeApi + page.toString()); if (response.statusCode == 200) { List<NoticeModel> demoList = noticeModelFromJson(response.body['data']['notices']['data']); if (demoList.isEmpty) { hasNextPage.value = false; } else { noticeList.addAll(demoList); noticeList.refresh(); } } else { ApiChecker.checkApi(response); } isLoadMoreRunning(false); } } handleSave(int id,int index)async{ Response response = await ApiClient.postData(ApiConstant.saveNotice,jsonEncode({ 'notice_id':id })); if(response.statusCode==200){ noticeList[index].isSaved=true; noticeList.refresh(); } } handleUnSave(int id,int index)async{ Response response = await ApiClient.postData(ApiConstant.unSaveNotice, jsonEncode({ 'notice_id':id })); if(response.statusCode==200){ noticeList[index].isSaved=false; noticeList.refresh(); } } @override void onClose() { scrollController.removeListener(loadMore); super.onClose(); } }
// // main.swift // suitcase // // Created by Drew Volz on 2/7/21. // import ArgumentParser import Foundation struct Suitcase: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Packing or unpacking a directory into a single file and back.", subcommands: [Pack.self, Unpack.self] ) } extension Suitcase { struct Pack: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Pack a directory of files into a single file.") @Argument(help: ArgumentHelp("The directory that will be parsed.")) public var directory = "" @Argument(help: ArgumentHelp("The name of the file that will be generated.")) var outfile = "outfile.txt" @Option(name: .shortAndLong, help: "Filter out hidden files.") var filter = true func validate() throws { guard !directory.isEmpty else { throw ValidationError("Missing expected argument '<directory>'") } } func run() { removeOldFile(path: outfile) let files = getFileNames(path: directory, filter: filter) let contents = getContentsOfFiles(path: directory, fileNames: files) save(contents: contents, to: outfile) } } struct Unpack: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Unpack a packed file back into a directory.") @Argument(help: ArgumentHelp("The packed file that will be unpacked.")) public var infile = "" @Option(name: .shortAndLong, help: "Filter out hidden files.") var filter = true func validate() throws { guard !infile.isEmpty else { throw ValidationError("Missing expected argument '<infile>'") } } func run() { let data = getPackedContents(path: infile) save(contents: data) } } } Suitcase.main()
import React, { useEffect, useState, useContext } from 'react' import { useNavigate, useParams, useSearchParams } from 'react-router-dom' import { NavBar, Form, Input, Button, Dialog, TextArea } from 'antd-mobile' import axios from 'axios' import { UserInfoContext } from '../../App' import './index.css' function rand(min, max) { return (Math.random() * (max - min + 1) + min) | 0 } const billColumns = [['申请单', '报销单', '借款单']] const approveColumns = [['审批流A', '审批流B', '审批流C', '审批流D', '审批流E']] const person = ['张三', '李四', '王五', '赵六'] const applyReason = ['申请去北京的出差报销', '报销 4 月份的办公室费用', '6 月份团建费用报销'] const applyMoney = [12, 23, 200, 400, 666] const TodoDetail = (props) => { const navigate = useNavigate() const context = useContext(UserInfoContext) const [form] = Form.useForm() const routeParams = useParams() const [searchParams, setSearchParams] = useSearchParams() const [loading, setLoading] = useState(false) const [loading1, setLoading1] = useState(false) const [isDone, setIsDone] = useState('yes') const back = () => { navigate('/todoList', { replace: true }) } const onAgree = () => { const { id } = routeParams setLoading(true) axios .post(context.domain + '/biz/update', { userId: context.userId, userName: context.userName, workRecordId: id, flowStatus: 'agree' }) .then((res) => { setLoading(false) if (res && res.data.success) { Dialog.alert({ content: '同意成功!', onConfirm: () => { back() } }) } else { alert('request failed --->' + JSON.stringify(res)) } }) .catch((error) => { setLoading(false) alert('httpRequest failed --->' + JSON.stringify(error)) }) } const onReject = () => { const { id } = routeParams setLoading1(true) axios .post(context.domain + '/biz/update', { userId: context.userId, userName: context.userName, workRecordId: id, flowStatus: 'refuse' }) .then((res) => { setLoading1(false) if (res && res.data.success) { Dialog.alert({ content: '驳回成功!', onConfirm: () => { back() } }) } else { alert('request failed --->' + JSON.stringify(res)) } }) .catch((error) => { setLoading1(false) alert('httpRequest failed --->' + JSON.stringify(error)) }) } useEffect(() => { const str = searchParams.get('data') const isDone = searchParams.get('isDone') setIsDone(isDone) console.log('routeParams', routeParams, str) try { const data = JSON.parse(str) form.setFieldsValue({ 单据模板: data?.title?.split('的')?.[1] || billColumns[0][rand(0, billColumns[0].length - 1)], 审批流: approveColumns[0][rand(0, approveColumns[0].length - 1)], 报销人: data?.['报销人'] || person[rand(0, person.length - 1)], 报销事由: data?.['申请事由'] || applyReason[rand(0, applyReason.length - 1)], 报销金额: data?.['申请金额'] || applyMoney[rand(0, applyMoney.length - 1)] }) console.log('routeParams', routeParams, data) } catch (error) { form.setFieldsValue({ 单据模板: billColumns[0][rand(0, billColumns[0].length - 1)], 审批流: approveColumns[0][rand(0, approveColumns[0].length - 1)], 报销人: person[rand(0, person.length - 1)], 报销事由: applyReason[rand(0, applyReason.length - 1)], 报销金额: applyMoney[rand(0, applyMoney.length - 1)] }) } }, []) console.log('---1---', isDone) return ( <div className="todo-detail"> <NavBar onBack={back}>待办详情</NavBar> <div className="todo-detail-content"> <Form form={form}> <Form.Item className="row" layout="horizontal" name="单据模板" label="单据模板" rules={[{ required: true, message: '请选择单据模板' }]} > <Input placeholder="请选择单据模板" disabled value={billColumns[0][rand(0, billColumns[0].length - 1)]} /> </Form.Item> <Form.Item name="审批流" label="审批流" rules={[{ required: true, message: '请选择审批流' }]}> <Input placeholder="请选择审批流" disabled value={approveColumns[0][rand(0, approveColumns[0].length - 1)]} /> </Form.Item> <Form.Item name="报销人" label="报销人" rules={[{ required: true, message: '请选择报销人' }]}> <Input placeholder="请选择报销人" disabled value={person[rand(0, person.length - 1)]} /> </Form.Item> <Form.Item name="报销事由" label="报销事由" rules={[{ required: true, message: '请输入报销事由' }]}> <TextArea placeholder="请输入报销事由" disabled value={applyReason[rand(0, applyReason.length - 1)]} /> </Form.Item> <Form.Item name="报销金额" label="报销金额" rules={[{ required: true, message: '请输入报销金额' }]}> <Input placeholder="请输入报销金额" disabled value={applyMoney[rand(0, applyMoney.length - 1)]} /> </Form.Item> </Form> {isDone === 'no' ? ( <div style={{ display: 'flex', marginTop: '10px', padding: '10px' }}> <Button block type="submit" color="primary" onClick={onAgree} loading={loading}> 同意 </Button> <Button block style={{ marginLeft: '10px' }} type="submit" color="danger" onClick={onReject} loading={loading1} > 驳回 </Button> </div> ) : ( <></> )} </div> </div> ) } export default TodoDetail
import torch import torch.nn as nn import torch.nn.functional as F from torch.utils import data #from utils import transforms from utils_dir import transforms import torchvision import pandas as pd import os import numpy as np import imageio import random import collections import csv import librosa import config labels_file = pd.read_csv('./data/labeled_ADSMI/labels_int.csv', index_col=0) class MyDataset_finetune(data.Dataset): def __init__(self, train=True): self.root = './data/labeled_ADSMI/labeled_data_2013-535/' self.train = train #getting name of all files inside the all of the train_folds temp = os.listdir(self.root) temp.sort() self.file_names = [] self.class_ids = [] if self.train: for i in range(len(labels_file["Label_int"])): if int(labels_file["fold"][i]) in config.ADSMI_train_folds: self.file_names.append(labels_file["filename"][i]) self.class_ids.append(labels_file["Label_int"][i]) else: for i in range(len(labels_file["Label_int"])): if int(labels_file["fold"][i]) in config.ADSMI_test_fold: self.file_names.append(labels_file["filename"][i]) self.class_ids.append(labels_file["Label_int"][i]) if self.train: self.wave_transforms = torchvision.transforms.Compose([ transforms.ToTensor1D(), transforms.RandomScale(max_scale = 1.25), transforms.RandomPadding(out_len = 220500), transforms.RandomCrop(out_len = 220500)]) self.spec_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor() , transforms.FrequencyMask(max_width = config.freq_masks_width, numbers = config.freq_masks), transforms.TimeMask(max_width = config.time_masks_width, numbers = config.time_masks)]) else: #for test self.wave_transforms = torchvision.transforms.Compose([ transforms.ToTensor1D(), transforms.RandomPadding(out_len = 220500), transforms.RandomCrop(out_len = 220500)]) self.spec_transforms = torchvision.transforms.Compose([torchvision.transforms.ToTensor() ]) def __len__(self): return len(self.file_names) def __getitem__(self, index): file_name = self.file_names[index ] path = self.root + file_name wave, rate = librosa.load(path, sr=44100) #identifying the label of the sample from its name class_id = int(self.class_ids[index]) if wave.ndim == 1: wave = wave[:, np.newaxis] # normalizing waves to [-1, 1] if np.abs(wave.max()) > 1.0: wave = transforms.scale(wave, wave.min(), wave.max(), -1.0, 1.0) wave = wave.T * 32768.0 nonzero_rows, nonzero_cols = wave.nonzero() if nonzero_rows.size > 0: start = nonzero_cols.min() end = nonzero_cols.max() wave = wave[:, start: end + 1] else: # Create a default or zero tensor of appropriate shape for empty waveforms default_spec_shape = (config.channels, default_freq_dim, default_time_dim) # You have to define default_freq_dim and default_time_dim based on what's appropriate for your application return file_name, torch.zeros(default_spec_shape), class_id wave = wave[:, start: end + 1] wave_copy = np.copy(wave) wave_copy = self.wave_transforms(wave_copy) wave_copy.squeeze_(0) s = librosa.feature.melspectrogram(y=wave_copy.numpy(), sr=44100, n_mels=128, n_fft=1024, hop_length=512) log_s = librosa.power_to_db(s, ref=np.max) # masking the spectrograms log_s = self.spec_transforms(log_s) #creating 3 channels by copying log_s1 3 times if config.channels == 3: spec = torch.cat((log_s, log_s, log_s), dim=0) else: spec = log_s return file_name, spec, class_id def create_generators_finetune(): train_dataset = MyDataset_finetune(train=True) test_dataset = MyDataset_finetune(train=False) train_loader = data.DataLoader(train_dataset, batch_size = config.batch_size, shuffle=True, num_workers=0 ,drop_last=False) test_loader = data.DataLoader(test_dataset, batch_size = config.batch_size, shuffle=True, num_workers=0 ,drop_last=False) return train_loader, test_loader
from collections import defaultdict, deque import random import time from typing import Optional, Any, List, Dict, Set, Tuple, Generator from tqdm import tqdm from multiprocessing import Process, Manager import matplotlib.pyplot as plt class Graph: """ Graph class """ def __init__(self): self._graph = {} self._index = 0 self._stack = [] self._indices = {} self._low_links = {} self._on_stack = set() self._sccs = [] def add_vertex(self, vertex: str, data: Optional[Any]=None) -> None: """ Adds a vertex to the graph :param vertex: the vertex name :param data: data associated with the vertex """ if vertex not in self._graph: self._graph[vertex] = {'data': data, 'neighbors': {}} def add_edge(self, vertex1: str, vertex2: str, data: Optional[Any]=None) -> None: """ Adds an edge to the graph :param vertex1: vertex1 key :param vertex2: vertex2 key :param data: the data associated with the vertex """ if not vertex1 in self._graph or not vertex2 in self._graph: raise ValueError("The vertices do not exist") self._graph[vertex1]['neighbors'][vertex2] = data def get_neighbors(self, vertex: str) -> List[str]: """ Get the list of vertex neighbors :param vertex: the vertex to query :return: the list of neighbor vertices """ if vertex in self._graph: return list(self._graph[vertex]['neighbors'].keys()) else: return [] def vertex_exists(self, vertex: str) -> bool: """ If contains a vertex :param vertex: the vertex name :return: boolean """ return vertex in self._graph def edge_exists(self, vertex1: str, vertex2: str) -> bool: """ If contains an edge :param vertex1: the vertex1 name :param vertex2: the vertex2 name :return: boolean """ return vertex1 in self._graph and vertex2 in self._graph[vertex1]['neighbors'] def connected_components(self, undirected_graph: 'Graph') -> List[List[str]]: connected_components = [] is_visited = {vertex: False for vertex in undirected_graph._graph} for vertex in undirected_graph._graph: if not is_visited[vertex]: component = self.find_connected_component(vertex, is_visited, undirected_graph) connected_components.append(component) return connected_components def find_connected_component(self, src: str, is_visited: Dict[str, bool], undirected_graph: 'Graph') -> List[str]: component = [] stack = [src] while stack: vertex = stack.pop() if not is_visited[vertex]: is_visited[vertex] = True component.append(vertex) for neighbor in undirected_graph.get_neighbors(vertex): if not is_visited[neighbor]: stack.append(neighbor) return component def weakly_connected_components(self) -> List[List[str]]: undirected_graph = self.make_copy_graph_undirected() return self.connected_components(undirected_graph) def largest_weakly_connected_component(self) -> int: components = self.weakly_connected_components() return max(len(component) for component in components) if components else 0 def number_of_weakly_connected_components(self) -> int: components = self.weakly_connected_components() return len(components) def bfs(self, start: str) -> Tuple[Dict[str, str], Dict[str, int]]: """ Perform BFS and return parent and distance dictionaries :param start: The start vertex :return: parent and distance dictionaries """ par = {v: None for v in self._graph} dist = {v: float('inf') for v in self._graph} q = deque([start]) dist[start] = 0 while q: node = q.popleft() for neighbor in self.get_neighbors(node): if dist[neighbor] == float('inf'): par[neighbor] = node dist[neighbor] = dist[node] + 1 q.append(neighbor) return par, dist def print_shortest_path(self, start: str, end: str) -> None: """ Print the shortest path from start to end :param start: The start vertex :param end: The end vertex """ if not self.vertex_exists(start) or not self.vertex_exists(end): print("One or both vertices not found in the graph") return par, dist = self.bfs(start) if dist[end] == float('inf'): print("Source and Destination are not connected") return path = [] current_node = end while current_node is not None: path.append(current_node) current_node = par[current_node] path.reverse() print(" -> ".join(path)) def estimate_shortest_paths(self, samples: int) -> float: vertices = list(self._graph.keys()) sampled_vertices = random.sample(vertices, samples) start_time = time.time() for vertex in sampled_vertices: self.bfs(vertex) end_time = time.time() return end_time - start_time def estimate_diameter(self, samples: int) -> float: """ Estimate the diameter of the graph by sampling a subset of vertices and performing BFS from each sampled vertex to find the maximum distance to any other vertex. :param samples: The number of vertices to sample :return: An estimate of the diameter of the graph """ vertices = list(self._graph.keys()) max_distance = 0 for _ in range(samples): # takes into account not analyzing only one connected component vertex = random.choice(vertices) for _ in range(samples): _, dist = self.bfs(vertex) dist = {k: v for k, v in dist.items() if v < float('inf')} #get the maximum distance and the vertex that has it max_dist = max(dist.values()) max_vertex = max(dist, key=dist.get) # print(f"Vertex: {vertex}, Max Distance: {max_dist}, Max Vertex: {max_vertex}") #if the maximum distance is greater than the current maximum distance, update it if max_dist > max_distance: max_distance = max_dist vertex = max_vertex return max_distance def page_rank(self, damping_factor: float = 0.85, max_iterations: int = 100, tol: float = 1.0e-6) -> Dict[str, float]: """ Computes PageRank for each vertex in the graph. :param graph: the graph :param damping_factor: the damping factor (default 0.85) :param max_iterations: maximum number of iterations (default 100) :param tol: tolerance for convergence (default 1.0e-6) :return: a dictionary of vertex PageRank values """ vertices = list(self._graph.keys()) num_vertices = len(vertices) if num_vertices == 0: return {} # Initialize PageRank values page_rank_values = {vertex: 1.0 / num_vertices for vertex in vertices} #create L dictionary L = {vertex: len(self.get_neighbors(vertex)) for vertex in vertices} #create dict of vertices that reference the current vertex # R = {vertex: [v for v in vertices if self.edge_exists(v, vertex)] for vertex in vertices} transposed_graph = self.transpose() R = {vertex: list(transposed_graph.get_neighbors(vertex)) for vertex in transposed_graph._graph} for iteration in tqdm(range(max_iterations), desc="PageRank", unit="iteration"): new_page_rank_values = {} for vertex in vertices: rank_sum = 0.0 for v in R[vertex]: rank_sum += page_rank_values[v] / L[v] new_page_rank_values[vertex] = (1 - damping_factor) / num_vertices + damping_factor * rank_sum # Check for convergence diff = sum(abs(new_page_rank_values[vertex] - page_rank_values[vertex]) for vertex in vertices) if diff < tol: print(f"Converged after {iteration + 1} iterations") break page_rank_values = new_page_rank_values return page_rank_values def transpose(self) -> 'Graph': """ Returns the transpose of the graph :return: A new Graph object that is the transpose of the current graph """ transposed = Graph() for vertex in self._graph: transposed.add_vertex(vertex, self._graph[vertex]['data']) for vertex in self._graph: for neighbor in self._graph[vertex]['neighbors']: transposed.add_edge(neighbor, vertex, self._graph[vertex]['neighbors'][neighbor]) return transposed def count_and_list_cycle_triangles(self) -> Tuple[int, List[Tuple[str, str, str]]]: """ Counts and optionally lists the cycle triangles in the graph. :return: A tuple containing the number of cycle triangles and the list of triangles """ GT = self.transpose() c = 0 triangles = [] for u in self._graph: for v in self.get_neighbors(u): if u < v: S = set(GT.get_neighbors(u)).intersection(self.get_neighbors(v)) for w in S: if u < w: triangles.append((u, v, w)) c += 1 return c, triangles def make_copy_graph_undirected(self): """ Makes a copy of the graph as an undirected graph """ undirected_graph = Graph() for vertex in self._graph: undirected_graph.add_vertex(vertex, self._graph[vertex]['data']) for vertex in self._graph: for neighbor in self._graph[vertex]['neighbors']: undirected_graph.add_edge(vertex, neighbor) undirected_graph.add_edge(neighbor, vertex) return undirected_graph def count_triangles(self) -> int: """ Counts the number of triangles in the graph """ undirected_graph = self.make_copy_graph_undirected() count = 0 for vertex in self._graph: neighbors = undirected_graph.get_neighbors(vertex) for i in range(len(neighbors)): for j in range(i + 1, len(neighbors)): if undirected_graph.edge_exists(neighbors[i], neighbors[j]): count += 1 return count // 3 def has_k_cycle_util(self, v: str, visited: set, recStack: dict, k: int): stack = [(v, [v])] while stack: (node, path) = stack.pop() if node not in visited: visited.add(node) recStack[node] = path for neighbour in self.get_neighbors(node): if neighbour not in visited: stack.append((neighbour, path + [neighbour])) elif neighbour in recStack and neighbour in path: cycle_path = path if len(cycle_path) - cycle_path.index(neighbour) == k: return cycle_path[cycle_path.index(neighbour):] elif node in recStack and node in path: if len(path) - path.index(node) == k: return path[path.index(node):] else: return [] return [] def has_k_cycle(self, k=3, timeout=10): recStack = {} start = time.time() for node in tqdm(self._graph, desc="Checking for cycles of length " + str(k)): if time.time() - start > timeout: break visited = set() # reset visited set for each node cycle = self.has_k_cycle_util(node, visited, recStack, k=k) if cycle: return cycle return [] def worker(self, k): cycle = self.has_k_cycle(k) if cycle: return len(cycle) return 0 def circumference(self): vertices = list(self._graph.keys()) circumference = [0] def binary_search_time(low, high): if low > high: return mid = (low + high) // 2 cycle_length = self.worker(mid) circumference[0] = max(circumference[0], cycle_length) if cycle_length == mid: binary_search_time(mid + 1, high) else: binary_search_time(low, mid - 1) binary_search_time(2, len(vertices)) return circumference[0] # def _strong_connect(self, vertex: str) -> None: # """ # Non-recursive helper function for Tarjan's algorithm to find strongly connected components # """ # stack = [(vertex, 0)] # visited = set() # while stack: # v, index = stack[-1] # if v not in visited: # visited.add(v) # self._indices[v] = self._index # self._low_links[v] = self._index # self._index += 1 # self._stack.append(v) # self._on_stack.add(v) # neighbors = self.get_neighbors(v) # if index < len(neighbors): # neighbor = neighbors[index] # stack[-1] = (v, index + 1) # if neighbor not in self._indices: # stack.append((neighbor, 0)) # elif neighbor in self._on_stack: # self._low_links[v] = min(self._low_links[v], self._indices[neighbor]) # else: # if self._low_links[v] == self._indices[v]: # scc = set() # while True: # w = self._stack.pop() # self._on_stack.remove(w) # scc.add(w) # if w == v: # break # self._sccs.append(scc) # stack.pop() # if stack: # w, _ = stack[-1] # self._low_links[w] = min(self._low_links[w], self._low_links[v]) # def find_strongly_connected_components(self) -> List[Set[str]]: # """ # Finds and returns all strongly connected components # """ # self._index = 0 # self._stack = [] # self._indices = {} # self._low_links = {} # self._on_stack = set() # self._sccs = [] # for vertex in self._graph: # if vertex not in self._indices: # self._strong_connect(vertex) # return self._sccs # def largest_strongly_connected_component(self) -> int: # """ # Returns the size of the largest strongly connected component # """ # sccs = self.find_strongly_connected_components() # return max(len(scc) for scc in sccs) if sccs else 0 # def number_of_strongly_connected_components(self) -> int: # """ # Returns the number of strongly connected components # """ # sccs = self.find_strongly_connected_components() # return len(sccs) # def make_udirected_graph_of_scc(self, scc: Set[str]) -> 'Graph': # """ # Creates an undirected graph of the strongly connected component # """ # undirected_graph = Graph() # for vertex in scc: # undirected_graph.add_vertex(vertex, self._graph[vertex]['data']) # for vertex in scc: # for neighbor in self._graph[vertex]['neighbors']: # if neighbor in scc: # undirected_graph.add_edge(vertex, neighbor) # return undirected_graph # def dfs_find_cycles_in_scc(self, start_vertex: str) -> List[List[str]]: # """ # Perform DFS from the start vertex to find all cycles including this vertex. # :param start_vertex: The start vertex for the DFS # :param scc: The strongly connected component # :return: List of cycles found # """ # stack = [(start_vertex, [start_vertex])] # cycles = [] # while stack: # (vertex, path) = stack.pop() # for neighbor in self.get_neighbors(vertex): # if neighbor == start_vertex and len(path) > 2: # cycles.append(path) # elif neighbor not in path: # stack.append((neighbor, path + [neighbor])) # return cycles # def check_cycle(self, cycle: List[str]) -> bool: # """ # Check if a cycle is valid # """ # for i in range(len(cycle)): # if not self.edge_exists(cycle[i], cycle[(i + 1) % len(cycle)]): # return False # def max_scc_cycle(self) -> Tuple[int, List[str]]: # """ # Estimate the circumference of the graph by finding the largest cycle in the largest strongly connected component # """ # sccs = self.find_strongly_connected_components() # if not sccs: # return 0 # sccs = sorted(sccs, key=len, reverse=True) # max_cycle_length = 0 # max_cycle = [] # while len(sccs) > 0: # largest_scc = sccs.pop(0) # undirected_graph = self.make_udirected_graph_of_scc(largest_scc) # cycles = undirected_graph.dfs_find_cycles_in_scc(start_vertex=random.choice(list(largest_scc))) # for cycle in cycles: # if self.check_cycle(cycle): # max_cycle_length = max(max_cycle_length, len(cycle)) # max_cycle = max(max_cycle, cycle, key=len) # #remove the scc that have less vertices than the current max_cycle_length # sccs = [scc for scc in sccs if len(scc) >= max_cycle_length] # return max_cycle_length, max_cycle def average_clustering_coefficient_undirected(self) -> float: """ Calculate the average clustering coefficient of the undirected graph """ clustering_coefficient = 0 undirected_graph = self.make_copy_graph_undirected() computed_neighbors = {vertex: set(undirected_graph.get_neighbors(vertex)) for vertex in tqdm(undirected_graph._graph, desc="Compting neighbors", unit="vertex")} for vertex in tqdm(undirected_graph._graph, desc="Calculating clustering coefficient", unit="vertex"): neighbors = computed_neighbors[vertex] count = 0 for neighbor in neighbors: count += len(set(undirected_graph.get_neighbors(neighbor)).intersection(neighbors)) clustering_coefficient += count / (len(neighbors) * (len(neighbors) - 1)) if len(neighbors) > 1 else 0 return clustering_coefficient / len(undirected_graph._graph) def average_clustering_coefficient_directed(self) -> float: """ Calculate the average clustering coefficient of the directed graph """ clustering_coefficient = 0 computed_neighbors = {vertex: set(self.get_neighbors(vertex)) for vertex in tqdm(self._graph, desc="Compting neighbors", unit="vertex")} for vertex in tqdm(self._graph, desc="Calculating clustering coefficient", unit="vertex"): neighbors = computed_neighbors[vertex] count = 0 for neighbor in neighbors: count += len(set(self.get_neighbors(neighbor)).intersection(neighbors)) clustering_coefficient += count / (len(neighbors) * (len(neighbors) - 1)) if len(neighbors) > 1 else 0 return clustering_coefficient / len(self._graph) def bfs_bc_helper(self, start: str) -> Tuple[Dict[str, int], Dict[str, List[str]]]: """ Perform BFS and return the shortest paths and predecessor lists. :param start: The start vertex :return: distance dictionary and predecessor lists """ dist = {v: float('inf') for v in self._graph} pred = {v: [] for v in self._graph} dist[start] = 0 q = deque([start]) while q: node = q.popleft() for neighbor in self.get_neighbors(node): if dist[neighbor] == float('inf'): dist[neighbor] = dist[node] + 1 q.append(neighbor) if dist[neighbor] == dist[node] + 1: pred[neighbor].append(node) return dist, pred def estimate_betweenness_centrality(self, samples: int = 10) -> str: """ Estimate the vertex with the highest betweenness centrality. :param samples: The number of vertices to sample :return: The vertex with the highest estimated betweenness centrality """ vertices = list(self._graph.keys()) sampled_vertices = random.sample(vertices, samples) betweenness = defaultdict(float) for vertex in tqdm(sampled_vertices): # Get shortest paths and predecessor lists from the current vertex dist, pred = self.bfs_bc_helper(vertex) # Initialize the dependencies delta = {v: 0 for v in self._graph} # Perform accumulation of dependencies in reverse order stack = [v for v in vertices if dist[v] < float('inf')] stack.sort(key=lambda v: -dist[v]) for w in stack: coeff = (1 + delta[w]) / len(pred[w]) if pred[w] else 1 for v in pred[w]: delta[v] += dist[v] / dist[w] * coeff if w != vertex: betweenness[w] += delta[w] # Find the vertex with the highest betweenness centrality max_vertex = max(betweenness, key=betweenness.get) return max_vertex def find_k_cycles(self, start_node, k): """Find all k-cycles starting from a given node.""" transposed = self.transpose() stack = [(start_node, [start_node], 1)] k_cycles = [] while stack: current_node, path, current_depth = stack.pop() if current_depth == k: if start_node in set(self.get_neighbors(current_node)) | set(transposed.get_neighbors(current_node)): k_cycles.append(path) elif current_depth < k: for neighbor in set(self.get_neighbors(current_node)) | set(transposed.get_neighbors(current_node)): if neighbor not in path: stack.append((neighbor, path + [neighbor], current_depth + 1)) return k_cycles def estimate_k_cycles(self, k, n): """Estimate the number of k-cycles in the graph by sampling n nodes.""" total_k_polygons = 0 vertices = list(self._graph.keys()) random.shuffle(vertices) for i in range(n): start_node = vertices[i] k_cycles = self.find_k_cycles(start_node, k) total_k_polygons += len(k_cycles) return total_k_polygons / (2 * k) / n * len(vertices) def plot_polygons(self, sides_range, tries_range): polygons_count = [self.estimate_k_cycles(k, tries) for k, tries in tqdm(zip(sides_range, tries_range))] plt.bar(sides_range, polygons_count) plt.yscale('log') plt.xlabel('Number of sides') plt.ylabel('Number of polygons') plt.title('Number of polygons by number of sides') plt.show()
package com.github.olivereivak.ui.sis.guice.module; import org.gwizard.hibernate.DatabaseConfig; import org.gwizard.logging.LoggingConfig; import org.gwizard.web.WebServer; import com.github.olivereivak.ui.sis.config.ApplicationConfig; import com.github.olivereivak.ui.sis.guice.provider.ObjectMapperProvider; import com.github.olivereivak.ui.sis.resource.BaseResource; import com.github.olivereivak.ui.sis.services.ShutdownService; import com.github.olivereivak.ui.sis.util.ReflectionUtils; import com.github.olivereivak.ui.sis.web.ApplicationWebServer; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.AbstractModule; import com.google.inject.Provides; import lombok.extern.slf4j.Slf4j; /** * <p>Among the duties of your application module(s), you must explicitly bind every JAXRS resource class. * Consider using Reflections to do this automatically.</p> * * <p>We must provide bindings for the LoggingConfig, WebConfig, and DatabaseConfig to use the * logging, rest, and hibernate modules.</p> */ @Slf4j public class ApplicationModule extends AbstractModule { @Override protected void configure() { bindResources(); bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class); bind(WebServer.class).to(ApplicationWebServer.class); bind(ShutdownService.class).asEagerSingleton(); } private void bindResources() { for (Class resource : ReflectionUtils.getClasses("com.github.olivereivak.ui.sis.resource", BaseResource.class)) { log.debug("Binding resource " + resource.getSimpleName()); bind(resource); } } @Provides public LoggingConfig loggingConfig(ApplicationConfig cfg) { return cfg.getLogging(); } @Provides public DatabaseConfig databaseConfig(ApplicationConfig cfg) { return cfg.getDatabase(); } }
import java.util.HashMap; import java.util.Map; public class IntegerToRoman { public static String intToRoman(int num) { int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; StringBuilder result = new StringBuilder(); int i = 0; while (num > 0) { if (num >= values[i]) { result.append(symbols[i]); num -= values[i]; } else { i++; } } return result.toString(); } public static void main(String args[]) { int num = 3549; String romanNumeral = intToRoman(num); System.out.println("Roman numeral representation of " + num + " is: " + romanNumeral); } }
#' Sample Exponential Family #' #' @param b Vector of coefficients for (x^k, x^k-1, ..., x). If normalized, #' include the normalization constant as well. #' @param n Number of samples. #' @param is_normalized Has the normalizing constant been included in the #' coefficient vector? Default: TRUE #' @param xmin Lower bound on interval to search when inverting the CDF. #' @param xmax Upper bound on interval to search when inverting the CDF. #' @return Numeric vector of samples from the distribution. #' @examples #' # Draw from standard normal distribution. #' x <- rExpFam(b = c(-0.5, 0.0, -0.5 * log(2 * pi)), n = 10) #' @export rExpFam <- function(b, n, is_normalized = TRUE, xmin = -2, xmax = 2) { # Calculate normalizing constant. if (!is_normalized) { b <- NormalizingConstant(b) } # Generate sample. u <- stats::runif(n = n) out <- GetQuantile(b, probs = u, xmin = xmin, xmax = xmax) return(out) }
# Prepares raw data downloaded from CDC (NISPUF20) for analysis by re-factoring # variables, handling missing values # CONSTANTS IN_PATH = "FILEPATH" OUT_PATH = "FILEPATH" # Read in data, if necessary # NISPUF20 <- read.csv(IN_PATH, "IN_FILE") # Social and Demographic Fields ## Age Groups (AGEGRP) NISPUF20$AGEGRP <- factor( NISPUF20$AGEGRP, levels = c(1, 2, 3), labels = c( "19-23 months", "24-29 months", "30-35 months" ) ) ## Number of people in household (C1R) NISPUF20$C1R <- factor( NISPUF20$C1R, levels = c(2, 3, 4, 5, 6, 7, 8), labels = c( "2", "3", "4", "5", "6", "7", "8+" ) ) ## Relationship of Respondent to Child (C5R) NISPUF20$C5R <- factor( NISPUF20$C5R, levels = c(1, 2, 3, 4, 77, 99), labels = c( "mother or female guardian", "father or male guardian", "grandparent", "other family/friend", "don't know", "refused" ) ) ## (US) Region NISPUF20$CEN_REG <- replace(NISPUF20$CEN_REG, is.na(NISPUF20$CEN_REG), 99) NISPUF20$CEN_REG <- factor( NISPUF20$CEN_REG, levels = c(1, 2, 3, 4, 99), labels = c( "northeast", "midwest", "south", "west", "territory or missing" ) ) ## Children under 18 in HH NISPUF20$CHILDNM <- factor( NISPUF20$CHILDNM, levels = c(1, 2, 3), labels = c( "one", "two or three", "four or more" ) ) ## Child received WIC benefits? NISPUF20$CWIC_01 <- factor( NISPUF20$CWIC_01, levels = c(1, 2, 3, 77, 99), labels = c( "yes", "no", "never heard of wic", "don't know", "refused" ) ) ## Education of mother categories NISPUF20$EDUC1 <- factor( NISPUF20$EDUC1, levels = c(1, 2, 3, 4), labels = c( "< 12 years", "12 years", "> 12 years, non-college grad", "college grad" ) ) ## Firstborn? NISPUF20$FRSTBRN <- factor( NISPUF20$FRSTBRN, levels = c(1, 2), labels = c( "no", "yes" ) ) ## Hispanic? NISPUF20$I_HISP_K <- factor( NISPUF20$I_HISP_K, levels = c(1, 2), labels = c( "hispanic", "non-hispanic" ) ) ## Poverty Status NISPUF20$INCPOV1 <- factor( NISPUF20$INCPOV1, levels = c(1, 2, 3, 4), labels = c( "above poverty, >$75k", "above poverty, <=$75k", "below poverty", "unknown" ) ) ## Income bucket NISPUF20$INCQ298A <- factor( NISPUF20$INCQ298A, levels = c(3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 77, 99), labels = c( "$0 - $7500", "$7501 - $10000", "$10001 - $17500", "$17501 - $20000", "$20001 - $25000", "$25001 - $30000", "$30001 - $35000", "$35001 - $40000", "$40001 - $50000", "$50001 - $60000", "$60001 - $75000", "$75001+", "don't know", "refused" ) ) ## Language of interview (Eng or Esp or Other) NISPUF20$LANGUAGE <- factor( NISPUF20$LANGUAGE, levels = c(1, 2, 3), labels = c( "english", "spanish", "other" ) ) ## Age of mother (<30yr or >=30yr) NISPUF20$M_AGEGRP2 <- factor( NISPUF20$M_AGEGRP2, levels = c(1, 2), labels = c( "<=29 years", ">=30 years" ) ) ## Marital status of mother NISPUF20$MARITAL2 <- factor( NISPUF20$MARITAL2, levels = c(1, 2), labels = c( "married", "not married at time of interview" ) ) ## Geographic mobility status (interview date vs at birth) NISPUF20$MOBIL_I <- factor( NISPUF20$MOBIL_I, levels = c(1, 2), labels = c( "moved from different state", "did not move from different state" ) ) ## Race of child (Black or White) NISPUF20$RACE_K <- factor( NISPUF20$RACE_K, levels = c(1, 2, 3), labels = c( "white only", "black only", "other + multiple race" ) ) ## Race/Ethnicity of child (Hispanic?) NISPUF20$RACEETHK <- factor( NISPUF20$RACEETHK, levels = c(1, 2, 3, 4), labels = c( "hispanic", "non-hispanic white only", "non-hispanic black only", "non-hispanic other + multiple race" ) ) ## Home being rented or owned NISPUF20$RENT_OWN <- factor( NISPUF20$RENT_OWN, levels = c(1, 2, 3, 77, 99), labels = c( "owned or being bought", "rented", "other arrangement", "don't know", "refused" ) ) ## Sex of child (M or F) NISPUF20$SEX <- factor( NISPUF20$SEX, levels = c(1, 2), labels = c( "male", "female" ) ) # Geographic variables ## State of residence (FIPS code) postal_codes <- c( "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY", "PR" ) fips <- c( 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 72 ) states <- data.frame( postal_code = postal_codes, fips = fips ) NISPUF20$state <- factor( NISPUF20$STATE, levels = fips, labels = postal_codes ) ## Number of providers identified by respondent NISPUF20$D6R <- replace(NISPUF20$D6R, is.na(NISPUF20$D6R), 99) NISPUF20$D6R <- factor( NISPUF20$D6R, levels = c(0, 1, 2, 3, 99), labels = c( "0", "1", "2", "3+", "missing" ) ) ## Number of providers responding with vaccination data for child NISPUF20$N_PRVR <- factor( NISPUF20$N_PRVR, levels = c(0, 1, 2, 3), labels = c( "0", "1", "2", "3+" ) ) ## Provider facility types (public, private, mixed, etc.) NISPUF20$PROV_FAC <- replace(NISPUF20$PROV_FAC, is.na(NISPUF20$PROV_FAC), 99) NISPUF20$PROV_FAC <- factor( NISPUF20$PROV_FAC, levels = c(1, 2, 3, 4, 5, 99), labels = c( "all public", "all hospital", "all private", "all military/other", "mixed", "missing" ) ) ## Whether all or some or none of providers reported vaccinations to ## immunization registry NISPUF20$REGISTRY <- replace(NISPUF20$REGISTRY, is.na(NISPUF20$REGISTRY), 99) NISPUF20$REGISTRY <- factor( NISPUF20$REGISTRY, levels = c(1, 2, 3, 4, 99), labels = c( "all providers", "some providers but probably not all", "no providers", "unknown", "missing" ) ) ## Whether all or some or none of providers ordered vaccines from state/local ## health dept. NISPUF20$VFC_ORDER <- replace(NISPUF20$VFC_ORDER, is.na(NISPUF20$VFC_ORDER), 99) NISPUF20$VFC_ORDER <- factor( NISPUF20$VFC_ORDER, levels = c(1, 2, 3, 4, 99), labels = c( "all providers", "some providers but probably not all", "no providers", "unknown", "missing" ) ) # Write prepared data object to file write.csv(NISPUF20, paste0(OUT_PATH, "nispuf20_refactored.csv"))
/* eslint-disable @typescript-eslint/no-unused-vars */ import { FC, useCallback } from 'react' import { Tree, TreeProps } from 'antd' import { DataNode } from 'antd/es/tree' import { NavLink } from 'react-router-dom' import { UUID } from '../../../types/common' import useChapterStore from '../../chapter/chapterStore' import usePartStore from '../../part/partStore' import { useStoryStore } from '../storyStore' import { IStory } from '../type' import styles from './StoryMenu.module.scss' type Props = { story: IStory expandedKeys?: UUID[] onAddChapter: (index: number, partId: string) => void } export const StoryMenu: FC<Props> = ({ story, expandedKeys, onAddChapter }) => { const { updateStory } = useStoryStore() const { getPartById, getPartByChapterId, updatePart } = usePartStore() const { getChapterById } = useChapterStore() const buildMenu = useCallback(() => { if (!story) return return story.partsIds?.map(partId => { const part = getPartById(partId) if (!part) return return { key: partId, title: part.title, children: part.chaptersIds?.map(chaptersId => { const chapter = getChapterById(chaptersId) return { key: chaptersId, title: chapter?.title } }) || [], } }) as DataNode[] }, [getChapterById, getPartById, story]) const onDragEnter: TreeProps['onDragEnter'] = () => { // console.log('onDragEnter', info) // expandedKeys, set it when controlled is needed // setExpandedKeys(info.expandedKeys) } const onDrop2: TreeProps['onDrop'] = event => { const dropKey = event.node.key as UUID const dragKey = event.dragNode.key as UUID const dragPos = event.dragNode.pos.split('-') const dropPos = event.node.pos.split('-') const dropPosition = event.dropPosition - Number(dropPos[dropPos.length - 1]) if (!dropKey || !event.dropToGap || dragPos.length !== dropPos.length) return const activePart = getPartById(dropKey) const activeChapter = getChapterById(dropKey) if (activePart) { const partsIds = [...(story.partsIds || [])] const dragIndex = partsIds.indexOf(dragKey) const dropIndex = partsIds.indexOf(dropKey) const lastIndex = dropPosition === -1 ? 0 : dragIndex > dropIndex ? dropIndex + 1 : dropIndex partsIds.splice(dragIndex, 1) partsIds.splice(lastIndex, 0, dragKey) updateStory(story.id, { ...story, partsIds, }) } if (activeChapter) { const oldPart = getPartByChapterId(dragKey) if (!oldPart) return const chaptersIds = [...(oldPart?.chaptersIds || [])] const dragIndex = chaptersIds.indexOf(dragKey) const dropIndex = chaptersIds.indexOf(dropKey) const lastIndex = dropPosition === -1 ? 0 : dragIndex > dropIndex ? dropIndex + 1 : dropIndex chaptersIds.splice(dragIndex, 1) chaptersIds.splice(lastIndex, 0, dragKey) updatePart(oldPart.id, { ...oldPart, chaptersIds, }) } } return ( <nav className={styles.menu}> <Tree className={styles.tree} defaultExpandedKeys={expandedKeys} draggable blockNode treeData={buildMenu()} checkStrictly={true} titleRender={nodeData => ( <span className={styles.item}> <NavLink to={`/stories/${story.id}/${nodeData.key}`}>{`${nodeData.title}`}</NavLink> {nodeData.children && ( <button className={styles.add} onClick={() => onAddChapter(nodeData?.children?.length || 0, nodeData.key as string) } > + </button> )} </span> )} onDragEnter={onDragEnter} onDrop={onDrop2} selectable={false} /> </nav> ) }
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { DeleteStatusesTransactionsResDto } from '../../dto/statuses-transactions/delete-statuses-transactions-res-dto'; import { GetAllStatusesTransactionsResDto } from '../../dto/statuses-transactions/get-all-statuses-transactions-res-dto'; import { GetByCodeStatusesTransactionsResDto } from '../../dto/statuses-transactions/get-by-code-statuses-transactions-res-dto'; import { GetByIdStatusesTransactionsResDto } from '../../dto/statuses-transactions/get-by-id-statuses-transactions-res-dto'; import { SaveStatusesTransactionsResDto } from '../../dto/statuses-transactions/save-statuses-transactions-res-dto'; import { StatusesTransactions } from '../../dto/statuses-transactions/statuses-transactions'; import { UpdateStatusesTransactionsResDto } from '../../dto/statuses-transactions/update-statuses-transactions-res-dto'; @Injectable({ providedIn: 'root' }) export class StatusesTransactionsService { constructor(private http: HttpClient) { } getAll(): Observable<StatusesTransactions[]>{ return this.http.get<StatusesTransactions[]>('http://localhost:8888/statuses-transactions/') } getByCode(code: string): Observable<StatusesTransactions>{ return this.http.get<StatusesTransactions>('http://localhost:8888/statuses-transactions/code/?code='+code) } getById(id:string): Observable<StatusesTransactions>{ return this.http.get<StatusesTransactions>('http://localhost:8888/statuses-transactions/id/?id='+id) } save(statusesTrasanctions: StatusesTransactions): Observable<SaveStatusesTransactionsResDto>{ return this.http.post<SaveStatusesTransactionsResDto>('http://localhost:8888/statuses-transactions/', statusesTrasanctions) } update(statusesTrasanctions: StatusesTransactions): Observable<UpdateStatusesTransactionsResDto>{ return this.http.put<UpdateStatusesTransactionsResDto>('http://localhost:8888/statuses-transactions/', statusesTrasanctions) } delete(id: string): Observable<DeleteStatusesTransactionsResDto>{ return this.http.delete<DeleteStatusesTransactionsResDto>('http://localhost:8888/statuses-transactions/' + id) } }
"use client"; import {useState} from "react"; import Image from "next/image"; export default function ImageGallery({images}: {images: string[]}) { const [mainImage, setMainImage] = useState<string>(images[0]); function getImage(img: string) { return ( <> {mainImage === img ? ( <Image src={img} alt="Image of a product" width={80} height={80} className="aspect-square object-fill rounded-full border-blue-400 border-[3px]" ></Image> ) : ( <Image src={img} alt="Image of a product" width={80} height={80} className="aspect-square object-fill rounded-full" ></Image> )} </> ); } return ( <article className="flex flex-col items-center gap-4"> <Image src={mainImage} alt="Image of a product" width={150} height={150} className="aspect-square rounded-full" /> <div className="flex gap-3"> {images.map((img, i) => ( <button key={i} onClick={(e) => setMainImage(img)}> {getImage(img)} </button> ))} </div> </article> ); }
package model.world; import java.awt.image.BufferedImage; import java.util.List; /** * The World interface represents the game world, which consists of rooms and entities. * It provides various methods for interacting with the game world. */ public interface World { /** * Gets a list of neighboring rooms for a given room name. * * @param roomName The name of the room. * @return A list of neighboring room names. * @throws IllegalArgumentException If the room name is not valid. * @throws NullPointerException If the provided room name is null. */ List<String> getNeighborsRoomList(String roomName) throws IllegalArgumentException, NullPointerException; /** * Gets the name of the world. * * @return The name of the world. */ String getWorldName(); /** * Gets the total number of rooms in the world. * * @return The total number of rooms. */ int getTotalOfRoom(); /** * Gets the total number of items in the world. * * @return The total number of items. */ int getTotalOfItem(); /** * Gets information about a specific room in the world. * * @param roomName The name of the room. * @return Information about the room. * @throws IllegalArgumentException If the room name is not valid. * @throws NullPointerException If the provided room name is null. */ String getOneRoomInfo(String roomName) throws IllegalArgumentException, NullPointerException; /** * Moves Dr. Lucky within the world. */ void moveDrLucky(); /** * Creates a graphical representation of the world as a BufferedImage. * * @return An image representation of the world. */ BufferedImage createGraphBufferedImage(); /** * Prints the neighbor map of the world to the console. */ void printWorldNeighborMap(); /** * Prints a 2D array representation of the world to the console. */ void printWorld2dArray(); /** * Gets information about Dr. Lucky within the world. * * @return Information about Dr. Lucky. */ String getDrLuckyInfo(); /** * Prints information about all rooms in the world to the console. */ void printAllRoomInfo(); /** * Add a human or computer player into the game world. * * @param name String of the player name. * @param initialRoomNum Int of player's initial room number index base 0. * @param limit Player's limit for carrying number of items. * @param checkComputer Ture if it is a computer player, otherwise false. * @throws IllegalArgumentException Due to invalid input. * @throws NullPointerException Due to invalid input. */ void addOnePlayer(String name, int initialRoomNum, boolean checkComputer, int limit) throws IllegalArgumentException, NullPointerException; /** * Gets the total number of players allowed in the game. * * @return The total number of players allowed in the game. */ int getTotalAllowedPlayers(); /** * Sets the total allowed number of players in the game. * * @param totalAllowedPlayers The total number of players allowed in the game. */ void setTotalAllowedPlayers(int totalAllowedPlayers); /** * Gets the total number of turns allowed in the game. * * @return The total number of turns allowed in the game. */ int getTotalAllowedTurns(); /** * Sets the total allowed number of turns in the game. * * @param totalAllowedTurns The total number of turns allowed in the game. */ void setTotalAllowedTurns(int totalAllowedTurns); /** * Perform a computer player's action in the game and return the result. * * @return The result of the computer player's action. * @throws IllegalStateException If the game is illegal state for the computer player's action. * @throws IllegalAccessException If there is an illegal access attempt during the action. */ String cmdComputerPlayerAction() throws IllegalStateException, IllegalAccessException; /** * Move the current player to the specified room. * * @param roomName The name of the room to which the player should move. * @throws IllegalArgumentException If the provided room name is not valid. * @throws IllegalAccessException If there is an illegal access attempt during the move. */ void cmdPlayerMove(String roomName) throws IllegalArgumentException, IllegalAccessException; /** * Move the Pet to the specified room. * * @param roomName The name of the room to which the player should move. * @throws IllegalArgumentException If the provided room name is not valid. * @throws IllegalAccessException If there is an illegal access attempt during the move. */ void cmdPetMove(String roomName) throws IllegalArgumentException, IllegalAccessException; /** * Get information about the current player's current room. * * @return Information about the current player's current room. * @throws IllegalArgumentException If the current player's room information is not valid. */ String cmdPlayerLook() throws IllegalArgumentException; /** * Allow the current player to pick up an item in the room. * * @param inputItemName The name of the item to be picked up. * @throws NullPointerException If the item name is null. * @throws IllegalArgumentException If item name is not valid, or if picking up is not allowed. * @throws IllegalAccessException If there is an illegal access attempt during item pickup. * @throws IllegalStateException If item pickup is not allowed in the current state. */ void cmdPlayerPick(String inputItemName) throws NullPointerException, IllegalArgumentException, IllegalAccessException, IllegalStateException; /** * Get information about the items that a player can pick up in the current room. * * @param playerName The name of the player for which to retrieve item information. * @return Information about the items that the player can pick up in the room. */ String getPlayerWhatCanPickInfo(String playerName); /** * Check if the game is over. * * @return True if the game is over, false otherwise. */ boolean checkGameOver(); /** * Gets a list of names of all players in the game world. * * @return A list of player names. */ List<String> getAllPlayerNames(); /** * Gets information about all players in the game world. * * @return Information about all players. */ String getAllPlayerInfo(); /** * Gets a list of names of all rooms in the game world. * * @return A list of room names. */ List<String> getAllRoomNames(); /** * Gets information about a specific player and their current room. * * @param playerName The name of the player for which to retrieve information. * @return Information about the specified player and their current room. */ String getOnePlayerAndRoomInfo(String playerName); /** * Gets the room name of the current player in the game. * * @param playerName The name of the player for which to retrieve information. * @return The room name string of where the current player is in. */ String getOnePlayerCurrentRoomName(String playerName); /** * Gets the name of the current player in the game. * * @return The name String of the current player. */ String getCurrentPlayerName(); /** * Checks if the current player is a computer player. * * @return True if the current player is a computer player, false otherwise. */ boolean isCurrentPlayerComputer(); /** * Gets the index of the current player. * * @return The index of the current player. */ int getCurrentPlayerIndex(); /** * Gets the current turn number in the game. * * @return The current turn number. */ int getCurrentTurnNumber(); /** * Checks if the current player is in the same room as Dr. Lucky. * * @return {@code true} if the current player is in the same room as Dr. Lucky, false otherwise. */ boolean checkCurPlayerSameRoomWithDrLucky(); /** * Checks if the current player can be seen by other players in the game. * * @return {@code true} if the current player is visible; {@code false} otherwise. */ boolean checkCurPlayerCanBeSeen(); /** * Executes a player attack with a specified item in the game world. * * @param itemName the name of the item used for the attack. * @return a string representation of the result of the player's attack. * @throws NullPointerException if a required parameter is null. * @throws IllegalArgumentException if an illegal argument is provided. * @throws IllegalAccessException if there is an issue with the player's attack. */ String cmdPlayerKill(String itemName) throws NullPointerException, IllegalArgumentException, IllegalAccessException; /** * Retrieves a string containing information about all items carried by a specific player, * including their names and damage values. * * @param playerName the name of the player. * @return a string representation of the player's carried items and their damage values. */ String getPlayerAllCarryingItemStringWithDamage(String playerName); /** * Retrieves the name of the pet. * * @return the name of the pet. */ String getPetName(); /** * Retrieves the name of the player who has won the game. * * @return the name of the game winner. */ String getWinnerName(); /** * Retrieves the name of Dr. Lucky in the game world. * * @return the name of Dr. Lucky. */ String getDrLuckyName(); /** * Retrieves the current health points of Dr. Lucky in the game world. * * @return the health points of Dr. Lucky. */ int getDrLuckyHp(); /** * Retrieves the room number where the pet is currently located in the game world. * * @return the room number of the pet. */ int getPetRoomNumber(); /** * Retrieves information about a specified room, excluding details about its neighbors. * The method takes a room name as input, checks for items, the presence of Dr. Lucky, the pet, * player in the room. The resulting information is formatted into a string and returned. * * @param roomName the name of the room for which information is requested. * @return a formatted string containing details about the specified room, its contents. * @throws IllegalArgumentException if the provided room name is invalid. * @throws NullPointerException if the room name is null. */ String getOneRoomInfoWithOutNeighbor(String roomName) throws IllegalArgumentException, NullPointerException; }
import { describe, expect, it, vi } from "vitest"; import CachedService from "../lib/CachedService.js"; const optimizer = { check: vi.fn(), buildCache: vi.fn(), select: vi.fn(), }; const store = { list: vi.fn(), save: vi.fn(), load: vi.fn(), putCaches: vi.fn(), getCache: vi.fn(), listCache: vi.fn(), }; const loadRequest = { name: "maoG0wFHmNhgAcMkRo1J.png", parameters: {}, codecs: [], acceptTypes: [], acceptEncodings: [], }; const loadResponse = { type: "webp", file: { data: "foobar", mtime: new Date(), size: 123456, }, }; const service = new CachedService(store, optimizer); describe("load", () => { it("should return null if no original file with type=origin", async () => { store.load.mockResolvedValueOnce(null); const result = await service.load({ ...loadRequest, parameters: { type: "origin" }, }); expect(result).toBeNull(); expect(optimizer.select).not.toHaveBeenCalled(); expect(store.load).toHaveBeenCalledOnce(); }); it("should return the original file if specified", async () => { store.load.mockResolvedValueOnce(loadResponse.file); const result = await service.load({ ...loadRequest, parameters: { type: "origin" }, }); expect(result!.file).toBe(loadResponse.file); expect(result!.type).toBe("png"); expect(optimizer.select).not.toHaveBeenCalled(); expect(store.load).toHaveBeenCalledOnce(); }); it("should return only cached by default", async () => { const result = await service.load({ ...loadRequest, parameters: {}, }); expect(result).toBeNull(); expect(optimizer.select).toHaveBeenCalledOnce(); expect(store.load).not.toHaveBeenCalled(); }); it("should get cache list to select", async () => { const attrsList = [ { type: "webp" }, { type: "png" }, { type: "avif" }, ]; store.listCache.mockResolvedValue(attrsList); optimizer.select.mockReturnValue({ type: "webp" }); await service.load(loadRequest); expect(optimizer.select).toHaveBeenCalledWith(attrsList, loadRequest); }); it("should get file from cache", async () => { store.getCache.mockResolvedValue(loadResponse.file); optimizer.select.mockReturnValue({ type: "webp" }); const result = await service.load(loadRequest); expect(result).toStrictEqual(loadResponse); expect(store.getCache).toHaveBeenCalledWith("maoG0wFHmNhgAcMkRo1J", { type: "webp" }); }); }); describe("save", () => { it("should skip build cache if already saved", async () => { store.save.mockResolvedValue(false); const result = await service.save({ type: "png", parameters: {}, buffer: Buffer.alloc(0), }); expect(result).toBe("maoG0wFHmNhgAcMkRo1J.png"); expect(store.save).toHaveBeenCalledOnce(); expect(optimizer.buildCache).not.toHaveBeenCalled(); }); it("should build cache for new file", async () => { const cacheItems = [ { data: "123", params: { type: "png" } }, { data: "456", params: { type: "avif" } }, ]; optimizer.buildCache.mockResolvedValue(cacheItems); store.save.mockResolvedValue(true); const result = await service.save({ type: "png", parameters: {}, buffer: Buffer.alloc(0), }); expect(result).toBe("maoG0wFHmNhgAcMkRo1J.png"); expect(optimizer.buildCache).toHaveBeenCalledOnce(); expect(store.putCaches).toHaveBeenCalledOnce(); }); });
// // AlertView.swift // SwiftUiCustomAlert // // Created by Mustafa Hegy on 25/10/2023. // import SwiftUI public struct AlertView: View { public let title: String public let description: String public let confirmButtonLabel: String public let cancelButtonLabel: String public let confirmAction: () -> Void public let cancelAction: () -> Void public init(title: String, description: String, confirmButtonLabel: String, cancelButtonLabel: String, confirmAction: @escaping () -> Void, cancelAction: @escaping () -> Void) { self.title = title self.description = description self.confirmButtonLabel = confirmButtonLabel self.cancelButtonLabel = cancelButtonLabel self.confirmAction = confirmAction self.cancelAction = cancelAction } @available(iOS 13.0.0, *) public var body: some View { ZStack { Color.black .opacity(0.3) .edgesIgnoringSafeArea(.all) VStack { Spacer() RoundedRectangle(cornerRadius: 12) // Rounded background .fill(Color.white) .frame(width: UIScreen.main.bounds.width - 60, height: UIScreen.main.bounds.width - 60) .overlay( VStack { Text(title) .font(.title) Text(description) .font(.body) .padding() HStack { Button(cancelButtonLabel) { cancelAction() } .padding() .background(Color.red) .foregroundColor(.white) .cornerRadius(8) Button(confirmButtonLabel) { confirmAction() } .padding() .background(Color.green) .foregroundColor(.white) .cornerRadius(8) } } ) .shadow(radius: 5) // Shadow Spacer() } .position(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2) } } }
#ifdef __CYGWIN__ #include <windows.h> #endif #include "terminator_terminal_pty_PTYProcess.h" #include "DirectoryIterator.h" #include "JniString.h" #include "join.h" #include "PtyGenerator.h" #include "toString.h" #include "unix_exception.h" #include <stdlib.h> #include <sys/stat.h> #ifdef __APPLE__ // sysctl.h doesn't exist on Cygwin. #include <sys/sysctl.h> #endif #include <sys/types.h> #include <termios.h> // Deque is the default choice of container in C++. // Using vector connotes a requirement for contiguity. // See http://www.gotw.ca/gotw/054.htm. #include <deque> #include <fstream> #include <string> #include <vector> typedef std::vector<std::string> StringArray; struct JavaStringArrayToStringArray : StringArray { JavaStringArrayToStringArray(JNIEnv* env, jobjectArray javaStringArray) { int arrayLength = env->GetArrayLength(javaStringArray); for (int i = 0; i != arrayLength; ++i) { jstring s = static_cast<jstring>(env->GetObjectArrayElement(javaStringArray, i)); push_back(JniString(env, s)); } } }; struct Argv : std::vector<char*> { // Non-const because execvp is anti-social about const. Argv(StringArray& arguments) { for (StringArray::iterator it = arguments.begin(); it != arguments.end(); ++it) { // We must point to the memory in arguments, not a local. std::string& argument = *it; push_back(&argument[0]); } // execvp wants a null-terminated array of pointers to null terminated strings. push_back(0); } }; static void waitUntilFdWritable(int fd) { int rc; do { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); rc = ::select(fd + 1, 0, &fds, 0, 0); } while (rc == -1 && errno == EINTR); if (rc != 1) { throw unix_exception("select(" + toString(fd) + ", ...) failed"); } } void terminator_terminal_pty_PTYProcess::nativeStartProcess(jstring javaExecutable, jobjectArray javaArgv, jstring javaWorkingDirectory) { PtyGenerator ptyGenerator; fd = ptyGenerator.openMaster(); JavaStringArrayToStringArray arguments(m_env, javaArgv); Argv argv(arguments); std::string executable(JniString(m_env, javaExecutable)); std::string workingDirectory(""); if (javaWorkingDirectory != 0) { workingDirectory = JniString(m_env, javaWorkingDirectory); } pid = ptyGenerator.forkAndExec("terminator", executable, &argv[0], workingDirectory); // On Linux, the TIOCSWINSZ ioctl sets the size of the pty (without blocking) even if it hasn't been opened by the child yet. // On Mac OS, it silently does nothing, meaning that when the child does open the pty, TIOCGWINSZ reports the wrong size. // We work around this by explicitly blocking the parent until the child has opened the pty. // We can recognize this on Mac OS by the fact that a write would no longer block. // (The fd is writable on Linux even before the child has opened the pty.) // FIXME: If the fd never becomes writable, for example because the specified working directory doesn't exist, then this locks up the whole Terminator. waitUntilFdWritable(fd.get()); slavePtyName = newStringUtf8(ptyGenerator.getSlavePtyName()); } void terminator_terminal_pty_PTYProcess::sendResizeNotification(jobject jSize) { if (fd.get() == -1) return; struct winsize size; size.ws_col = JniField<jint, false>(m_env, jSize, "width", "I").get(); size.ws_row = JniField<jint, false>(m_env, jSize, "height", "I").get(); if (ioctl(fd.get(), TIOCSWINSZ, &size) < 0) throw unix_exception("I/O control command TIOCSWINSZ failed on " + toString(fd.get())); }
package controller import ( "bank-merchant-api/model/domain" "bank-merchant-api/model/web" "bank-merchant-api/service" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "net/http" ) type MerchantController struct { service service.MerchantService } func NewMerchantController(service service.MerchantService) *MerchantController { return &MerchantController{service: service} } func (controller *MerchantController) CreateMerchant(ctx *gin.Context) { var req web.MerchantRequest if err := ctx.ShouldBindJSON(&req); err != nil { ctx.JSON(http.StatusBadRequest, web.Response{Status: "error", Message: err.Error()}) return } validate := validator.New() if err := validate.Struct(req); err != nil { ctx.JSON(http.StatusBadRequest, web.Response{Status: "error", Message: err.Error()}) return } merchant := domain.Merchant{ Name: req.Name, Balance: 0, } if err := controller.service.CreateMerchant(&merchant); err != nil { ctx.JSON(http.StatusInternalServerError, web.Response{Status: "error", Message: err.Error()}) return } ctx.JSON(http.StatusOK, web.Response{Status: "success", Message: "merchant created"}) } func (controller *MerchantController) GetMerchant(ctx *gin.Context) { id := ctx.Param("id") merchant, err := controller.service.GetMerchant(id) if err != nil { ctx.JSON(http.StatusInternalServerError, web.Response{Status: "error", Message: err.Error()}) return } ctx.JSON(http.StatusOK, merchant) } func (controller *MerchantController) DeleteMerchant(ctx *gin.Context) { id := ctx.Param("id") if err := controller.service.DeleteMerchant(id); err != nil { ctx.JSON(http.StatusInternalServerError, web.Response{Status: "error", Message: err.Error()}) return } ctx.JSON(http.StatusOK, web.Response{Status: "success", Message: "merchant deleted"}) }
import React, { useState } from "react"; import "./Create.css"; import axios from "axios"; import { useNavigate } from "react-router-dom"; function Create() { const navigate = useNavigate(); const [value, setValue] = useState({ fname: "", lname: "", email: "", phone: "", passwd: "", }); const handleSubmit = (event) => { event.preventDefault(); axios .post("http://localhost:5000/api/post", value) .then(res => { console.log(res.data.data); setValue(res.data.data); navigate('/') }) .catch(error => { console.log(error); }); }; return ( <div className="page-content"> <div className="form-v4-content"> <div className="form-left"> <h2>INFOMATION</h2> <p className="text-1"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Et molestie ac feugiat sed. Diam volutpat commodo. </p> <p className="text-2"> <span>Eu ultrices:</span> Vitae auctor eu augue ut. Malesuada nunc vel risus commodo viverra. Praesent elementum facilisis leo vel. </p> </div> <form className="form-detail" onSubmit={handleSubmit}> <h2>REGISTER FORM</h2> <div className="form-group"> <div className="form-row form-row-1"> <label htmlFor="lname">First Name</label> <input type="text" name="fname" id="fname" className="input-text" value={value.fname} onChange={(e) => setValue({ ...value, fname: e.target.value })} /> </div> <div className="form-row form-row-1"> <label htmlFor="lname">Last Name</label> <input type="text" name="lname" id="lname" className="input-text" value={value.lname} onChange={(e) => setValue({ ...value, lname: e.target.value })} /> </div> </div> <div className="form-row"> <label htmlFor="email">Your Email</label> <input type="text" name="email" id="email" className="input-text" required pattern="[^@]+@[^@]+.[a-zA-Z]{2,6}" value={value.email} onChange={(e) => setValue({ ...value, email: e.target.value })} /> </div> <div className="form-row"> <label htmlFor="phone">Phone-Number</label> <input type="number" name="phone" id="phone" className="input-text" value={value.phone} onChange={(e) => setValue({ ...value, phone: e.target.value })} /> </div> <div className="from-control"> <div className="form-row form-row-1"> <label htmlFor="passwd">Password</label> <input type="password" name="passwd" id="passwd" className="input-text" required value={value.passwd} onChange={(e) => setValue({ ...value, passwd: e.target.value })} /> </div> </div> <div className="form-row-last"> <button className="btn btn-info" type="submit">Submit</button> <button className="btn btn-info float-end">Back</button> </div> </form> </div> </div> ); } export default Create;
#Cytogenetics and IPSS-R tool for MDS v1.1.0 import streamlit as st import pandas as pd import numpy as np import re # CG STRING PROCESSING #--idem processing def process_idem(row): cytogenetics_value = str(row[cytovar]) cytogenetics_value = cytogenetics_value.replace(" ", "") #whitespace elimination cytogenetics_value = cytogenetics_value.replace("{", "[" ) #bracket change cytogenetics_value = cytogenetics_value.replace("}", "]" ) #bracket change cytogenetics_value = cytogenetics_value.replace("]", "]/") #add / after bracet for it to detect segment cytogenetics_value = cytogenetics_value.replace("];", "]/") #semi-colon change to fit split below cytogenetics_value = cytogenetics_value.replace("],", "]/") #comma change to fit split below cytogenetics_value = cytogenetics_value.replace("]//", "]/") #double / elimination fit split below if cytogenetics_value.endswith("/"): cytogenetics_value = cytogenetics_value.rstrip("/") cytogenetics_value = "".join([char.lower() if char not in ['X', 'Y'] else char for char in cytogenetics_value]) segments = cytogenetics_value.split('/') first_segment_abnl = re.sub(r'\[\d+\]', '', ",".join(segments[0].split(',')[1:])) #cum abnl, first segment cumulative_abnl = first_segment_abnl for i in range(1, len(segments)): #skip first segment if 'idem' in segments[i]: #get the chromosomes chromosome_count = segments[i].split(',')[0] #replace idem with cum abnl segments[i] = chromosome_count + "," + cumulative_abnl + "," + ",".join(segments[i].split(',')[1:]).replace('idem,', '') #update the cumm abnormalities without adding duplicates current_segment_abnl = re.sub(r'\[\d+\]', '', ",".join(segments[i].split(',')[1:])) for abnl in current_segment_abnl.split(','): if abnl and abnl not in cumulative_abnl: cumulative_abnl += "," + abnl return '/'.join(segments) def count_abn(row): cytogenetics_value = str(row["processed_cg"]) segments = cytogenetics_value.split('/') max_abn = 0 for segment in segments: if segment.endswith('[1]'): #ignoring the [1] segments continue abns = segment.split(',')[2:] seg_abn_count = len(abns) if seg_abn_count > max_abn: max_abn = seg_abn_count return max_abn # VERY GOOD RISK ABNORMALITIES# %% #"""-Y(minusy)""" def minusy(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'-Y|- Y' match = re.search(pattern, segment) if match: return 1 return 0 # """del11q(delelevenq)""" def elevenq(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'del\(11\)\(q' match = re.search(pattern, segment) if match: return 1 return 0 # GOOD RISK ABNORMALITIES # """"del5q""" def delfiveq(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'del\(5\)\(q' match = re.search(pattern, segment) if match: return 1 return 0 # """"del12p""" def deltwelvep(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'del\(12\)\(p' match = re.search(pattern, segment) if match: return 1 return 0 # # """del20q""" def deltwentyq(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'del\(20\)\(q' match = re.search(pattern, segment) if match: return 1 return 0 # INTERMEDIATE RISK ABNORMALITIES # """del7q""" def delsevenq(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'del\(7\)\(q' match = re.search(pattern, segment) if match: return 1 return 0 # """"plus8""" def pluseight(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'\+8' match = re.search(pattern, segment) if match: return 1 return 0 # """plus19""" def plusnineteen(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'\+19' match = re.search(pattern, segment) if match: return 1 return 0 # """i17q""" def iseventeenq(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'i\(17\)\(q' match = re.search(pattern, segment) if match: return 1 return 0 # POOR RISK ABNORMALITIES # """minus7""" def minusseven(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(segment, str): pattern = r'\-7' match = re.search(pattern, segment) if match: return 1 return 0 # """inv3/t3q/del3q (inv_del_t_3q)""" def chr3abn(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(cytogenetics_value, str): pattern = r'inv\(3|t\(3|del\(3\)\(q' match = re.search(pattern, cytogenetics_value) if match: return 1 return 0 # """"DEL 17p AND -17""" #not in CG risk but useful for IPSS-M calculation def delseventeen(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(cytogenetics_value, str): pattern = r'del\(17\)\(p|-17|- 17' match = re.search(pattern, cytogenetics_value) if match: return 1 return 0 # """Diploid or 46,XX or 46,XY """ othervars = ["del77q", "del55q", "del1717p", "elevenq", "minusy"] def diploid(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split('/') for segment in segments: if segment.endswith('[1]'): continue if isinstance(cytogenetics_value, str): pattern = r'46,XX\[|46,XY\[|Diploid CG' match = re.search(pattern, cytogenetics_value) if match: return 1 return 0 # CG-RISK CALCULATION def segments(row): cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split("/") count = 0 for segment in segments: if not segment.endswith('[1]'): count += 1 return count # """CALCULATE CG RISK""" good_vars = ["del20q", "del12p", "del5q"] intermediate_or_higher_vars = ["del7q", "minus7", "plus8", "plus19", "i17q", "inv_del_t_3q"] higher_vars = ["minus7", "inv_del_t_3q"] def cg_risk(row): #this is the right order of resolving the if statements to call cg_risk 10/2023 cytogenetics_value = row["processed_cg"] segments = cytogenetics_value.split("/") for segment in segments: if segment.endswith("[1]"): continue #easy: 4 "Very Poor" if highly complex more than 3 abnormalities (see count_abn function) if row["abn_total"] >3: return 4 #easy: "Very Good" if isolated -Y or isolated del11q if ((row["minusy"] == 1) and (row[good_vars].any() ==0) and (row[intermediate_or_higher_vars].any() ==0)) or \ ((row["delelevenq"] == 1) and (row[good_vars].any() ==0) and (row[intermediate_or_higher_vars].any() ==0)): return 0 #step 1 complexity, #diploid must be 1 #del12p must be isolated + abn_total = 1, #del20p must be isolated + abn_total = 1, #del5q must be isolated, or del5q + other clone, except clones with intermediate or high-risk abnormalities if (row["diploid"] == 1) or \ ((row["del12p"] == 1) and (row["abn_total"] == 1)) or \ ((row["del20q"]) == 1 and (row["abn_total"] == 1)) or \ ((row["del5q"] ==1) and (row["clone_total"] <=2) and (row[intermediate_or_higher_vars].any() == 0)): return 1 #step 2 complexity, minus7 or del7 + another, -7 alone, abn3 any, or 3 abnormalities (complex=3) if (row["minus7"] == 1) or \ (row["inv_del_t_3q"] == 1) or \ ((row["minus7"] == 1) and (row["clone_total"] == 2)) or \ ((row["del7q"] == 1) and (row["abn_total"] >= 2)) or \ (row["abn_total"] == 3 ): return 3 #basically almost anything else, isolated del7q, isolated +8, isolated +19, isolated i17q, or clone >=2 and abn total =2, or any other clone, #with diploid, del5q, intermediate or higher vars have to be 0 if ((row["del7q"] == 1) and (row["abn_total"] == 1)) or\ ((row["plus8"] == 1) and (row["abn_total"] == 1)) or \ ((row["plus19"] == 1) and (row["abn_total"] == 1)) or \ ((row["i17q"] == 1) and (row["abn_total"] == 1)) or \ ((row["clone_total"] >= 2) and (row["abn_total"] <= 2) and (row["diploid"] == 0) and (row[higher_vars].any() == 0) and (row["del5q"]== 0)) or \ ((row["clone_total"] == 2) and (row[higher_vars].any() == 0)): return 2 if not any(char.isdigit() for char in segment): return "manual check required" else: return "manual check required" return "manual check required" def check_numeric_and_sum(row): if row.apply(lambda x: isinstance(x, str)).any(): return "manual check required" else: return row.sum() def master_function(data): data["processed_cg"] = data.apply(process_idem, axis=1) data["abn_total"] = data.apply(count_abn, axis=1) data["clone_total"] = data.apply(lambda row: segments(row), axis=1) data["minusy"] = data.apply(lambda row: minusy(row) if row["abn_total"] == 1 else 0, axis=1) data["delelevenq"] = data.apply(lambda row: elevenq(row) if row["abn_total"] == 1 else 0, axis=1) data['del5q'] = data.apply(lambda row: delfiveq(row), axis=1) data['del12p'] = data.apply(lambda row: deltwelvep(row), axis=1) data['del20q'] = data.apply(lambda row: deltwentyq(row), axis=1) data["del7q"] = data.apply(lambda row: delsevenq(row), axis=1) data["plus8"] = data.apply(lambda row: pluseight(row), axis=1) data["plus19"] = data.apply(lambda row: plusnineteen(row), axis=1) data["i17q"] = data.apply(lambda row: iseventeenq(row), axis=1) data["minus7"] = data.apply(lambda row: minusseven(row), axis=1) data["inv_del_t_3q"] = data.apply(lambda row: chr3abn(row), axis=1) #includes those with any amount of abnormalities data["del1717p"] = data.apply(lambda row: delseventeen(row), axis=1) data["diploid"] = data.apply(lambda row: diploid(row) if row['abn_total'] == 0 else 0, axis=1) #this function may need work data["cg_risk_ipssr"] = data.apply(lambda row: cg_risk(row), axis=1) conditionshb = [ data[hbvar] < 8, # Low (data[hbvar] >= 8) & (data[hbvar] < 10), # Moderate ] choiceshb = [1.5, 1] data["hbrisk"] = np.select(conditionshb, choiceshb, default=0) conditionsplt =[ data[pltvar] < 50, (data[pltvar] >= 50) & (data[pltvar] < 100), ] choicesplt = [1, 0.5] data["pltrisk"] = np.select(conditionsplt, choicesplt, default=0) conidtionsanc = [ data[ancvar] < 0.8 ] choicesanc = [0.5] data["ancrisk"] = np.select(conidtionsanc, choicesanc, default=0) conditionsblasts = [ (data[blastvar] > 10), (data[blastvar] <= 10) & (data[blastvar] > 5), (data[blastvar] <= 5) & (data[blastvar] > 2), (data[blastvar] <= 2), ] chocicesblasts = [3,2,1,0] data["blastrisk"] = np.select(conditionsblasts, chocicesblasts) ipssr_cols = ['ancrisk', 'blastrisk', 'pltrisk', 'hbrisk', 'cg_risk_ipssr'] data['IPSS_R_scores'] = data[ipssr_cols].apply(check_numeric_and_sum, axis=1) conditionipssr = [ data["IPSS_R_scores"].apply(lambda x: x >= 0 and x <= 1.5 if isinstance(x, (int, float)) else False), #VL data["IPSS_R_scores"].apply(lambda x: x > 1.5 and x <= 3 if isinstance(x, (int, float)) else False), #L data["IPSS_R_scores"].apply(lambda x: x > 3 and x <= 4.5 if isinstance(x, (int, float)) else False), #I data["IPSS_R_scores"].apply(lambda x: x > 4.5 and x <= 6 if isinstance(x, (int, float)) else False), #H data["IPSS_R_scores"].apply(lambda x: x > 6 if isinstance(x, (int, float)) else False), #VH ] choicesipssr = ["Very Low", "Low", "Intermediate", "High", "Very High"] data["IPSS_R_cat"] = np.select(conditionipssr, choicesipssr, default="manual check required") return data st.title("Cytogenetic risk and IPSS-R calculator for myelodysplastic syndrome") st.markdown("""Please enter the column names in your file without spaces below: Please make sure your columns contain **only** numeric values.""") cytovar = st.text_input("Enter the name of the cytogenetics column (better performance with ISCN 2020)") blastvar = st.text_input("Enter the name of the bone marrow blast column in percentage (e.g., normal = 2)") hbvar= st.text_input("Enter the name of the hemoglobin column in g/dl (e.g., normal = 14)") pltvar = st.text_input("Enter the name of the platelet column in x10^9/L (e.g., normal = 300)") ancvar = st.text_input("Enter the name of the ANC column x10^9/L (e.g., normal = 2.5)") u_file = st.file_uploader("Please upload a CSV file. Please convert your Excel file to CSV prior to uploading.", type =['csv']) inputvars = [blastvar,hbvar,pltvar,ancvar] if st.button('Disclaimer'): st.write("This is an app in development. Pease check the results. The cytogenetic risk caller performs better (>99%) with ISCN 2020 nomenclature.") st.markdown(""" #### Contact Information: - **Created by:** Samuel Urrutia - **Email:** surrutia@mdanderson.org - All files are deleted upon closing the browser. """) if u_file is not None: if u_file.name.endswith('.csv'): data = pd.read_csv(u_file) st.write("Original Data") st.write(data) try: for var in inputvars: data[var] = pd.to_numeric(data[var], errors='coerce') if data[inputvars].isnull().any().any(): st.write("ANC, hemoglobin, or platelets contain non-numeric values that could not be converted. Please edit your file and try again.") else: processed_data = master_function(data.copy()) st.write("Processed Data") st.write(processed_data) proc_data = processed_data.to_csv(index=False) st.download_button( label="Download Processed Data", data=proc_data, file_name="processed_cytogenetic_data.csv", mime="text/csv" ) except Exception as e: st.write(f"An error occurred: {e}") else: st.write("Please upload a file.")
package LayeredArchitectureDemo.registry; import LayeredArchitectureDemo.entity.Message; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; /** * unit testing {@link MessageLib} */ public class MessageLibTest { private MessageLib messageLib; private ObjectMapper objMapper = new ObjectMapper(); @BeforeEach public void reset(){ messageLib = new MessageLib(); } @Test public void crudTest() throws JsonProcessingException { Message message1 = new Message(); Message message2 = new Message(); message1.setId(1L); message2.setId(2L); messageLib.put(message1); messageLib.put(message2); assertThat(messageLib.get(1L).getId()).isEqualTo(1L); assertThat(messageLib.get(2L).getId()).isEqualTo(2L); messageLib.remove(2L); messageLib.replace(message2); assertThat(messageLib.contains(1L)).isTrue(); assertThat(messageLib.contains(2L)).isFalse(); assertThat(messageLib.size()).isEqualTo(1); messageLib.toString(); messageLib.clear(); assertThat(messageLib.size()).isEqualTo(0); HashMap<Long, Message> library = new HashMap<>(); messageLib.setLibrary(library); String expected = objMapper.writeValueAsString(library); String actual = objMapper.writeValueAsString(messageLib.getLibrary()); assertThat(actual).isEqualTo(expected); } }
// Obtener el archivo JSON de pasos. async function fetchSteps() { try { const response = await fetch('./resources/json/narrativa/tiempoSteps.json') const data = await response.json(); return data; } catch(error) { console.error(error); } } // Ejecutar las funciones cuando se reciba la respuesta. fetchSteps().then(data => scrollSteps(data)); // Iniciar Scrollama y ejecutar funciones cuando se cargue el DOM y se entre en cada paso. const scrollSteps = (data) => { const scroller = scrollama(); scroller .setup({ step: '.narrativaStep' }) .onStepEnter((step) => { document.readyState === 'loading' ? console.log('Cargando') : changeContent(data, step); changeMap(step.index); }); } // Crear los mapas. const tiempoMap_1 = new maplibregl.Map({ container: 'tiempoMapElm_1', style: './resources/json/map_styles/narrativaMap_1.json', center: [-69.35067, 2.85314], zoom: 5, pitch: 0, bearing: 0, interactive: false, attributionControl: false }); const tiempoMap_2 = new maplibregl.Map({ container: 'tiempoMapElm_2', style: './resources/json/map_styles/narrativaMap_1.json', center: [-64.13079, 5.70012], zoom: 9.24, pitch: 0, bearing: 0, interactive: false, attributionControl: false }); // Agregar sources, layers y animar. tiempoMap_1.on('load', () => { tiempoMap_1.addSource('transformacionOrinoco_1', { type: 'geojson', data: './resources/geojson/narrativa/transformacionOrinoco.geojson' }); // Línea sólida. tiempoMap_1.addLayer({ id: 'stepSolid', type: 'line', source: 'transformacionOrinoco_1', paint: { 'line-color': ['get', 'color'], 'line-width': 7, 'line-opacity': ['match', ['get', 'step'], 2, 0.5, 0] } }); // Línea animada. tiempoMap_1.addLayer({ id: 'stepAnim', type: 'line', source: 'transformacionOrinoco_1', paint: { 'line-color': ['get', 'color'], 'line-width': 7, 'line-opacity': ['match', ['get', 'step'], 2, 1, 0] } }); enableLineAnim(tiempoMap_1, 'stepAnim', 0.3, 8, 8, stepInit); }); tiempoMap_2.on('load', () => { tiempoMap_2.addSource('transformacionOrinoco_2', { type: 'geojson', data: './resources/geojson/narrativa/transformacionOrinoco.geojson' }); // Línea sólida. tiempoMap_2.addLayer({ id: 'step_6_solid', type: 'line', filter: ['==', 'step', 6], source: 'transformacionOrinoco_2', paint: { 'line-color': ['get', 'color'], 'line-width': 7, 'line-opacity': 0.5 } }); // Línea animada. tiempoMap_2.addLayer({ id: 'step_6_anim', type: 'line', filter: ['==', 'step', 6], source: 'transformacionOrinoco_2', paint: { 'line-color': ['get', 'color'], 'line-width': 7, 'line-opacity': 1 } }); enableLineAnim(tiempoMap_2, 'step_6_anim', 0.1, 5, 5, stepInit); }); // Cambiar el contenido de los divs de texto e imagen. const changeContent = (data, step) => { let divTxt = document.getElementById('tiempoTxt_' + data[step.element.id].div); let divImg = document.getElementById('tiempoImg_' + data[step.element.id].div); if (divTxt) divTxt.innerHTML = data[step.element.id].text; if (divImg) divImg.innerHTML = data[step.element.id].img; } // Cambiar el contenido del mapa 1. const changeMap = (index) => { if (tiempoMap_1.getSource('transformacionOrinoco_1')) { switch(index) { case 2: tiempoMap_1.setPaintProperty('stepSolid', 'line-opacity', ['match', ['get', 'step'], 2, 0.5, 0]); tiempoMap_1.setPaintProperty('stepAnim', 'line-opacity', ['match', ['get', 'step'], 2, 1, 0]); changeMapView(0, 0.36); break; case 3: tiempoMap_1.setPaintProperty('stepSolid', 'line-opacity', ['match', ['get', 'step'], 3, 0.5, 0]); tiempoMap_1.setPaintProperty('stepAnim', 'line-opacity', ['match', ['get', 'step'], 3, 1, 0]); changeMapView(1, 0.36); break; case 4: tiempoMap_1.setPaintProperty('stepSolid', 'line-opacity', ['match', ['get', 'step'], 4, 0.5, 0]); tiempoMap_1.setPaintProperty('stepAnim', 'line-opacity', ['match', ['get', 'step'], 4, 1, 0]); changeMapView(2, 0.8); break; case 5: tiempoMap_1.setPaintProperty('stepSolid', 'line-opacity', ['match', ['get', 'step'], 5, 0.5, 0]); tiempoMap_1.setPaintProperty('stepAnim', 'line-opacity', ['match', ['get', 'step'], 5, 1, 0]); changeMapView(3, 0.8); break; } } } // Cambiar el centro y el zoom del mapa 1. const changeMapView = (index, vel) => { tiempoMap_1.flyTo({ center: mapViews[index][0], zoom: mapViews[index][1], speed: vel }); } // Centros y zooms para el mapa 1. const mapViews = [ [ [-69.35067, 2.85314], 5 ], [ [-66.2, 5.96424], 5.5 ], [ [-66.2, 5.96424], 5.5 ], [ [-73.26332, 4.50225], 10.5 ] ]; // Animación de las lineas. Original en https://stackoverflow.com/a/43079655/10102175 var stepInit = 0; const enableLineAnim = (mapId, layerId, animSpeed, dashLength, gapLength, step) => { if (mapId.getLayer(layerId)) { const dashSteps = 40 * dashLength / (gapLength + dashLength); const gapSteps = 40 - dashSteps; step = step + animSpeed; if (step >= 40) step = 0; var t, a, b, c, d; if (step < dashSteps) { t = step / dashSteps; a = (1 - t) * dashLength; b = gapLength; c = t * dashLength; d = 0; } else { t = (step - dashSteps) / gapSteps; a = 0; b = (1 - t) * gapLength; c = dashLength; d = t * gapLength; } mapId.setPaintProperty(layerId, 'line-dasharray', [d, c, b, a]); requestAnimationFrame(() => enableLineAnim(mapId, layerId, animSpeed, dashLength, gapLength, step)); } } // Iniciar tippy.js para tooltips. tippy.delegate('.sectionContent', { target: ['#spanMioceno', '#spanCamino', '#spanBlancasNegras', '#spanEcosistemas'], content: (reference) => reference.dataset.tooltip, trigger: 'mouseenter focus', theme: 'colombia' });
import logger from '@/infra/adapter/logger/logger' import { Email } from '@/infra/adapter/typeorm/entity/entity' import { EmailNotFoundError } from '@/core/errors/error' import { Repository } from '../port/repository/repository' import { EmailDTO } from '../domain/domain' import { Mail } from '../port/mail/mail' import { EmailConsumer } from '../domain/emailConsumer' const log = logger({ context: 'EmailService' }) export class EmailService { constructor (private readonly emailRepository: Repository<Email>, private readonly emailSender: Mail) {} async sendEmail (emailConsumer: EmailConsumer): Promise<void> { const email = new EmailDTO(undefined, "", emailConsumer.email, '', '', false) const emailSaved = await this.emailRepository.save(email) await this.emailSender.send(emailSaved) await this.emailRepository.update(emailSaved) } async searchAllSentByEmail (email: string): Promise<EmailDTO[]> { log.info(`Find all emails sent to ${email}`) const emailArray = await this.emailRepository.findByEmailAndIsSent(email) if (!emailArray) throw new EmailNotFoundError(`Emails not found for ${email}`) return emailArray.map(email => EmailDTO.fromEntity(email)) } async findEmailById (id: number): Promise<EmailDTO> { log.info(`Finding by id - ${id}`) const email = await this.emailRepository.findOne(id) if (!email) { throw new EmailNotFoundError(`Email not found for id ${id}`) } return EmailDTO.fromEntity(email) } async findAll (): Promise<EmailDTO[]> { log.info('Finding all emails') const emails = await this.emailRepository.findAll() if (!emails) { throw new EmailNotFoundError('Email not found') } return emails.map(email => EmailDTO.fromEntity(email)) } }
<?php /* Criação da classe Atividade com o CRUD */ require_once __DIR__ . '../../conexao/Conexao.php'; require_once __DIR__ . '../../model/Atividade.php'; class AtividadeDAO { public function SalvarAtividade( Atividade $atividade ) { try { $sql = "INSERT INTO atividade( nm_Atividade,vlr_mensal_Atividade,desco_mensal_Atividade, vlr_total_Atividade,desc_Atividade,data_cad_Treino) VALUES ( :nm_Atividade, :vlr_mensal_Atividade, :desco_mensal_Atividade, :vlr_total_Atividade, :desc_Atividade, :data_cad_Treino)"; $Conexao = new Conexao(); date_default_timezone_set( 'America/Sao_Paulo' ); $Data_Cadastro = date( 'Y-m-d' ); $statement_sql = $Conexao->Conectar()->prepare( $sql ); $vlr_mensal_Atividade = str_replace( ',', '.', $atividade->getvlr_mensal_Atividade() ); $vlr_total_Atividade = str_replace( ',', '.', $atividade->getvlr_total_Atividade() ); $statement_sql->bindValue( ':nm_Atividade', $atividade->getnm_Atividade() ); $statement_sql->bindValue( ':vlr_mensal_Atividade', $vlr_mensal_Atividade ); $statement_sql->bindValue( ':desco_mensal_Atividade', $atividade->getdesco_mensal_Atividade() ); $statement_sql->bindValue( ':vlr_total_Atividade', $vlr_total_Atividade ); $statement_sql->bindValue( ':desc_Atividade', $atividade->getdesc_Atividade() ); $statement_sql->bindValue( ':data_cad_Treino', $Data_Cadastro ); return $statement_sql->execute(); } catch ( Exception $e ) { print 'Erro ao Inserir usuario <br>' . $e . '<br>'; } } public function updateAtividade( Atividade $atividade ) { try { $sql = "UPDATE atividade set nm_Atividade = :nm_Atividade, vlr_mensal_Atividade = :vlr_mensal_Atividade, desco_mensal_Atividade = :desco_mensal_Atividade, vlr_total_Atividade = :vlr_total_Atividade, desc_Atividade = :desc_Atividade, data_cad_Treino = :data_cad_Treino WHERE id_Atividade = :id_Atividade"; $Conexao = new Conexao(); date_default_timezone_set( 'America/Sao_Paulo' ); $Data_Cadastro = date( 'Y-m-d' ); $statement_sql = $Conexao->Conectar()->prepare( $sql ); $vlr_mensal_Atividade = str_replace( ',', '.', $atividade->getvlr_mensal_Atividade() ); $vlr_total_Atividade = str_replace( ',', '.', $atividade->getvlr_total_Atividade() ); $statement_sql->bindValue( ':id_Atividade', $atividade->getid_Atividade() ); $statement_sql->bindValue( ':nm_Atividade', $atividade->getnm_Atividade() ); $statement_sql->bindValue( ':vlr_mensal_Atividade', $vlr_mensal_Atividade ); $statement_sql->bindValue( ':desco_mensal_Atividade', $atividade->getdesco_mensal_Atividade() ); $statement_sql->bindValue( ':vlr_total_Atividade', $vlr_total_Atividade ); $statement_sql->bindValue( ':desc_Atividade', $atividade->getdesc_Atividade() ); $statement_sql->bindValue( ':data_cad_Treino', $Data_Cadastro ); return $statement_sql->execute(); } catch ( Exception $e ) { print "Ocorreu um erro ao tentar fazer Update<br> $e <br>"; } } public function getAtividade() { try { $sql = 'SELECT * FROM atividade order by nm_Atividade asc'; $Conexao = new Conexao(); $statement_sql = $Conexao->Conectar()->query( $sql ); $resultado = array(); while ( $row = $statement_sql->fetch( PDO::FETCH_ASSOC ) ) { $atividade = new Atividade(); $atividade->setid_Atividade( $row[ 'id_Atividade' ] ); $atividade->setnm_Atividade( $row[ 'nm_Atividade' ] ); $atividade->setvlr_mensal_Atividade( $row[ 'vlr_mensal_Atividade' ] ); $atividade->setdesco_mensal_Atividade( $row[ 'desco_mensal_Atividade' ] ); $atividade->setvlr_total_Atividade( $row[ 'vlr_total_Atividade' ] ); $atividade->setdesc_Atividade( $row[ 'desc_Atividade' ] ); $resultado[] = $atividade; } return $resultado; } catch ( Exception $e ) { print 'Ocorreu um erro ao tentar Buscar Todos.' . $e; } } public function paginacao_Atividade( $inicio, $registros ) { try { $condition = ''; if ( isset( $_POST[ 'search' ] ) and $_POST[ 'search' ] != '' ) { $condition .= 'Where nm_Atividade LIKE :search '; } $sql = 'select * from atividade '.$condition." LIMIT $inicio, $registros"; $Conexao = new Conexao(); $statement_sql = $Conexao->Conectar()->prepare( $sql ); if ( isset( $_POST[ 'search' ] ) ) { $search = $_POST[ 'search' ]; $search = '%' . $search . '%'; $statement_sql->bindParam( ':search', $search ); } $statement_sql->execute(); $resultado = array(); while ( $row = $statement_sql->fetch( PDO::FETCH_ASSOC ) ) { $atividade = new Atividade(); $atividade->setid_Atividade( $row[ 'id_Atividade' ] ); $atividade->setnm_Atividade( $row[ 'nm_Atividade' ] ); $atividade->setvlr_mensal_Atividade( $row[ 'vlr_mensal_Atividade' ] ); $atividade->setdesco_mensal_Atividade( $row[ 'desco_mensal_Atividade' ] ); $atividade->setvlr_total_Atividade( $row[ 'vlr_total_Atividade' ] ); $atividade->setdesc_Atividade( $row[ 'desc_Atividade' ] ); $resultado[] = $atividade; } return $resultado; } catch ( PDOException $e ) { print ' Erro ' . $e->getMessage(); } } public function ProcurarAtividadePorCodigo( Atividade $atividade ) { try { $sql = 'select * from atividade where id_Atividade = :id_Atividade'; $Conexao = new Conexao(); $statement_sql = $Conexao->Conectar()->prepare( $sql ); $statement_sql->bindValue( ':id_Atividade', $atividade->getid_Atividade() ); $statement_sql->execute(); $row = $statement_sql->fetch( PDO::FETCH_ASSOC ) ; if ( $statement_sql ) { $atividade->setid_Atividade( $row[ 'id_Atividade' ] ); $atividade->setnm_Atividade( $row[ 'nm_Atividade' ] ); $atividade->setvlr_mensal_Atividade( $row[ 'vlr_mensal_Atividade' ] ); $atividade->setdesco_mensal_Atividade( $row[ 'desco_mensal_Atividade' ] ); $atividade->setvlr_total_Atividade( $row[ 'vlr_total_Atividade' ] ); $atividade->setdesc_Atividade( $row[ 'desc_Atividade' ] ); } return $atividade; //$statement_sql->debugDumpParams(); } catch ( PDOException $exc ) { print 'Erro :: ' . $exc->getMessage(); } } public function deletarAtividade( Atividade $atividade ) { try { $sql = 'DELETE FROM atividade WHERE id_Atividade = :id_Atividade'; $Conexao = new Conexao(); $statement_sql = $Conexao->Conectar()->prepare( $sql ); $statement_sql->bindValue( ':id_Atividade', $atividade->getid_Atividade() ); return $statement_sql->execute(); } catch ( Exception $e ) { echo "Erro ao Excluir Atividade<br> $e <br>"; } } private function listaAtividade( $row ) { $atividade = new Atividade(); $atividade->setid_Atividade( $row[ 'id_Atividade' ] ); $atividade->setnm_Atividade( $row[ 'nm_Atividade' ] ); $atividade->setvlr_mensal_Atividade( $row[ 'vlr_mensal_Atividade' ] ); $atividade->setdesco_mensal_Atividade( $row[ 'desco_mensal_Atividade' ] ); $atividade->setvlr_total_Atividade( $row[ 'vlr_total_Atividade' ] ); $atividade->setdesc_Atividade( $row[ 'desc_Atividade' ] ); return $atividade; } } ?>
import { Button, Flex, Heading, useColorModeValue, useDisclosure, } from '@chakra-ui/react'; import TodoDeleteModal from '@client/components/Todos/TodoDeleteModal'; import TodoEditModal from '@client/components/Todos/TodoEditModal'; import TodosList from '@client/components/Todos/TodosList'; import { fetchTodosList } from '@client/services/todos'; import type { Todo } from '@prisma/client'; import type { NextPage } from 'next'; import { useCallback, useState } from 'react'; import { useQuery } from 'react-query'; const Todos: NextPage = () => { const headerTextColor = useColorModeValue('gray.600', 'white'); const addButtonColor = useColorModeValue('white', 'teal.600'); const [editingTodo, setEditingTodo] = useState<Todo | null>(null); const [deletingTodo, setDeletingTodo] = useState<Todo | null>(null); const { isLoading: isTodosLoading, data: todos } = useQuery( 'todos', fetchTodosList ); const { isOpen: isEditModalOpen, onOpen: onEditModalOpen, onClose: onEditModalClose, } = useDisclosure(); const { isOpen: isDeleteModalOpen, onOpen: onDeleteModalOpen, onClose: onDeleteModalClose, } = useDisclosure(); const onEdit = useCallback( (todo: Todo) => { setEditingTodo(todo); onEditModalOpen(); }, [onEditModalOpen] ); const onDelete = useCallback( (todo: Todo) => { setDeletingTodo(todo); onDeleteModalOpen(); }, [onDeleteModalOpen] ); const onAdd = useCallback(() => { setEditingTodo(null); onEditModalOpen(); }, [onEditModalOpen]); return ( <Flex w="full" maxW="3xl" direction="column" py="8" mx="auto"> <Flex justifyContent="space-between" align="center" color={headerTextColor} > <Heading size="lg">Todos list</Heading> <Button aria-label="Add todo" size="sm" color={addButtonColor} onClick={onAdd} > Add </Button> </Flex> <TodosList todos={todos || []} onDelete={onDelete} onEdit={onEdit} isLoading={isTodosLoading} /> <TodoEditModal isOpen={isEditModalOpen} onClose={onEditModalClose} todo={editingTodo} /> {deletingTodo && ( <TodoDeleteModal isOpen={isDeleteModalOpen} onClose={onDeleteModalClose} todo={deletingTodo} /> )} </Flex> ); }; export default Todos;
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"; import { corsHeaders } from "../_shared/cors.ts"; serve(async (req) => { const systemMessage = "점수 : 1~10 사이의 점수를 부여. 상대방의 요구를 잘 반영하고 공감하고 있으면 높은 점수를, 그렇지 않으면 낮은 점수를 부여. 조금이라도 상대방의 요구사항을 반영하지 못하거나 공감을 하지 못하면 5점 미만의 낮은 점수를 부여."; // const systemMessage = // "점수 : 1~10 사이의 점수를 부여. 상대방의 요구를 잘 반영하고 공감하고 있으면 높은 점수를, 그렇지 않으면 낮은 점수를 부여."; if (req.method === "OPTIONS") { return new Response("ok", { headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST", "Access-Control-Expose-Headers": "Content-Length, X-JSON", "Access-Control-Allow-Headers": "apikey,X-Client-Info, Content-Type, Authorization, Accept, Accept-Language, X-Authorization", }, }); } else { try { const { prompt } = await req.json(); const res = await fetch("https://api.openai.com/v1/chat/completions", { body: JSON.stringify({ model: "gpt-4-1106-preview", // model: "gpt-3.5-turbo-1106", messages: [ { role: "system", content: systemMessage }, { role: "user", content: prompt }, ], temperature: 0.7, max_tokens: 512, top_p: 0.3, frequency_penalty: 0, presence_penalty: 0, }), headers: { Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`, "Content-Type": "application/json", }, method: "POST", }); const data = await res.json(); return new Response(JSON.stringify(data), { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: 200, }); } catch (error) { console.error(error); return new Response(JSON.stringify({ error: error.message }), { headers: { ...corsHeaders, "Content-Type": "application/json" }, status: 400, }); } } });
\documentclass[12pt]{article} \title{\textbf{CAP6635 Project Report 1}} \author{William L. Thomson Jr.} \date{Spring Semester 2024} \usepackage{enumitem} \usepackage{float} \usepackage{hyperref} \usepackage{graphicx} \usepackage[T1]{fontenc} \usepackage{titlesec} \usepackage[tmargin=1in,lmargin=1in,rmargin=1in]{geometry} \addtolength{\topmargin}{-3cm} \addtolength{\textheight}{3cm} \hypersetup{ colorlinks=true, linkcolor=blue, urlcolor=blue } \titleformat{\section}{\normalfont\bfseries}{\thesection}{0.5em}{} \titlespacing\section{0pt}{12pt plus 4pt minus 8pt}{4pt plus 2pt minus 8pt} \begin{document} \maketitle \vspace{-2em} \section{Research} \indent \indent Initial research done thus far is mostly in understanding the paper implementation and how we are deviating from that. We will not be changing the start location, as they change the start location when a new goal is set. We will also not be changing the goal location. Pending further research and the ultimate solution, we may or may not be returning back to the original path as determined by IRRT*. It is not clear at this time to what extent we will be re-wiring the tree, pruning any leaf nodes and adding others. This might be done as part of Tangent Bug implementation, and/or after the fact with the new route taken, either back to original or entirely new path to goal, which might entail another round of IRRT*. \section{Plan} The current plan of action is as follows: \begin{description}[style=multiline,leftmargin=8em] \itemsep0em \item[IRRT*] Run IRRT* to determine the path to goal with random obstacles \item[New Obstacle] A new obstacle is randomly added/detected as the path is being traversed, the path that IRRT* identified, the new obstacle intersects that path. \item[Collision Zone] The path will be traversed till the obstacle enters a collision zone, which might require adding a new node, as the collision zone might be smaller than the distance from the previous node to the new obstacle \item[Tangent Bug] Use Tangent Bug to go around the obstacle at some distance, to some next point \item[To Be Decided] From Tangent Bug it has yet to be decided the method used to either return to the initial path from IRRT* or to re-route to a shorter path to the goal via some method to be decided. \end{description} \section{Progress} \indent \indent Initial prototype code has been written using \href{https://github.com/AtsushiSakai/PythonRobotics/tree/master/PathPlanning/InformedRRTStar}{PythonRobotics implementation of IRRT*}, with randomized start, goal, and obstacles. After IRRT* is run, a obstacle is randomly added long the path as seen in Figure \ref{figure1}. Alternative prototyping was also done with a new random goal, per the paper implementation as seen in Figure \ref{figure2} and \ref{figure3}, but we will not be exploring that approach. Although, it does present an additional challenge, if that new obstacle causes a new goal, \emph{e.g.} door closed obstacle, or other none traversal. \section{What's next} \indent \indent The next step is to code in a variable collision zone, and code for detecting the nearest node to the newly detected object, and potentially, creating another outside the collision zone distance, that will be used as a buffer distance for Tangent Bug to remain that distance away from the obstacle. \vspace{1em} \newpage \addtolength{\topmargin}{2cm} \begin{figure}[H] \begin{center} \includegraphics[scale=0.35]{screenshots/shot1_random_obstacle} \caption{Screenshot of random obstacle on IRRT* path} \label{figure1} \end{center} \end{figure} \vspace{-2em} \begin{figure}[H] \begin{center} \includegraphics[scale=0.35]{screenshots/shot2_new_goal} \caption{Screenshot of random new goal on IRRT* path} \label{figure2} \end{center} \vspace{-2em} \end{figure} \begin{figure}[H] \begin{center} \includegraphics[scale=0.35]{screenshots/shot3_new_goal} \caption{Screenshot of random new goal on IRRT* path} \label{figure3} \end{center} \end{figure} \vspace{-3em} \end{document}
/** * @file main.c * @author timwilliam (findtimwilliam@gmail.com) * @brief LeetCode: 1768. Merge Strings Alternately * @version 1.0 * @date 2024-02-16 */ #include <stdio.h> #include <stdlib.h> #include <string.h> /** * @brief Merge two string alternately * * @remark Time complexity = O(n) * * @param word1 Input string 1 * @param word2 Input string 1 * @return char* Alternately merged string */ char *mergeAlternately(char * word1, char * word2){ int word1Len = strlen(word1); int word2Len = strlen(word2); int i = 0; // for tracking index of word1 int j = 0; // for tracking index of word2 int k = 0; // for tracking index of mergedWord // create char array and initialize it with '/0' // notice the extra space for '\0' (terminating NULL character) char *mergedWord = malloc((word1Len + word2Len + 1) * sizeof(char)); memset(mergedWord, '\0', ((word1Len + word2Len + 1) * sizeof(char))); while(1) { if(i >= word1Len && j >= word2Len) { break; } if(i < word1Len) { mergedWord[k] = word1[i]; i++; k++; } if(j < word2Len) { mergedWord[k] = word2[j]; j++; k++; } } return mergedWord; } /** * @brief Keep adding char from word1 and word2 to mergedWord until both tracking index * for word1 and word2 are equal to word1Len and word2Len * */ int main(void){ // char word1[] = "abc"; // char word2[] = "pqr"; char word1[] = "ab"; char word2[] = "pqrs"; // char word1[] = "abcd"; // char word2[] = "pq"; // char word1[] = "a"; // char word2[] = "p"; printf("%s\n", mergeAlternately(word1, word2)); return 0; }
import { useState } from "react"; import { Link } from "react-router-dom"; import { LIST_TYPES } from "../config"; import FormAddNewTask from "../Forms/FormAddNewTask"; import style from './List.module.css' import Add_image from '../../images/Add_task.svg' const List = ({type, title, tasks, addNewTask, setTasks, prevTaskList}) => { const [formVisible, setFormVisible] = useState(false); const toggleForm = () => { setFormVisible(!formVisible) } const formSubmit = (title, description) => { addNewTask(title, description) setFormVisible(false) } const changeStatus = (e, status) => { const tasksList = JSON.parse(window.localStorage.getItem('tasks')); const tasksCopy = tasksList.map((t) => { if (t.id === e.target.value) {t.status = status} return t }); setTasks(tasksCopy); setFormVisible(!formVisible); } return ( <div className={style.list}> <h2 className={style.list_title}>{title}</h2> {tasks.length? tasks.map(task => <Link key={task.id} to={`/tasks/${task.id}`}> <div className={style.task}>{task.title}</div> </Link> ) : <p>No tasks added yet</p> } {type === LIST_TYPES.BACKLOG && <button onClick={toggleForm} className={style.add_button}><img src={Add_image}/> Add card</button>} {type === LIST_TYPES.BACKLOG && formVisible && ( <FormAddNewTask formSubmit={formSubmit}/> )} {type !== LIST_TYPES.BACKLOG && <form onSubmit={(e) => {e.preventDefault(); setFormVisible(false);}} className={style.option_form}> <select className={style.select} onChange={(e) => changeStatus(e, type)} defaultValue={"default"} disabled={Boolean(prevTaskList.length < 1)}> <option className={style.option} value={'default'} >Add card </option> {prevTaskList.map(task => { return( <option className={style.option} key={task.id} value={task.id}> {task.title} </option> ) })} </select> </form> } </div> ) }; export default List;
import { Button } from 'App/components/Button' import { TextField } from 'App/components/Input' import { SelectField } from 'App/components/Select' import { useForm } from 'App/hooks/useForm' import { Account, CreateAccount, currencies, Currency } from 'lib/accounts' import { validators } from 'lib/Form/Validation' import React from 'react' import './Accounts.scss' type FormValues = { name: string currency: Currency } const toFormValues = (data: CreateAccount | null): FormValues => ({ name: data === null ? '' : data.name, currency: data === null ? ('' as Currency) : data.currency, }) type AddAccountProps = { editableAccount: Account | null onSubmit: (account: CreateAccount | Account) => void } export const AddAccount: React.FC<AddAccountProps> = props => { const { fieldProps, handleSubmit } = useForm({ initialValues: toFormValues(props.editableAccount), validators: () => ({ name: validators.maxLength(18), currency: validators.nonBlankString<Currency>(), }), validationStrategy: 'onBlur', onSubmit: values => { if (props.editableAccount === null) { props.onSubmit(values) } else { props.onSubmit({ uid: props.editableAccount.uid, ...values }) } }, }) return ( <form className='add-account-form'> <TextField {...fieldProps('name')} className='add-account-form__input' placeholder='Account name' /> <SelectField {...fieldProps('currency')} hiddenLabel='Choose a currency' options={currencies} /> <Button type='submit' variant='primary' className='add-account-form__button' onClick={handleSubmit}> Submit </Button> </form> ) }
#include <bits/stdc++.h> /** * O(n^2)의 알고리즘이면 n이 3만 이상인 알고리즘을 1초 이내로 풀기는 어렵다. * 포인터 변수를 가지고 교집합을 조정할 수 있다. * 다만 이런 교집합 문제는 두 집합을 정렬해서 병합정렬처럼 해야한다. * 생각을 하자 * vector.begin(), vector.end()의 이더레이터패턴은 많이 쓴다. * 외워두자 */ void same(int* arr1, int* arr2, int size1, int size2, int resultsize, int* result) { int i = 0, j = 0, k = 0; while (i < size1 && j < size2) { if (arr1[i] == arr2[j]) { result[k] = arr1[i]; k++; i++; j++; } else { if (arr1[i] > arr2[j]) { j++; } else { i++; } } } } int main() { int n, m; std::cin >> n; std::vector<int> arr1(n); for (int i = 0; i < n; i++) { std::cin >> arr1[i]; } std::sort(arr1.begin(), arr1.end()); std::cin >> m; std::vector<int> arr2(m); for (int i = 0; i < m; i++) { std::cin >> arr2[i]; } int resultsize = std::min(n, m); std::vector<int> result(resultsize); std::sort(arr2.begin(), arr2.end()); same(arr1.data(), arr2.data(), n, m, resultsize, result.data()); for (int i = 0; i < resultsize; i++) { if(result[i] == 0){ continue; } std::cout << result[i] << ' '; } return 0; }
import { useEffect, useState } from 'react'; import { AccountCard, Spinner } from '../../components'; import MainLayout from '../../layouts/MainLayout'; import { getAccounts } from '../../services/account'; import { Account } from '../../services/account/types'; import styles from './index.module.css'; const MyAccounts = () => { const [loading, setLoading] = useState<boolean>(); const [accounts, setAccounts] = useState<Account[]>([]); useEffect(() => { setLoading(true); Promise.all([getAccounts()]).then(([accounts]) => { setAccounts(accounts); setLoading(false); }); }, []); return ( <MainLayout> <Spinner show={loading} /> <div className={styles.myAccountsContainer}> {accounts.map((account) => ( <AccountCard key={`account-${account.id}`} account={account} /> ))} </div> </MainLayout> ); }; export default MyAccounts;
import Joi from 'joi' export const validatePromotionsAndIncrement = (data) => { const promotionsAndIncrementSchema = Joi.object({ previous_designation: Joi.string().required().messages({ 'string.base': 'previous designation should be a type of text', 'string.empty': 'previous designation cannot be empty', 'any.required': 'previous designation is required' }), new_designation: Joi.string().required().messages({ 'string.base': 'new designation should be a type of text', 'string.empty': 'new designation cannot be empty', 'any.required': 'new designation is required' }), employee: Joi.string().required().messages({ 'string.base': 'employee code should be a type of text', 'string.empty': 'employee code cannot be empty', 'any.required': 'employee code is required' }), promotion_date: Joi.date().required().messages({ 'date.base': 'promotion date should be a type of date', 'date.empty': 'promotion date cannot be empty', 'any.required': 'promotion date is required' }), remarks: Joi.date().required().messages({ 'string.base': 'remarks should be a type of text', 'string.empty': 'remarks cannot be empty', 'any.required': 'remarks is required' }), basic: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), houseRent: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), conveyance: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), medicalAllowance: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), fuelAllowance: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), specialAllowance: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), grossSalary: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), overtimePayment: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), arrearAdjustment: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), compensation: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), festivalAllowance: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), utilityAllowance: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), leaveEncashment: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), otherAdjustment: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), grossPay: Joi.number().optional().message({ 'number.base': ' allowance should be a type of number', }), }) const options = { abortEarly: false, allowUnknown: false }; return promotionsAndIncrementSchema.validate(data, options); }
.. _guide_decoder_plugins: Pixel Data Decoder Plugins .. note:: This guide is intended for advanced users who need support for something not provided by the :doc:`existing decoder plugins </reference/pixels.decoders>`. *Pixel Data* decoding in *pydicom* uses a :class:`~pydicom.pixels.decoders.base.Decoder` instance to manage plugins that perform the actual decoding work. This guide covers the requirements for those plugins and how to add them to *pydicom*. Plugin Requirements Each available pixel data decoder in *pydicom* corresponds directly to a single DICOM *Transfer Syntax UID*, and is intended to provide a mechanism for converting raw encoded source data to unencoded pixel values. In order to do so, each decoder for compressed transfer syntaxes has at least one decoding plugin which performs the actual conversion. An decoding plugin must implement three objects within the same module: * A function named ``is_available`` with the following signature: .. code-block:: python def is_available(uid: pydicom.uid.UID) -> bool: Where `uid` is the *Transfer Syntax UID* for the corresponding decoder as a :class:`~pydicom.uid.UID`. If the plugin supports the `uid` and has its dependencies met then it should return ``True``, otherwise it should return ``False``. * A :class:`dict` named ``DECODER_DEPENDENCIES`` with the type ``dict[pydicom.uid.UID, tuple[str, ...]``, such as: .. code-block:: python from pydicom.uid import RLELossless, JPEG2000 DECODER_DEPENDENCIES = { RLELossless: ('numpy', 'pillow', 'imagecodecs'), JPEG2000: ('numpy', 'gdcm'), } This will be used to provide the user with a list of dependencies required by the plugin. * A function that performs the decoding with the following function signature: .. code-block:: python def decoder(src: bytes, runner: DecodeRunner) -> bytearray | bytes: Where * `src` is a single frame's worth of raw compressed data to be decoded. * `runner` is a :class:`~pydicom.pixels.decoders.base.DecodeRunner` instance that manages the decoding process and has access to the decoding options, either directly through the class properties or indirectly with the :meth:`~pydicom.pixels.decoders.base.DecodeRunner.get_option` method. At a minimum the following decoding options should be available: * ``transfer_syntax_uid``: :class:`~pydicom.uid.UID` - the *Transfer Syntax UID* of the encoded data. * ``rows``: :class:`int` - the number of rows of pixels in decoded data. * ``columns``: :class:`int` - the number of columns of pixels in the decoded data. * ``samples_per_pixel``: :class:`int` - the number of samples used per pixel, e.g. 1 for grayscale images or 3 for RGB. * ``number_of_frames``: :class:`int` - the number of image frames contained in `src` * ``bits_allocated``: :class:`int` - the number of bits used to contain each pixel in `src`, should be a multiple of 8. * ``bits_stored``: :class:`int` - the number of bits actually used by each pixel in `src`, e.g. 12-bit pixel data (range 0 to 4095) will be contained by 16-bits (range 0 to 65535). * ``photometric_interpretation``: :class:`str` - the color space of the encoded data, such as ``'YBR_FULL'`` * ``pixel_keyword``: :class:`str` - one of ``"PixelData"``, ``"FloatPixelData"``, ``"DoubleFloatPixelData"``. And conditionally: * ``pixel_representation``: :class:`int` - required when `pixel_keyword` is ``"PixelData"``, ``0`` for unsigned integers, ``1`` for signed. * ``planar_configuration``: :class:`int` - required when ``samples_per_pixel`` > 1, ``0`` for color-by-pixel, ``1`` for color-by-plane. If your decoder needs to signal that one of the decoding option values needs to be modified then this can be done with the :meth:`~pydicom.pixels.decoders.base.DecodeRunner.set_option` method. This should only be done after successfully decoding the frame, as if the decoding fails changing the option value may cause issues with other decoding plugins that may also attempt to decode the same frame. It's also important to be aware that any changes you make will also affect following frames (if any). When possible it's recommended that the decoding function return the decoded pixel data as a :class:`bytearray` to minimize later memory usage. An example of the requirements of a plugin is available :gh:`here <pydicom/blob/main/src/pydicom/pixels/decoders/rle.py>`. Adding Plugins to a Decoder Additional plugins can be added to an existing decoder with the :meth:`~pydicom.pixels.decoders.base.Decoder.add_plugin` method, which takes the a unique :class:`str` `plugin_label`, and a :class:`tuple` of ``('the import path to the decoder function's module', 'decoder function name')``. For example, if you'd import your decoder function `my_decoder_func` with ``from my_package.decoders import my_decoder_func``, then you'd do the following: .. code-block:: python from pydicom.pixels.decoders import RLELosslessDecoder RLELosslessDecoder.add_plugin( 'my_decoder', # the plugin's label ('my_package.decoders', 'my_decoder_func') # the import paths ) The ``my_package.decoders`` module must contain the encoding function and the ``DECODER_DEPENDENCIES`` and ``is_available`` objects.
import { ObjectLiteral, Repository } from 'typeorm'; export function transactionMock<T extends ObjectLiteral>(repositoty: Repository<T>) { const transaction = jest.fn((fn) => Promise.resolve(fn())); const manager: any = { transaction }; jest.replaceProperty(repositoty, 'manager', manager); return { manager, transaction, }; } export function insertQueryBuilderMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const execute = jest.fn(() => Promise.resolve({ raw: result })); const returning = jest.fn(() => ({ execute })); const orIgnore = jest.fn(() => ({ returning, execute })); const orUpdate = jest.fn(() => ({ returning, execute })); const values = jest.fn(() => ({ returning, execute, orIgnore, orUpdate })); const into = jest.fn(() => ({ values })); const insert = jest.fn(() => ({ values, into })); const query_builder: any = { insert }; jest.spyOn(repositoty, 'createQueryBuilder').mockReturnValueOnce(query_builder); return { query_builder, insert, into, values, orIgnore, orUpdate, returning, execute, }; } export function updateQueryBuilderMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const execute = jest.fn(() => Promise.resolve({ raw: result })); const returning = jest.fn(() => ({ execute })); const andWhere = jest.fn(() => ({ returning, execute })); const where = jest.fn(() => ({ returning, execute, andWhere })); const set = jest.fn(() => ({ where, returning })); const update = jest.fn(() => ({ set })); const query_builder: any = { update }; jest.spyOn(repositoty, 'createQueryBuilder').mockReturnValueOnce(query_builder); return { query_builder, update, set, where, andWhere, returning, execute, }; } export function deleteQueryBuilderMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const execute = jest.fn(() => Promise.resolve({ raw: result })); const returning = jest.fn(() => ({ execute })); const andWhere = jest.fn(() => ({ returning, execute })); const where = jest.fn(() => ({ returning, execute, andWhere })); const deleteFn = jest.fn(() => ({ where })); const query_builder: any = { delete: deleteFn }; jest.spyOn(repositoty, 'createQueryBuilder').mockReturnValueOnce(query_builder); return { query_builder, delete: deleteFn, where, andWhere, returning, execute, }; } export function insertMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const insert: any = jest.fn(() => Promise.resolve({ raw: result })); jest.spyOn(repositoty, 'insert').mockImplementationOnce(insert); return { insert, }; } export function updateMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const update: any = jest.fn(() => Promise.resolve({ raw: result })); jest.spyOn(repositoty, 'update').mockImplementationOnce(update); return { update, }; } export function deleteMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const delete_fn: any = jest.fn(() => Promise.resolve({ raw: result })); jest.spyOn(repositoty, 'delete').mockImplementationOnce(delete_fn); return { delete: delete_fn, }; } export function findMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T[] = []) { const find: any = jest.fn(() => Promise.resolve(result)); jest.spyOn(repositoty, 'find').mockImplementationOnce(find); return { find, }; } export function findOneMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: T | null = null) { const find_one: any = jest.fn(() => Promise.resolve(result)); jest.spyOn(repositoty, 'findOne').mockImplementationOnce(find_one); return { findOne: find_one, }; } export function findOneOrFailMock<T extends ObjectLiteral>(repositoty: Repository<T>, result?: T) { const find_one_or_fail: any = jest.fn(() => Promise.resolve(result)); jest.spyOn(repositoty, 'findOneOrFail').mockImplementationOnce(find_one_or_fail); return { findOneOrFail: find_one_or_fail, }; } export function countMock<T extends ObjectLiteral>(repositoty: Repository<T>, result: number = 0) { const count: any = jest.fn(() => Promise.resolve(result)); jest.spyOn(repositoty, 'count').mockImplementationOnce(count); return { count, }; }
import * as React from 'react'; import { render } from '@testing-library/react'; import { initIcons } from '../../../../src/components'; import { UIFormattedText, formatText } from '../../../../src/components/UITranslationInput/UIFormattedText'; describe('<UIMessageText />', () => { initIcons(); const values = { key: 'testKey', value: 'testValue', dummy: 'dummy' }; const testCases = [ { name: 'No key and matches', text: 'dummy test', values: values, expectedResult: 'dummy test' }, { name: 'Single match', text: 'dummy {{{value}}} test', values: values, expectedResult: 'dummy testValue test' }, { name: 'Multiple matches 1', text: 'dummy {{{value}}} test {{{key}}}', values: values, expectedResult: 'dummy testValue test testKey' }, { name: 'Multiple matches 2', text: 'My {{{key}}} dummy {{{value}}} test {{{dummy}}} scenario with multiple {{{value}}} matches', values: values, expectedResult: 'My testKey dummy testValue test dummy scenario with multiple testValue matches' }, { name: 'No matches', text: 'dummy {{{unknown}}} test', values: values, expectedResult: 'dummy {{{unknown}}} test' } ]; describe('UIMessageText component', () => { test.each(testCases)('$name', ({ text, values }) => { const { container } = render(<UIFormattedText values={values}>{text}</UIFormattedText>); expect(container.querySelector('div')?.innerHTML).toMatchSnapshot(); }); }); describe('formatText', () => { test.each(testCases)('$name', ({ text, values, expectedResult }) => { const result = formatText(text, values); expect(result).toEqual(expectedResult); }); }); });
<!DOCTYPE html> <html> <head> <title>Best ONline Food Delivery in india | MyOnlineMeal.com</title> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" media="screen and(max-width: 1170px)" href="css/phone.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=Baloo+Bhaina+2&family=Baloo+Tamma+2&family=Balsamiq+Sans:ital,wght@0,400;1,700&display=swap" rel="stylesheet"> <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=Baloo+Bhaina+2&family=Baloo+Tamma+2&family=Balsamiq+Sans:ital,wght@0,400;1,700&family=Zen+Antique&display=swap" rel="stylesheet"> </head> <body> <nav id="navbar"> <div id="logo"> <img src="logo.jpg" alt="MyOnlineMeal.com"> </div> <ul> <li class="item"><a href="#"> Home</a></li> <li class="item"><a href="#" >Services</a></li> <li class="item"><a href="#" >About Us</a></li> <li class="item"><a href="#" >Contact Us</a></li> </ul> </nav> <section id="home"> <h1 class="h-primary">Welcome to MyOnlineMeal</h1> <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Culpa expedita alias possimus voluptatem aperiam sed repudiandae eveniet laudantium mollitia vero veniam itaque illo, error numquam temporibus ex exercitationem. Rerum, quasi.</p> <p> Lorem ipsum, dolor sit amet consectetur adipisicing elit. Voluptas explicabo, maiores ullam sit ea eos tenetur eaque, aliquid deleniti repellat provident iste laboriosam minima quos sed molestias dolorum a officia. </p> <button class="btn">Order Now</button> </section> <section class="services-container"> <h1 class="h-primary center">Our Services</h1> <div id="services"> <div class="box"> <img src="img/1.jpg" alt=""> <h2 class="h-secondary center">Food Ordering</h2> <p class="center"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi, pariatur iure! Repellat eum, iusto fugiat culpa sequi nam et earum voluptatum dignissimos accusantium voluptas soluta mollitia similique cupiditate quidem optio! </p> </div> <div class="box"> <img src="img/2.jpg" alt=""> <h2 class="h-secondary center">Food catering</h2> <p class="center"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi, pariatur iure! Repellat eum, iusto fugiat culpa sequi nam et earum voluptatum dignissimos accusantium voluptas soluta mollitia similique cupiditate quidem optio! </p> </div> <div class="box"> <img src="img/3.jpg" alt=""> <h2 class="h-secondary center">Bulk Ordering</h2> <p class="center"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi, pariatur iure! Repellat eum, iusto fugiat culpa sequi nam et earum voluptatum dignissimos accusantium voluptas soluta mollitia similique cupiditate quidem optio! </p> </div> </div> </section> <section id="client-section"> <h1 class="h-primary center">Our Client</h1> <div id="client"> <div class="client-item"> <img src="img/logo1.jpg" alt="" class="src"> </div> <div class="client-item"> <img src="img/logo2.jpg" alt="" class="src"> </div> <div class="client-item"> <img src="img/logo3.jpg" alt="" class="src"> </div> <div class="client-item"> <img src="img/logo4.jpg" alt="" class="src"> </div> </section> <section id="contact"> <h1 class="h-primary center">Contact Us</h1> <div id="contact-box"> <form action=""> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" id="name" placeholder="Enter Your name"> </div> <div class="form-group"> <label for="name">Email</label> <input type="email" name="name" id="Email" placeholder="Enter Your Email"> </div> <div class="form-group"> <label for="name">Phone</label> <input type="Phone" name="name" id="phone" placeholder="Enter Your Phone"> </div> <div class="form-group"> <label for="name">Message</label> <textarea name="Message" id="Message" cols="30" rows="10"></textarea> </div> </form> </div> </section> <footer> <div class="center"> Copyright &copy; www.MyOnlineMeal.com All right reserved </div> </footer> </body> </html>
/* eslint-disable react-hooks/exhaustive-deps */ import React, { useState, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { useParams } from 'react-router-dom' import NotFound from '../pages/NotFound' import NotesDetail from '../components/ContentNote/NotesDetail' import { deleteNote, unarchiveNote, archiveNote, getNote, } from '../utils/network-data' export default function All() { const navigate = useNavigate(); const init_value = { id: "", title: "", body: "", createdAt: "", archived: false, owner: "", }; const { id } = useParams(); const updateData = () => { getNoteById(id); }; const [result, setResult] = useState(init_value); const [isloading, setIsLoading] = useState(false); const getNoteById = async (idData) => { setIsLoading(true); const { data } = await getNote(idData); setResult(data); setIsLoading(false); }; const archiveNoteHandler = async (data) => { await archiveNote(data); navigate("/"); }; const unarchiveNoteHandler = async (data) => { await unarchiveNote(data); navigate("/"); }; const deleteNoteHandler = async (data) => { await deleteNote(data); navigate("/"); }; useEffect(() => { updateData(); }, [id]); if (result === null) { return ( <section> <h2>Data Tidak Dapat Ditemukan !</h2> </section> ); } return ( <> {result === undefined ? ( <NotFound /> ) : ( <NotesDetail notes={result} loading={isloading} onDelete={deleteNoteHandler} onArchived={archiveNoteHandler} onUnArchived={unarchiveNoteHandler} /> )} </> ); }
package com.example.githubuser.service.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.githubuser.service.database.dao.LikesDao import com.example.githubuser.service.database.entity.Likes @Database(entities = [Likes::class], version = 1) abstract class LikesRoomDatabase : RoomDatabase() { abstract fun noteDao(): LikesDao companion object { @Volatile private var INSTANCE: LikesRoomDatabase? = null @JvmStatic fun getDatabase(context: Context): LikesRoomDatabase { if (INSTANCE == null) { synchronized(LikesRoomDatabase::class.java) { INSTANCE = Room.databaseBuilder( context.applicationContext, LikesRoomDatabase::class.java, "note_database" ).build() } } return INSTANCE as LikesRoomDatabase } } }
#include "gtest/gtest.h" // 0, 0, 0, 0, 0, 0, 0, 0 // 0, 0, 0, 0, 0, 0, 0, 0 // 1, 1, 1, 1, 1, 1, 1, 1 // 1, 1, 1, 1, 1, 1, 1, 1 // 2, 2, 2, 2, 2, 2, 2, 2 // 2, 2, 2, 2, 2, 2, 2, 2 // 3, 3, 3, 3, 3, 3, 3, 3 // 3, 3, 3, 3, 3, 3, 3, 3 uint8_t tile_data_1[] = { 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 // 0, 0, 1, 1, 2, 2, 3, 3 uint8_t tile_data_2[] = { 0x33, 0x0F, 0x33, 0x0F, 0x33, 0x0F, 0x33, 0x0F, 0x33, 0x0F, 0x33, 0x0F, 0x33, 0x0F, 0x33, 0x0F }; MemoryMap setup_tile(uint8_t *tile_data, uint16_t starting_address) { MemoryMap mem_map; int tile_size = 2 * TILE_HEIGHT; for (int i = 0; i < tile_size; i++) { mem_map.write(starting_address + i, tile_data[i]); } return mem_map; } TEST(Tile, InitTile) { uint16_t starting_address = 0x8000; int buffer_size = TILE_WIDTH * TILE_HEIGHT; MemoryMap memory_map; Tile tile(starting_address, memory_map); tile.init_tile(); PixelColour_t *buffer = tile.get_pixel_buffer(); for (int i = 0; i < buffer_size; i++) { EXPECT_EQ(Colour0, buffer[i]); } } TEST(Tile, GetTileRow) { uint16_t starting_address = 0x8000; uint8_t lsb = 0x55; // 0101 0101 uint8_t msb = 0x33; // 0011 0011 MemoryMap memory_map; TileRow tile_row(starting_address, memory_map); std::vector<PixelColour_t> row = tile_row.get_tile_row(lsb, msb); EXPECT_EQ(TILE_WIDTH, row.size()); EXPECT_EQ(Colour0, row[0]); EXPECT_EQ(Colour1, row[1]); EXPECT_EQ(Colour2, row[2]); EXPECT_EQ(Colour3, row[3]); EXPECT_EQ(Colour0, row[4]); EXPECT_EQ(Colour1, row[5]); EXPECT_EQ(Colour2, row[6]); EXPECT_EQ(Colour3, row[7]); } TEST(Tile, GetTileRowFromMemory) { uint16_t starting_address = 0x8000; uint8_t lsb = 0x55; // 0101 0101 uint8_t msb = 0x33; // 0011 0011 MemoryMap memory_map; memory_map.write(starting_address, lsb); memory_map.write(starting_address + 1, msb); EXPECT_EQ(lsb, memory_map.read(starting_address)); EXPECT_EQ(msb, memory_map.read(starting_address + 1)); TileRow tile_row(starting_address, memory_map); uint8_t lsb_new = memory_map.read(starting_address); uint8_t msb_new = memory_map.read(starting_address + 1); std::vector<PixelColour_t> row = tile_row.get_tile_row(lsb_new, msb_new); EXPECT_EQ(TILE_WIDTH, row.size()); EXPECT_EQ(Colour0, row[0]); EXPECT_EQ(Colour1, row[1]); EXPECT_EQ(Colour2, row[2]); EXPECT_EQ(Colour3, row[3]); EXPECT_EQ(Colour0, row[4]); EXPECT_EQ(Colour1, row[5]); EXPECT_EQ(Colour2, row[6]); EXPECT_EQ(Colour3, row[7]); } TEST(Tile, GetPixelIndexFromTile) { uint16_t starting_address = 0x8000; // 0 1 2 3 4 5 6 7 // 8 9 10 11 12 13 14 15 // 16 17 18 19 20 21 22 23 // 24 25 26 27 28 29 30 31 // 32 33 34 35 36 37 38 39 // 40 41 42 43 44 45 46 47 // 48 49 50 51 52 53 53 55 // 56 57 58 59 60 61 62 63 MemoryMap memory_map; Tile tile(starting_address, memory_map); EXPECT_EQ(0, tile.get_index(0, 0)); EXPECT_EQ(35, tile.get_index(3, 4)); EXPECT_EQ(63, tile.get_index(7, 7)); } TEST(Tile, LoadTileHorizontal) { uint16_t starting_address = 0x8000; MemoryMap memory_map = setup_tile(tile_data_1, starting_address); Tile tile(starting_address, memory_map); for (int y = 0; y < TILE_HEIGHT; y++) { for (int x = 0; x < TILE_WIDTH; x++) { if (y <= 1) { EXPECT_EQ(Colour0, tile.get_pixel(x, y)); } else if (y > 1 && y <= 3) { EXPECT_EQ(Colour1, tile.get_pixel(x, y)); } else if (y > 3 && y <= 5) { EXPECT_EQ(Colour2, tile.get_pixel(x, y)); } else { EXPECT_EQ(Colour3, tile.get_pixel(x, y)); } } } } TEST(Tile, LoadTileVertical) { uint16_t starting_address = 0x8000; MemoryMap memory_map = setup_tile(tile_data_2, starting_address); Tile tile(starting_address, memory_map); for (int y = 0; y < TILE_HEIGHT; y++) { for (int x = 0; x < TILE_WIDTH; x++) { if (x <= 1) { EXPECT_EQ(Colour0, tile.get_pixel(x, y)); } else if (x > 1 && x <= 3) { EXPECT_EQ(Colour1, tile.get_pixel(x, y)); } else if (x > 3 && x <= 5) { EXPECT_EQ(Colour2, tile.get_pixel(x, y)); } else { EXPECT_EQ(Colour3, tile.get_pixel(x, y)); } } } } TEST(Tile, DrawTileHorizontal) { uint16_t starting_address = 0x8000; int tile_x = 100; int tile_y = 100; Palette palette; palette.colour0 = WHITE; palette.colour1 = LIGHT_GRAY; palette.colour2 = DARK_GRAY; palette.colour3 = BLACK; MemoryMap memory_map = setup_tile(tile_data_1, starting_address); Tile tile(starting_address, memory_map); FrameBuffer buffer(LCD_WIDTH, LCD_HEIGHT); UI_SFML ui(memory_map); Video video(memory_map, ui); ui.init_display("TEST"); for (int y = 0; y < TILE_HEIGHT; y++) { for (int x = 0; x < TILE_WIDTH; x++) { Colour_t pixel = video.get_real_colour(tile.get_pixel(x, y), palette); buffer.set_pixel(tile_x + x, tile_y + y, pixel); } } for (int i = 0; i < DISPLAY_TIME; i++) { ui.render(buffer); } } TEST(Tile, DrawTileVertical) { uint16_t starting_address = 0x8000; int tile_x = 100; int tile_y = 100; Palette palette; palette.colour0 = WHITE; palette.colour1 = LIGHT_GRAY; palette.colour2 = DARK_GRAY; palette.colour3 = BLACK; MemoryMap memory_map = setup_tile(tile_data_2, starting_address); Tile tile(starting_address, memory_map); FrameBuffer buffer(LCD_WIDTH, LCD_HEIGHT); UI_SFML ui(memory_map); Video video(memory_map, ui); ui.init_display("TEST"); for (int y = 0; y < TILE_HEIGHT; y++) { for (int x = 0; x < TILE_WIDTH; x++) { Colour_t pixel = video.get_real_colour(tile.get_pixel(x, y), palette); buffer.set_pixel(tile_x + x, tile_y + y, pixel); } } for (int i = 0; i < DISPLAY_TIME; i++) { ui.render(buffer); } }
; ;#include <stdio.h> ;#include <gtk/gtk.h> ; ;/* This function rotates the position of the tabs */ ;void rotate_book( GtkButton *button, ; GtkNotebook *notebook ) ;{ ; gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos + 1) % 4); ;} ; ;/* Add/Remove the page tabs and the borders */ ;void tabsborder_book( GtkButton *button, ; GtkNotebook *notebook ) ;{ ; gint tval = FALSE; ; gint bval = FALSE; ; if (notebook->show_tabs == 0) ; tval = TRUE; ; if (notebook->show_border == 0) ; bval = TRUE; ; ; gtk_notebook_set_show_tabs (notebook, tval); ; gtk_notebook_set_show_border (notebook, bval); ;} ; ;/* Remove a page from the notebook */ ;void remove_book( GtkButton *button, ; GtkNotebook *notebook ) ;{ ; gint page; ; ; page = gtk_notebook_get_current_page (notebook); ; gtk_notebook_remove_page (notebook, page); ; /* Need to refresh the widget -- ; This forces the widget to redraw itself. */ ; gtk_widget_queue_draw (GTK_WIDGET (notebook)); ;} ; ;gint delete( GtkWidget *widget, ; GtkWidget *event, ; gpointer data ) ;{ ; gtk_main_quit (); ; return FALSE; ;} ; ;int main( int argc, ; char *argv[] ) ;{ ; GtkWidget *window; ; GtkWidget *button; ; GtkWidget *table; ; GtkWidget *notebook; ; GtkWidget *frame; ; GtkWidget *label; ; GtkWidget *checkbutton; ; int i; ; char bufferf[32]; ; char bufferl[32]; ; ; gtk_init (&argc, &argv); ; ; window = gtk_window_new (GTK_WINDOW_TOPLEVEL); ; ; g_signal_connect (G_OBJECT (window), "delete_event", ; G_CALLBACK (delete), NULL); ; ; gtk_container_set_border_width (GTK_CONTAINER (window), 10); ; ; table = gtk_table_new (3, 6, FALSE); ; gtk_container_add (GTK_CONTAINER (window), table); ; ; /* Create a new notebook, place the position of the tabs */ ; notebook = gtk_notebook_new (); ; gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP); ; gtk_table_attach_defaults (GTK_TABLE (table), notebook, 0, 6, 0, 1); ; gtk_widget_show (notebook); ; ; /* Let's append a bunch of pages to the notebook */ ; for (i = 0; i < 5; i++) { ; sprintf(bufferf, "Append Frame %d", i + 1); ; sprintf(bufferl, "Page %d", i + 1); ; ; frame = gtk_frame_new (bufferf); ; gtk_container_set_border_width (GTK_CONTAINER (frame), 10); ; gtk_widget_set_size_request (frame, 100, 75); ; gtk_widget_show (frame); ; ; label = gtk_label_new (bufferf); ; gtk_container_add (GTK_CONTAINER (frame), label); ; gtk_widget_show (label); ; ; label = gtk_label_new (bufferl); ; gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label); ; } ; ; /* Now let's add a page to a specific spot */ ; checkbutton = gtk_check_button_new_with_label ("Check me please!"); ; gtk_widget_set_size_request (checkbutton, 100, 75); ; gtk_widget_show (checkbutton); ; ; label = gtk_label_new ("Add page"); ; gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2); ; ; /* Now finally let's prepend pages to the notebook */ ; for (i = 0; i < 5; i++) { ; sprintf (bufferf, "Prepend Frame %d", i + 1); ; sprintf (bufferl, "PPage %d", i + 1); ; ; frame = gtk_frame_new (bufferf); ; gtk_container_set_border_width (GTK_CONTAINER (frame), 10); ; gtk_widget_set_size_request (frame, 100, 75); ; gtk_widget_show (frame); ; ; label = gtk_label_new (bufferf); ; gtk_container_add (GTK_CONTAINER (frame), label); ; gtk_widget_show (label); ; ; label = gtk_label_new (bufferl); ; gtk_notebook_prepend_page (GTK_NOTEBOOK (notebook), frame, label); ; } ; ; /* Set what page to start at (page 4) */ ; gtk_notebook_set_current_page (GTK_NOTEBOOK (notebook), 3); ; ; /* Create a bunch of buttons */ ; button = gtk_button_new_with_label ("close"); ; g_signal_connect_swapped (G_OBJECT (button), "clicked", ; G_CALLBACK (delete), NULL); ; gtk_table_attach_defaults (GTK_TABLE (table), button, 0, 1, 1, 2); ; gtk_widget_show (button); ; ; button = gtk_button_new_with_label ("next page"); ; g_signal_connect_swapped (G_OBJECT (button), "clicked", ; G_CALLBACK (gtk_notebook_next_page), ; notebook); ; gtk_table_attach_defaults (GTK_TABLE (table), button, 1, 2, 1, 2); ; gtk_widget_show (button); ; ; button = gtk_button_new_with_label ("prev page"); ; g_signal_connect_swapped (G_OBJECT (button), "clicked", ; G_CALLBACK (gtk_notebook_prev_page), ; notebook); ; gtk_table_attach_defaults (GTK_TABLE (table), button, 2, 3, 1, 2); ; gtk_widget_show (button); ; ; button = gtk_button_new_with_label ("tab position"); ; g_signal_connect (G_OBJECT (button), "clicked", ; G_CALLBACK (rotate_book), ; notebook); ; gtk_table_attach_defaults (GTK_TABLE (table), button, 3, 4, 1, 2); ; gtk_widget_show (button); ; ; button = gtk_button_new_with_label ("tabs/border on/off"); ; g_signal_connect (G_OBJECT (button), "clicked", ; G_CALLBACK (tabsborder_book), ; notebook); ; gtk_table_attach_defaults (GTK_TABLE (table), button, 4, 5, 1, 2); ; gtk_widget_show (button); ; ; button = gtk_button_new_with_label ("remove page"); ; g_signal_connect (G_OBJECT (button), "clicked", ; G_CALLBACK (remove_book), ; notebook); ; gtk_table_attach_defaults (GTK_TABLE (table), button, 5, 6, 1, 2); ; gtk_widget_show (button); ; ; gtk_widget_show (table); ; gtk_widget_show (window); ; ; gtk_main (); ; ; return 0; ;} (defpackage "10.12-notebook" (:use :excl :common-lisp)) (in-package "10.12-notebook") (ff:defun-foreign-callable rotate-book ((button (* gtk:GtkButton)) (notebook (* gtk:GtkNotebook))) (declare (ignore button)) (gtk:gtk_notebook_set_tab_pos notebook (mod (1+ (ff:fslot-value-typed 'gtk:GtkNotebook nil notebook 'gtk::tab_pos)) 4))) (ff:defun-foreign-callable tabsborder-book ((button (* gtk:GtkButton)) (notebook (* gtk:GtkNotebook))) (declare (ignore button)) (let ((tval gtk:FALSE) (bval gtk:FALSE)) (when (eql (ff:fslot-value-typed 'gtk:GtkNotebook nil notebook 'gtk::show_tabs) 0) (setq tval gtk:TRUE)) (when (eql (ff:fslot-value-typed 'gtk:GtkNotebook nil notebook 'gtk::show_border) 0) (setq bval gtk:TRUE)) (gtk:gtk_notebook_set_show_tabs notebook tval) (gtk:gtk_notebook_set_show_border notebook bval))) (ff:defun-foreign-callable remove-book ((button (* gtk:GtkButton)) (notebook (* gtk:GtkNotebook))) (declare (ignore button)) (let ((page nil)) (setq page (gtk:gtk_notebook_get_current_page notebook)) (gtk:gtk_notebook_remove_page notebook page) (gtk:gtk_widget_queue_draw (gtk:GTK_WIDGET notebook)))) (ff:defun-foreign-callable nb-delete ((widget (* gtk:GtkWidget)) (event (* gtk:GtkWidget)) (data gtk:gpointer)) (declare (ignore widget event data)) #+original (gtk:gtk_main_quit) #-original (gtk:gtk-main-quit) gtk:FALSE) (defun notebook () (let ((window nil) (button nil) (table nil) (notebook nil) (frame nil) (label nil) (checkbutton nil) (bufferf nil) (bufferl nil)) (gtk:gtk_init 0 0) (setq window (gtk:gtk_window_new gtk:GTK_WINDOW_TOPLEVEL)) (gtk:g_signal_connect (gtk:G_OBJECT window) "delete_event" (gtk:G_CALLBACK (ff:register-foreign-callable 'nb-delete)) gtk:NULL) (gtk:gtk_container_set_border_width (gtk:GTK_CONTAINER window) 10) (setq table (gtk:gtk_table_new 3 6 gtk:FALSE)) (gtk:gtk_container_add (gtk:GTK_CONTAINER window) table) (setq notebook (gtk:gtk_notebook_new)) (gtk:gtk_notebook_set_tab_pos (gtk:GTK_NOTEBOOK notebook) gtk:GTK_POS_TOP) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) notebook 0 6 0 1) ; (gtk:gtk_widget_show notebook) (dotimes (i 5) (setq bufferf (format nil "Append Frame ~d" (1+ i))) (setq bufferl (format nil "Page ~d" (1+ i))) (setq frame (gtk:gtk_frame_new bufferf)) (gtk:gtk_container_set_border_width (gtk:GTK_CONTAINER frame) 10) (gtk:gtk_widget_set_size_request frame 100 75) (gtk:gtk_widget_show frame) (setq label (gtk:gtk_label_new bufferf)) (gtk:gtk_container_add (gtk:GTK_CONTAINER frame) label) (gtk:gtk_widget_show label) (setq label (gtk:gtk_label_new bufferl)) (gtk:gtk_notebook_append_page (gtk:GTK_NOTEBOOK notebook) frame label)) (setq checkbutton (gtk:gtk_check_button_new_with_label "Check me please!")) (gtk:gtk_widget_set_size_request checkbutton 100 75) (gtk:gtk_widget_show checkbutton) (setq label (gtk:gtk_label_new "Add page")) (gtk:gtk_notebook_insert_page (gtk:GTK_NOTEBOOK notebook) checkbutton label 2) (dotimes (i 5) (setq bufferf (format nil "Prepend Frame ~d" (1+ i))) (setq bufferl (format nil "PPage ~d" (1+ i))) (setq frame (gtk:gtk_frame_new bufferf)) (gtk:gtk_container_set_border_width (gtk:GTK_CONTAINER frame) 10) (gtk:gtk_widget_set_size_request frame 100 75) (gtk:gtk_widget_show frame) (setq label (gtk:gtk_label_new bufferf)) (gtk:gtk_container_add (gtk:GTK_CONTAINER frame) label) (gtk:gtk_widget_show label) (setq label (gtk:gtk_label_new bufferl)) (gtk:gtk_notebook_prepend_page (gtk:GTK_NOTEBOOK notebook) frame label)) (gtk:gtk_notebook_set_current_page (gtk:GTK_NOTEBOOK notebook) 3) (setq button (gtk:gtk_button_new_with_label "close")) (gtk:g_signal_connect_swapped (gtk:G_OBJECT button) "clicked" (gtk:G_CALLBACK (ff:register-foreign-callable 'nb-delete)) gtk:NULL) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) button 0 1 1 2) (gtk:gtk_widget_show button) (setq button (gtk:gtk_button_new_with_label "next page")) (gtk:g_signal_connect_swapped (gtk:G_OBJECT button) "clicked" (gtk:G_CALLBACK (ff:get-entry-point "gtk_notebook_next_page")) notebook) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) button 1 2 1 2) (gtk:gtk_widget_show button) (setq button (gtk:gtk_button_new_with_label "prev page")) (gtk:g_signal_connect_swapped (gtk:G_OBJECT button) "clicked" (gtk:G_CALLBACK (ff:get-entry-point "gtk_notebook_prev_page")) notebook) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) button 2 3 1 2) (gtk:gtk_widget_show button) (setq button (gtk:gtk_button_new_with_label "tab position")) (gtk:g_signal_connect (gtk:G_OBJECT button) "clicked" (gtk:G_CALLBACK (ff:register-foreign-callable 'rotate-book)) notebook) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) button 3 4 1 2) (gtk:gtk_widget_show button) (setq button (gtk:gtk_button_new_with_label "tabs/border on/off")) (gtk:g_signal_connect (gtk:G_OBJECT button) "clicked" (gtk:G_CALLBACK (ff:register-foreign-callable 'tabsborder-book)) notebook) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) button 4 5 1 2) (gtk:gtk_widget_show button) (setq button (gtk:gtk_button_new_with_label "remove page")) (gtk:g_signal_connect (gtk:G_OBJECT button) "clicked" (gtk:G_CALLBACK (ff:register-foreign-callable 'remove-book)) notebook) (gtk:gtk_table_attach_defaults (gtk:GTK_TABLE table) button 5 6 1 2) (gtk:gtk_widget_show button) (gtk:gtk_widget_show table) (gtk:gtk_widget_show window) #+original (gtk:gtk_main) #-original (gtk:gtk-main))) (flet ((run-example (name function) ;; workaround for bogus (imo) redef. warnings generated by defvar (declare (special gtk::*run-example*)) (unless (boundp 'gtk::*run-example*) (setq gtk::*run-example* t)) (when gtk::*run-example* (mp:process-run-function (format nil "GTK+ Example: ~a" name) function)))) (run-example "10.12-notebook" #'notebook))
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:yayasan_sekar_telkom_apps/navigator/main_menu.dart'; import 'package:yayasan_sekar_telkom_apps/screen/proposal/form_proposal.dart'; import 'package:yayasan_sekar_telkom_apps/screen/proposal/list_proposal.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: SplashScreen(), ); } } class SplashScreen extends StatefulWidget { const SplashScreen({Key? key}) : super(key: key); @override State<SplashScreen> createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> { startTime() async { String? token = await const FlutterSecureStorage().read(key: "token"); Future.delayed(const Duration(seconds: 2), () { if (token == "" || token == null) { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (BuildContext context) => const MainMenuNavigator()), (Route<dynamic> route) => false); } else { Navigator.pushAndRemoveUntil( context, MaterialPageRoute( builder: (BuildContext context) => const MainMenuNavigator()), (Route<dynamic> route) => false); } }); } @override void initState() { startTime(); super.initState(); } @override Widget build(BuildContext context) { Widget logo() { return Stack( children: [ SvgPicture.asset( 'assets/background.svg', fit: BoxFit.cover, ), Center( child: Image.asset( 'assets/yst_logo.png', width: 200, ), ), ], ); } return Scaffold( body: logo(), ); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>게시글 수정</title> <jsp:include page="../module/head.jsp"></jsp:include> <link rel="stylesheet" href="http://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css"> <c:url value="/static/ckeditor" var="ckUrl"/> <script type="text/javascript" src="${ckUrl}/ckeditor.js"></script> </head> <body> <header></header> <section class="container"> <c:url var="boardModUrl" value="/board/modify"/> <form action="${boardModUrl}" method="post"> <div class="mt-3"> <div class="mb-1 border-bottom border-2 border-secondary"> <input type="text" name="title" value="${data.title}"> </div> <div class="mb-3"> <label class="pe-3 text-secondary text-opacity-75">${empData.empName}</label> <fmt:formatDate value="${data.createDate}" var="createDate" dateStyle="long"/> <label class="pe-3 text-secondary text-opacity-75">${createDate}</label> <label class="pe-3 text-secondary text-opacity-75">조회수: ${data.viewCnt}</label> <input type="text" name="id" value="${data.id}" hidden=""> </div> <div class="mb-1 border-bottom border-2 border-secondary"> <textarea name="content" cols="150" rows="20">${data.content}</textarea> </div> <div class="mb-1"> <div> <i class="bi bi-hand-thumbs-up text-secondary text-opacity-50"></i> <label id="id_like" class="text-secondary text-opacity-75">${data.like}</label> </div> </div> <!-- 작성자 = 로그인 유저 -> 수정 가능하도록 해야 함 --> <div class="mb-1 text-end"> <c:url value="/board" var="boardUrl"/> <button class="btn btn-primary" type="button" onclick="location.href='${boardUrl}'">목록</button> <c:url value="/board/modify" var="boardModUrl"> <c:param name="id" value="${data.id}"/> <!-- 게시글 id 전달 --> </c:url> <c:url value="/board/del" var="boardDelUrl"> <c:param name="id" value="${data.id}"/> <!-- 게시글 id 전달 --> </c:url> <button class="btn btn-primary" type="submit">저장</button> <button class="btn btn-primary" type="button" onclick="location.href='${boardDelUrl}'">삭제</button> </div> </div> </form> </section> <footer></footer> <c:url var="imageUrl" value="/upload/image"/> <script type="text/javascript"> CKEDITOR.replace("content", { filebrowserUploadUrl : "${imageUrl}?type=image" }); // 이미지 처리하는 url을 알려주면 여기에 이미지가 전달이 된다. </script> </body> </html>
<template> <form v-on:submit="changeProject"> <div id="project-form-wrapper"> <label id="project-select" for="project-select">Select Project: </label> <select v-if="this.currentProjectId" id="project-select" type="text" name="project_id" placeholder="Project ID" @change="this.changeProject($event)"> <option v-for="project in projects" :key="project.id" :value="project.id" :selected="project.selected"> {{project.name}} </option> </select> <label v-if="this.currentProjectId" for="add-project-input">Or</label> <input v-model="projectNameInput" id="add-project-input" type="text" name="projectNameInput" placeholder="Add Project"> <button id="add-project" type="submit">Add Project</button> </div> </form> <form v-if="this.currentProjectId" v-on:submit="addTask"> <div id="task-form-wrapper"> <input v-model="taskNameInput" id="name-input" type="text" name="name" placeholder="Task name"> <input v-model="inputPriority" id="priority-input" type="number" name="priority" placeholder="Priority"> <button id="add-task" type="submit">Add Task</button> </div> </form> <div id="tasks-wrapper"> <Task v-for="(task, index) in tasks" :key="task.id" :task="task" :priority="index" draggable="true"/> </div> </template> <script> import Task from './Task.vue' export default { components:{ Task, }, data(){ return { projects: [], currentProjectId : null, tasks : [], priority: 0, projectNameInput : null, taskNameInput : null, inputPriority : null, dragStartIndex : null, } }, methods:{ getProjects(){ axios.get("/api/project").then((response) => { // console.log('retrieved projects') this.projects = response.data //get currently selected project this.projects.forEach(project => { if(project.selected == 1){ this.currentProjectId = project.id return } }); this.getTasks() }) }, getTasks(){ axios.get(`/api/task?project_id=${this.currentProjectId}`).then((response) => { // console.log('retrieved tasks') this.tasks = response.data setTimeout(() => { this.addDraggableEvents() }, 500); }) }, changeProject(e){ // console.log('changing project') if(this.projectNameInput){ axios({ method: "post", url: "/api/project", data: { name : this.projectNameInput, }, }) .then((response) => { this.projectNameInput = "" this.getProjects() }) .catch(() => { console.log('an error has occured.') }) } else{ // console.log('updating..') axios({ method: "put", url: `/api/project/${e.target.value}`, data: { selected : 1, }, }) .then((response) => { this.projectNameInput = "" this.getProjects() }) .catch(() => { console.log('an error has occured.') }) } // To prevent the form from submitting e.preventDefault(); }, addTask(e){ axios({ method: "post", url: "/api/task", data: { name : this.taskNameInput, priority : this.inputPriority ?? null, project_id: this.currentProjectId, }, }) .then((response) => { this.taskNameInput = "" this.inputPriority = "" return this.getTasks() }) .catch(() => { console.log('an error has occured.') }) // To prevent the form from submitting e.preventDefault(); }, addDraggableEvents(){ const taskElements = document.getElementsByClassName('task'); for(let i=0; i<taskElements.length; i++){ taskElements[i].addEventListener('dragstart', this.dragStart); taskElements[i].addEventListener('dragover', this.dragOver); taskElements[i].addEventListener('drop', this.drop); taskElements[i].addEventListener('dragenter', this.dragEnter); taskElements[i].addEventListener('dragleave', this.dragLeave); } }, dragStart(e) { this.dragStartIndex = e.target.getAttribute('priority'); }, dragOver(e) { e.preventDefault(); }, swapItems(from, to) { const task1 = this.tasks[from] const task2 = this.tasks[to] // console.log(task1, task2) axios({ method: "post", url: "/api/task/swap-tasks", data: { task1 : task1.id, task2 : task2.id, }, }) .then((response) => { }) .catch(() => { console.log('an error has occured.') }) this.tasks[from] = task2 this.tasks[to] = task1 }, dragEnter(e) { // console.log(e.target) let el = e.target if (el.classList.contains('task')){ el.classList.add('highlight') }else{ el.closest(".task").classList.add("highlight") } }, dragLeave(e) { let el = e.target if (el.classList.contains('task')){ el.classList.remove('highlight') }else{ el.closest(".task").classList.remove("highlight") } }, drop(e) { let el = e.target if (!el.classList.contains('task')){ el = e.target.closest(".task") } const dragEndIndex = el.getAttribute('priority'); this.swapItems(this.dragStartIndex, dragEndIndex); this.dragStartIndex = null; e.target.classList.remove('highlight'); } }, mounted(){ this.getProjects() this.getTasks() } } </script> <style scoped> #task-form-wrapper{ display: flex; justify-content: space-between; } label{ color: #252525; } input, select, button{ padding: 0.5rem; margin: 0.5rem; border-radius: 5px; } #add-project{ background: none; border: 1px solid rgb(0, 103, 3); cursor: pointer; } #task-form-wrapper #add-task{ background: rgba(0, 191, 255, 0); padding: 0.5rem; color: rgb(57, 57, 57); border: 1px solid deepskyblue; border-radius: 5px; cursor: pointer; } #task-form-wrapper #add-task:hover{ background: deepskyblue; color: rgb(57, 57, 57); transition: 0.5s background; } #task-form-wrapper input{ width: 40%; } #tasks-wrapper{ /* margin-top: 0.5rem; */ padding-right: 1rem; max-height: 50rem; overflow-y: scroll; scroll-behavior: smooth; } .highlight{ background: #c7c7c753 !important; } </style>
package com.kuryeraze.kuryeraze.service.impl.courier; import com.kuryeraze.kuryeraze.dao.courier.CourierRepository; import com.kuryeraze.kuryeraze.dto.courier.CourierDto; import com.kuryeraze.kuryeraze.model.courier.Courier; import com.kuryeraze.kuryeraze.service.inter.courier.CourierServiceInter; import org.modelmapper.ModelMapper; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class CourierServiceImpl implements CourierServiceInter { private final CourierRepository courierRepository; private final ModelMapper modelMapper; public CourierServiceImpl(CourierRepository courierRepository, ModelMapper modelMapper) { this.courierRepository = courierRepository; this.modelMapper = modelMapper; } @Override public ResponseEntity<CourierDto> createCourier(CourierDto courierDto) { Courier courierEntity = modelMapper.map(courierDto, Courier.class); if (isCourierEmailTaken(courierEntity.getEmail()) || isCourierUsernameTaken(courierEntity.getUsername())) { return ResponseEntity.badRequest().build(); } courierEntity.setIsDisable(false); Courier savedCourier = courierRepository.save(courierEntity); return ResponseEntity.ok(modelMapper.map(savedCourier, CourierDto.class)); } @Override public List<CourierDto> getAllCouriers() { List<CourierDto> listDto = new ArrayList<>(); List<Courier> listEntity = courierRepository.findAll(); for (Courier entity : listEntity) { CourierDto dto = modelMapper.map(entity, CourierDto.class); listDto.add(dto); } return listDto; } @Override public CourierDto getCourierById(Long id) { Courier entity = courierRepository.findById(id).orElse(null); if (entity != null) { return modelMapper.map(entity, CourierDto.class); } return null; } @Override public Boolean isCourierEmailTaken(String email) { return courierRepository.findCourierByEmail(email) != null; } @Override public Boolean isCourierUsernameTaken(String username) { return courierRepository.findCourierByUsername(username) != null; } @Override public CourierDto findCourierByEmail(String email) { Courier courier = courierRepository.findCourierByEmail(email); if (courier != null) { return modelMapper.map(courier, CourierDto.class); } return null; } @Override public CourierDto findCourierByUsername(String username) { Courier courier = courierRepository.findCourierByUsername(username); if (courier != null) { return modelMapper.map(courier, CourierDto.class); } return null; } @Override public CourierDto updateCourier(Long id, CourierDto courierDto) { Optional<Courier> courierOptional = courierRepository.findById(id); if (courierOptional.isPresent()) { Courier courier = courierOptional.get(); if (courierDto.getOneSignal() != null) { courier.setOneSignal(courierDto.getOneSignal()); } if (courierDto.getFirstName() != null) { courier.setFirstName(courierDto.getFirstName()); } if (courierDto.getLastName() != null) { courier.setLastName(courierDto.getLastName()); } if (courierDto.getLocation() != null) { courier.setLocation(courierDto.getLocation()); } if (courierDto.getPhoneNumber() != null) { courier.setPhoneNumber(courierDto.getPhoneNumber()); } if (courierDto.getFamilyPhoneNumber() != null) { courier.setFamilyPhoneNumber(courierDto.getFamilyPhoneNumber()); } if (courierDto.getFinCode() != null) { courier.setFinCode(courierDto.getFinCode()); } if (courierDto.getUsername() != null) { courier.setUsername(courierDto.getUsername()); } if (courierDto.getEmail() != null) { courier.setEmail(courierDto.getEmail()); } if (courierDto.getPassword() != null) { courier.setPassword(courierDto.getPassword()); } if (courierDto.getCreatedDate() != null) { courier.setCreatedDate(courierDto.getCreatedDate()); } if (courierDto.getIsDisable() != null) { courier.setIsDisable(courierDto.getIsDisable()); } courier = courierRepository.save(courier); return modelMapper.map(courier, CourierDto.class); } return null; } @Override public void deleteCourier(Long id) { courierRepository.deleteById(id); } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Favorite; use Illuminate\Support\Facades\Log; // Import Log facade class FavoriteController extends Controller { public function add(Request $request) { try { $userId = auth()->id(); // Get the current user's ID $itemGroupId = $request->input('item_group_id'); // Get the item group ID from the request Log::info('User ID: ' . $userId); // Log the user ID Log::info('Item Group ID: ' . $itemGroupId); // Log the item group ID // Check if the item is already favorited by the user if (Favorite::where('user_id', $userId)->where('item_group_id', $itemGroupId)->exists()) { Log::info('Item already favorited.'); // Log the duplicate favorite case return response()->json(['message' => 'Item already favorited.'], 422); } // Create a new favorite record Favorite::create([ 'user_id' => $userId, 'item_group_id' => $itemGroupId, ]); Log::info('Item added to favorites.'); // Log the successful addition return response()->json(['message' => 'Item added to favorites.']); } catch (\Exception $e) { Log::error('Error adding item to favorites: ' . $e->getMessage()); // Log any exception return response()->json(['message' => 'An error occurred while adding the item to favorites.'], 500); } } public function index() { $favorites = auth()->user()->favorites; // Assuming you have a relationship set up correctly return view('favourites', compact('favorites')); } public function destroy($id) { $userId = auth()->id(); // Get the current user's ID // Find the favorite record $favorite = Favorite::where('user_id', $userId)->where('item_group_id', $id)->first(); if ($favorite) { // If the favorite record exists, delete it $favorite->delete(); return response()->json(['message' => 'Item removed from favorites.']); } else { // If the favorite record does not exist, return an error message return response()->json(['message' => 'Item not found in favorites.'], 404); } } }
/** @page conceptsSensorFw Sensor Framework The Legato Sensor Framework provides a standard way of making sensor and actuator information available to other Legato applications. This is accomplished using the DataHub in conjunction with a sensor application and plugins which implement the handling of specific sensor interfaces. The framework is composed of one application which mediates the interaction with DataHub, and several plugins. The sensor framework application does not contain any code that reads sensors and writes actuators. The plugins contained within a Legato Component has code to read the sensor and are dynamically linked by the Sensor Framework. The role of the Sensor Framework is to adapt a standard C interface provided by the Plugins into data to and from the DataHub. @image html sensorFrameworkArchitecture.png @subsection Registering Handlers The plugins can register their read or write function to the Sensor Framework by calling the api sensorFw_RegisterCallback(). The function takes in the information describing the sensor in a JSON format and creates resources in the Data Hub based on this information. The standard information that must be passed to register a handler is: @code { "name": "furnace sensor", // Long form name (for use with debug / cli) "path": "temp", // The short form name, would be used in the // DataHub path name "readOnce": true, // Is this resource changeable - i.e. is it // a fixed static value that only needs to be // read once at startup. "type": "temperature", // The description of the measured data for // sensor/actuator (user defined) "unit": "degree celcius", // Unit of measurement (user defined) "input": true // Is this capable of producing Input (true) // into the Sensor Framework, } @endcode @subsection Static Information The Sensor Framework is also used to read static information of the device such as serial number. Registering a static resource with "readOnce" set to false in the JSON file will appear in the Data Hub as follows. @code / app sensorFw device SN <input> = "xxxxxxxxxxxx" (ts: yy.zz) data type = string @endcode @subsection Periodic Sensor All other sensors are considered periodic and follow a schema as mentioned below. @code +--/value = the temperature sensor value | +--/period = an output used to configure the temperature sensor's sampling period | +--/trigger = an output used to immediately trigger a single temperature sensor sample | +--/enable = an output used to enable or disable the temperature sensor | +--/config = A new standard field for configuring a device - can be output or input @endcode For example creating a temperature sensor with "readOnce" set to true will appear in the Data Hub as follows. @code temp value <input> = 32988.281250 (ts: 1556834900.509102) data type = numeric units = 'milli degree celcius' enable <output> = true (ts: 1556818352.405519) data type = Boolean period <output> = 2.000000 (ts: 1556818352.406531) data type = numeric units = 's' trigger <output> = data type = trigger config <output> = {"scale": [1.95312]} (ts: 1556818352.414592) data type = JSON (e.g., '{"scale": [1.95312]}') @endcode @subsection Configuration To enable free-form configuration of sensors and actuators a new standard field per sensor is created in the Data Hub, the "/config" field. This field is of type JSON and is transparent from the Sensor Framework perspective. The author of a Sensor Plugin will is expected to document the fields contained within the /config JSON data. Copyright (C) Sierra Wireless Inc. **/
import React from 'react'; import { View, Picker } from 'react-native'; import { Container, Text, Header, Content, Form, Item, Input, Button, Label, CheckBox, ListItem, Body} from 'native-base'; import { observer } from "mobx-react"; import {NativeRouter, Route, Link, Redirect} from 'react-router-native'; import auth from "./auth"; import store from "../Store" export default observer(class NewPost extends React.Component { constructor(props){ super(props); this.state = { url: "http://139.59.119.40/api/update/"+this.props.store.slug, post: { "title": "", "content": "", "draft": false, "publish": "" }, year: '', month: '', day: '', requestOK: false, }; } handleSubmit(e){ this.sendData(); this.props.store.posts.dataFetched = false; } invertDraft(){ var status = this.state.post.draft; this.setState({ draft: !status, }) } getData(){ console.log('Fetching Post to update'); //console.log(this.state.url); console.log("token", this.props.store.token); console.log("title", this.props.store.pageTitle); console.log(headers:{ // "Accept": 'application/json', // "Content-Type":"application/json", "Authorization": "JWT ", this.props.store.token, }); fetch(this.state.url, { method: 'GET', headers:{ // "Accept": 'application/json', // "Content-Type":"application/json", "Authorization": "JWT "+this.props.store.token, }, }) .then((response) => response.json()) .then((response) => { // console.log("Aquired data:"); console.log(response); this.setState({ post: response, fetchOK: true, year: response.publish.slice(0,4), month: response.publish.slice(5,7), day: response.publish.slice(8,), }); }).catch((error) => console.log(error)).done(); } componentWillMount(){ auth.firstLoad(); this.props.store.pageTitle = "Update Post" this.getData(); } sendData(){ console.log('Sending Data'); fetch(this.state.url, { method: 'POST', headers:{ "Accept": 'application/json', "Content-Type":"application/json", "Authorization": "JWT "+this.props.store.token, }, body:JSON.stringify({ "title": this.state.title, "content": this.state.content, "publish": this.state.year+"-"+this.state.month+"-"+this.state.day, }) }).then((response) => { console.log("Aquired data:"); console.log(response); this.setState({ requestOK: response.ok, }); console.log(this.state.requestOK); }) .catch((error) => console.log(error)).done(); } render() { if(!this.state.requestOK){ return ( <Container style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-start'}}> <Form> <Item floatingLabel style = {styles.textInput}> <Label>Title:</Label> <Input rounded autoCapitalize = 'none' defaultValue = {this.state.post.title} onChangeText={(title) => this.setState({"title": title}, )} /> </Item> <Item floatingLabel style = {styles.textInput}> <Label>Content:</Label> <Input rounded defaultValue = {this.state.post.content} autoCapitalize = 'none' onChangeText={(content) => this.setState({"content": content}, )} /> </Item> <ListItem style={{backgroundColor: 'gainsboro'}}> <CheckBox checked={this.state.post.draft} color='black' onPress={this.invertDraft.bind(this)} /> <Body> <Text>Draft</Text> </Body> </ListItem> <Label style={{marginTop: 20}}>Publish Date:</Label> <View style={{flexDirection: 'row', justifyContent: 'center',}}> <Item floatingLabel style = {styles.input}> <Label>YYYY</Label> <Input rounded autoCapitalize = 'none' keyboardType = 'number-pad' maxLength = {4} defaultValue = {this.state.year} style = {styles.input} onChangeText={(year) => this.setState({"year": year}, )} /> </Item> <Item floatingLabel style = {styles.input}> <Label>MM</Label> <Input rounded autoCapitalize = 'none' keyboardType = 'number-pad' defaultValue = {this.state.month} maxLength = {2} onChangeText={(month) => this.setState({"month": month}, )} /> </Item> <Item floatingLabel style = {styles.input}> <Label>DD</Label> <Input rounded autoCapitalize = 'none' keyboardType = 'number-pad' defaultValue = {this.state.day} maxLength = {2} onChangeText={(day) => this.setState({"day": day}, )} /> </Item> </View> <Button style={{marginTop: 20}} block primary onPress={this.handleSubmit.bind(this)}> <Text>Submit</Text> </Button> </Form> </Container> ); }else{ return ( <Container> <Redirect exact to="/Posts"/> </Container> ) } } }) const styles = { input:{ borderColor: 'black', flex: 1, //width: 100, }, textInput:{ borderColor: 'black', } };
using System; using System.Web.Services; using Newtonsoft.Json; namespace Laboratorio14_analsis_disenio { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class WebService1 : System.Web.Services.WebService { private static int lastOrderId = 0; private static int quantity = 0; private static string sandwichType = ""; private static string address = ""; [WebMethod] public string CreateOrder(int quantity, string sandwichType, string address) { int orderId = GenerateOrderId(); // Guardar los datos de la orden en las variables estáticas WebService1.quantity = quantity; WebService1.sandwichType = sandwichType; WebService1.address = address; // Crear un objeto Order con los datos proporcionados Order order = new Order(orderId, quantity, sandwichType, address); // Convertir el objeto Order a JSON string jsonOrder = JsonConvert.SerializeObject(order); return jsonOrder; } private int GenerateOrderId() { // Incrementar el ID de la última orden y retornarlo return ++lastOrderId; } [WebMethod] public string GetOrderDetails(int orderId) { // Aquí iría la lógica para recuperar detalles del pedido basados en el orderId // Obtener los datos de la orden de las variables estáticas int quantity = WebService1.quantity; string sandwichType = WebService1.sandwichType; string address = WebService1.address; // Crear un objeto Order con los datos obtenidos Order orderDetails = new Order(orderId, quantity, sandwichType, address); // Convertir el objeto Order a JSON string jsonOrderDetails = JsonConvert.SerializeObject(orderDetails); return jsonOrderDetails; } } // Clase para almacenar detalles de la orden public class Order { public int OrderId { get; set; } public int Quantity { get; set; } public string SandwichType { get; set; } public string Address { get; set; } // Constructor public Order(int orderId, int quantity, string sandwichType, string address) { OrderId = orderId; Quantity = quantity; SandwichType = sandwichType; Address = address; } } }
import Image from "next/image" import React from "react" import { useSettings } from "@/contexts/SettingsProvider/SettingsProvider" import GasOptionButton from "../GasPriorityButton/GasPriorityButton" import Message from "../MessageTag/MessageTag" export const SettingsCard = () => { const { gas: { selectedGasOption, setSelectedGasOption }, } = useSettings() return ( <div className="py-[30px] px-[20px] flex-1 flex flex-col gap-5"> <div className="flex flex-col gap-3 "> <div className="flex items-center justify-between gap-1"> <div className="flex items-center gap-2"> <Image src="/icons/gas.svg" loading="eager" width={20} height={20} alt="" /> <p className="opacity-60">Gas priority</p> </div> </div> <GasOptionButton selectedGasOption={selectedGasOption} setSelectedGasOption={setSelectedGasOption} /> <Message message={ selectedGasOption === "low" ? "Normal: Standard speed with regular network fees" : "Fast: Speedy transactions with increased network fees" } type="message" /> </div> </div> ) }
/** * @Author: Hardews * @Date: 2023/4/5 21:57 * @Description: **/ package api import ( "errors" "spirit-core/model" "spirit-core/my_consts" "spirit-core/service" "spirit-core/tool" "github.com/gin-gonic/gin" "log" ) func Register(ctx *gin.Context) { gmtId, res := ctx.Get("gmt_id") if !res { tool.OperateForbid(ctx) return } var user = model.User{} var exist bool user.Username, exist = ctx.GetPostForm("username") if !exist { tool.ParamFailed(ctx) return } user.Password, exist = ctx.GetPostForm("password") if !exist { tool.ParamFailed(ctx) return } user.Nickname, exist = ctx.GetPostForm("nickname") if !exist { tool.ParamFailed(ctx) return } user.Address, exist = ctx.GetPostForm("address") if !exist { tool.ParamFailed(ctx) return } tool.OKWithData(ctx, service.AddUser(gmtId.(string), user)) } func Token(ctx *gin.Context) { var req struct { Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` } err := ctx.ShouldBindJSON(&req) if err != nil || req.Username == "" || req.Password == "" { log.Println("get param failed,err:", err) tool.ParamFailed(ctx) return } var user = model.User{ Username: req.Username, Password: req.Password, } // 登陆 token, rt, err := service.GetToken(user) if err != nil { if errors.Is(err, my_consts.ErrOfNoThisUser) || errors.Is(err, my_consts.ErrOfWrongPassword) { tool.OKWithData(ctx, err.Error()) return } else { log.Println("get token failed,err:", err) tool.InternetError(ctx) return } } resp := struct { Token string `json:"token,omitempty"` RefreshToken string `json:"refresh_token,omitempty"` }{ token, rt, } tool.OKWithData(ctx, resp) } func TokenRefresh(ctx *gin.Context) { var req struct { RefreshToken string `json:"refresh_token,omitempty"` } err := ctx.ShouldBindJSON(&req) if err != nil || req.RefreshToken == "" { log.Println("get param failed,err:", err) tool.ParamFailed(ctx) return } if len(req.RefreshToken) != 64 { tool.NeedLogin(ctx) return } token, rt, err := service.RefreshToken(req.RefreshToken) if err != nil { log.Println("get token failed,err:", err) tool.InternetError(ctx) return } resp := struct { Token string `json:"token,omitempty"` RefreshToken string `json:"refresh_token,omitempty"` }{ token, rt, } tool.OKWithData(ctx, resp) } func ChangePasswordByToken(ctx *gin.Context) { var user model.User iUsername, _ := ctx.Get("username") user.Username = iUsername.(string) ChangePassword(ctx, user) } func ChangePassword(ctx *gin.Context, user model.User) { var res bool gmtId, res := ctx.Get("gmt_id") if !res { tool.OperateForbid(ctx) return } // 检验入参 user.Password, res = ctx.GetPostForm("new") if !res { tool.ErrorWithData(ctx, "新密码为空") return } oldPassword, res := ctx.GetPostForm("old") if !res { tool.ErrorWithData(ctx, "旧密码为空") return } res, err := service.ChangePassword(user, oldPassword, gmtId.(string)) if !res { tool.InternetError(ctx) log.Println(":change password failed,err:" + err.Error()) return } if err != nil { tool.ErrorWithData(ctx, err.Error()) return } tool.OK(ctx) } func GetIdentity(ctx *gin.Context) { gmtId, exist := ctx.Get("gmt_id") if !exist { tool.OperateForbid(ctx) return } tool.OKWithData(ctx, service.GetIdentity(gmtId.(string))) }
import React, { useState, useContext } from "react"; import { Link } from "react-router-dom"; import usePasswordToggle from "../hooks/usePasswordToggle"; import Navbar from "../components/Navbar"; import { AuthContext } from "../context/authContext"; import { useNavigate } from "react-router-dom"; import { ToastContainer, toast, Bounce, Zoom } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const LoginPage = () => { const navigate = useNavigate(); const { login } = useContext(AuthContext); const [PasswordInputType, ToggleIcon] = usePasswordToggle(); // Алдааны мэдээлэл хадгалах төлөв const [Err, setErr] = useState(null); // Хэрэглэгчийн оруулсан мэдээллийг хадгалах төлөв const [Inputs, setInputs] = useState({ email: "", password: "", }); const toastSuccessHandler = () => { toast.success("Амжилттай Нэвтэрлээ", { position: "top-center", autoClose: 2000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, theme: "colored", transition: Zoom, }); }; // Хэрэглэгчийн оруулсан мэдээллийг төлөврүү дамжуулах const handleChange = (e) => { setInputs((prev) => ({ ...prev, [e.target.name]: e.target.value })); }; const handleLogin = async (e) => { e.preventDefault(); try { await login(Inputs); toastSuccessHandler(); navigate("/home"); } catch (Err) { setErr(Err.response.data); } }; return ( <> <ToastContainer position="top-center" autoClose={1500} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover theme="light" transition:Bounce /> <Navbar /> <div className="flex justify-center items-center h-screen bg-gray-100"> <form action=""> <div className="bg-white px-6 pt-4 pb-4 rounded-md w-[300px] drop-shadow-md"> {/* Гарчиг */} <h1 className="text-2xl text-center mb-4 font-medium text-gray-700"> Нэвтрэх </h1> {/* Хэрэглэгчийн и-мэйл input */} <div className="my-3"> <label htmlFor="email" className="block pb-1"> И-мэйл <span className="text-red-800 font-bold">*</span> </label> <input type="email" id="email" name="email" onChange={handleChange} className="border border-slate-300 rounded-md w-[100%] h-8 pl-2 focus:outline-none transition ease-in-out focus:border-blue-400 focus:border-2 focus:duration-100" required />{" "} </div> {/* Хэрэглэгчийн нууц үг оруулах хэсэг */} <div> <label htmlFor="password" className="block pb-1"> Нууц үг <span className="text-red-800 font-bold">*</span> </label> <div className="flex justify-end"> <input type={PasswordInputType} id="password" name="password" onChange={handleChange} className="border border-slate-300 rounded-md w-[100%] h-8 pl-2 focus:outline-none transition ease-in-out focus:border-blue-400 focus:border-2 focus:duration-100" required /> <span className="absolute mt-2 mr-2 z-50 cursor-pointer"> {ToggleIcon} </span> </div> </div> <div className="flex justify-center"> <button type="submit" className="block w-[95%] bg-green-600 rounded-md py-1 mt-6 font-bold text-white mb-2 hover:bg-green-500 ease-in-out duration-300" onClick={handleLogin} > Нэвтрэх </button> </div> <div className="w-[90%] pt-2 m-auto"> <hr /> </div> {/* Алдаа харуулах хэсэг */} {Err && ( <p className="text-center text-sm text-red-600 mt-3">{Err}</p> )} </div> <div className="bg-white px-6 pt-4 pb-4 rounded-md w-[300px] drop-shadow-md mt-3"> <p className="text-sm text-center"> Шинэ хэрэглэгч бол -{" "} <Link to="/register"> <span className="text-blue-800 font-medium hover:text-blue-500 "> Бүртгэл үүсгэх </span> </Link> </p> </div> </form> </div> </> ); }; export default LoginPage;
from __future__ import annotations import json import sys from isa import Addressing, Code, MachineCode, MachineCodeEncoder, Opcode # flake8: noqa: C901 def translate(text: str): code: list[Code] = [Code(0, Opcode.NOP), Code(1, Opcode.NOP)] data: list[int] = [] labels: dict[str, int] = {} words: dict[str, int] = {} prog_position: int = 2 data_position: int = 4 last_label: str = "" for line in text.splitlines(): token = line.split(";", 1)[0].strip() if token == "": continue if token.endswith(":"): label = token.strip(":") assert label not in labels, "Redefinition of label: {}".format(label) labels[label] = prog_position last_label = label elif token.startswith("WORD"): word = token[4:].strip() word_data = parse_number(word) if last_label != "": prog_position = labels[last_label] if last_label not in words: labels[last_label] = data_position words[last_label] = data_position data.append(word_data) data_position += 1 elif token.startswith("VEC"): sub_tokens = token.split(" ") assert len(sub_tokens) == 3, "Invalid vector format" mnemonic, vec, arg = sub_tokens vec_data = int(vec) assert vec_data in {0, 1}, "Invalid vector" code[vec_data].arg = arg elif " " in token: sub_tokens = token.split(" ") assert len(sub_tokens) == 2, "Invalid instruction: {}".format(token) mnemonic, arg = sub_tokens opcode = Opcode(mnemonic) code.append(Code(prog_position, opcode, arg)) prog_position += 1 else: opcode = Opcode(token) code.append(Code(prog_position, opcode, addressing=Addressing.NONE.value)) prog_position += 1 return MachineCode(second_stage(code, labels), data) # flake8: noqa: C901 def second_stage(code: list[Code], labels: dict[str, int]): for instruction in code: if instruction.arg is not None: label = instruction.arg addressing = Addressing.DIRECT if label.startswith("["): if label.endswith("]"): addressing = Addressing.INDIRECT elif label.endswith("]+"): addressing = Addressing.POST_INC elif label.endswith("]-"): addressing = Addressing.POST_DEC elif label.startswith("#"): addressing = Addressing.LOAD label = label.strip("#[]+-") instruction.addressing = addressing.value try: instruction.arg = str(parse_number(label)) continue except ValueError: pass assert label in labels, "Label not defined: {}".format(label) instruction.arg = str(labels[label]) return code def parse_number(label: str) -> int: if label.startswith("0x"): return int(label[2:], 16) return int(label) def write_code(filename: str, code: MachineCode): with open(filename, "w", encoding="utf-8") as file: file.write(json.dumps(code, cls=MachineCodeEncoder, indent=4)) def main(source: str, target: str): with open(source, encoding="utf-8") as f: source_text = f.read() code = translate(source_text) write_code(target, code) print("source LoC:", len(source.split("\n")), "code instr:", len(code.code)) if __name__ == "__main__": assert len(sys.argv) == 3, "Wrong arguments: translator.py <input_file> <target_file>" _, src, tar = sys.argv main(src, tar)
using System.Collections.Generic; using System.Linq; using BaseCLI.Validation; using NUnit.Framework; namespace BaseCLI.Tests.ArgInfo { public class StringCollectionArgInfoTests { private const string Flag = "test"; private const string FriendlyName = "String collection flag"; private const string PropertyName = "Test"; private string _dashedFlag = $"-{Flag}"; [Test] public void Parse_SingleFlagPassedIn_SetsPropertyAsListWithOneValue() { const string flagValue = "PleaseWork"; var parsedArgs = new TestParsedArgs(); var args = new List<string> { _dashedFlag, flagValue, "Something", }; Parse(args, parsedArgs); Assert.AreEqual(1, parsedArgs.Test.Count); Assert.True(parsedArgs.Test.Contains(flagValue)); } [Test] public void Parse_MultipleFlagsPassedIn_SetsPropertyAsListWithAllValues() { const string flagValue1 = "PleaseWork"; const string flagValue2 = "I'm begging you"; var parsedArgs = new TestParsedArgs(); var args = new List<string> { _dashedFlag, flagValue1, "Something", _dashedFlag, flagValue2 }; Parse(args, parsedArgs); Assert.AreEqual(2, parsedArgs.Test.Count); Assert.True(parsedArgs.Test.Contains(flagValue1)); Assert.True(parsedArgs.Test.Contains(flagValue2)); } [Test] public void Parse_NoFlagsPassedIn_SetsPropertyAsEmptyList() { var parsedArgs = new TestParsedArgs(); var args = new List<string> { "Something" }; Parse(args, parsedArgs); Assert.False(parsedArgs.Test.Any()); } [Test] public void Validate_FlagIsMandatoryAndNoArgs_Throws() { Assert.Throws<ArgValidatorException>(() => Validate(new List<string>(), true)); } [Test] public void Validate_FlagIsNotMandatoryAndNoArgs_ArgsRemainUnchanged() { var args = new List<string> { "Something" }; Validate(args); Assert.AreEqual(1, args.Count); } [Test] public void Validate_ArgsArePassedIn_KeyAndValuesAreRemoved() { const string otherArg = "Something"; var args = new List<string> { _dashedFlag, "Flag Value 1", otherArg, _dashedFlag, "Flag Value 2" }; Validate(args); Assert.AreEqual(otherArg, args.Single()); } [Test] public void Validate_ValueIsMissingForFlag_Throws() { const string otherArg = "Something"; var args = new List<string> { _dashedFlag, "Flag Value 1", otherArg, _dashedFlag }; Assert.Throws<ArgValidatorException>(() => Validate(args)); } private void Validate(List<string> args, bool mandatory = false) { new StringCollectionArgInfo<TestParsedArgs>(Flag, FriendlyName, PropertyName, mandatory) .Validate(args); } private void Parse(List<string> args, TestParsedArgs parsedArgs) { new StringCollectionArgInfo<TestParsedArgs>(Flag, FriendlyName, PropertyName) .Parse(parsedArgs, args); } private class TestParsedArgs { public List<string> Test { get; set; } } } }
const students = [ { name: "Dhishan Debnath", Roll: 1 }, { name: "Animesh Gupta", Roll: 2 }, { name: "Tapas Sen", Roll: 3 }, { name: "Misti Dutta", Roll: 4 }, { name: "Chini Misra", Roll: 5 } ]; const Details = [ { Roll: 5, subjects: { math: 35, english: 56, chemistry: 76, computer: 68 } }, { Roll: 3, subjects: { math: 33, chemistry: 12, computer: 50, english: 35 } }, { Roll: 1, subjects: { math: 55, english: 75, chemistry: 76, computer: 94 } }, { Roll: 4, subjects: { english: 12, chemistry: 85, computer: 68, math: 45 } }, { Roll: 2, subjects: { math: 55, english: 56, computer: 48, chemistry: 12 } } ]; function generateStudentMarkSheets(students, Details) { const studentsMarkSheets = []; students.forEach(student => { const studentDetails = Details.find(detail => detail.Roll === student.Roll); let totalMarks = 0; let status = "fail"; if (studentDetails) { const subjects = studentDetails.subjects; totalMarks = Object.values(subjects).reduce((acc, val) => acc + val, 0); status = totalMarks >= 200 ? "pass" : "fail"; } const markSheet = { ...student, ...studentDetails.subjects, total: totalMarks, status }; studentsMarkSheets.push(markSheet); }); return studentsMarkSheets; } const studentsMarkSheets = generateStudentMarkSheets(students, Details); console.log(studentsMarkSheets);
#include <Arduino.h> #include "IMU.h" // Click here to get the library: http://librarymanager/All#SparkFun_ICM_20948_IMU #define SERIAL_PORT Serial #define SPI_PORT SPI // Your desired SPI port. Used only when "USE_SPI" is defined #define CS_PIN 2 // Which pin you connect CS to. Used only when "USE_SPI" is defined #define WIRE_PORT Wire // Your desired Wire port. Used when "USE_SPI" is not defined #define AD0_VAL 1 // The value of the last bit of the I2C address. // On the SparkFun 9DoF IMU breakout the default is 1, and when // the ADR jumper is closed the value becomes 0 wrapIMU::wrapIMU() { ICM_20948_I2C myICM; // create ICM_20948_I2C object } // Below here are some helper functions to print the data nicely! void wrapIMU::printPaddedInt16b(int16_t val) { if (val > 0) { SERIAL_PORT.print(" "); if (val < 10000) { SERIAL_PORT.print("0"); } if (val < 1000) { SERIAL_PORT.print("0"); } if (val < 100) { SERIAL_PORT.print("0"); } if (val < 10) { SERIAL_PORT.print("0"); } } else { SERIAL_PORT.print("-"); if (abs(val) < 10000) { SERIAL_PORT.print("0"); } if (abs(val) < 1000) { SERIAL_PORT.print("0"); } if (abs(val) < 100) { SERIAL_PORT.print("0"); } if (abs(val) < 10) { SERIAL_PORT.print("0"); } } SERIAL_PORT.print(abs(val)); } void wrapIMU::printRawAGMT(ICM_20948_AGMT_t agmt) { SERIAL_PORT.print("RAW. Acc [ "); printPaddedInt16b(agmt.acc.axes.x); SERIAL_PORT.print(", "); printPaddedInt16b(agmt.acc.axes.y); SERIAL_PORT.print(", "); printPaddedInt16b(agmt.acc.axes.z); SERIAL_PORT.print(" ], Gyr [ "); printPaddedInt16b(agmt.gyr.axes.x); SERIAL_PORT.print(", "); printPaddedInt16b(agmt.gyr.axes.y); SERIAL_PORT.print(", "); printPaddedInt16b(agmt.gyr.axes.z); SERIAL_PORT.print(" ], Mag [ "); printPaddedInt16b(agmt.mag.axes.x); SERIAL_PORT.print(", "); printPaddedInt16b(agmt.mag.axes.y); SERIAL_PORT.print(", "); printPaddedInt16b(agmt.mag.axes.z); SERIAL_PORT.print(" ], Tmp [ "); printPaddedInt16b(agmt.tmp.val); SERIAL_PORT.print(" ]"); SERIAL_PORT.println(); } void wrapIMU::printFormattedFloat(float val, uint8_t leading, uint8_t decimals) { float aval = abs(val); if (val < 0) { Serial.print("-"); } else { Serial.print(" "); } for (uint8_t indi = 0; indi < leading; indi++) { uint32_t tenpow = 0; if (indi < (leading - 1)) { tenpow = 1; } for (uint8_t c = 0; c < (leading - 1 - indi); c++) { tenpow *= 10; } if (aval < tenpow) { Serial.print("0"); } else { break; } } if (val < 0) { Serial.print(-val, decimals); } else { Serial.print(val, decimals); } } void wrapIMU::printScaledAGMT(ICM_20948_AGMT_t agmt) { SERIAL_PORT.print("Scaled. Acc (mg) [ "); printFormattedFloat(myICM.accX(), 5, 2); SERIAL_PORT.print(", "); printFormattedFloat(myICM.accY(), 5, 2); SERIAL_PORT.print(", "); printFormattedFloat(myICM.accZ(), 5, 2); SERIAL_PORT.print(" ], Gyr (DPS) [ "); printFormattedFloat(myICM.gyrX(), 5, 2); SERIAL_PORT.print(", "); printFormattedFloat(myICM.gyrY(), 5, 2); SERIAL_PORT.print(", "); printFormattedFloat(myICM.gyrZ(), 5, 2); SERIAL_PORT.print(" ], Mag (uT) [ "); printFormattedFloat(myICM.magX(), 5, 2); SERIAL_PORT.print(", "); printFormattedFloat(myICM.magY(), 5, 2); SERIAL_PORT.print(", "); printFormattedFloat(myICM.magZ(), 5, 2); SERIAL_PORT.print(" ], Tmp (C) [ "); printFormattedFloat(myICM.temp(), 5, 2); SERIAL_PORT.print(" ]"); SERIAL_PORT.println(); } // Here are the main functions void wrapIMU::setup() { #ifdef USE_SPI SPI_PORT.begin(); #else WIRE_PORT.begin(); WIRE_PORT.setClock(400000); #endif bool initialized = false; Serial.print("Setting up IMU..."); while (!initialized) { #ifdef USE_SPI myICM.begin(CS_PIN, SPI_PORT); #else myICM.begin(WIRE_PORT, AD0_VAL); #endif // Set full scale ranges for both acc and gyr ICM_20948_fss_t myFSS; // This uses a "Full Scale Settings" structure that can contain values for all configurable sensors myFSS.a = gpm4; // (ICM_20948_ACCEL_CONFIG_FS_SEL_e) // gpm2 // gpm4 // gpm8 // gpm16 myFSS.g = dps250; // (ICM_20948_GYRO_CONFIG_1_FS_SEL_e) // dps250 // dps500 // dps1000 // dps2000 myICM.setFullScale((ICM_20948_Internal_Acc | ICM_20948_Internal_Gyr), myFSS); //SERIAL_PORT.print( F("Initialization of the sensor returned: ") ); //SERIAL_PORT.println( myICM.statusString() ); if (myICM.status != ICM_20948_Stat_Ok) { Serial.println("Failed, retrying"); delay(500); } else { initialized = true; Serial.println("Success!"); } } } void wrapIMU::update() { if (myICM.dataReady()) { myICM.getAGMT(); // The values are only updated when you call 'getAGMT' } else { Serial.println("Waiting for data"); } } void wrapIMU::print() { printFormattedFloat(myICM.accX(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.accY(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.accZ(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.gyrX(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.gyrY(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.gyrZ(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.magX(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.magY(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.magZ(), 5, 2); Serial.print(", "); printFormattedFloat(myICM.temp(), 5, 2); Serial.println(); } // Report Raw Values float wrapIMU::getRawgyrX() { return myICM.gyrX(); } float wrapIMU::getRawgyrY() { return myICM.gyrY(); } float wrapIMU::getRawgyrZ() { return myICM.gyrZ(); } float wrapIMU::getRawmagX() { return myICM.magX(); } float wrapIMU::getRawmagY() { return myICM.magY(); } float wrapIMU::getRawmagZ() { return myICM.magZ(); } // Report non-biased Values float wrapIMU::getaccX() { return myICM.accX(); } float wrapIMU::getaccY() { return myICM.accY(); } float wrapIMU::getaccZ() { return myICM.accZ(); } float wrapIMU::getgyrX() // (deg/s) { return myICM.gyrX() - BIAS_GYR_X; } float wrapIMU::getgyrY() // (deg/s) { return myICM.gyrY() - BIAS_GYR_Y; } float wrapIMU::getgyrZ() // (deg/s) { return myICM.gyrZ() - BIAS_GYR_Z; } float wrapIMU::getmagX() // uT { return myICM.magX() - BIAS_MAG_X; } float wrapIMU::getmagY() // uT { return myICM.magY() - BIAS_MAG_Y; } float wrapIMU::getmagZ() // uT { return myICM.magZ() - BIAS_MAG_Z; } float wrapIMU::gettemp() // C { return myICM.temp(); }
# # Copyright 2019 The FATE Authors. All Rights Reserved. # # 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. # import json import os import time import typing from datetime import timedelta from pathlib import Path from fate_client.flow_sdk import FlowClient from fate_test import _config from fate_test._parser import Data class FLOWClient(object): def __init__(self, address: typing.Optional[str], data_base_dir: typing.Optional[Path], cache_directory: typing.Optional[Path]): self.address = address self.version = "v2" self._client = FlowClient(self.address.split(':')[0], self.address.split(':')[1], self.version) self._data_base_dir = data_base_dir self._cache_directory = cache_directory self.data_size = 0 def set_address(self, address): self.address = address def transform_local_file_to_dataframe(self, data: Data, callback=None, output_path=None): #data_warehouse = self.upload_data(data, callback, output_path) #status = self.transform_to_dataframe(data.namespace, data.table_name, data_warehouse, callback) status = self.upload_file_and_convert_to_dataframe(data, callback, output_path) return status def upload_file_and_convert_to_dataframe(self, data: Data, callback=None, output_path=None): conf = data.config # if conf.get("engine", {}) != "PATH": if output_path is not None: conf['file'] = os.path.join(os.path.abspath(output_path), os.path.basename(conf.get('file'))) else: if _config.data_switch is not None: conf['file'] = os.path.join(str(self._cache_directory), os.path.basename(conf.get('file'))) else: conf['file'] = os.path.join(str(self._data_base_dir), conf.get('file')) path = Path(conf.get('file')) if not path.exists(): raise Exception('The file is obtained from the fate flow client machine, but it does not exist, ' f'please check the path: {path}') response = self._client.data.upload_file(file=str(path), head=data.head, meta=data.meta, extend_sid=data.extend_sid, partitions=data.partitions, namespace=data.namespace, name=data.table_name) try: if callback is not None: callback(response) status = self._awaiting(response["job_id"], "local", 0) status = str(status).lower() else: status = response["retmsg"] except Exception as e: raise RuntimeError(f"upload data failed") from e job_id = response["job_id"] self._awaiting(job_id, "local", 0) return status """def upload_data(self, data: Data, callback=None, output_path=None): response, file_path = self._upload_data(data, output_path=output_path) try: if callback is not None: callback(response) code = response["code"] if code != 0: raise ValueError(f"Return code {code}!=0") namespace = response["data"]["namespace"] name = response["data"]["name"] job_id = response["job_id"] except BaseException: raise ValueError(f"Upload data fails, response={response}") # self.monitor_status(job_id, role=self.role, party_id=self.party_id) self._awaiting(job_id, "local", 0) return dict(namespace=namespace, name=name) def transform_to_dataframe(self, namespace, table_name, data_warehouse, callback=None): response = self._client.data.dataframe_transformer(namespace=namespace, name=table_name, data_warehouse=data_warehouse) try: if callback is not None: callback(response) status = self._awaiting(response["job_id"], "local", 0) status = str(status).lower() else: status = response["retmsg"] except Exception as e: raise RuntimeError(f"upload data failed") from e job_id = response["job_id"] self._awaiting(job_id, "local", 0) return status""" def delete_data(self, data: Data): try: table_name = data.config['table_name'] if data.config.get( 'table_name', None) is not None else data.config.get('name') self._client.table.delete(name=table_name, namespace=data.config['namespace']) except Exception as e: raise RuntimeError(f"delete data failed") from e def output_data_table(self, job_id, role, party_id, task_name, output_data_name): data_info = self._output_data_table(job_id=job_id, role=role, party_id=party_id, task_name=task_name) output_data_info = data_info.get(output_data_name)[0] if output_data_info is None: raise ValueError(f"output data name {output_data_name} not found") return output_data_info def table_query(self, table_name, namespace): result = self._table_query(name=table_name, namespace=namespace) return result def add_notes(self, job_id, role, party_id, notes): self._client.job.add_notes(job_id, role=role, party_id=party_id, notes=notes) """def add_notes(self, job_id, role, party_id, notes): self._add_notes(job_id=job_id, role=role, party_id=party_id, notes=notes)""" def _awaiting(self, job_id, role, party_id, callback=None): while True: response = self._query_job(job_id, role=role, party_id=party_id) if response.status.is_done(): return response.status if callback is not None: callback(response) time.sleep(1) """def _upload_data(self, data, output_path=None, verbose=0, destroy=1): conf = data.config # if conf.get("engine", {}) != "PATH": if output_path is not None: conf['file'] = os.path.join(os.path.abspath(output_path), os.path.basename(conf.get('file'))) else: if _config.data_switch is not None: conf['file'] = os.path.join(str(self._cache_directory), os.path.basename(conf.get('file'))) else: conf['file'] = os.path.join(str(self._data_base_dir), conf.get('file')) path = Path(conf.get('file')) if not path.exists(): raise Exception('The file is obtained from the fate flow client machine, but it does not exist, ' f'please check the path: {path}') response = self._client.data.upload(file=str(path), head=data.head, meta=data.meta, extend_sid=data.extend_sid, partitions=data.partitions) return response, conf["file"]""" def _output_data_table(self, job_id, role, party_id, task_name): response = self._client.output.data_table(job_id, role=role, party_id=party_id, task_name=task_name) if response.get("code") is not None: raise ValueError(f"Query output data table failed, response={response}") return response def _table_query(self, name, namespace): response = self._client.table.query(namespace=namespace, name=name) try: code = response["code"] if code != 0: raise ValueError(f"Return code {code}!=0") return json.dumps(response["data"], indent=4) except BaseException: raise ValueError(f"Query table fails, response={response}") def _delete_data(self, table_name, namespace): response = self._client.table.delete(namespace=namespace, table_name=table_name) return response def query_task(self, job_id, role, party_id): response = self._client.task.query(job_id, role=role, party_id=party_id) return response def query_job(self, job_id, role, party_id): response = self._client.job.query(job_id, role=role, party_id=party_id) return QueryJobResponse(response) def _query_job(self, job_id, role, party_id): response = self._client.job.query(job_id, role, party_id) return QueryJobResponse(response) def get_version(self): response = self._client.provider.query(name="fate") try: retcode = response['code'] retmsg = response['message'] if retcode != 0 or retmsg != 'success': raise RuntimeError(f"get version error: {response}") fate_version = response["data"][0]["provider_name"] except Exception as e: raise RuntimeError(f"get version error: {response}") from e return fate_version """def _add_notes(self, job_id, role, party_id, notes): data = dict(job_id=job_id, role=role, party_id=party_id, notes=notes) response = AddNotesResponse(self._post(url='job/update', json=data)) return response""" def _table_bind(self, data): response = self._post(url='table/bind', json=data) try: retcode = response['retcode'] retmsg = response['retmsg'] if retcode != 0 or retmsg != 'success': raise RuntimeError(f"table bind error: {response}") except Exception as e: raise RuntimeError(f"table bind error: {response}") from e return response class Status(object): def __init__(self, status: str): self.status = status def is_done(self): return self.status.lower() in ['complete', 'success', 'canceled', 'failed', "timeout"] def is_success(self): return self.status.lower() in ['complete', 'success'] def __str__(self): return self.status def __repr__(self): return self.__str__() class QueryJobResponse(object): def __init__(self, response: dict): try: status = Status(response.get('data')[0]["status"]) progress = response.get('data')[0]['progress'] elapsed = response.get('data')[0]['elapsed'] if elapsed is not None: elapsed = elapsed / 1000 except Exception as e: raise RuntimeError(f"query job error, response: {json.dumps(response, indent=4)}") from e self.status = status self.progress = progress self.elapsed = elapsed class UploadDataResponse(object): def __init__(self, response: dict): try: self.job_id = response["jobId"] except Exception as e: raise RuntimeError(f"upload error, response: {response}") from e self.status: typing.Optional[Status] = None class AddNotesResponse(object): def __init__(self, response: dict): try: retcode = response['retcode'] retmsg = response['retmsg'] if retcode != 0 or retmsg != 'success': raise RuntimeError(f"add notes error: {response}") except Exception as e: raise RuntimeError(f"add notes error: {response}") from e class DataProgress(object): def __init__(self, role_str): self.role_str = role_str self.start = time.time() self.show_str = f"[{self.elapse()}] {self.role_str}" self.job_id = "" def elapse(self): return f"{timedelta(seconds=int(time.time() - self.start))}" def submitted(self, job_id): self.job_id = job_id self.show_str = f"[{self.elapse()}]{self.job_id} {self.role_str}" def update(self): self.show_str = f"[{self.elapse()}]{self.job_id} {self.role_str}" def show(self): return self.show_str class JobProgress(object): def __init__(self, name): self.name = name self.start = time.time() self.show_str = f"[{self.elapse()}] {self.name}" self.job_id = "" self.progress_tracking = "" def elapse(self): return f"{timedelta(seconds=int(time.time() - self.start))}" def set_progress_tracking(self, progress_tracking): self.progress_tracking = progress_tracking + " " def submitted(self, job_id): self.job_id = job_id self.show_str = f"{self.progress_tracking}[{self.elapse()}]{self.job_id} submitted {self.name}" def running(self, status, progress): if progress is None: progress = 0 self.show_str = f"{self.progress_tracking}[{self.elapse()}]{self.job_id} {status} {progress:3}% {self.name}" def exception(self, exception_id): self.show_str = f"{self.progress_tracking}[{self.elapse()}]{self.name} exception({exception_id}): {self.job_id}" def final(self, status): self.show_str = f"{self.progress_tracking}[{self.elapse()}]{self.job_id} {status} {self.name}" def show(self): return self.show_str class JobStatus(object): WAITING = 'waiting' READY = 'ready' RUNNING = "running" CANCELED = "canceled" TIMEOUT = "timeout" FAILED = "failed" PASS = "pass" SUCCESS = "success"
from collections import defaultdict from datetime import datetime, timezone from django.contrib.postgres.aggregates.general import ArrayAgg from django.db.models import Max, OuterRef, Q, Subquery from attendees.occasions.models import Meet from attendees.persons.models import Attendee, Folk, Utility, AttendingMeet class FolkService: @staticmethod def families_in_directory(directory_meet_id, member_meet_id, row_limit=26, targeting_attendee_id=None, divisions=[]): """ It generates data for printing/previewing single or participating families in chosen divisions. The output includes indexes (families grouped in cities) and families (header and family member contacts). An attendee will NOT be unique if it belongs to multiple families. Folkattendees role of masked won't be shown. It has no scope checks, so callers need to limit the scope by passing targeting_attendee_id or divisions. Phones/emails will be empty when there's no parents. For kids-only families please assign 'self' role to the first kid to show its phone/email """ families = [] index = defaultdict(lambda: {}) index_list = [] directory_meet = Meet.objects.filter(pk=directory_meet_id).first() member_meet = Meet.objects.filter(pk=member_meet_id).first() targeting_families = Attendee.objects.get(pk=targeting_attendee_id).folks if targeting_attendee_id else Folk.objects.filter(division__in=divisions).prefetch_related('attendees', 'folkattendee_set') if directory_meet: attendee_subquery = Attendee.objects.filter( attendings__attendingmeet__is_removed=False, attendings__attendingmeet__meet=directory_meet, attendings__attendingmeet__finish__gte=Utility.now_with_timezone(), folks=OuterRef('pk'), deathday=None, is_removed=False, ).order_by('folkattendee__display_order') families_in_directory = targeting_families.annotate( householder_last_name=Subquery(attendee_subquery.values_list('last_name')[:1]), householder_first_name=Subquery(attendee_subquery.values_list('first_name')[:1]), householder_first_name2=Subquery(attendee_subquery.values_list('first_name2')[:1]), ).filter( category=Attendee.FAMILY_CATEGORY, is_removed=False, infos__print_directory=True, attendees__in=Attendee.objects.filter( attendings__in=directory_meet.attendings.filter( attendingmeet__is_removed=False, attendingmeet__finish__gte=Utility.now_with_timezone() ), deathday=None, is_removed=False, ), ).distinct().order_by('householder_last_name', 'householder_first_name', 'householder_first_name2') for family in families_in_directory: attrs = {} attendees = family.attendees.filter( deathday=None, attendings__in=directory_meet.attendings.filter( attendingmeet__is_removed=False, attendingmeet__finish__gte=Utility.now_with_timezone() ), # only for attendees join the meet ).exclude( folkattendee__role__title="masked", # for joined attendees not to be shown in certain families ).exclude( folkattendee__finish__lte=datetime.now(timezone.utc) ).distinct().order_by('folkattendee__display_order') if attendees: parents = attendees.filter( folkattendee__role__title__in=['self', 'spouse', 'husband', 'wife', 'father', 'mother', 'parent'] # no father/mother-in-law ) attrs['household_last_name'] = attendees.first().last_name if parents: phone1 = parents.first() and parents.first().infos.get('contacts', {}).get('phone1') # only phone1 published in directory phone2 = None if phone1: attrs['phone1'] = Utility.phone_number_formatter(phone1) email1 = parents.first() and parents.first().infos.get('contacts', {}).get('email1') # only email1 published in directory if email1: attrs['email1'] = email1 is_householder_member = member_meet and AttendingMeet.check_participation_of(attendees.first(), member_meet) householder_title = f'{attendees.first().last_name}, {attendees.first().first_name}{"*" if is_householder_member else ""}' name2_title = f'{attendees.first().name2()}' if len(parents) > 1: name2_title += f' {parents[1].name2()}' is_parent1_member = member_meet and AttendingMeet.check_participation_of(parents[1], member_meet) householder_title += f' & {parents[1].first_name}{"*" if is_parent1_member else ""}' phone2 = parents[1].infos.get('contacts', {}).get('phone1') # only phone1 published in directory if phone2 and phone1 != phone2: attrs['phone2'] = Utility.phone_number_formatter(phone2) email2 = parents[1].infos.get('contacts', {}).get('email1') # only email1 published in directory if email2 and email1 != email2: attrs['email2'] = email2 attrs['household_title'] = householder_title family_address = family.places.first() and family.places.first().address # implicitly ordered by display_order of place if family_address: address_line1 = f'{family_address.street_number} {family_address.route}' address_line2 = f'{family_address.locality.name}, {family_address.locality.state.code} {family_address.locality.postal_code}' attrs['address_link'] = f'{address_line1}+{address_line2}'.replace(' ', '+') if family_address.extra: address_line1 += f' {family_address.extra}' attrs['address_line1'] = address_line1 attrs['address_line2'] = address_line2 index[family_address.locality.name][f'{householder_title} {name2_title}'.strip()] = Utility.phone_number_formatter(phone1 or phone2) attendees_attr = [] for attendee in attendees: is_attendee_member = member_meet and AttendingMeet.check_participation_of(attendee, member_meet) attendees_attr.append({ 'id': attendee.id, 'first_name': f'{attendee.first_name}{"*" if is_attendee_member else ""}', 'name2': attendee.name2(), 'photo_url': attendee.photo and attendee.photo.url, 'is_member': member_meet and AttendingMeet.check_participation_of(attendee, member_meet), }) attrs['attendees'] = attendees_attr families.append(attrs) if targeting_attendee_id is None: for i, (town_name, family_rows) in enumerate(sorted(index.items())): if i > 0: # No line breaks before the first town index_list.append({'BREAKER': 'LINE'}) if len(index_list) % row_limit < 1: index_list.append({'BREAKER': 'PAGE'}) index_list.append({'TOWN_NAME': town_name}) if len(index_list) % row_limit < 1: index_list.append({'BREAKER': 'PAGE'}) for title, number in sorted(index[town_name].items()): index_list.append({title: number}) if len(index_list) % row_limit < 1: index_list.append({'BREAKER': 'PAGE'}) return index_list, families @staticmethod def families_in_participations(meet_slug, user_organization, show_paused, division_slugs): """ Returns a list of not-paused unique attendingmeet of a meet limited by user_organization and divisions, grouped by families for print. If an Attendee belongs to many families, only 1) lowest display order 2) the last created folkattendee will be shown. Attendees will NOT be shown if the category of the attendingmeet is "paused". For cache computation final results may contain empty families so template need to filter them out. It does NOT provide attendee counting, as view/template does css-counter or https://stackoverflow.com/a/34059709/4257237 """ families = {} # {family_pk: {family_name: "AAA", families: {attendee_pk: {first_name: 'XYZ', name2: 'ABC', rank: last_folkattendee_display_order, created_at: last_folkattendee_created_at}}}} attendees_cache = {} # {attendee_pk: {last_family_pk: last_family_pk, rank: last_folkattendee_display_order, created_at: last_folkattendee_created_at}} meet = Meet.objects.filter(slug=meet_slug, assembly__division__organization=user_organization).first() if meet: original_meets_attendings = meet.attendings.filter( attendingmeet__is_removed=False, attendingmeet__finish__gte=Utility.now_with_timezone(), ) meets_attendings = original_meets_attendings if show_paused else original_meets_attendings.exclude( attendingmeet__category=Attendee.PAUSED_CATEGORY, ) original_attendee_subquery = Attendee.objects.filter( attendings__attendingmeet__is_removed=False, attendings__attendingmeet__meet=meet, attendings__attendingmeet__finish__gte=Utility.now_with_timezone(), folks=OuterRef('pk'), deathday=None, is_removed=False, ).order_by('folkattendee__display_order') attendee_subquery = original_attendee_subquery if show_paused else original_attendee_subquery.exclude( attendings__attendingmeet__category=Attendee.PAUSED_CATEGORY, ) families_in_directory = Folk.objects.filter( division__organization=user_organization, ).prefetch_related('folkattendee_set', 'attendees').annotate( householder_last_name=Subquery(attendee_subquery.values_list('last_name')[:1]), householder_first_name=Subquery(attendee_subquery.values_list('first_name')[:1]), householder_first_name2=Subquery(attendee_subquery.values_list('first_name2')[:1]), ).filter( category=Attendee.FAMILY_CATEGORY, is_removed=False, attendees__in=Attendee.objects.filter( division__slug__in=division_slugs, attendings__in=meets_attendings, deathday=None, is_removed=False, ), ).distinct().order_by('householder_last_name', 'householder_first_name', 'householder_first_name2') for family in families_in_directory: candidates_qs = family.attendees.select_related('division', 'attendings', 'folkattendee_set').filter( division__slug__in=division_slugs, deathday=None, attendings__in=meets_attendings, ).exclude( folkattendee__finish__lte=datetime.now(timezone.utc) ) attendee_candidates = candidates_qs.distinct().order_by('folkattendee__display_order').values( 'id', 'first_name', 'last_name', 'first_name2', 'last_name2', 'folkattendee__display_order', 'created', 'division__infos__acronym' ).annotate( attendingmeet_id=Max('attendings__attendingmeet__id', filter=Q(attendings__attendingmeet__meet=meet)), attendingmeet_category=Max('attendings__attendingmeet__category', filter=Q(attendings__attendingmeet__meet=meet)), attendingmeet_note=ArrayAgg('attendings__attendingmeet__infos__note', filter=(Q(attendings__attendingmeet__meet=meet) & Q(attendings__attendingmeet__infos__note__isnull=False)), distinct=True), ) family_attrs = {"families": {}, 'family_name': 'no last names!'} if attendee_candidates[0]: family_attrs['family_name'] = attendee_candidates[0].get('last_name') or attendee_candidates[0].get('last_name2') for attendee in attendee_candidates: attendee_id = attendee.get('id') attendee_last_record = attendees_cache.get(attendee_id) if attendee_last_record: current_rank = attendee.get('folkattendee__display_order') last_rank = attendee_last_record.get('rank') current_created = attendee.get('created') last_created = attendee_last_record.get('created') last_family = attendee_last_record.get('family_id') if current_rank > last_rank or (current_rank == last_rank and current_created < last_created): continue # unique by 1) lowest display order 2) the last created folkattendee else: # current one will replace last one del families[last_family]['families'][attendee_id] if len(families[last_family]['families']) < 1: del families[last_family] elif str(attendee_id) == families[last_family].get('first_attendee_id'): first_attendee = next(iter(families[last_family]['families'].items()))[1] families[last_family]['first_attendee_id'] = str(first_attendee.get('id', '')) attendees_cache[attendee_id] = { 'rank': attendee.get('folkattendee__display_order'), 'created': attendee.get('created'), 'family_id': family.id, } family_attrs['families'][attendee_id] = { 'id': attendee.get('id'), 'first_name': attendee.get('first_name'), 'first_name2': attendee.get('first_name2'), 'last_name2': attendee.get('last_name2'), 'division': attendee.get('division__infos__acronym'), 'attendingmeet_id': attendee.get('attendingmeet_id'), 'attendingmeet_category': attendee.get('attendingmeet_category'), 'attendingmeet_note': ''.join(attendee.get('attendingmeet_note')), 'paused': attendee.get('attendingmeet_category') == Attendee.PAUSED_CATEGORY, } if len(family_attrs['families']) > 0: first_attendee = next(iter(family_attrs['families'].items()))[1] family_attrs['first_attendee_id'] = str(first_attendee.get('id', '')) families[family.id] = family_attrs return families.values() @staticmethod def folk_addresses_in_participations(meet_slug, user_organization, show_paused, division_slugs): """ Because attendee may be in multiple families and envelopes only needs the lowest display order ones, iteration of attendee is required. It's mostly copy from families_in_participations. """ families = {} # {family_pk: {family_name: "AAA", families: {attendee_pk: {first_name: 'XYZ', name2: 'ABC', rank: last_folkattendee_display_order, created_at: last_folkattendee_created_at}}}} attendees_cache = {} # {attendee_pk: {last_family_pk: last_family_pk, rank: last_folkattendee_display_order, created_at: last_folkattendee_created_at}} meet = Meet.objects.filter(slug=meet_slug, assembly__division__organization=user_organization).first() if meet: original_meets_attendings = meet.attendings.filter( attendingmeet__is_removed=False, attendingmeet__finish__gte=Utility.now_with_timezone(), ) meets_attendings = original_meets_attendings if show_paused else original_meets_attendings.exclude( attendingmeet__category=Attendee.PAUSED_CATEGORY, ) original_attendee_subquery = Attendee.objects.filter( attendings__attendingmeet__is_removed=False, attendings__attendingmeet__meet=meet, attendings__attendingmeet__finish__gte=Utility.now_with_timezone(), folks=OuterRef('pk'), is_removed=False, deathday=None, ).order_by('folkattendee__display_order') attendee_subquery = original_attendee_subquery if show_paused else original_attendee_subquery.exclude( attendings__attendingmeet__category=Attendee.PAUSED_CATEGORY, ) families_in_directory = Folk.objects.filter( division__organization=user_organization, ).prefetch_related('folkattendee_set', 'attendees', 'places').annotate( householder_last_name=Subquery(attendee_subquery.values_list('last_name')[:1]), householder_first_name=Subquery(attendee_subquery.values_list('first_name')[:1]), householder_first_name2=Subquery(attendee_subquery.values_list('first_name2')[:1]), ).filter( category=Attendee.FAMILY_CATEGORY, is_removed=False, attendees__in=Attendee.objects.filter( division__slug__in=division_slugs, attendings__in=meets_attendings, deathday=None, is_removed=False, ), ).distinct().order_by('householder_last_name', 'householder_first_name', 'householder_first_name2') for family in families_in_directory: candidates_qs = family.attendees.select_related('division', 'attendings', 'folkattendee_set').filter( division__slug__in=division_slugs, deathday=None, attendings__in=meets_attendings, ).exclude( folkattendee__finish__lte=datetime.now(timezone.utc) ) attendee_candidates = candidates_qs.distinct().order_by('folkattendee__display_order').values( 'id', 'first_name', 'last_name', 'first_name2', 'last_name2', 'folkattendee__display_order', 'created', ).annotate( attendingmeet_category=Max('attendings__attendingmeet__category', filter=Q(attendings__attendingmeet__meet=meet)), ) family_attrs = {'families': {}} for attendee in attendee_candidates: attendee_id = attendee.get('id') attendee_last_record = attendees_cache.get(attendee_id) if attendee_last_record: current_rank = attendee.get('folkattendee__display_order') last_rank = attendee_last_record.get('rank') current_created = attendee.get('created') last_created = attendee_last_record.get('created') last_family = attendee_last_record.get('family_id') if current_rank > last_rank or (current_rank == last_rank and current_created < last_created): continue # unique by 1) lowest display order 2) the last created folkattendee else: # current one will replace last one del families[last_family]['families'][attendee_id] families_count = len(families[last_family]['families']) if families_count < 1: del families[last_family] else: families_iter = iter(families[last_family]['families'].items()) home_head = next(families_iter)[1] families[last_family]['recipient_attendee_id'] = str(home_head.get('id', '')) families[last_family]['recipient_paused'] = home_head.get('paused') families[last_family]['recipient_name'] = FolkService.get_recipient(home_head, None if families_count < 2 else next(families_iter)[1]) attendees_cache[attendee_id] = { 'rank': attendee.get('folkattendee__display_order'), 'created': attendee.get('created'), 'family_id': family.id, } family_attrs['families'][attendee_id] = { 'id': attendee.get('id'), 'first_name': attendee.get('first_name') or '', 'first_name2': attendee.get('first_name2') or '', 'last_name': attendee.get('last_name') or '', 'last_name2': attendee.get('last_name2') or '', 'paused': attendee.get('attendingmeet_category') == Attendee.PAUSED_CATEGORY, } if len(family_attrs['families']) > 0: families_iter = iter(family_attrs['families'].items()) home_head = next(families_iter)[1] family_attrs['recipient_name'] = FolkService.get_recipient(home_head, None) family_attrs['recipient_attendee_id'] = str(home_head.get('id', '')) family_attrs['recipient_paused'] = home_head.get('paused') folk_place = family.places.first() if len(family_attrs['families']) > 1: family_attrs['recipient_name'] = FolkService.get_recipient(home_head, next(families_iter)[1]) if folk_place: address = family.places.first().address if address: family_attrs['address_line1'] = f"{address.street_number} {address.route} {address.extra or ''}".strip() family_attrs['address_line2'] = f"{address.locality.name}, {address.locality.state.code} {address.locality.postal_code or ''}".strip() families[family.id] = family_attrs return families.values() @staticmethod def get_recipient(home_head, spouse): home_head_name2 = f"{home_head.get('last_name2', '')}{home_head.get('first_name2', '')}".strip() if spouse: spouse_name2 = f"{spouse.get('last_name2', '')}{spouse.get('first_name2', '')}".strip() both_name = f"{' & '.join([i for i in [home_head.get('first_name', ''), spouse.get('first_name', '')] if i != ''])} {home_head.get('last_name', '')}" both_name2 = f"{home_head_name2} {spouse_name2}".strip() return f"{both_name} {both_name2}".strip() else: home_head_name = f"{home_head.get('first_name', '')} {home_head.get('last_name', '')}".strip() return f"{home_head_name} {home_head_name2}".strip() @staticmethod def destroy_with_associations(folk, attendee): """ No permission check. if family have more than one FamilyAttendees: only delete the FamilyAttendees, and reset non-blood Relationships. Places and Family still remained if family have only one FamilyAttendees (regardless which FamilyAttendees): delete family, places, FamilyAttendees and reset non-blood Relationships :param folk: a folk object :param attendee: an attendee object, whose name will be removed from family display_name :return: None """ if ( folk.folkattendee_set.count() < 2 and folk.folkattendee_set.first() == attendee ): # Relationship.objects.filter(in_family=folk.id, relation__consanguinity=False, is_removed=False).delete() # Relationship.objects.filter(in_family=folk.id, relation__consanguinity=True, is_removed=False).update(in_family=None) folk.places.filter(is_removed=False).delete() folk.folkattendee_set.filter(is_removed=False).delete() folk.delete() else: family_name = folk.display_name for attendee_name in attendee.all_names(): if attendee_name is not None: family_name.replace(attendee_name, "") folk.display_name = family_name folk.save() # Relationship.objects.filter(from_attendee=attendee, in_family=folk.id, relation__consanguinity=False, is_removed=False).delete() folk.folkattendee_set.filter(attendee=attendee, is_removed=False).delete()
/* Copyright (C) 2002-2013 by Peter Eastman Changes copyright (C) 2023 by Maksim Khramov 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. */ package artofillusion.script; import artofillusion.*; import artofillusion.ui.MessageDialog; import artofillusion.util.*; import java.io.*; import java.lang.reflect.*; import java.util.*; import lombok.extern.slf4j.Slf4j; /** * This class is used for executing scripts. */ @Slf4j public class ScriptRunner { private static SearchlistClassLoader parentLoader; private static PrintStream output; // This is a cache of script engine instances private static final HashMap<String, ScriptEngine> engines = new HashMap<>(); private static final String[] IMPORTS = {"artofillusion.*", "artofillusion.image.*", "artofillusion.material.*", "artofillusion.math.*", "artofillusion.object.*", "artofillusion.script.*", "artofillusion.texture.*", "artofillusion.procedural.*", "artofillusion.ui.*", "buoy.event.*", "buoy.widget.*"}; public static final String UNKNOWN_LANGUAGE = "?"; public enum Language { BEANSHELL("BeanShell", "bsh", BeanshellScriptEngine.class), GROOVY("Groovy", "groovy", GroovyScriptEngine.class); public final String name; public final String fileNameExtension; public final Class<? extends ScriptEngine> engineClass; Language(String name, String extension, Class<? extends ScriptEngine> engineClass) { this.name = name; this.fileNameExtension = extension; this.engineClass = engineClass; } } private static final String[] languageNames; static { List<String> names = new ArrayList<>(); for (Language l : Language.values()) { names.add(l.name); } languageNames = names.toArray(String[]::new); } public static String[] getLanguageNames() { return languageNames; } /** * Get the ScriptEngine for running scripts written in a particular language. */ public static ScriptEngine getScriptEngine(String language) throws ScriptException { if (!engines.containsKey(language)) { if (parentLoader == null) { parentLoader = new SearchlistClassLoader(ScriptRunner.class.getClassLoader()); for (ClassLoader plugin : PluginRegistry.getPluginClassLoaders()) { parentLoader.add(plugin); } } ScriptEngine engine; Class<? extends ScriptEngine> languageEngine = null; for (Language implementedLanguage : Language.values()) { if (implementedLanguage.name.equals(language)) { languageEngine = implementedLanguage.engineClass; } } if (languageEngine == null) { throw new IllegalArgumentException("Unknown name for scripting language: " + language); } try { engine = languageEngine.getConstructor(ClassLoader.class).newInstance(parentLoader); } catch (ReflectiveOperationException | SecurityException ex) { throw new ScriptException("Could not create a script engine of class " + languageEngine, -1, ex); } engines.put(language, engine); try { for (String packageName : IMPORTS) { engine.addImport(packageName); } } catch (Exception e) { throw new ScriptException("Could not import the required packages (" + IMPORTS.toString() + ")", -1, e); } output = new PrintStream(new ScriptOutputWindow()); engine.setOutput(output); } return engines.get(language); } /** * Execute a script. */ public static void executeScript(String language, String script, Map<String, Object> variables) { try { getScriptEngine(language).executeScript(script, variables); } catch (ScriptException ex) { log.atError().setCause(ex).log("Error in line {}: {}", ex.getLineNumber(), ex.getMessage()); } } /** * Parse a Tool script. */ public static ToolScript parseToolScript(String language, String script) throws Exception { return getScriptEngine(language).createToolScript(script); } /** * Parse an Object script. */ public static ObjectScript parseObjectScript(String language, String script) throws Exception { return getScriptEngine(language).createObjectScript(script); } /** * Display a dialog showing an exception thrown by a script. This returns the line number * in which the error occurred, or -1 if it could not be determined. */ public static int displayError(String language, Exception ex) { if (ex instanceof UndeclaredThrowableException) { ex = (Exception) ((UndeclaredThrowableException) ex).getUndeclaredThrowable(); } String head = "An error occurred while executing the script:"; String message = null, errorText = null, column = null; int line = -1; try { if (ex instanceof ScriptException) { ScriptException t = (ScriptException) ex; message = t.getMessage(); if (t.getLineNumber() > -1) { line = t.getLineNumber(); } ex.printStackTrace(output); } else { message = ex.getMessage(); ex.printStackTrace(output); } if (message == null || message.isEmpty()) { message = ex.toString(); } } catch (Exception ex2) { log.atError().setCause(ex2).log("Error: {}", ex2.getMessage()); } List<String> v = new ArrayList<>(); v.add(head); if (message != null) { if (message.contains("Inline eval of")) { int i = message.lastIndexOf("> Encountered"); if (i > -1) { int j = message.lastIndexOf(", column"); if (j > i) { column = (message.substring(j)); } } } else { v.add(message); } } if (line > -1 && errorText != null) { if (column == null) { v.add("Encountered \"" + errorText + "\" at line " + line + "."); } else { v.add("Encountered \"" + errorText + "\" at line " + line + column); } } MessageDialog.create().error(String.join("\n", v)); return line; } /** * Given the name of a file, determine what language it contains based on the fileNameExtension. * * @return {@link #UNKNOWN_LANGUAGE} if the language is not recognized */ public static String getLanguageForFilename(String filename) { for (Language knownLanguage : Language.values()) { if (filename.endsWith("." + knownLanguage.fileNameExtension)) { return knownLanguage.name; } } return UNKNOWN_LANGUAGE; } /** * Return the standard filename fileNameExtension to use for a language. * * @return {@link #UNKNOWN_LANGUAGE} if the language is not recognized */ public static String getFilenameExtension(String language) { for (Language knownLanguage : Language.values()) { if (knownLanguage.name.equals(language)) { return knownLanguage.fileNameExtension; } } return UNKNOWN_LANGUAGE; } }
package tools.flink import org.apache.flink.table.api.DataTypes import org.apache.flink.table.data.{DecimalData, StringData} import org.apache.flink.table.types.DataType import org.apache.flink.table.types.logical._ import org.apache.flink.table.types.logical.utils.LogicalTypeChecks import java.math.BigDecimal import java.time.{Instant, ZoneId} object RowUtils { def convertValue(value: Any, dataType: DataType): Any = { if (value == null) { return null } val logicalType = dataType.getLogicalType logicalType match { case _: VarCharType | _: CharType => StringData.fromString(value.asInstanceOf[String]) case _: DoubleType | _: FloatType => value.asInstanceOf[BigDecimal].doubleValue() case _: DecimalType => val decimalPrecision = LogicalTypeChecks.getPrecision(logicalType) val decimalScale = LogicalTypeChecks.getScale(logicalType) DecimalData.fromBigDecimal(value.asInstanceOf[BigDecimal], decimalPrecision, decimalScale) case _: TinyIntType | _: SmallIntType | _: IntType => value.asInstanceOf[Int] case _: BigIntType => value.asInstanceOf[Long] case _: BooleanType => value.asInstanceOf[Byte] case _: TimestampType | _: TimeType | _: DateType => val epochMillis = value match { case intValue: Integer => intValue.toLong case longValue: Long => longValue case _ => throw new IllegalArgumentException("Unsupported value type") } val t = Instant.ofEpochMilli(epochMillis).atZone(ZoneId.systemDefault()) if (logicalType.isInstanceOf[DateType]) t.toLocalDate else t.toLocalDateTime case _: BinaryType | _: VarBinaryType | _ => value.asInstanceOf[Array[Byte]] } } def transMySQLColType(colType: String): DataType = { val t = colType.toLowerCase t match { case _ if t.contains("numeric") || t.contains("decimal") => val subarr = t.substring(t.indexOf("(") + 1, t.indexOf(")")).split(",") subarr.length match { case 1 => DataTypes.DECIMAL(subarr(0).trim.toInt, 38) case 2 => DataTypes.DECIMAL(subarr(0).trim.toInt, subarr(1).trim.toInt) case _ => DataTypes.STRING() } case _ if t.contains("bigint") => DataTypes.BIGINT() case _ if t.contains("float") => DataTypes.FLOAT() case _ if t.contains("double") => DataTypes.DOUBLE() case _ if t.contains("boolean") => DataTypes.BOOLEAN() case _ if t.contains("datetime") || t.contains("timestamp") => DataTypes.TIMESTAMP() case _ if t.contains("time") => DataTypes.TIME() case _ if t.contains("date") => DataTypes.DATE() case _ if t.contains("varchar") || t.contains("text") || t.contains("char") || t.contains("binary") || t.contains("blob") => DataTypes.STRING() case _ if t.contains("tinyint") => DataTypes.TINYINT() case _ if t.contains("smallint") => DataTypes.SMALLINT() case _ if t.contains("mediumint") || t.contains("int") => DataTypes.INT() case _ => DataTypes.STRING() } } }
"use client"; import Link from "next/link"; import styles from "./NavLink.module.scss"; import { usePathname } from "next/navigation"; interface Props { href: string; title: string; active: boolean; color?: string; } const NavLink = ({ href, title, color }: Props) => { const pathname = usePathname(); const active = pathname === href; return ( <Link href={href} passHref> <div className={`${styles.button} ${active ? styles.active : ""}`} style={{ backgroundColor: active ? color : "" }} > {title} </div> </Link> ); }; export default NavLink;
<div class="d-flex justify-content-center vh-100 align-items-center"> <div class="centering-position"> <h2 class="text-center">Login Form</h2> <form [formGroup]="loginForm"(ngSubmit)="submitForm()"> <div class="form-group mb-3"> <label for="email">Email Address</label> <input class="form-control py-3 Input" id="email" formControlName="email" type="email" placeholder="Email Address" /> <ng-container *ngIf="!loginForm.controls['email'].valid && loginForm.controls['email'].touched"> <p *ngIf="loginForm.controls['email'].errors?.['required']" class="text-danger"> This field is Required </p> <p *ngIf="loginForm.controls['email'].errors?.['pattern']" class="text-danger"> Plz Enter Correct Email Address </p> </ng-container> </div> <div class="form-group mb-3"> <label for="password">Password</label> <input class="form-control py-3 Input" id="password" formControlName="password" type="password" placeholder="Password" /> <ng-container *ngIf="!loginForm.controls['password'].valid && loginForm.controls['password'].touched"> <p *ngIf="loginForm.controls['password'].errors?.['required']" class="text-danger"> This field is Required </p> <p *ngIf="loginForm.controls['password'].errors?.['minLength']" class="text-danger"> 4 char at least </p> </ng-container> </div> <button class="btn btn-primary m-2">Login</button> </form> </div> </div>
package nus.cs5248.project.mr; import java.io.File; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.hardware.Camera; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.widget.ToggleButton; @SuppressWarnings("deprecation") public class MediaRecorderRecipe extends Activity implements SurfaceHolder.Callback { private static final String VIDEO_PATH_NAME = "/Pictures/test.mp4"; private MediaRecorder mMediaRecorder; private Camera mCamera; private SurfaceView mSurfaceView; private SurfaceHolder mHolder; private View mToggleButton; private boolean mInitSuccesful; File file; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_recorder_recipe); file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + VIDEO_PATH_NAME); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView); mHolder = mSurfaceView.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mToggleButton = (ToggleButton) findViewById(R.id.toggleRecordingButton); mToggleButton.setOnClickListener(new OnClickListener() { @Override // toggle video recording public void onClick(View v) { if (((ToggleButton)v).isChecked()) mMediaRecorder.start(); else { File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + VIDEO_PATH_NAME); if(file.exists()) System.out.println("EXISTS"); else System.out.println("NAH"); mMediaRecorder.stop(); mMediaRecorder.reset(); try { initRecorder(mHolder.getSurface()); } catch (IOException e) { e.printStackTrace(); } } } }); } /* Init the MediaRecorder, the order the methods are called is vital to * its correct functioning */ // Replace this function with below and build please private void initRecorder(Surface surface) throws IOException { // It is very important to unlock the camera before doing setCamera // or it will results in a black preview if(mCamera == null) { mCamera = Camera.open(); mCamera.unlock(); } if(mMediaRecorder == null) mMediaRecorder = new MediaRecorder(); //mMediaRecorder.setPreviewDisplay(surface); mMediaRecorder.setCamera(mCamera); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mMediaRecorder.setOutputFile(file.getAbsolutePath()); mMediaRecorder.setVideoSize(720, 480); mMediaRecorder.setVideoEncodingBitRate(3000000); mMediaRecorder.setVideoFrameRate(30); mMediaRecorder.setPreviewDisplay(surface); mMediaRecorder.setMaxDuration(3600000); mMediaRecorder.setMaxFileSize(2000000000); /*mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P)); //mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); //mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); //mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264); mMediaRecorder.setVideoEncodingBitRate(3000000); //File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + VIDEO_PATH_NAME); // "touch" the file if(!file.exists()) { File parent = file.getParentFile(); if(parent != null) if(!parent.exists()) if(!parent.mkdirs()) throw new IOException("Cannot create " + "parent directories for file: " + file); file.createNewFile(); System.out.println("********CREATED FILE********"); } else System.out.println("File ALREADY found"); mMediaRecorder.setOutputFile(file.getAbsolutePath()); */ try { mMediaRecorder.prepare(); } catch (IllegalStateException e) { // This is thrown if the previous calls are not called with the // proper order e.printStackTrace(); } mInitSuccesful = true; } @Override public void surfaceCreated(SurfaceHolder holder) { try { if(!mInitSuccesful) initRecorder(mHolder.getSurface()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { shutdown(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } private void shutdown() { // Release MediaRecorder and especially the Camera as it's a shared // object that can be used by other applications mMediaRecorder.reset(); mMediaRecorder.release(); mCamera.release(); // once the objects have been released they can't be reused mMediaRecorder = null; mCamera = null; } }
<!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <style> /* Remove the navbar's default margin-bottom and rounded borders */ .navbar { margin-bottom: 0; border-radius: 0; } /* Set height of the grid so .sidenav can be 100% (adjust as needed) */ .row.content {height: 450px} /* Set gray background color and 100% height */ .sidenav { padding-top: 20px; background-color: #f1f1f1; height: 100%; } </style> </head> <body> <%! String getCookieValue(Cookie[] cookies,String key){ if(cookies!=null){ for(int i=0;i<cookies.length;i++){ if(cookies[i].getName().equals(key)){ return cookies[i].getValue(); } } } return null; } %> <% String uri=request.getParameter("uri"); String msg=request.getParameter("msg"); //board나 lecture에서 넘어왔다면 "u should login" String from="/filter_0601/index.jsp";//from= 끝나고 보내야할곳 if(uri!=null){ from=uri; } if(msg!=null){ %> <script>alert("<%=msg%>");</script> <% } //c.쿠키가 있는지 확인한다 String rememberid = getCookieValue(request.getCookies(),"rememberid"); System.out.println("리멤버아이디"+rememberid); String chk=""; System.out.println("rememberid!-null?"+rememberid!=null); if(rememberid!=null){//0-1.쿠키가 있으면 //1.쿠키의 내용을 읽어서 id에 보내준다 //2.체크박스를 체크한다 chk="checked"; }else{ rememberid=""; chk="";//0-2.없으면 아무일도 안한다 } %> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/filter_0601/index.jsp">OurBoard</a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="/filter_0601/index.jsp">Home</a></li> <li><a href="/filter_0601/about.jsp">About</a></li> <li><a href="/filter_0601/board.jsp">Board</a></li> <li><a href="/filter_0601/lecture.jsp">Lecture</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="/filter_0601/login.jsp"><span class="glyphicon glyphicon-log-in"></span> Login</a></li> </ul> </div> </div> </nav> <div class="container-fluid text-center"> <div class="row content"> <div class="col-sm-2 sidenav"> <!-- 비워둠 --> </div> <div class="col-sm-8 text-center"> <div class="login" style="margin-top:100px"> <h1>LOGIN</h1> <form action="/filter_0601/LoginAction" method="get"> <table width="200px" align="center"> <tr> <td>ID: <input type="text" size="10" name="inputid" value="<%=rememberid%>"></td> </tr> <tr> <td>pw: <input type="password" size="10" name="inputpw"><br><br> </td> </tr> </table> <input type="checkbox" name="remember" <%=chk %>>remember this ID <input type="hidden" name="from" value="<%=from%>"><%--공갈용 --%> &nbsp;&nbsp;<input type="submit" value="login"> </form> </div> </div> <div class="col-sm-2 sidenav"> <div class="well"> <p>ADS</p> </div> <div class="well"> <p>ADS</p> </div> </div> </div> </div> <footer class="container-fluid text-center"> <jsp:include page="inc/footer.jsp"></jsp:include> </footer> </body> </html>
import { useState } from 'react' import Botao from '../Botao' import CampoTexto from '../CampoTexto' import ListaSuspensa from '../ListaSuspensa' import './Formulario.css' const Formulario = (props) => { const [nome, setNome] = useState('') const [posicao, setPosicao] = useState('') const [timeAtual, setTimeAtual] = useState('') const [imagem, setImagem] = useState('') const [times, setTime] = useState('') const aoSalvar = (evento) => { evento.preventDefault() props.aoColaboradorCadastrado({ nome, posicao, timeAtual, imagem }) setNome('') setPosicao('') setTimeAtual('') setImagem('') } return ( <section className='formulario'> <form onSubmit={aoSalvar}> <h2>Preencha os dados para criar o card</h2> <CampoTexto label="Nome" obrigatorio={true} placeholder="Digite o nome" valor={nome} aoAlterado={valor => setNome(valor)}/> <CampoTexto label="Posicao" obrigatorio={true} placeholder="Digite a posicao" valor={posicao} aoAlterado={valor => setPosicao(valor)} /> <CampoTexto label="Time atual" obrigatorio={true} placeholder="Digite o time atual" valor={timeAtual} aoAlterado={valor => setTimeAtual(valor)} /> <CampoTexto label="Imagem" placeholder="Digite o endereco da imagem" valor={imagem} aoAlterado={valor => setImagem(valor)} /> <ListaSuspensa label="Times" obrigatorio={true} itens={props.times.sort()} valor={times} aoAlterado={valor => setTime(valor)}/> <Botao> Criar card </Botao> </form> </section> ) } export default Formulario
<?php declare(strict_types=1); namespace App\Http\Requests\Event; use Illuminate\Foundation\Http\FormRequest; class EventStoreRequest extends FormRequest { /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string> */ public function rules(): array { return [ 'name'=> ['required', 'string', 'min:3', 'max:500'], 'description'=> ['required', 'string', 'min:3', 'max:5000'], 'start_time'=> ['required', 'string', 'min:3', 'max:500'], 'end_time'=> ['required', 'string', 'min:3', 'max:500'], 'location'=> ['required', 'string', 'min:3', 'max:500'], 'image'=> ['required', 'string', 'min:3', 'max:500'], 'url'=> ['required', 'string', 'min:3', 'max:500'], 'user_id' => ['exists:users,id'], ]; } }
import { FC } from 'react'; import { ClientRoleSelectorProps } from '@/modules/client/client-role-selector.interface'; import Button from '@mui/material/Button'; import Icon from '@mui/material/Icon'; import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import ListItemText from '@mui/material/ListItemText'; import { getContainer } from '@agros/core'; import { LocaleService } from '@modules/locale/locale.service'; import _ from 'lodash'; import { PopoverProps } from '@modules/common/popover.interface'; import { PopoverComponent } from '@modules/common/popover.component'; import useTheme from '@mui/material/styles/useTheme'; const ClientRoleSelector: FC<ClientRoleSelectorProps> = ({ role, triggerProps = {}, popoverProps = {}, listItemButtonProps, onRoleChange = _.noop, }) => { const container = getContainer(ClientRoleSelector); const localeService = container.get<LocaleService>(LocaleService); const Popover = container.get<FC<PopoverProps>>(PopoverComponent); const theme = useTheme(); const getLocaleText = localeService.useLocaleContext('components.clientRoleSelector'); return ( <Popover variant="menu" Trigger={({ open, openPopover }) => { return ( <Button variant="text" endIcon={<Icon className={`icon-chevron-${open ? 'up' : 'down'}`} />} {...triggerProps} sx={{ ...(open ? { backgroundColor: theme.palette.mode === 'dark' ? theme.palette.grey[700] : theme.palette.grey[300], } : {}), }} onClick={(event) => { event.stopPropagation(); openPopover(event); }} >{getLocaleText(`roles[${role}]`) || getLocaleText('unknown')}</Button> ); }} muiPopoverProps={{ ...popoverProps, onBackdropClick: (event) => event.stopPropagation(), }} > { ({ closePopover }) => { return ( <> { new Array(2).fill(null).map((value, index) => { const currentRole = index + 1; return ( <ListItemButton key={index} selected={currentRole === role} { ...( listItemButtonProps ? typeof listItemButtonProps === 'function' ? listItemButtonProps(role, currentRole === role) : listItemButtonProps : {} ) } onClick={(event) => { event.stopPropagation(); onRoleChange(currentRole); closePopover(); }} > <ListItemIcon> { currentRole === role && <Icon className="icon-check" /> } </ListItemIcon> <ListItemText primaryTypographyProps={{ noWrap: true, style: { minWidth: 64, maxWidth: 120, }, }} >{getLocaleText(`roles[${currentRole}]`)}</ListItemText> </ListItemButton> ); }) } </> ); } } </Popover> ); }; export default ClientRoleSelector;
import { HttpClient } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-update-profile', templateUrl: './update-profile.component.html', styleUrl: './update-profile.component.css', }) export class UpdateProfileComponent implements OnInit { user: any = {}; formData: any = { username: '', profilePicUrl: '', phoneNo: '', }; userEmail: String | null = null; error: string = ''; bookings: any[] = []; constructor(private http: HttpClient) {} ngOnInit(): void { this.userEmail = sessionStorage.getItem('userEmail'); this.getUserDetails(this.userEmail); } handleChange(event: any): void { const { name, value } = event.target; this.formData[name] = value; } getAllBookings(): void { if (!this.user?._id) { // If userData or _id is not available, return return; } const url = `http://localhost:80/api/bookings/${this.user._id}`; this.http.get<any[]>(url).subscribe( (resData) => { this.bookings = resData; }, (error) => { console.error('Error fetching bookings:', error); } ); } // Get user Details getUserDetails(email: any): void { if (!email) { return; } const url = `http://localhost:80/api/user/${email}`; this.http.get(url).subscribe( (response: any) => { this.user = response; }, (error) => { console.error('Error fetching user details:', error); } ); } setUserDetails(): void { this.formData = { username: this.user?.username, profilePicUrl: this.user?.profilePicUrl, phoneNo: this.user?.phoneNo, }; } updateUserData(): void { const url = `http://localhost:80/api/user/${this.user?._id}`; this.http.put(url, this.formData).subscribe( (resData: any) => { alert(resData.message); }, (error) => { console.error('Error during updating the user:', error); this.error = 'An error occurred during updating the user: ' + error.message; } ); } }