text
stringlengths
184
4.48M
# TypeScript TypeScript에 대한 자세한 기초 내용은 아래에서 확인하기 [👉 타입스크립트로 블록체인 만들기](/TypeScript/01_타입스크립트로_블록체인_만들기/00_목차.md) ## Introduction 타입스크립트는 strongly-typed 언어이다. strongly-typed 란, **프로그래밍 언어가 작동하기 전에 type을 확인한다는 것이다.** 타입스크립트를 작성하면 자바스크립코드로 return 된다. ## Definitely Typed [🔗 Adding TypeScript(CRA)](https://create-react-app.dev/docs/adding-typescript/) 기존의 리액트 프로젝트에 타입스크립트 추가하기 ```npm npm install --save typescript @types/node @types/react @types/react-dom @types/jest ``` > [!CAUTION] > 에러가 났다면 다음과 같이 실행하자.<br> 1. npm install --save typescript @types/node @types/react @types/react-dom @types/jest<br> 2. src 폴더 안에 있던 App.js와 index.js 파일을 App.tsx와 index.tsx 로 바꾼다.<br> 3. "npx tsc --init" 명령어로 tsconfig.json 파일 생성한 후, tsconfig.json 파일에 "jsx": "react-jsx"추가<br> -------------------------------------------<br> {<br> "compilerOptions": {<br> ......<br> "jsx": "react-jsx"<br> }<br> }<br> -------------------------------------------<br> 4. src/index.tsx에서 수정<br> --------------------------------------------------------------<br> import ReactDOM from "react-dom/client"<br> const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);<br> 5. npm i --save-dev @types/styled-components ### @types 는 무엇일까? `@types`는 **아주 큰 Github Repository** 로, **모든 유명한 npm 라이브러리를 가지고 있는 저장소**이다. 여기서 *라이브러리나 패키지의 type definition을 알려준다.* ## Typing the Props 어떻게 component가 필요로 하는 prop을 TypeScript에게 설명할 수 있는지를 알아보자. ### Prop Types - prop이 해당 위치에 존재하는지 확인해 준다. - 브라우저의 콘솔에 경고표시를 해준다. - 코드를 실행한 '후'에만 확인이 가능하다. - 우리가 TypeScript를 사용하는 이유는 코드를 실행하기 전에 오류를 확인하기 위해서이다. - 그래서 우리는 Prop Types을 사용하지 않을 것이다. - 대신, 우리의 prop들을 TypeScript로 보호해줄 것이다. > App.tsx Component에 prop을 보낸다. ```typescript import Circle from './Circle'; function App() { return ( <div> <Circle bgColor="teal" /> <Circle bgColor="tomato" /> </div> ); } export default App; ``` > Circle.tsx - Circle : 인터페이스를 통해 object 모양을 잡아주고 App에서 보낸 prop을 받는다. - Circle : styled-component에 prop을 넘겨준다. - Container : 인터페이스를 통해 object 모양을 잡아주고 component에서 보낸 prop을 받아서 style에 적용한다. ```typescript import styled from 'styled-components' interface ContainerProps { bgColor:string; } const Container = styled.div<ContainerProps>` width: 200px; height: 200px; background-color: ${(props) => props.bgColor}; border-radius: 100px; `; interface CircleProps { bgColor:string; } function Circle({bgColor}:CircleProps){ return <Container bgColor={bgColor} /> } export default Circle; ``` ## Optional Props > App.tsx ```typescript import Circle from './Circle'; function App() { return ( <div> <Circle borderColor="yellow" bgColor="teal" /> <Circle text="hi text" bgColor="tomato" /> </div> ); } export default App; ``` > Circle.tsx - `?`를 통해 옵션여부를 설정할 수 있다. - `borderColor={borderColor ?? bgColor}>` 와 같이 `undefined`일 경우 넣어줄 값을 설정해줄 수 있다. - `text = "default text"`처럼 값을 넣어주지 않을 때 기본값을 설정할 수 있다(이건 타입스크립트가 아닌 ES6 JS) ```typescript import styled from 'styled-components' interface ContainerProps { bgColor:string; borderColor: string; } const Container = styled.div<ContainerProps>` width: 200px; height: 200px; background-color: ${(props) => props.bgColor}; border-radius: 100px; border: 2px solid ${(props) => props.borderColor}; `; interface CircleProps { bgColor:string; borderColor?:string; text?:string; } function Circle({bgColor, borderColor, text = "default text"}:CircleProps){ return ( <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}> {text} </Container> ) } export default Circle; ``` ## State - useState()에 값을 넣으면 타입스크립트에서 타입을 추론해서 설정해준다. ```typescript const [counter, setCounter] = useState(0); setCounter("heelo") // error : counter는 number type이기 때문. ``` ## Forms > App.tsx - `event`로만 작성하면 데이터 타입이 `any`가 된다. any는 최대한 배제해야 함으로 정확한 데이터 타입 작성을 해야한다. ```typescript import { useState } from 'react'; function App() { const [value, setValue] = useState(""); const onChange = (event: React.FormEvent<HTMLInputElement>) => { const { currentTarget: {value}, } = event; setValue(value); }; const onSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); console.log("hello", value); }; return ( <div> <form onSubmit={onSubmit}> <input value={value} onChange={onChange} type="text" placeholder="username"/> <button>Log In</button> </form> </div> ); } export default App; ``` ## Themes [🔗 styled-componnets_typescript](https://styled-components.com/docs/api#typescript) 1. styled.d.ts 파일 생성하기 2. 위의 링크에서 아래의 코드 복사해서 붙여넣기 ```typescript // import original module declarations import 'styled-components'; // and extend them! declare module 'styled-components' { export interface DefaultTheme { borderRadius: string; colors: { main: string; secondary: string; }; } } ``` 1. DefaultTheme 아래와 같이 수정하기 ```typescript declare module 'styled-components' { export interface DefaultTheme { textColor:string; bgColor:string; } ``` 3. theme.ts 파일 생성하고 아래와 같이 작성하기 - 이때 테마는 styled.d.ts 파일 속 속성들하고 동일해야 한다. ```typescript import { DefaultTheme } from 'styled-components/dist/types'; export const lightTheme:DefaultTheme = { bgColor:"white", textColor:"balck", btnColor:"tomato", } export const darkTheme:DefaultTheme = { bgColor:"balck", textColor:"white", btnColor:"teal", } ``` 4. index.tsx에서 ThemeProvider를 import 해주고 아래와 같이 작성하기 ```typescript import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import { ThemeProvider } from 'styled-components'; import { lightTheme } from './theme'; const root = ReactDOM.createRoot(document.getElementById('root')as HTMLElement); root.render( <React.StrictMode> <ThemeProvider theme={lightTheme}> <App /> </ThemeProvider> </React.StrictMode> ); ``` 5. App.tsx에 다음과 같이 작성하기 ```typescript import styled from 'styled-components'; function App() { const Container = styled.div` background-color: ${(props) => props.theme.bgColor}; `; const H1 = styled.h1` color:${(props) => props.theme.textColor}; `; return ( <Container> <H1>protected</H1> </Container> ); } export default App; ``` ## Recap
/** * Estimates the number of tokens in a text according to the formula * characters * (1 / e) + safteyMargin(characters) where e is the base of the natural logarithm * and safteyMargin is a linear function of the number of characters. * * The formula is based on the stackoverflow answer https://stackoverflow.com/a/76416463 * * @param {string} text - The text to estimate the number of tokens for * @returns Estimated number of tokens */ export function estimateTokenCount(text: string) : number { const characters = text.length; return characters * 0.36787944117 + safteyMargin(characters); } /** * Linearly increasing saftey margin from 2 to 10 tokens for 1 to 2000 characters. * @param {number} characters - The number of characters in the text to estimate the saftey margin for * @returns saftey margin for the given number of characters */ function safteyMargin(characters: number) : number { return Math.round(characters * 0.004 + 2); }
usage: polygraphy convert [-h] [-v] [-q] [--silent] [--log-format {timestamp,line-info,no-colors} [{timestamp,line-info,no-colors} ...]] [--log-file LOG_FILE] [--model-type {frozen,keras,ckpt,onnx,engine,uff,trt-network-script,caffe}] [--input-shapes INPUT_SHAPES [INPUT_SHAPES ...]] [--ckpt CKPT] [--tf-outputs TF_OUTPUTS [TF_OUTPUTS ...]] [--freeze-graph] [--opset OPSET] [--no-const-folding] [--shape-inference] [--external-data-dir LOAD_EXTERNAL_DATA] [--onnx-outputs ONNX_OUTPUTS [ONNX_OUTPUTS ...]] [--onnx-exclude-outputs ONNX_EXCLUDE_OUTPUTS [ONNX_EXCLUDE_OUTPUTS ...]] [--save-external-data [SAVE_EXTERNAL_DATA]] [--external-data-size-threshold EXTERNAL_DATA_SIZE_THRESHOLD] [--no-save-all-tensors-to-one-file] [--seed SEED] [--val-range VAL_RANGE [VAL_RANGE ...]] [--int-min INT_MIN] [--int-max INT_MAX] [--float-min FLOAT_MIN] [--float-max FLOAT_MAX] [--iterations NUM] [--load-inputs LOAD_INPUTS [LOAD_INPUTS ...]] [--data-loader-script DATA_LOADER_SCRIPT] [--data-loader-func-name DATA_LOADER_FUNC_NAME] [--trt-min-shapes TRT_MIN_SHAPES [TRT_MIN_SHAPES ...]] [--trt-opt-shapes TRT_OPT_SHAPES [TRT_OPT_SHAPES ...]] [--trt-max-shapes TRT_MAX_SHAPES [TRT_MAX_SHAPES ...]] [--tf32] [--fp16] [--int8] [--obey-precision-constraints] [--strict-types] [--sparse-weights] [--workspace BYTES] [--calibration-cache CALIBRATION_CACHE] [--calib-base-cls CALIBRATION_BASE_CLASS] [--quantile QUANTILE] [--regression-cutoff REGRESSION_CUTOFF] [--timing-cache TIMING_CACHE] [--tactic-replay TACTIC_REPLAY | --save-tactics SAVE_TACTICS | --load-tactics LOAD_TACTICS] [--tactic-sources [TACTIC_SOURCES [TACTIC_SOURCES ...]]] [--trt-config-script TRT_CONFIG_SCRIPT] [--trt-config-func-name TRT_CONFIG_FUNC_NAME] [--trt-safety-restricted] [--use-dla] [--allow-gpu-fallback] [--plugins PLUGINS [PLUGINS ...]] [--explicit-precision] [--trt-outputs TRT_OUTPUTS [TRT_OUTPUTS ...]] [--trt-exclude-outputs TRT_EXCLUDE_OUTPUTS [TRT_EXCLUDE_OUTPUTS ...]] [--trt-network-func-name TRT_NETWORK_FUNC_NAME] -o OUTPUT [--convert-to {onnx,trt,onnx-like-trt-network}] [--fp-to-fp16] model_file Convert models to other formats. optional arguments: -h, --help show this help message and exit -o OUTPUT, --output OUTPUT Path to save the converted model --convert-to {onnx,trt,onnx-like-trt-network} The format to attempt to convert the model to.'onnx- like-trt-network' is EXPERIMETNAL and converts a TensorRT network to a format usable for visualization. See 'OnnxLikeFromNetwork' for details. Logging: Options for logging and debug output -v, --verbose Increase logging verbosity. Specify multiple times for higher verbosity -q, --quiet Decrease logging verbosity. Specify multiple times for lower verbosity --silent Disable all output --log-format {timestamp,line-info,no-colors} [{timestamp,line-info,no-colors} ...] Format for log messages: {{'timestamp': Include timestamp, 'line-info': Include file and line number, 'no-colors': Disable colors}} --log-file LOG_FILE Path to a file where Polygraphy logging output should be written. This will not include logging output from dependencies, like TensorRT or ONNX-Runtime. Model: Options for the model model_file Path to the model --model-type {frozen,keras,ckpt,onnx,engine,uff,trt-network-script,caffe} The type of the input model: {{'frozen': TensorFlow frozen graph, 'keras': Keras model, 'ckpt': TensorFlow checkpoint directory, 'onnx': ONNX model, 'engine': TensorRT engine, 'trt-network-script': A Python script that defines a `load_network` function that takes no arguments and returns a TensorRT Builder, Network, and optionally Parser, 'uff': UFF file [deprecated], 'caffe': Caffe prototxt [deprecated]}} --input-shapes INPUT_SHAPES [INPUT_SHAPES ...], --inputs INPUT_SHAPES [INPUT_SHAPES ...] Model input(s) and their shape(s). Used to determine shapes to use while generating input data for inference. Format: --input-shapes <name>:<shape>. For example: --input-shapes image:[1,3,224,224] other_input:[10] TensorFlow Loader: Options for TensorFlow Loader --ckpt CKPT [EXPERIMENTAL] Name of the checkpoint to load. Required if the `checkpoint` file is missing. Should not include file extension (e.g. to load `model.meta` use `--ckpt=model`) --tf-outputs TF_OUTPUTS [TF_OUTPUTS ...] Name(s) of TensorFlow output(s). Using '--tf-outputs mark all' indicates that all tensors should be used as outputs --freeze-graph [EXPERIMENTAL] Attempt to freeze the graph TensorFlow-ONNX Loader: Options for TensorFlow-ONNX conversion --opset OPSET Opset to use when converting to ONNX --no-const-folding Do not fold constants in the TensorFlow graph prior to conversion ONNX Shape Inference: Options for ONNX Shape Inference --shape-inference Enable ONNX shape inference when loading the model ONNX Loader: Options for the ONNX Loader --external-data-dir LOAD_EXTERNAL_DATA, --load-external-data LOAD_EXTERNAL_DATA, --ext LOAD_EXTERNAL_DATA Path to a directory containing external data for the model. Generally, this is only required if the external data is not stored in the model directory. --onnx-outputs ONNX_OUTPUTS [ONNX_OUTPUTS ...] Name(s) of ONNX tensor(s) to mark as output(s). Using the special value 'mark all' indicates that all tensors should be used as outputs --onnx-exclude-outputs ONNX_EXCLUDE_OUTPUTS [ONNX_EXCLUDE_OUTPUTS ...] [EXPERIMENTAL] Name(s) of ONNX output(s) to unmark as outputs. --fp-to-fp16 Convert all floating point tensors in an ONNX model to 16-bit precision. This is *not* needed in order to use TensorRT's fp16 precision, but may be useful for other backends. Requires onnxmltools. ONNX Save Options: Options for saving ONNX models --save-external-data [SAVE_EXTERNAL_DATA] Whether to save weight data in external file(s). To use a non-default path, supply the desired path as an argument. This is always a relative path; external data is always written to the same directory as the model. --external-data-size-threshold EXTERNAL_DATA_SIZE_THRESHOLD The size threshold, in bytes, above which tensor data will be stored in the external file. Tensors smaller that this threshold will remain in the ONNX file. Optionally, use a `K`, `M`, or `G` suffix to indicate KiB, MiB, or GiB respectively. For example, `--external-data-size-threshold=16M` is equivalent to `--external-data-size-threshold=16777216`. Has no effect if `--save-external-data` is not set. --no-save-all-tensors-to-one-file Do not save all tensors to a single file when saving external data. Has no effect if `--save-external-data` is not set Data Loader: Options for controlling how input data is loaded or generated --seed SEED Seed to use for random inputs --val-range VAL_RANGE [VAL_RANGE ...] Range of values to generate in the data loader. To specify per-input ranges, use the format: --val-range <input_name>:[min,max]. If no input name is provided, the range is used for any inputs not explicitly specified. For example: --val-range [0,1] inp0:[2,50] inp1:[3.0,4.6] --int-min INT_MIN [DEPRECATED: Use --val-range] Minimum integer value for random integer inputs --int-max INT_MAX [DEPRECATED: Use --val-range] Maximum integer value for random integer inputs --float-min FLOAT_MIN [DEPRECATED: Use --val-range] Minimum float value for random float inputs --float-max FLOAT_MAX [DEPRECATED: Use --val-range] Maximum float value for random float inputs --iterations NUM, --iters NUM Number of inference iterations for which to supply data --load-inputs LOAD_INPUTS [LOAD_INPUTS ...], --load-input-data LOAD_INPUTS [LOAD_INPUTS ...] [EXPERIMENTAL] Path(s) to load inputs. The file(s) should be a JSON-ified List[Dict[str, numpy.ndarray]], i.e. a list where each element is the feed_dict for a single iteration. Other data loader options are ignored when this option is used --data-loader-script DATA_LOADER_SCRIPT Path to a Python script that defines a function that loads input data. The function should take no arguments and return a generator or iterable that yields input data (Dict[str, np.ndarray]). When this option is specified, all other data loader arguments are ignored. --data-loader-func-name DATA_LOADER_FUNC_NAME When using a data-loader-script, this specifies the name of the function that loads data. Defaults to `load_data`. TensorRT Builder Configuration: Options for TensorRT Builder Configuration --trt-min-shapes TRT_MIN_SHAPES [TRT_MIN_SHAPES ...] The minimum shapes the optimization profile(s) will support. Specify this option once for each profile. If not provided, inference-time input shapes are used. Format: --trt-min-shapes <input0>:[D0,D1,..,DN] .. <inputN>:[D0,D1,..,DN] --trt-opt-shapes TRT_OPT_SHAPES [TRT_OPT_SHAPES ...] The shapes for which the optimization profile(s) will be most performant. Specify this option once for each profile. If not provided, inference-time input shapes are used. Format: --trt-opt-shapes <input0>:[D0,D1,..,DN] .. <inputN>:[D0,D1,..,DN] --trt-max-shapes TRT_MAX_SHAPES [TRT_MAX_SHAPES ...] The maximum shapes the optimization profile(s) will support. Specify this option once for each profile. If not provided, inference-time input shapes are used. Format: --trt-max-shapes <input0>:[D0,D1,..,DN] .. <inputN>:[D0,D1,..,DN] --tf32 Enable tf32 precision in TensorRT --fp16 Enable fp16 precision in TensorRT --int8 Enable int8 precision in TensorRT. If calibration is required but no calibration cache is provided, this option will cause TensorRT to run int8 calibration using the Polygraphy data loader to provide calibration data. --obey-precision-constraints Enable enforcing precision constraints in TensorRT, forcing it to use tactics based on the layer precision set, even if another precision is faster. Build fails if such an engine cannot be built. --strict-types [DEPRECATED] Enable preference for precision constraints and avoidance of I/O reformatting in TensorRT, and fall back to ignoring the request if such an engine cannot be built. --sparse-weights Enable optimizations for sparse weights in TensorRT --workspace BYTES Amount of memory, in bytes, to allocate for the TensorRT builder's workspace. Optionally, use a `K`, `M`, or `G` suffix to indicate KiB, MiB, or GiB respectively. For example, `--workspace=16M` is equivalent to `--workspace=16777216`. --calibration-cache CALIBRATION_CACHE Path to load/save a calibration cache. Used to store calibration scales to speed up the process of int8 calibration. If the provided path does not yet exist, int8 calibration scales will be calculated and written to it during engine building. If the provided path does exist, it will be read and int8 calibration will be skipped during engine building. --calib-base-cls CALIBRATION_BASE_CLASS, --calibration-base-class CALIBRATION_BASE_CLASS The name of the calibration base class to use. For example, 'IInt8MinMaxCalibrator'. --quantile QUANTILE The quantile to use for IInt8LegacyCalibrator. Has no effect for other calibrator types. --regression-cutoff REGRESSION_CUTOFF The regression cutoff to use for IInt8LegacyCalibrator. Has no effect for other calibrator types. --timing-cache TIMING_CACHE Path to load/save tactic timing cache. Used to cache tactic timing information to speed up the engine building process. Existing caches will be appended to with any new timing information gathered. --tactic-replay TACTIC_REPLAY [DEPRECATED - use --load/save-tactics] Path to load/save a tactic replay file. Used to record and replay tactics selected by TensorRT to provide deterministic engine builds. If the provided path does not yet exist, tactics will be recorded and written to it. If the provided path does exist, it will be read and used to replay previously recorded tactics. --save-tactics SAVE_TACTICS Path to save a Polygraphy tactic replay file. Details about tactics selected by TensorRT will be recorded and stored at this location as a JSON file. --load-tactics LOAD_TACTICS Path to load a Polygraphy tactic replay file, such as one created by --save-tactics. The tactics specified in the file will be used to override TensorRT's default selections. --tactic-sources [TACTIC_SOURCES [TACTIC_SOURCES ...]] Tactic sources to enable. This controls which libraries (e.g. cudnn, cublas, etc.) TensorRT is allowed to load tactics from. Values come from the names of the values in the trt.TacticSource enum, and are case-insensitive. If no arguments are provided, e.g. '--tactic-sources', then all tactic sources are disabled. --trt-config-script TRT_CONFIG_SCRIPT Path to a Python script that defines a function that creates a TensorRT IBuilderConfig. The function should take a builder and network as parameters and return a TensorRT builder configuration. When this option is specified, all other config arguments are ignored. --trt-config-func-name TRT_CONFIG_FUNC_NAME When using a trt-config-script, this specifies the name of the function that creates the config. Defaults to `load_config`. --trt-safety-restricted Enable safety scope checking in TensorRT --use-dla [EXPERIMENTAL] Use DLA as the default device type --allow-gpu-fallback [EXPERIMENTAL] Allow layers unsupported on the DLA to fall back to GPU. Has no effect if --dla is not set. TensorRT Plugin Loader: Options for TensorRT Plugin Loader --plugins PLUGINS [PLUGINS ...] Path(s) of plugin libraries to load TensorRT Network Loader: Options for TensorRT Network Loader --explicit-precision Enable explicit precision mode --trt-outputs TRT_OUTPUTS [TRT_OUTPUTS ...] Name(s) of TensorRT output(s). Using '--trt-outputs mark all' indicates that all tensors should be used as outputs --trt-exclude-outputs TRT_EXCLUDE_OUTPUTS [TRT_EXCLUDE_OUTPUTS ...] [EXPERIMENTAL] Name(s) of TensorRT output(s) to unmark as outputs. --trt-network-func-name TRT_NETWORK_FUNC_NAME When using a trt-network-script instead of other model types, this specifies the name of the function that loads the network. Defaults to `load_network`.
import { DartHitEvent, dartHitEventToPoints, DartHitKind, multiplierToDisplayString, scoreAreaToString } from '@/lib/dart-types'; import { Flex } from '@chakra-ui/react'; export type DartHitDisplayProps = { event?: DartHitEvent; hidePoints?: boolean; sx?: object; }; export default function DartHitDisplay( props: DartHitDisplayProps ): JSX.Element { // Dart display const dartDisplayStyles = { '.multiplier': { color: 'var(--bright-text-color)', fontSize: '1rem' }, '.scoreArea': { color: 'var(--bright-text-color)', fontSize: '1.5rem', fontWeight: 'bold' } }; let dartDisplay: JSX.Element = undefined; if (props.event) { if (props.event.kind === DartHitKind.Miss) { dartDisplay = ( <Flex sx={dartDisplayStyles}> <p className='scoreArea'>Miss</p> </Flex> ); } else if (props.event.kind === DartHitKind.BounceOut) { dartDisplay = ( <Flex sx={dartDisplayStyles}> <p className='scoreArea'>BO</p> </Flex> ); } else { const multDispStr = multiplierToDisplayString(props.event.multiplier); const scoreAreaStr = scoreAreaToString(props.event.scoreArea); dartDisplay = ( <Flex sx={dartDisplayStyles} alignItems='baseline'> <p className='multiplier'>{multDispStr}</p> <p className='scoreArea'>{scoreAreaStr}</p> </Flex> ); } } // Points display let pointsDisplay: JSX.Element = undefined; if (!props.hidePoints) { if (props.event) { const pointsStr = `${dartHitEventToPoints(props.event)}`; pointsDisplay = ( <Flex justifyContent='center' alignItems='center' lineHeight='0.2rem' paddingBottom='0.8rem' sx={{ '.points': { color: 'var(--middle-text-color)' } }} > <p className='points'>{pointsStr}</p> </Flex> ); } } return ( <Flex direction='column' alignItems='center' sx={props.sx}> {dartDisplay} {pointsDisplay} </Flex> ); }
import React, { useState } from 'react'; import { DatePickerIOS } from '@react-native-community/datetimepicker'; import { format } from 'date-fns'; import pt from 'date-fns/locale/pt'; import Icon from 'react-native-vector-icons/MaterialIcons'; import { Container, DateButton, DateText, Picker } from './styles'; export default function DateInput({ date, onChange }) { const { opened, setOpened } = useState(false); const dateFormatted = useMemo( () => format(date, "dd 'de' MMMM 'de' yyyy", { locale: pt }), [date] ) return ( <Container> <DateButton onPress={() => setOpened(!opened)}> <Icon name="event" color="#fff" size={20} /> <DateText>{dateFormatted} </DateText> </DateButton> {opened && ( <Picker> <DatePickerIOS Date={date} onDateChange={onChange} minimumDate={new Date()} minuteInterval={60} local="pt" mode="date" /> </Picker> )} </Container> ); }
import React, { useState, useEffect } from "react"; import { Editor } from "@tinymce/tinymce-react"; import { Controller } from "react-hook-form"; import conf from "../conf/conf"; import { Popover, PopoverTrigger, PopoverContent, Button, } from "@nextui-org/react"; const RTE = ({ name, control, label, defaultValue = "" }) => { const [characterCount, setCharacterCount] = useState(defaultValue.length); const [componentsLoaded, setComponentsLoaded] = useState(false); useEffect(() => { // Check if Controller and Editor are loaded if (control && defaultValue !== "") { setComponentsLoaded(true); } }, [control, defaultValue]); const handleEditorChange = (content, editor) => { const newCharacterCount = content.length; setCharacterCount(newCharacterCount); }; return ( <div className="w-full relative"> {label && <label className="inline-block mb-1 pl-1">{label}</label>} <Controller name={name || "content"} control={control} defaultValue={defaultValue} render={({ field: { onChange } }) => ( <Editor apiKey={import.meta.env.VITE_TINYMCE_API_KEY} initialValue={defaultValue} init={{ height: 500, menubar: true, plugins: [ "letters", "image", "advlist", "autolink", "lists", "link", "image", "charmap", "preview", "anchor", "searchreplace", "visualblocks", "code", "fullscreen", "insertdatetime", "media", "table", "code", "help", "wordcount", "anchor", ], toolbar: "letters | undo redo | blocks | image | bold italic forecolor | alignleft aligncenter bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent |removeformat | help", content_style: "body { font-family: Helvetica, Arial, sans-serif; font-size: 14px }", }} onInit={() => setComponentsLoaded(true)} // Editor loaded callback onEditorChange={(content, editor) => { onChange(content); // Update react-hook-form value handleEditorChange(content, editor); // Update character count }} /> )} /> {componentsLoaded && ( <> <p className={`absolute top-8 w-[20%] text-center right-2 ${ characterCount > 1500 ? "text-red-500 border-red-500" : "text-[#222f3e]" } text-base font-medium border-1 border-solid px-2 border-[#e3e3e3] z-50`} > {characterCount > 1500 ? "!" : ""} {characterCount} / 1500 </p> <div className={`bg-red-100 border flex flex-col text-center left-[50%] -translate-x-[50%] border-red-400 absolute top-32 text-red-700 transition-transform duration-500 ease-in-out-quad px-4 py-3 rounded ${ characterCount > 1500 ? "translate-y-0" : "-translate-y-24" } `} role="alert" > <strong className="font-bold">Warning!!</strong> <span className="block sm:inline"> Character count exceeds 1500 </span> </div> </> )} </div> ); }; export default React.memo(RTE);
import React from 'react'; import clsx from 'clsx'; import { Avatar as DefaultAvatar } from '../Avatar'; import { useComponentContext } from '../../context/ComponentContext'; import { useMessageContext } from '../../context/MessageContext'; import { useTranslationContext } from '../../context/TranslationContext'; import { useChannelActionContext } from '../../context/ChannelActionContext'; import type { DefaultOneChatGenerics, TranslationLanguages } from '../../types'; export const QuotedMessage = < OneChatGenerics extends DefaultOneChatGenerics = DefaultOneChatGenerics >() => { const { Attachment, Avatar: ContextAvatar } = useComponentContext<OneChatGenerics>( 'QuotedMessage', ); const { isMyMessage, message } = useMessageContext<OneChatGenerics>('QuotedMessage'); const { t, userLanguage } = useTranslationContext('QuotedMessage'); const { jumpToMessage } = useChannelActionContext('QuotedMessage'); const Avatar = ContextAvatar || DefaultAvatar; const { quoted_message } = message; if (!quoted_message) return null; const quotedMessageDeleted = quoted_message.deleted_at || quoted_message.type === 'deleted'; const quotedMessageText = quotedMessageDeleted ? t('This message was deleted...') : quoted_message.i18n?.[`${userLanguage}_text` as `${TranslationLanguages}_text`] || quoted_message.text; const quotedMessageAttachment = quoted_message.attachments?.length && !quotedMessageDeleted ? quoted_message.attachments[0] : null; if (!quotedMessageText && !quotedMessageAttachment) return null; return ( <> <div className={clsx('str-chat__quoted-message-preview quoted-message', { mine: isMyMessage() })} data-testid='quoted-message' onClickCapture={(e) => { e.stopPropagation(); e.preventDefault(); jumpToMessage(quoted_message.id); }} > {quoted_message.user && ( <Avatar image={quoted_message.user.image} name={quoted_message.user.name || quoted_message.user.id} size={20} user={quoted_message.user} /> )} <div className='quoted-message-inner str-chat__quoted-message-bubble' data-testid='quoted-message-contents' > {quotedMessageAttachment && <Attachment attachments={[quotedMessageAttachment]} />} <div data-testid='quoted-message-text'>{quotedMessageText}</div> </div> </div> {message.attachments?.length ? <Attachment attachments={message.attachments} /> : null} </> ); };
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract FundMe { AggregatorV3Interface internal priceFeed; mapping(address => uint256) public addressToAmountFunded; address[] funders; address public owner; uint256 minimumUsd = 50; constructor() { // Kovan address priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); owner = msg.sender; } function fund() public payable { uint256 _minimunUsd = minimumUsd * 10 ** 18; require(getConversionRate(msg.value) >= _minimunUsd, "You need to spend more ETH!"); addressToAmountFunded[msg.sender] += msg.value; funders.push(msg.sender); } function getPrice() public view returns (uint256){ (,int price,,,) = priceFeed.latestRoundData(); return uint256(price * 10 ** 10 ); } function getConversionRate(uint256 ethAmount) public view returns (uint256) { uint256 ethPrice = getPrice(); uint256 ethAmountInUsd = (ethPrice * ethAmount) / (10 * 10 ** 18 ); return ethAmountInUsd; } modifier onlyOwner { require(msg.sender == owner, "Only Owner can call this function"); _; } function withdraw() payable onlyOwner public { payable(msg.sender).transfer(address(this).balance); // set mappings to 0 for (uint256 funderIndex=0; funderIndex < funders.length; funderIndex++) { address funder = funders[funderIndex]; addressToAmountFunded[funder] = 0; } funders = new address[](0); } function setMinimum(uint256 _minimumAmount) public onlyOwner { minimumUsd = _minimumAmount; } }
// // WeatherManager.swift // Clima // // Created by Stewart Clay on 2022/09/04. // Copyright © 2022 App Brewery. All rights reserved. // import Foundation import CoreLocation //Weather Delegate protocol DailyWeatherManagerDelegate { func didUpdateWeather(_ DailyWeatherManager: DailyWeatherManager, dailyWeather: DailyWeatherModel) func didFailWithError(error: Error) } struct DailyWeatherManager { let weatherURL = "https://api.openweathermap.org/data/2.5/forecast?appid=f468ed161a9fbfaa134527067d0b0c20&units=metric" var delegate: DailyWeatherManagerDelegate? let dateFormatter = DateFormatter() //Fetch Weather based on city name func fetchWeather(cityName: String) { let urlString = "\(weatherURL)&q=\(cityName)" performRequest(with: urlString) } //Fetch Weather based on longitude and Latitude func fetchWeather(latitude: CLLocationDegrees, longitude: CLLocationDegrees) { let urlString = "\(weatherURL)&lat=\(latitude)&lon=\(longitude)" performRequest(with: urlString) } //Fetch data from the weather URL func performRequest(with urlString: String) { if let url = URL(string: urlString) { let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { data, response, error in if error != nil { self.delegate?.didFailWithError(error: error!) print(error!) return } if let safeData = data { if let weather = self.parseJSON(dailyWeatherData: safeData) { self.delegate?.didUpdateWeather(self, dailyWeather: weather) } } } task.resume() } } //Decode the data based on the Daily Weather Data structs in the WeatherData.swift file //Return the data in the structs fround in the DailyWeatherModel.swift file func parseJSON(dailyWeatherData: Data) -> DailyWeatherModel? { let decoder = JSONDecoder() do { let decodedData = try decoder.decode(DailyWeatherData.self, from: dailyWeatherData) let dates = decodedData.list[0].dt_txt let startDate = dateConverter(date: dates) //Variable Declerations var forecast = [Int]() var temperature = [Double]() var forecastIcon = [Int]() var weekName = [String]() var count = 0 //The API gives weather in 3 hours, we need one day weather forecast //This loop and if statement gets rid of the 3 hours and shows the predicted weather for each day //If the predicted days weather has already been added skip till a new day is found while count < decodedData.list.count-1 { count += 1 var weekday: String = "" let date = decodedData.list[count].dt_txt let nextData = dateConverter(date: date) if startDate != nextData && forecast.contains(nextData) == false{ forecast.append(nextData) temperature.append(decodedData.list[count].main.temp) forecastIcon.append(decodedData.list[count].weather[0].id) dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" //Function to convert String to Date data type and retrive the date e.g 21 october 2022 to 21 //This then will allow us to get the weekday name let dailyDate = dateFormatter.date(from:date)! dateFormatter.dateFormat = "cccc" weekday = dateFormatter.string(from: dailyDate) weekName.append(weekday) } } //Add weather data to WeatherModel and return its data to be used in the WeatherViewController let weather = DailyWeatherModel(days: forecast, temp: temperature, conditionId: forecastIcon, weekName: weekName) return weather } catch { delegate?.didFailWithError(error: error) return nil } } //convert each string date from the API to a date data type func dateConverter(date: String) -> Int{ dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let date = dateFormatter.date(from:date)! let calanderDate = Calendar.current.dateComponents([.day], from: date).day! return calanderDate } }
const TOKEN = artifacts.require("Token"); const TruffleAssert = require('truffle-assert'); contract("Token", function(accounts) { let token; let admin = accounts[0] let userA = accounts[1] let userB = accounts[2] let user3 = accounts[3] let user4 = accounts[4] let user5 = accounts[5] let user6 = accounts[6] let user7 = accounts[7] let user8 = accounts[8] let user9 = accounts[9] let deployed = false; let id; console.log("admin: "+admin) console.log("userA: "+userA) console.log("userB: "+userB) it("should deploy ERC20 token(MT)", async function() { if (deployed){ token = await TOKEN.at("0x71fefC2B5C6c8fF8bDAAC1025baDdF498298F015"); return; } const name = "MyToken"; const symbol = "MT"; const supply = web3.utils.toWei("99999999999999999999999"); token = await TOKEN.new(name, symbol, supply, {from: admin}); console.log("Token:: "+token.address) assert.isTrue(token.address != null); }); return; it("userA should deposit 10 MT", async function() { // return; const balance = web3.utils.toWei("200"); const amount = web3.utils.toWei("100"); // transferring MT froma admin to userA, so userA can be able to deposit later for (let i = 1; i < 4; i++) { // token.transfer(accounts[i],balance,{from: admin} ) // await token.deposit(amount, {from: accounts[i]}) await token.deposit(amount, {from: admin}) } // await // await token.transfer(userB,balance,{from: admin} ) // await token.transfer(user3,balance,{from: admin} ) // await token.transfer(user4,balance,{from: admin} ) // await token.transfer(user5,balance,{from: admin} ) // await token.transfer(user6,balance,{from: admin} ) // await token.transfer(user7,balance,{from: admin} ) // await token.transfer(user8,balance,{from: admin} ) // await token.transfer(user9,balance,{from: admin} ) // depositing MT by userA // let tx = await token.deposit(amount, {from: userA}) // await // await token.deposit(amount, {from: user3}) // await token.deposit(amount, {from: user4}) // await token.deposit(amount, {from: user5}) // await token.deposit(amount, {from: user6}) // await token.deposit(amount, {from: user7}) // await token.deposit(amount, {from: user8}) // await token.deposit(amount, {from: user9}) // TruffleAssert.eventEmitted(tx, "Deposit", ev =>{ // return ev.depositer == userA && ev.amount.toString() == ""+amount; // }) }); return; it("userA should withdraw 10 MT", async function() { return; const bal = await token.balanceOf(userA); // const dep = await token.deposits(userA); console.log("balance before withdrawal Request: "+web3.utils.fromWei(bal)) // console.log("Deposits before withdrawal Request: "+web3.utils.fromWei(dep)) const amount = web3.utils.toWei("10"); let tx = await token.withdraw(amount, {from: userA}) TruffleAssert.eventEmitted(tx, "Withdrawal", ev =>{ id = ev.id.toString(); return ev.withdrawer == userA && ev.amount.toString() == ""+amount; }) }); it("Bulk users should withdraw 10 MT", async function() { // return; const amount = web3.utils.toWei("0.05"); for (let j = 0; j < 100; j++) { for (let i = 1; i < 10; i++) { token.withdraw(amount, {from: accounts[i]}) } } const ids = await token.pendingWithdrawals(); console.log("withdrawId# "+ids.toString()) // await token.withdraw(amount, {from: user9}) }); return; it("Admin should handle withdrawals", async function() { const ids = await token.pendingWithdrawals(); console.log("withdrawId# "+ids.toString()) let pendings // while (parseInt(pendings.toString()) == 0) { // pendings = await token.pendingWithdrawals() // } pendings = await token.pendingWithdrawals(); console.log("pendingWIthdrawals# "+pendings.toString()) pendings = parseInt(pendings.toString()); if (pendings == 0){ console.log("No withdrawals found!!!") return; } const batchSize = 50; let txs = pendings / batchSize let tx = [] for (let j = 0; j < txs; j++) { tx.push(j); } let id; // tx.forEach(async (element) => { // console.log("Loop# "+element); // await token.handleWithdrawals(batchSize, {from: admin}) // id = await token.pendingWithdrawals(); // console.log("pendingWithdrawals# "+id.toString()) // }); let txx; for (let i = 0; i < tx.length; i++) { console.log("Loop# "+i); txx = await token.handleWithdrawals(batchSize, {from: admin}) console.log(txx) id = await token.pendingWithdrawals(); console.log("pendingWithdrawals# "+id.toString()) } console.log("after forEach loop") }); return; it("Admin should handle userA withdrawals", async function() { const amount = web3.utils.toWei("10"); let amounts = [amount] let ids = [id] let withdrawers = [userA] let tx = await token.handleWithdrawals(ids, withdrawers, amounts, {from: admin}) const bal = await token.balanceOf(userA); // const dep = await token.deposits(userA); console.log("balance after withdrawal Handled: "+web3.utils.fromWei(bal)) }); return; it("userB should not be able to withdraw MT (without deposit)", async function() { const amount = web3.utils.toWei("10"); TruffleAssert.fails( token.withdraw(amount, {from: userB}), TruffleAssert.ErrorType.REVERT, "insufficient funds deposited" ) }); it("userB should deposit 20 MT", async function() { const balance = web3.utils.toWei("20"); const amount = web3.utils.toWei("20"); // transferring MT from admin to userB, so userB can be able to deposit later await token.transfer(userB,balance,{from: admin} ) // depositing by userB let tx = await token.deposit(amount, {from: userB}) TruffleAssert.eventEmitted(tx, "Deposit", ev =>{ return ev.depositer == userB && ev.amount.toString() == ""+amount; }) }); it("userB should not be able to withdraw more than deposited MT", async function() { const amount = web3.utils.toWei("30"); TruffleAssert.fails( token.withdraw(amount, {from: userB}), TruffleAssert.ErrorType.REVERT, "insufficient funds deposited" ) }); it("userB should withdraw 20 MT", async function() { return; const amount = web3.utils.toWei("20"); let tx = await token.withdraw(amount, {from: userB}) TruffleAssert.eventEmitted(tx, "Withdrawal", ev =>{ return ev.withdrawer == userB && ev.amount.toString() == ""+amount; }) }); });
import torch import torch.nn as nn class ConvBlock(nn.Module): def __init__(self, shape, in_c, out_c, kernel_size=3, stride=1, padding=1, activation=None, normalize=True) -> None: super(ConvBlock, self).__init__() self.ln = nn.LayerNorm(shape) self.conv1 = nn.Conv2d(in_channels=in_c, out_channels=out_c, kernel_size=kernel_size, stride=stride, padding=padding) self.conv2 = nn.Conv2d(in_channels=out_c, out_channels=out_c, kernel_size=kernel_size, stride=stride, padding=padding) self.activation = nn.SiLU() if activation is None else activation self.normalize = normalize def forward(self, x): out = self.ln(x) if self.normalize else x out = self.conv1(out) out = self.activation(out) out = self.conv2(out) out = self.activation(out) return out class UNet(nn.Module): def __init__(self, steps=1000, time_emb_dim=100) -> None: super(UNet, self).__init__() # Sinusoidal embedding self.time_embed = nn.Embedding(steps, time_emb_dim) self.time_embed.weight.data = sinusoidal_embedding(steps, time_emb_dim) self.time_embed.requires_grad_(False) self.te1 = self._make_te(time_emb_dim, 1) self.b1 = nn.Sequential( ConvBlock((1, 28, 28), 1, 10), ConvBlock((10, 28, 28), 10, 10), ConvBlock((10, 28, 28), 10, 10) ) self.down1 = nn.Conv2d(10, 10, 4, 2, 1) self.te2 = self._make_te(time_emb_dim, 10) self.b2 = nn.Sequential( ConvBlock((10, 14, 14), 10, 20), ConvBlock((20, 14, 14), 20, 20), ConvBlock((20, 14, 14), 20, 20) ) self.down2 = nn.Conv2d(20, 20, 4, 2, 1) self.te3 = self._make_te(time_emb_dim, 20) self.b3 = nn.Sequential( ConvBlock((20, 7, 7), 20, 40), ConvBlock((40, 7, 7), 40, 40), ConvBlock((40, 7, 7), 40, 40) ) self.down3 = nn.Sequential( nn.Conv2d(40, 40, 2, 1), nn.SiLU(), nn.Conv2d(40, 40, 4, 2, 1) ) # Bottleneck self.te_mid = self._make_te(time_emb_dim, 40) self.b_mid = nn.Sequential( ConvBlock((40, 3, 3), 40, 20), ConvBlock((20, 3, 3), 20, 20), ConvBlock((20, 3, 3), 20, 40) ) # Second half self.up1 = nn.Sequential( nn.ConvTranspose2d(40, 40, 4, 2, 1), nn.SiLU(), nn.ConvTranspose2d(40, 40, 2, 1) ) self.te4 = self._make_te(time_emb_dim, 80) self.b4 = nn.Sequential( ConvBlock((80, 7, 7), 80, 40), ConvBlock((40, 7, 7), 40, 20), ConvBlock((20, 7, 7), 20, 20) ) self.up2 = nn.ConvTranspose2d(20, 20, 4, 2, 1) self.te5 = self._make_te(time_emb_dim, 40) self.b5 = nn.Sequential( ConvBlock((40, 14, 14), 40, 20), ConvBlock((20, 14, 14), 20, 10), ConvBlock((10, 14, 14), 10, 10) ) self.up3 = nn.ConvTranspose2d(10, 10, 4, 2, 1) self.te_out = self._make_te(time_emb_dim, 20) self.b_out = nn.Sequential( ConvBlock((20, 28, 28), 20, 10), ConvBlock((10, 28, 28), 10, 10), ConvBlock((10, 28, 28), 10, 10, normalize=False) ) self.conv_out = nn.Conv2d(10, 1, 3, 1, 1) def forward(self, x, t): # x is (N, 2, 28, 28) (image with positional embedding stacked on channel dimension) t = self.time_embed(t) n = len(x) #print(self.te1(t).shape) out1 = self.b1(x + self.te1(t).reshape(n, -1, 1, 1)) # (N, 10, 28, 28) out2 = self.b2(self.down1(out1) + self.te2(t).reshape(n, -1, 1, 1)) # (N, 20, 14, 14) out3 = self.b3(self.down2(out2) + self.te3(t).reshape(n, -1, 1, 1)) # (N, 40, 7, 7) out_mid = self.b_mid(self.down3(out3) + self.te_mid(t).reshape(n, -1, 1, 1)) # (N, 40, 3, 3) out4 = torch.cat((out3, self.up1(out_mid)), dim=1) # (N, 80, 7, 7) out4 = self.b4(out4 + self.te4(t).reshape(n, -1, 1, 1)) # (N, 20, 7, 7) out5 = torch.cat((out2, self.up2(out4)), dim=1) # (N, 40, 14, 14) out5 = self.b5(out5 + self.te5(t).reshape(n, -1, 1, 1)) # (N, 10, 14, 14) out = torch.cat((out1, self.up3(out5)), dim=1) # (N, 20, 28, 28) out = self.b_out(out + self.te_out(t).reshape(n, -1, 1, 1)) # (N, 1, 28, 28) out = self.conv_out(out) return out def _make_te(self, dim_in, dim_out): return nn.Sequential( nn.Linear(dim_in, dim_out), nn.SiLU(), nn.Linear(dim_out, dim_out) ) def sinusoidal_embedding(n, d): embedding = torch.zeros(n, d) wk = torch.tensor([1 / 10000 ** (2 * j /d) for j in range(d)]) wk = wk.reshape((1, d)) t = torch.arange(n).reshape((n, 1)) embedding[:, ::2] = torch.sin(t * wk[:, ::2]) embedding[:, 1::2] = torch.cos(t * wk[:, ::2]) return embedding
/* * EasyDriver is a library that let a programmer build queries easier * than using plain JDBC. * Copyright (C) 2011 Paolo Proni * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.byteliberi.easydriver.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import org.byteliberi.easydriver.ObjectFactory; /** * This class is a mapper which reads some data from a Result Set and creates * zero, one or more value objects: for each found records in the result set, * this class creates one value object and fills its property values. * <P> * This class should not be used directly by the user of this libray. * * @author Paolo Proni * @version 1.0 * @since 1.0 * * @param <T> Class of the value object that this class returns. */ class MultipleRecordObjectMap<T> implements RecordObjectMap<T> { /** * Result list, it is filled by the read data from the Result Set. */ private LinkedList<T> result = new LinkedList<T>(); /** * This method reads the Result Set data and calls the passed object factory, in order * to create a new instance of the Value Object and appends it to the result list. */ @Override public void map(final ResultSet rs, final ObjectFactory<T> mapper) throws SQLException { result.add( mapper.map(rs) ); } /** * This method simply get the list of value objects that have been created * by the {@link #map(ResultSet, ObjectFactory)} method. * * @return Result list, it is filled by the read data from the Result Set. * It can be an empy list, but it should never be null. */ public List<T> getResult() { return this.result; } }
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; class ApiService { final String baseUrl; final String electionShortName; final String trusteeCookie; final String trusteeUUID; final int pollingInterval = 5; const ApiService({ required this.baseUrl, required this.electionShortName, required this.trusteeCookie, required this.trusteeUUID, }); Future<Map<String, dynamic>> getEgParams() async { try { var egParamsResponse = await http.get( Uri.parse('$baseUrl/$electionShortName/get-eg-params'), headers: {'Cookie': 'session=$trusteeCookie'}, ); if (egParamsResponse.statusCode == 200) { return json.decode(egParamsResponse.body); } else { return { "status_code": egParamsResponse.statusCode.toString(), "error": "Error retrieving eg_params.", }; } } catch (e) { print(e); return { "status_code": "500", "error": "Error retrieving eg_params.", }; } } Future<String> getRandomness() async { var randomnessResponse = await http.get( Uri.parse('$baseUrl/$electionShortName/get-randomness'), headers: {'Cookie': 'session=$trusteeCookie'}, ); if (randomnessResponse.statusCode == 200) { return json.decode(randomnessResponse.body)["randomness"]; } else { return "error"; } } Future<bool> uploadPublicKey(String publicKey) async { var uploadPublicKey = await http.post( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/upload-pk'), headers: { 'Content-Type': 'application/json', 'Cookie': 'session=$trusteeCookie' }, body: json.encode({'public_key_json': publicKey}), ); return uploadPublicKey.statusCode == 200; } Future<bool> privateKeyValidated(String privateKey) async { var uploadPublicKey = await http.post( Uri.parse( '$baseUrl/$electionShortName/trustee/$trusteeUUID/private-key-validated'), headers: { 'Content-Type': 'application/json', 'Cookie': 'session=$trusteeCookie' }, ); return uploadPublicKey.statusCode == 200; } // Trustee Sync Stream<int?> pollTrusteeStep( StreamController<int> trusteeStepController) async* { while (true) { await Future.delayed(Duration(seconds: pollingInterval)); final response = await http.get(Uri.parse( '$baseUrl/$electionShortName/trustee/$trusteeUUID/get-step')); if (response.statusCode == 200) { int trusteeStep = json.decode(response.body)["status"]; yield trusteeStep; if (trusteeStep == 4) { break; } } } } Future<String> getTrusteeSyncStep1() async { var stepResponse = await http.get( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/step-1'), headers: {'Cookie': 'session=$trusteeCookie'}, ); if (stepResponse.statusCode == 200) { return json.decode(stepResponse.body)["certificates"]; } else { return "Error retrieving step 1 data."; } } Future<bool> postTrusteeSyncStep1(String coefficients, String points) async { var stepResponse = await http.post( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/step-1'), headers: { 'Content-Type': 'application/json', 'Cookie': 'session=$trusteeCookie' }, body: json.encode({ "coefficients": coefficients, "points": points, })); return stepResponse.statusCode == 200; } Future<Map<String, dynamic>> getTrusteeSyncStep2() async { var stepResponse = await http.get( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/step-2'), headers: {'Cookie': 'session=$trusteeCookie'}, ); if (stepResponse.statusCode == 200) { return json.decode(stepResponse.body); } else { return { "status_code": stepResponse.statusCode.toString(), "error": "Error retrieving step 2 data.", }; } } Future<bool> postTrusteeSyncStep2(String acknowledgements) async { var stepResponse = await http.post( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/step-2'), headers: { 'Content-Type': 'application/json', 'Cookie': 'session=$trusteeCookie' }, body: json.encode({ "acknowledgements": acknowledgements, })); return stepResponse.statusCode == 200; } Future<Map<String, dynamic>> getTrusteeSyncStep3() async { var stepResponse = await http.get( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/step-3'), headers: {'Cookie': 'session=$trusteeCookie'}, ); if (stepResponse.statusCode == 200) { return json.decode(stepResponse.body); } else { return { "status_code": stepResponse.statusCode.toString(), "error": "Error retrieving step 3 data.", }; } } Future<bool> postTrusteeSyncStep3(String verificationKey) async { var stepResponse = await http.post( Uri.parse('$baseUrl/$electionShortName/trustee/$trusteeUUID/step-3'), headers: { 'Content-Type': 'application/json', 'Cookie': 'session=$trusteeCookie' }, body: json.encode({ "verification_key": verificationKey, })); return stepResponse.statusCode == 200; } Future<Map<String, dynamic>> getPartialDecryptionData() async { var response = await http.get( Uri.parse( '$baseUrl/$electionShortName/trustee/$trusteeUUID/decrypt-and-prove'), headers: {'Cookie': 'session=$trusteeCookie'}, ); if (response.statusCode == 200) { return json.decode(response.body); } else { return { "status_code": response.statusCode.toString(), "error": "Error retrieving decryption data.", }; } } Future<bool> postPartialDecryption( List<Map<String, dynamic>> partialDecryption) async { var response = await http.post( Uri.parse( '$baseUrl/$electionShortName/trustee/$trusteeUUID/decrypt-and-prove'), headers: { 'Content-Type': 'application/json', 'Cookie': 'session=$trusteeCookie' }, body: json.encode({'decryptions': partialDecryption})); return response.statusCode == 200; } }
/******************************************************************** * gnc-rational.hpp - A rational number library * * Copyright 2014 John Ralls <jralls@ceridwen.us> * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License as * * published by the Free Software Foundation; either version 2 of * * the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License* * along with this program; if not, contact: * * * * Free Software Foundation Voice: +1-617-542-5942 * * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 * * Boston, MA 02110-1301, USA gnu@gnu.org * * * *******************************************************************/ #include <sstream> #include "gnc-rational.hpp" #include "gnc-numeric.hpp" GncRational::GncRational(GncNumeric n) noexcept : m_num(n.num()), m_den(n.denom()) { if (m_den.isNeg()) { m_num *= -m_den; m_den = 1; } } GncRational::GncRational (gnc_numeric n) noexcept : m_num (n.num), m_den (n.denom) { if (m_den.isNeg()) { m_num *= -m_den; m_den = 1; } } bool GncRational::valid() const noexcept { if (m_num.valid() && m_den.valid()) return true; return false; } bool GncRational::is_big() const noexcept { if (m_num.isBig() || m_den.isBig()) return true; return false; } GncRational::operator gnc_numeric () const noexcept { if (!valid()) return gnc_numeric_error(GNC_ERROR_OVERFLOW); try { return {static_cast<int64_t>(m_num), static_cast<int64_t>(m_den)}; } catch (std::overflow_error&) { return gnc_numeric_error (GNC_ERROR_OVERFLOW); } } GncRational GncRational::operator-() const noexcept { return GncRational(-m_num, m_den); } GncRational GncRational::inv () const noexcept { if (m_num == 0) return *this; if (m_num < 0) return GncRational(-m_den, -m_num); return GncRational(m_den, m_num); } GncRational GncRational::abs() const noexcept { if (m_num < 0) return -*this; return *this; } void GncRational::operator+=(GncRational b) { GncRational new_val = *this + b; *this = std::move(new_val); } void GncRational::operator-=(GncRational b) { GncRational new_val = *this - b; *this = std::move(new_val); } void GncRational::operator*=(GncRational b) { GncRational new_val = *this * b; *this = std::move(new_val); } void GncRational::operator/=(GncRational b) { GncRational new_val = *this / b; *this = std::move(new_val); } int GncRational::cmp(GncRational b) { if (m_den == b.denom()) { auto b_num = b.num(); return m_num < b_num ? -1 : b_num < m_num ? 1 : 0; } auto gcd = m_den.gcd(b.denom()); GncInt128 a_num(m_num * b.denom() / gcd), b_num(b.num() * m_den / gcd); return a_num < b_num ? -1 : b_num < a_num ? 1 : 0; } GncRational::round_param GncRational::prepare_conversion (GncInt128 new_denom) const { if (new_denom == m_den || new_denom == GNC_DENOM_AUTO) return {m_num, m_den, 0}; GncRational conversion(new_denom, m_den); auto red_conv = conversion.reduce(); GncInt128 old_num(m_num); auto new_num = old_num * red_conv.num(); if (new_num.isOverflow()) throw std::overflow_error("Conversion overflow"); auto rem = new_num % red_conv.denom(); new_num /= red_conv.denom(); return {new_num, red_conv.denom(), rem}; } GncInt128 GncRational::sigfigs_denom(unsigned figs) const noexcept { if (m_num == 0) return 1; auto num_abs = m_num.abs(); bool not_frac = num_abs > m_den; int64_t val{ not_frac ? num_abs / m_den : m_den / num_abs }; unsigned digits{}; while (val >= 10) { ++digits; val /= 10; } return not_frac ? powten(digits < figs ? figs - digits - 1 : 0) : powten(figs + digits); } GncRational GncRational::reduce() const { auto gcd = m_den.gcd(m_num); if (gcd.isNan() || gcd.isOverflow()) throw std::overflow_error("Reduce failed, calculation of gcd overflowed."); return GncRational(m_num / gcd, m_den / gcd); } GncRational GncRational::round_to_numeric() const { unsigned int ll_bits = GncInt128::legbits; if (m_num.isZero()) return GncRational(); //Default constructor makes 0/1 if (!(m_num.isBig() || m_den.isBig())) return *this; if (m_num.abs() > m_den) { auto quot(m_num / m_den); if (quot.isBig()) { std::ostringstream msg; msg << " Cannot be represented as a " << "GncNumeric. Its integer value is too large.\n"; throw std::overflow_error(msg.str()); } GncRational new_v; while (new_v.num().isZero()) { try { new_v = convert<RoundType::half_down>(m_den / (m_num.abs() >> ll_bits)); if (new_v.is_big()) { --ll_bits; new_v = GncRational(); } } catch(const std::overflow_error& err) { --ll_bits; } } return new_v; } auto quot(m_den / m_num); if (quot.isBig()) return GncRational(); //Smaller than can be represented as a GncNumeric GncRational new_v; while (new_v.num().isZero()) { auto divisor = m_den >> ll_bits; if (m_num.isBig()) { GncInt128 oldnum(m_num), num, rem; oldnum.div(divisor, num, rem); auto den = m_den / divisor; num += rem * 2 >= den ? 1 : 0; if (num.isBig() || den.isBig()) { --ll_bits; continue; } GncRational new_rational(num, den); return new_rational; } new_v = convert<RoundType::half_down>(m_den / divisor); if (new_v.is_big()) { --ll_bits; new_v = GncRational(); } } return new_v; } GncRational operator+(GncRational a, GncRational b) { if (!(a.valid() && b.valid())) throw std::range_error("Operator+ called with out-of-range operand."); GncInt128 lcm = a.denom().lcm(b.denom()); GncInt128 num(a.num() * lcm / a.denom() + b.num() * lcm / b.denom()); if (!(lcm.valid() && num.valid())) throw std::overflow_error("Operator+ overflowed."); GncRational retval(num, lcm); return retval; } GncRational operator-(GncRational a, GncRational b) { GncRational retval = a + (-b); return retval; } GncRational operator*(GncRational a, GncRational b) { if (!(a.valid() && b.valid())) throw std::range_error("Operator* called with out-of-range operand."); GncInt128 num (a.num() * b.num()), den(a.denom() * b.denom()); if (!(num.valid() && den.valid())) throw std::overflow_error("Operator* overflowed."); GncRational retval(num, den); return retval; } GncRational operator/(GncRational a, GncRational b) { if (!(a.valid() && b.valid())) throw std::range_error("Operator/ called with out-of-range operand."); auto a_num = a.num(), b_num = b.num(), a_den = a.denom(), b_den = b.denom(); if (b_num == 0) throw std::underflow_error("Divide by 0."); if (b_num.isNeg()) { a_num = -a_num; b_num = -b_num; } /* q = (a_num * b_den)/(b_num * a_den). If a_den == b_den they cancel out * and it's just a_num/b_num. */ if (a_den == b_den) return GncRational(a_num, b_num); /* Protect against possibly preventable overflow: */ if (a_num.isBig() || a_den.isBig() || b_num.isBig() || b_den.isBig()) { GncInt128 gcd = b_den.gcd(a_den); b_den /= gcd; a_den /= gcd; } GncInt128 num(a_num * b_den), den(a_den * b_num); if (!(num.valid() && den.valid())) throw std::overflow_error("Operator/ overflowed."); return GncRational(num, den); }
use std::collections::HashMap; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerPrivileges { #[serde(rename = "CredentialSpec")] pub credential_spec: Option<HashMap<String, String>>, #[serde(rename = "SELinuxContext")] pub selinux_context: Option<HashMap<String, String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerMountVolumeOptionsDriverConfig { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Name")] pub name: Option<String>, #[serde(rename = "Options")] pub options: Option<HashMap<String, String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerMountVolumeOptions { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Labels")] pub labels: Option<HashMap<String, String>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "DriverConfig")] pub driver_config: Option<ServiceContainerMountVolumeOptionsDriverConfig>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerMount { #[serde(rename = "Type")] pub r#type: String, #[serde(rename = "Source")] pub source: String, #[serde(rename = "Target")] pub target: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "VolumeOptions")] pub volume_options: Option<ServiceContainerMountVolumeOptions>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerSpecConfigFile { #[serde(rename = "Name")] pub name: String, #[serde(rename = "UID")] pub uid: String, #[serde(rename = "GID")] pub gid: String, #[serde(rename = "Mode")] pub mode: u64, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerSpecConfig { #[serde(rename = "File")] pub file: Option<ServiceContainerSpecConfigFile>, #[serde(rename = "ConfigID")] pub config_id: String, #[serde(rename = "ConfigName")] pub config_name: String, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerSpecHealthCheck { #[serde(rename = "Test")] pub test: Vec<String>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Interval")] pub interval: Option<u64>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Timeout")] pub timeout: Option<u64>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Retries")] pub retries: Option<u64>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceContainerSpec { #[serde(rename = "Image")] pub image: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Labels")] pub labels: Option<HashMap<String, String>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Args")] pub args: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Env")] pub env: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Privileges")] pub privileges: Option<ServiceContainerPrivileges>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Mounts")] pub mounts: Option<Vec<ServiceContainerMount>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Configs")] pub configs: Option<Vec<ServiceContainerSpecConfig>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Healthcheck")] pub health_check: Option<ServiceContainerSpecHealthCheck>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Isolation")] pub isolation: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceTaskTemplatePlacement { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Constraints")] pub constraints: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Platforms")] pub platforms: Option<Vec<HashMap<String, String>>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceTaskTemplateNetworks { #[serde(rename = "Target")] pub target: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Aliases")] pub aliases: Option<Vec<String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceTaskTemplateResources { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Limits")] pub limits: Option<HashMap<String, String>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Reservations")] pub reservations: Option<HashMap<String, String>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceTaskTemplate { #[serde(rename = "ContainerSpec")] pub container_spec: ServiceContainerSpec, #[serde(rename = "Resources")] pub resources: Option<ServiceTaskTemplateResources>, #[serde(rename = "Placement")] pub placement: Option<ServiceTaskTemplatePlacement>, #[serde(rename = "Networks")] pub networks: Option<Vec<ServiceTaskTemplateNetworks>>, #[serde(rename = "ForceUpdate")] pub force_update: Option<u64>, #[serde(rename = "Runtime")] pub runtime: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceSpecModeReplicated { #[serde(rename = "Replicas")] pub replicas: u64, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceSpecModeGlobal {} #[derive(Debug, Serialize, Deserialize)] pub struct ServiceSpecMode { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Replicated")] pub replicated: Option<ServiceSpecModeReplicated>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Global")] pub global: Option<ServiceSpecModeGlobal>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceEndpointSpecPortConfig { #[serde(rename = "Protocol")] pub protocol: String, #[serde(rename = "TargetPort")] pub target_port: u64, #[serde(rename = "PublishedPort")] pub published_port: Option<u64>, #[serde(rename = "PublishMode")] pub publish_mode: Option<String>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceEndpointSpec { #[serde(rename = "Mode")] pub mode: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Ports")] pub ports: Option<Vec<ServiceEndpointSpecPortConfig>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceSpec { #[serde(rename = "Name")] pub name: String, #[serde(rename = "Labels")] pub labels: Option<HashMap<String, String>>, #[serde(rename = "TaskTemplate")] pub task_template: ServiceTaskTemplate, #[serde(rename = "Mode")] pub mode: Option<ServiceSpecMode>, #[serde(rename = "EndpointSpec")] pub endpoint_spec: Option<ServiceEndpointSpec>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceVersion { #[serde(rename = "Index")] pub index: u64, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceEndpointVirtualIP { #[serde(rename = "NetworkID")] pub network_id: String, #[serde(rename = "Addr")] pub addr: String, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceEndpoint { #[serde(rename = "Spec")] pub spec: ServiceEndpointSpec, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "VirtualIPs")] pub virtual_ips: Option<Vec<ServiceEndpointVirtualIP>>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "Ports")] pub ports: Option<Vec<ServiceEndpointSpecPortConfig>>, } #[derive(Debug, Serialize, Deserialize)] pub struct ServiceUpdateStatus { #[serde(rename = "State")] pub state: String, #[serde(rename = "StartedAt")] pub started_at: DateTime<Utc>, #[serde(rename = "CompletedAt")] pub completed_at: DateTime<Utc>, #[serde(rename = "Message")] pub message: String, } #[derive(Debug, Serialize, Deserialize)] pub struct Service { #[serde(rename = "ID")] pub id: String, #[serde(rename = "Version")] pub version: ServiceVersion, #[serde(rename = "CreatedAt")] pub created_at: DateTime<Utc>, #[serde(rename = "UpdatedAt")] pub updated_at: DateTime<Utc>, #[serde(rename = "Spec")] pub spec: ServiceSpec, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "PreviousSpec")] pub previous_spec: Option<ServiceSpec>, #[serde(rename = "Endpoint")] pub endpoint: Option<ServiceEndpoint>, #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "UpdateStatus")] pub update_status: Option<ServiceUpdateStatus>, }
import 'package:flutter/material.dart'; import 'homepage.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( backgroundColor: const Color.fromARGB(252, 255, 255, 255), title: const Text('DayPlanner'), titleTextStyle: const TextStyle( color: Colors.black, fontFamily: 'BebasNeue', fontSize: 30), ), body: const GetStarted(), ), ); } } class GetStarted extends StatefulWidget { const GetStarted({super.key}); @override State<GetStarted> createState() => _GetStartedState(); } class _GetStartedState extends State<GetStarted> { @override Widget build(BuildContext context) { return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ const Image( width: 500, height: 500, image: AssetImage('assets/images/notebook.png')), const Expanded( child: Align( alignment: Alignment.center, child: Text('Plan your day easily!', style: TextStyle(fontFamily: 'BebasNeue', fontSize: 40)))), Expanded( child: Align( alignment: Alignment.topCenter, child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.black), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), side: const BorderSide(color: Colors.black), ))), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const homepage())); }, child: const Text("Get Started", style: TextStyle(fontSize: 14))), ), ), ], ), ); } }
-- | -- Module : Codec.Compression.SnappyC.Raw -- Copyright : (c) 2024 Finley McIlwaine -- License : BSD-3-Clause (see LICENSE) -- -- Maintainer : Finley McIlwaine <finley@well-typed.com> -- -- Raw format Snappy compression/decompression. -- -- > import Codec.Compression.SnappyC.Raw qualified as Snappy module Codec.Compression.SnappyC.Raw ( -- * Compression compress -- * Decompression , decompress ) where import Codec.Compression.SnappyC.Internal.C qualified as C import Data.ByteString.Internal (ByteString(..)) import Foreign import System.IO.Unsafe import Data.ByteString.Unsafe -- | Compress the input using [Snappy](https://github.com/google/snappy/). -- -- The result is in Snappy raw format, /not/ the framing format. compress :: ByteString -> ByteString compress bs = unsafePerformIO $ do unsafeUseAsCStringLen bs $ \(sptr, slen) -> do let dlen = C.snappy_max_compressed_length (fromIntegral slen) dptr <- mallocBytes (fromIntegral dlen) with dlen $ \dlen_ptr -> case C.snappy_compress (castPtr sptr) (fromIntegral slen) (castPtr dptr) dlen_ptr of 0 -> do len <- fromIntegral <$> peek dlen_ptr unsafePackMallocCStringLen (dptr, len) 1 -> error "impossible: there is no invalid input for compression" 2 -> error "impossible: the buffer size is always set correctly" status -> error $ "impossible: unexpected status from snappy_compress: " ++ show status -- | Decompress the input using [Snappy](https://github.com/google/snappy/). -- -- Returns 'Nothing' if the input is not in Snappy raw format or -- otherwise ill-formed. decompress :: ByteString -> Maybe ByteString decompress bs = unsafePerformIO $ do unsafeUseAsCStringLen bs $ \(sptr, slen) -> alloca $ \dlen_ptr -> case C.snappy_uncompressed_length (castPtr sptr) (fromIntegral slen) dlen_ptr of 0 -> do dlen <- fromIntegral <$> peek dlen_ptr dptr <- mallocBytes dlen case C.snappy_uncompress (castPtr sptr) (fromIntegral slen) (castPtr dptr) dlen_ptr of 0 -> do len <- fromIntegral <$> peek dlen_ptr Just <$> unsafePackMallocCStringLen (dptr, len) 1 -> -- Invalid input. Successful result from -- snappy_uncompressed_length does *not* mean the -- input is completely valid return Nothing status -> error $ "impossible: decompression failed with status " ++ show status 1 -> return Nothing status -> error $ "impossible: snappy_uncompressed_length failed with " ++ "status" ++ show status
// src/Login.js import React, { useState } from 'react'; function Login({ onLogin }) { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const handleLogin = () => { fetch('https://dummyjson.com/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password, }), }) .then(res => { if (res.status === 200) { return res.json(); } else { throw new Error('Invalid credentials'); } }) .then(data => { localStorage.setItem('user', JSON.stringify(data)); onLogin(data.id); }) .catch(error => { setError(error.message); }); }; return ( <div> <h2>Login</h2> {error && <p>{error}</p>} <input type="text" placeholder="Username" value={username} onChange={e => setUsername(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={e => setPassword(e.target.value)} /> <button onClick={handleLogin}>Login</button> </div> ); } export default Login;
import React, { useState, useEffect } from "react"; import axiosClient from "../../Components/AxiosClient.js"; import { IconButton, Container, Paper, Box, Grid, MenuItem, Typography, Breadcrumbs, Link, TextField, Button, Dialog, CircularProgress, } from "@mui/material"; import Pagination from "@mui/material/Pagination"; import SnackBar from "../../Components/SnackBar"; import BookCard from "../../Components/Book/BookCard"; import { useUserRole } from "../../Components/UserContext"; const FilterBook = () => { const [books, setBooks] = useState([]); const [openSnackbar, setOpenSnackbar] = useState(false); const [snackbarMessage, setSnackbarMessage] = useState(""); const [searchTerm, setSearchTerm] = useState(""); const [currentPage, setCurrentPage] = useState(1); const [itemsPerPage, setItemsPerPage] = useState(10); const { userRole } = useUserRole(); const queryParams = new URLSearchParams(window.location.search); const filterType = queryParams.get("filterType"); const filterValue1 = queryParams.get("filterValue"); const filterValue = decodeURI(filterValue1); const [loading, setLoading] = useState(true); useEffect(() => { axiosClient .get( `/filter-books?filterType=${filterType}&filterValue=${filterValue}`, { withCredentials: true } ) .then(function (response) { const data = response.data.Books; setBooks(data); setLoading(false); }) .catch(function (error) { alert(error); setLoading(false); }); }, []); const handleBookDelete = (id) => { // Remove the deleted book from the list const updatedBooks = books.filter((book) => book._id !== id); setBooks(updatedBooks); setSnackbarMessage("Book deleted successfully"); setOpenSnackbar(true); }; const handleSnackbarClose = (event, reason) => { if (reason === "clickaway") { return; } setOpenSnackbar(false); }; const handleSearch = (event) => { setSearchTerm(event.target.value); setCurrentPage(1); }; // Pagination const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const filteredBooks = books.filter((book) => book.name.toLowerCase().includes(searchTerm.toLowerCase()) ); const currentItems = filteredBooks.slice(indexOfFirstItem, indexOfLastItem); const paginate = (pageNumber) => setCurrentPage(pageNumber); return ( <Grid container> <Breadcrumbs aria-label="breadcrumb"> <Link color="primary" href="/dashboard/book"> Books </Link> <Typography color="text.primary">Filtered Books</Typography> </Breadcrumbs> <Grid item xs={12} sm={6} md={6} lg={6} marginBottom={3}> <TextField label="Search" variant="outlined" onChange={handleSearch} value={searchTerm} /> </Grid> {loading ? ( <CircularProgress /> ) : ( <> {currentItems.length > 0 ? ( <> <Grid container spacing={3} sx={{ display: "flex" }}> {currentItems.map((book, index) => ( <Grid item xs={12} sm={6} md={4} lg={3} key={index}> <BookCard bookDetail={book} userRole={userRole} onDelete={handleBookDelete} /> </Grid> ))} </Grid> <Box sx={{ mt: 4, display: "flex", justifyContent: "center", width: "100%", }} > <Pagination showFirstButton showLastButton count={Math.ceil(filteredBooks.length / itemsPerPage)} page={currentPage} onChange={(event, page) => paginate(page)} color="primary" /> </Box> </> ) : ( <Typography variant="h5" align="center" mt={4}> No Books of this {filterType} </Typography> )} <SnackBar open={openSnackbar} message={snackbarMessage} onClose={handleSnackbarClose} /> </>)} </Grid> ); }; export default FilterBook;
#include <stdio.h> // Function prototype int gcd(int num1, int num2); int main() { int num1, num2; printf("Enter two positive integers: "); scanf("%d %d", &num1, &num2); if (num1 <= 0 || num2 <= 0) { printf("Please enter positive integers only.\n"); } else { int result = gcd(num1, num2); printf("GCD of %d and %d is: %d\n", num1, num2, result); } return 0; } // Function to find GCD using recursion int gcd(int num1, int num2) { // Base case: if the second number is 0, then the GCD is the first number if (num2 == 0) { return num1; } else { // Recursive case: call the function with the second number and the remainder of num1 divided by num2 return gcd(num2, num1 % num2); } }
#ifndef HASH_H #define HASH_H #include <iostream> #include <cmath> #include <random> #include <chrono> #include <ctime> #include <cstdlib> typedef std::size_t HASH_INDEX_T; struct MyStringHash { HASH_INDEX_T rValues[5] { 983132572, 1468777056, 552714139, 984953261, 261934300 }; MyStringHash(bool debug = true) { if(false == debug){ generateRValues(); } } // hash function entry point (i.e. this is h(k)) HASH_INDEX_T operator()(const std::string& k) const { // Add your code here unsigned long long w[5]; //initializes all values to be 0 for (int i = 0; i < 5; i++) { w[i] = 0; } int wIndex = 4; for (int i = (int)k.length() - 1; i >= 0; i -= 6) { //generates substring std::string subString(""); for (int j = 5; j >= 0; j--) { if (i - j >= 0) { subString.push_back(k[i-j]); } } //calculates the value to go into w unsigned long long value = letterDigitToNumber(subString[0]); for (size_t a = 1; a < subString.size(); a++) { value = value * 36 + letterDigitToNumber(subString[a]); } w[wIndex] = value; wIndex--; } HASH_INDEX_T ans = 0; for (int i = 0; i < 5; i++) { ans += rValues[i] * w[i]; } return ans; } // A likely helper function is to convert a-z,0-9 to an integral value 0-35 HASH_INDEX_T letterDigitToNumber(char letter) const { // Add code here or delete this helper function if you do not want it HASH_INDEX_T ans = 0; //deals with uppercase letters size_t l = size_t(letter); if (l >= size_t('A') && l <= size_t('Z')) { ans = l - 65; } //deals with digits else if (l >= size_t('0') && l <= size_t('9')) { ans = l - 22; } //deals with lowercase letters else { ans = l - 97; } return ans; } // Code to generate the random R values void generateRValues() { // obtain a seed from the system clock: unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937 generator (seed); // mt19937 is a standard random number generator // Simply call generator() [it has an operator()] to get another random number for(int i{ 0 }; i < 5; ++i) { rValues[i] = generator(); } } }; #endif
<?php /** * Template part for displaying posts * * @link https://codex.wordpress.org/Template_Hierarchy * * @package unbound */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class( 'style-five' ); ?>> <div class="holder"> <div class="category-list"> <?php $category_detail = get_the_category( get_the_id() ); $result = ''; foreach ( $category_detail as $item ) : $category_link = get_category_link( $item->cat_ID ); $result .= '<span>' . $item->name . '</span>'; endforeach; echo wp_kses_post( $result ); ?> </div><!-- .category-list --> <?php if ( has_post_thumbnail() ) { ?> <div class="post-thumbnail"> <img src="<?php echo esc_url( get_parent_theme_file_uri( '/images/blank/Blank-Image-100x65.png' ) ); ?>" alt="<?php echo esc_attr__( 'Blank Image', 'unbound' ); ?>" width="100" height="65"> <?php if ( '' !== get_the_post_thumbnail() && ! is_single() ) : ?> <a class="placeholder" href="<?php the_permalink(); ?>" style="background-image:url('<?php the_post_thumbnail_url( 'full' ); ?>')"></a> <?php endif; ?> </div><!-- .post-thumbnail --> <?php } ?> <header class="entry-header"> <?php the_title( '<h3 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h3>' ); ?> </header><!-- .entry-header --> <div class="entry-content"> <?php echo wp_kses_post( get_the_excerpt() . '...' ); ?> <?php // echo wp_kses_post( substr( strip_tags( get_the_excerpt() ), 0, 300 ) . '...' ); ?> </div><!-- .entry-content --> </div><!-- .holder --> <div class="entry-meta"> <?php unbound_posted_on(); ?> </div><!-- .entry-meta --> </article><!-- #post-## -->
#ifndef COLUMN_H #define COLUMN_H #include <vector> #include <string> #include "CheckName.cpp" enum type { string = 0, integer, floating }; template <typename T> class Column { protected: type mType; std::string mName; std::vector<T> mColumn; public: Column(/* args */) = default; Column(type type, const std::string& name, const std::vector<T>& vector); Column(type type, const std::string& name); void SetType(type type); void SetName(const std::string &name); const T *GetAt(unsigned int index) const; const std::string &GetName() const; type GetType() const; void Add(const T *data); void Describe() const; bool IsValueIn(const T *data) const; void DeleteAt(unsigned int index); void ChangeAt(unsigned int index, const T *value); virtual ~Column(); }; int main(int argc, char const *argv[]) { Column<str> column; return 0; } #endif
import React, { Component } from 'react'; import { nanoid } from 'nanoid'; import Layout from './components/Layout/Layout'; import ContactList from './components/ContactList/ContactList'; import ContactForm from './components/ContactForm/ContactForm'; import Filter from './components/Filter/Filter'; export default class App extends Component { state = { contacts: [ { id: 'id-1', name: 'Rosie Simpson', number: '459-12-56' }, { id: 'id-2', name: 'Hermione Kline', number: '443-89-12' }, { id: 'id-3', name: 'Eden Clements', number: '645-17-79' }, { id: 'id-4', name: 'Annie Copeland', number: '227-91-26' }, ], filter: '', }; componentDidMount() { const parsedContacts = JSON.parse(localStorage.getItem('contacts')); if (parsedContacts !== null) { this.setState({ contacts: parsedContacts }); return; } localStorage.setItem('contacts', JSON.stringify(this.state.contacts)); } componentDidUpdate(prevProps, prevState) { if (prevState.contacts !== this.state.contacts) { localStorage.setItem('contacts', JSON.stringify(this.state.contacts)); } } addContact = ({ name, number }) => { const normalizedFilter = name.toLowerCase(); const checkByName = this.state.contacts.find( contact => contact.name.toLowerCase() === normalizedFilter ); if (checkByName) { alert(`${name} is already in contacts`); } else { const contact = { id: nanoid(), name, number, }; this.setState(({ contacts }) => ({ contacts: [...contacts, contact], })); } }; filterContact = () => { const { filter, contacts } = this.state; const normalizedFilter = filter.toLowerCase(); return contacts.filter(contact => contact.name.toLowerCase().includes(normalizedFilter) ); }; handleChange = event => { this.setState({ filter: event.currentTarget.value }); }; deleteContact = contactId => { this.setState(prevState => ({ contacts: prevState.contacts.filter(contact => contact.id !== contactId), })); }; render() { const { filter } = this.state; const filterContact = this.filterContact(); return ( <Layout> <h1 className="title">Phonebook</h1> <ContactForm onSubmit={this.addContact} /> <h2 className="title">Contacts</h2> <Filter value={filter} onChange={this.handleChange} /> <ContactList contacts={filterContact} onDeleteContact={this.deleteContact} /> </Layout> ); } }
<h2 scAutoFocus>rx-let</h2> <div class="buttons"> <button (click)="rxLetObs.setNull()">set null</button> <button (click)="rxLetObs.setNewEmpty()">set empty</button> <button (click)="rxLetObs.nextAsync()">next (timeout 1000)</button> <button (click)="rxLetObs.next()">next (sync)</button> <button (click)="rxLetObs.errorAsync()">error (timeout 1000)</button> <button (click)="rxLetObs.error()">error (sync)</button> </div> <div>{{randomNum()}} (changes whenever cd runs on component level)</div> <ng-template #errorTpl let-error> <div>error: {{error|json}}</div> </ng-template> <div class="wrapper"> <ng-template #suspenseTpl> <div>...no value yet. click next to start</div> </ng-template> <div *scRxLet="rxLetObs.value$ as value; suspense:suspenseTpl; error:errorTpl"> {{value}} (changes when observable emits) </div> </div> <h2>rx-if</h2> <div class="buttons"> <button (click)="rxIfObs.setNull()">set null</button> <button (click)="rxIfObs.setNewEmpty()">set empty</button> <button (click)="rxIfObs.nextAsync()">next (timeout 1000)</button> <button (click)="rxIfObs.next()">next (sync)</button> <button (click)="rxIfObs.errorAsync()">error (timeout 1000)</button> <button (click)="rxIfObs.error()">error (sync)</button> </div> <div>{{randomNum()}} (changes whenever cd runs on component level)</div> <div class="wrapper"> <ng-template #elseTpl> <div>The <i>else</i></div> </ng-template> <div *scRxIf="rxIfObs.value$ as value; error:errorTpl; else elseTpl"> {{value}} (changes when observable emits) </div> </div>
import { useParams, Link } from "react-router-dom"; import { useEffect, useState } from "react"; import Header from "../../../components/Header"; import styles from "./Styles.module.css" function Details() { const timeStamp = '1673185089'; const apiKey = '3edf2abbda9a7d9af0c2dda2daa1a0a0'; const md5 = 'a41c6af456049816c1bcb7548cf0b3c4'; const { id } = useParams(); const [comics, setComics] = useState({}) useEffect(() => { fetch(`http://gateway.marvel.com/v1/public/comics/${id}?ts=${timeStamp}&apikey=${apiKey}&hash=${md5}`) .then(response => response.json()) .then(data => { console.log(data.data.results[0].thumbnail) const { title, description, thumbnail, path, extension, modified, results } = data const comics = { id, title: data.data.results[0].title, sinopse: data.data.results[0].description, image: `${data.data.results[0].thumbnail.path}.${data.data.results[0].thumbnail.extension }`, releaseDate: data.data.results[0].modified } setComics(comics) }) }, [id]) return ( <div > <Header /> <div className={styles.container}> <div className={styles.comics}> <img className={styles.imgcomic} src={comics.image} alt={comics.sinopse} /> <div className={styles.details}> <h1>{comics.title}</h1> <span className={styles.sinopse}>Sinopse:{comics.sinopse}</span> <span className={styles.release}>Release date: {comics.releaseDate}</span> <Link to="/"><button className={styles.buttonGoBack} >Go back</button></Link> </div> </div> </div> </div> ) } export default Details;
/** * Tooflya Inc. Development * * @author Igor Mats from Tooflya Inc. * @copyright (c) 2013 by Igor Mats * http://www.tooflya.com/development/ * * License: Attribution NonCommercial NoDerivatives 4.0 International * * Creative Commons Corporation (“Creative Commons”) is not a law firm and does * not provide legal services or legal advice. Distribution of Creative Commons * public licenses does not create a lawyer-client or other relationship. * Creative Commons makes its licenses and related information available on * an “as-is” basis. Creative Commons gives no warranties regarding its licenses, * any material licensed under their terms and conditions, or any related * information. Creative Commons disclaims all liability for damages resulting * from their use to the fullest extent possible. * * Creative Commons public licenses provide a standard set of terms and * conditions that creators and other rights holders may use to share original * works of authorship and other material subject to copyright and certain other * rights specified in the public license below. The following considerations * are for informational purposes only, are not exhaustive, and do not form part * of our licenses. * * Creative Commons may be contacted at creativecommons.org. * * @version of cocos2d-x is 2.1.4 * */ Settings = Screen.extend({ ctor: function() { this._super(); Settings.instance = this; this.name = "Settings screen"; this.m_Background = Entity.create(Orientation.parse(s_ThirdPartyBackground), this, true); this.m_BackButton = Button.create(s_ButtonsSprite, 3, 4, this); this.m_CreditsButton = Button.create(s_LongButton, 1, 1, this); this.m_ProgressButton = Button.create(s_LongButton, 1, 1, this); this.m_MoreButton = Button.create(s_LongButton, 1, 1, this); this.m_LanguagesButton = Button.create(s_LongButton, 1, 1, this); this.m_SoundButton = Button.create(s_SfxButtonsSprite, 3, 2, this); this.m_MusicButton = Button.create(s_SfxButtonsSprite, 3, 2, this); this.m_BackgroundDecoration1 = Entity.create(s_BackgroundDecoration1, this); this.m_BackgroundDecoration2 = Entity.create(s_BackgroundDecoration2, this); this.m_LanguageIndicator = TiledEntity.create(s_SmallFlags, 2, 5, this.m_LanguagesButton); this.m_CreditsText = Text.create('about', this.m_CreditsButton); this.m_ProgressText = Text.create('progress', this.m_ProgressButton); this.m_MoreText = Text.create('more', this.m_MoreButton); this.m_LanguagesText = Text.create('language', this.m_LanguagesButton); this.m_BackButton.create().setCenterPosition(Camera.sharedCamera().coord(100), Camera.sharedCamera().coord(100)); this.m_CreditsButton.create().setCenterPosition(Camera.sharedCamera().center.x, Camera.sharedCamera().center.y + Camera.sharedCamera().coord(430)); this.m_ProgressButton.create().setCenterPosition(Camera.sharedCamera().center.x, Camera.sharedCamera().center.y + Camera.sharedCamera().coord(230)); this.m_MoreButton.create().setCenterPosition(Camera.sharedCamera().center.x, Camera.sharedCamera().center.y + Camera.sharedCamera().coord(30)); this.m_LanguagesButton.create().setCenterPosition(Camera.sharedCamera().center.x, Camera.sharedCamera().center.y - Camera.sharedCamera().coord(170)); this.m_MusicButton.create().setCenterPosition(Camera.sharedCamera().center.x - Camera.sharedCamera().coord(110), Camera.sharedCamera().center.y - Camera.sharedCamera().coord(380)); this.m_SoundButton.create().setCenterPosition(Camera.sharedCamera().center.x + Camera.sharedCamera().coord(110), Camera.sharedCamera().center.y - Camera.sharedCamera().coord(380)); this.m_BackgroundDecoration1.create().setCenterPosition(this.m_BackgroundDecoration1.getWidth() / 2, Camera.sharedCamera().height - this.m_BackgroundDecoration1.getHeight() / 2); this.m_BackgroundDecoration2.create().setCenterPosition(Camera.sharedCamera().width - this.m_BackgroundDecoration2.getWidth() / 2, this.m_BackgroundDecoration2.getHeight() / 2); this.m_LanguageIndicator.create().setCenterPosition(this.m_LanguagesButton.getWidth(), this.m_LanguagesButton.getHeight() / 2); this.m_CreditsText.setCenterPosition(this.m_CreditsButton.getWidth() / 2, this.m_CreditsButton.getHeight() / 2); this.m_ProgressText.setCenterPosition(this.m_ProgressButton.getWidth() / 2, this.m_ProgressButton.getHeight() / 2); this.m_MoreText.setCenterPosition(this.m_MoreButton.getWidth() / 2, this.m_MoreButton.getHeight() / 2); this.m_LanguagesText.setCenterPosition(this.m_LanguagesButton.getWidth() / 2, this.m_LanguagesButton.getHeight() / 2); this.m_BackButton.setCurrentFrameIndex(1); this.m_BackButton.setTouchHandler('onBackEvent', Settings); this.m_CreditsButton.setTouchHandler('onCreditsEvent', Settings); this.m_ProgressButton.setTouchHandler('onProgressEvent', Settings); this.m_MoreButton.setTouchHandler('onMoreEvent', Settings); this.m_LanguagesButton.setTouchHandler('onLanguagesEvent', Settings); this.m_SoundButton.setTouchHandler('onSoundEvent', Settings); this.m_MusicButton.setTouchHandler('onMusicEvent', Settings); }, onBackEvent: function() { ScreenManager.sharedManager().replace(Menu); }, onCreditsEvent: function() { ScreenManager.sharedManager().replace(Credits); }, onProgressEvent: function() { ScreenManager.sharedManager().replace(Reset); }, onMoreEvent: function() { /** ScreenManager.sharedManager().replace(More); */ openURL("//www.tooflya.com/"); }, onLanguagesEvent: function() { ScreenManager.sharedManager().replace(Languages); }, onSoundEvent: function() { Sound.sharedSound().changeState(); this.updateSoundButtonsState(); }, onMusicEvent: function() { Music.sharedMusic().changeState(); this.updateSoundButtonsState(); }, onShow: function() { this._super(); this.updateSoundButtonsState(); this.updateFlagIndicatorsState(); }, onHide: function() { this._super(); }, updateSoundButtonsState: function() { this.m_MusicButton.setCurrentFrameIndex(Music.sharedMusic().enabled ? 0 : 3); this.m_SoundButton.setCurrentFrameIndex(Sound.sharedSound().enabled ? 1 : 4); }, updateFlagIndicatorsState: function() { this.m_LanguageIndicator.setCurrentFrameIndex(LanguagesManager.sharedManager().getLanguageId()); }, update: function(time) { this._super(time); }, onKeyDown: function(e) { switch(e) { case 27: ScreenManager.sharedManager().replace(Menu); break; } } }); Settings.instance = false; Settings.sharedScreen = function() { return Settings.instance ? Settings.instance : new Settings(); };
package com.pnuema.android.githubprviewer.pullrequests.ui import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.pnuema.android.githubprviewer.pullrequests.ui.model.IPullModel import com.pnuema.android.githubprviewer.pullrequests.ui.model.NoPullsModel import com.pnuema.android.githubprviewer.pullrequests.ui.model.PullModel import com.pnuema.android.githubprviewer.pullrequests.ui.viewholder.NoPullRequestsViewHolder import com.pnuema.android.githubprviewer.pullrequests.ui.viewholder.PullRequestViewHolder class PullsAdapter(private val clickListener: IPullClicked): RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val items: ArrayList<IPullModel> = ArrayList() fun setItems(newItems: ArrayList<IPullModel>) { items.clear() items.addAll(newItems) if (items.isEmpty()) { items.add(NoPullsModel()) } notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { PullRequestViewHolder.type -> PullRequestViewHolder(parent) NoPullRequestsViewHolder.type -> NoPullRequestsViewHolder(parent) else -> throw java.lang.IllegalArgumentException("Illegal view holder creation") } } override fun getItemCount(): Int { return items.count() } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { is PullRequestViewHolder -> holder.bind(items[position] as PullModel, clickListener) } } override fun getItemViewType(position: Int): Int { return when (items[position]) { is PullModel -> PullRequestViewHolder.type is NoPullsModel -> NoPullRequestsViewHolder.type else -> throw IllegalArgumentException("Invalid view type") } } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { DashboardComponent } from './dashboard/dashboard.component'; import { TransactionComponent } from './transaction/transaction.component'; import { BudgetFormComponent } from './budget-form/budget-form.component'; const routes: Routes = [ { path: 'dashboard', component: DashboardComponent }, { path: 'transactions', component: TransactionComponent }, { path: 'add-transaction', component: BudgetFormComponent }, { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, // Default route ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
// Flutter imports: import 'package:flutter/material.dart'; // Package imports: import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; // Project imports: import 'package:starcat/settings/settings.dart'; import 'package:starcat/theme/theme.dart'; import '../../test_helpers/test_helpers.dart'; class MockThemeCubit extends MockCubit<ThemeState> implements ThemeCubit {} void main() { late ThemeCubit themeCubit; setUp(() { themeCubit = MockThemeCubit(); when(() => themeCubit.state).thenReturn( const ThemeState(ThemeMode.dark), ); }); group('SettingsPage', () { testWidgets('renders SettingsPage', (tester) async { await tester.pumpApp( const Scaffold( body: SettingsPage(), ), ); await tester.pumpAndSettle(); expect(find.byType(SettingsPage), findsOneWidget); }); }); group('SettingsView', () { testWidgets('renders SettingsView', (tester) async { await tester.pumpApp( const Scaffold( body: SettingsPage(), ), ); await tester.pumpAndSettle(); expect(find.byType(SettingsView), findsOneWidget); }); testWidgets('Material You SwitchListTile works', (tester) async { await tester.pumpApp( themeCubit: themeCubit, const Scaffold( body: SettingsPage(), ), ); await tester.pumpAndSettle(); await tester.tap(find.text('Material You')); await tester.pumpAndSettle(); verify(() => themeCubit.setMaterial3(isEnabled: false)).called(1); await tester.tap(find.text('Material You')); await tester.pumpAndSettle(); verify(() => themeCubit.setMaterial3(isEnabled: true)).called(1); }); testWidgets('ThemeMode selector works', (tester) async { await tester.pumpApp( themeCubit: themeCubit, const Scaffold( body: SettingsPage(), ), ); await tester.pumpAndSettle(); await tester.tap(find.text('System')); await tester.pumpAndSettle(); verify(() => themeCubit.setThemeMode(ThemeMode.system)).called(1); await tester.tap(find.text('Dark')); await tester.pumpAndSettle(); verify(() => themeCubit.setThemeMode(ThemeMode.dark)).called(1); await tester.tap(find.text('Light')); await tester.pumpAndSettle(); verify(() => themeCubit.setThemeMode(ThemeMode.light)).called(1); }); }); }
/* * This file is part of Openrouteservice. * * Openrouteservice is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; * if not, see <https://www.gnu.org/licenses/>. */ package org.heigit.ors.api.responses.routing.gpx; import com.graphhopper.util.Helper; import jakarta.xml.bind.annotation.XmlElement; import org.heigit.ors.api.requests.routing.RouteRequest; import org.heigit.ors.api.util.AppInfo; import org.heigit.ors.routing.APIEnums; public class GPXExtensions { @XmlElement(name = "attribution") private String attribution; @XmlElement(name = "engine") private String engine; @XmlElement(name = "build_date") private String buildDate; @XmlElement(name = "profile") private String profile; @XmlElement(name = "preference") private String preference; @XmlElement(name = "language") private String language; @XmlElement(name = "distance-units") private String units; @XmlElement(name = "instructions") private boolean includeInstructions; @XmlElement(name = "elevation") private boolean includeElevation; public GPXExtensions() { } public GPXExtensions(RouteRequest request, String attribution) { if (!Helper.isEmpty(attribution)) this.attribution = attribution; engine = AppInfo.getEngineInfo().getString("version"); buildDate = AppInfo.getEngineInfo().getString("build_date"); profile = request.getProfile().toString(); if (request.hasRoutePreference()) preference = request.getRoutePreference().toString(); if (request.hasLanguage()) language = request.getLanguage().toString(); else language = APIEnums.Languages.EN.toString(); if (request.hasUnits()) units = request.getUnits().toString(); else units = APIEnums.Units.METRES.toString(); if (request.hasIncludeInstructions()) includeInstructions = request.getIncludeInstructionsInResponse(); else includeInstructions = true; if (request.hasUseElevation()) includeElevation = request.getUseElevation(); else includeElevation = false; } }
import styles from './Header.module.scss'; import classNames from 'classnames/bind'; import images from '~/assets/images'; import Image from '~/components/Image'; import Tippy from '@tippyjs/react'; import 'tippy.js/dist/tippy.css'; // optional import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faBullhorn, faCoins, faEarthAsia, faEllipsisVertical, faGear, faSignIn, faSignOut, faUser, } from '@fortawesome/free-solid-svg-icons'; import routesConfig from '~/config/routes'; import Button from '~/components/Button'; import Menu from '~/components/Popper/Menu'; import { InboxIcon, MessageIcon, SearchIcon, UploadIcon } from '~/components/Icons'; import Search from '../Search'; import { Link } from 'react-router-dom'; const cx = classNames.bind(styles); const MENU_ITEMS = [ { title: ' English', icon: <FontAwesomeIcon icon={faEarthAsia} />, children: { title: 'Language', data: [ { type: 'language', code: 'en', title: 'English' }, { type: 'language', code: 'vi', title: 'Tiếng việt' }, ], }, }, { title: ' Feedback and help', icon: <FontAwesomeIcon icon={faBullhorn} />, to: '/feedback', }, { title: ' Keybroad shotcurt', icon: <FontAwesomeIcon icon={faEarthAsia} />, }, ]; function Header() { const currentUser = true; const handleMenuChange = (MenuItem) => { switch (MenuItem.type) { case 'language': console.log(MenuItem); default: } }; const USER_MENU = [ { title: ' View profile', icon: <FontAwesomeIcon icon={faUser} />, to: '/@vanquoc', }, { title: 'Get Coins', icon: <FontAwesomeIcon icon={faCoins} />, to: '/feedback', }, { title: ' Setting', icon: <FontAwesomeIcon icon={faGear} />, to: '/setting', }, ...MENU_ITEMS, { title: ' Log out', icon: <FontAwesomeIcon icon={faSignOut} />, to: '/logout', saparate: true, }, ]; return ( <header className={cx('wrapper')}> <div className={cx('inner')}> <div className={cx('logo')}> <Link to={routesConfig.home}> <img src={images.logo} alt="Titok" /> </Link> </div> <Search /> <div className={cx('actions')}> {currentUser ? ( <div className={cx('current-user')}> <Tippy delay={(0, 200)} content="Upload"> <button className={cx('action-btn')}> {/* <FontAwesomeIcon icon={faCloudUpload} /> */} <UploadIcon /> </button> </Tippy> <Tippy delay={(0, 200)} content="Message"> <button className={cx('action-btn')}> <MessageIcon /> {/* <FontAwesomeIcon icon={faMessage} /> */} </button> </Tippy> <Tippy delay={(0, 200)} content="Inbox"> <button className={cx('action-btn')}> <InboxIcon /> {/* <FontAwesomeIcon icon={faMessage} /> */} </button> </Tippy> </div> ) : ( <> <Button text>Upload</Button> <Button rounded primary leftIcon={<FontAwesomeIcon icon={faSignIn} />}> Log in </Button> </> )} <Menu items={currentUser ? USER_MENU : MENU_ITEMS} onChange={handleMenuChange}> {currentUser ? ( <Image className={cx('user-avatar')} src="https://p16-sign-va.tiktokcdn.com/tos-useast2a-avt-0068-aiso/65d3c6b1d1e205c75536ccf1f26d552d~c5_100x100.jpeg?x-expires=1666292400&x-signature=GIubOWFaHX78a63pT%2FyxrZ3aH0c%3Ds" alt="Nguyen Van Quoc" fallback="https://p16-sign-va.tiktokcdn.com/tos-useast2a-avt-0068-giso/fac92301a36c2275c99f393061ef04ca~c5_100x100.jpeg?x-expires=1666324800&x-signature=55stZ4lEN%2B3PkDuAuBOVMWvYEXE%3D" /> ) : ( <> <button className={cx('more-btn')}> <FontAwesomeIcon icon={faEllipsisVertical} /> </button> </> )} </Menu> </div> </div> </header> ); } export default Header;
#include "sort.h" /** * bitonic_sort - sorts an array of integers in ascending order using the * Bitonic sort algorithm * @array: array to be sorted * @size: size of the array * * Return: void */ void bitonic_sort(int *array, size_t size) { if (array == NULL || size < 2) return; bitonic_recur(array, 0, size, 1); } /** * bitonic_recur - recursive function for bitonic sort * @array: array to be sorted * @low: low index * @size: size of the array * @dir: direction (1 for UP, 0 for DOWN) * * This function recursively divides the array and merges it in a bitonic manner. * * Return: void */ void bitonic_recur(int *array, size_t low, size_t size, int dir) { size_t k = size / 2; if (size < 2) return; printf("Merging [%lu] (%s):\n", size, dir == 1 ? "UP" : "DOWN"); print_array(array + low, size); bitonic_recur(array, low, k, 1); bitonic_recur(array, low + k, k, 0); bitonic_merge(array, low, size, dir); printf("Result [%lu] (%s):\n", size, dir == 1 ? "UP" : "DOWN"); print_array(array + low, size); } /** * bitonic_merge - merge function for bitonic sort * @array: array to be sorted * @low: low index * @size: size of the array * @dir: direction (1 for UP, 0 for DOWN) * * This function recursively merges two bitonic sequences. * * Return: void */ void bitonic_merge(int *array, size_t low, size_t size, int dir) { size_t i; size_t k = size / 2; int tmp; if (size < 2) return; for (i = low; i < low + k; i++) { if (dir == (array[i] > array[i + k])) { tmp = array[i]; array[i] = array[i + k]; array[i + k] = tmp; } } bitonic_merge(array, low, k, dir); bitonic_merge(array, low + k, k, dir); }
package com.htk.ytubevideo.login.presentation import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.htk.ytubevideo.core.navigation.RouterNavigation import com.htk.ytubevideo.features.login.data.model.LoginAuthenticateCredentials import com.htk.ytubevideo.features.login.presentation.LoginAction import com.htk.ytubevideo.features.login.presentation.LoginProvider import com.htk.ytubevideo.features.login.presentation.LoginViewModel import com.htk.ytubevideo.utils.BaseUnitTest import com.htk.ytubevideo.utils.MainDispatcherRule import io.mockk.coEvery import io.mockk.mockk import io.mockk.spyk import io.mockk.verify import kotlinx.coroutines.flow.flow import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test class LoginViewModelTest : BaseUnitTest<LoginViewModel>() { private val routerNavigation: RouterNavigation = mockk(relaxed = true) private val loginProvider: LoginProvider = mockk(relaxed = true) @get:Rule val mainDispatcherRule = MainDispatcherRule() @get:Rule val rule = InstantTaskExecutorRule() @Before fun setup() { viewModel = spyk(LoginViewModel(routerNavigation, loginProvider)) } @Test fun `when signInAuthenticateFirebaseUseCase has successful then submitLogin should call saveCredentialsAndNavigateHome`() = runBlocking { // Given val someEmail = "aosdksoadk@hotmail.com" val somePassword = "13213213412424" val mockCredentials = LoginAuthenticateCredentials(uid = "123213214214") coEvery { loginProvider.signInAuthenticateFirebaseUseCase.invoke(someEmail, somePassword) } returns flow { emit(mockCredentials) } // When viewModel.submitLogin(someEmail, somePassword) // Then verify { viewModel.saveCredentialsAndNavigateToHome(mockCredentials) } } @Test fun `when signInAuthenticateFirebaseUseCase has successful then submitLogin should call LoginActionNavigateToHome`() = runBlocking { // Given val someEmail = "aosdksoadk@hotmail.com" val somePassword = "13213213412424" val mockCredentials = LoginAuthenticateCredentials(uid = "123213214214") coEvery { loginProvider.signInAuthenticateFirebaseUseCase.invoke(someEmail, somePassword) } returns flow { emit(mockCredentials) } // When viewModel.submitLogin(someEmail, somePassword) // Then viewModel.action.onChangedTest(LoginAction.NavigateToHome) } @Test fun `when signInAuthenticateFirebaseUseCase has error then submitLogin should call handleError`() { // Given val someEmail = "aosdksoadk@hotmail.com" val somePassword = "13213213412424" val mockThrowable = Throwable(message = "any error") coEvery { loginProvider.signInAuthenticateFirebaseUseCase.invoke(someEmail, somePassword) } returns flow { throw mockThrowable } // When viewModel.submitLogin(someEmail, somePassword) // Then verify { viewModel.handleError(mockThrowable) } } @Test fun `when signInAuthenticateFirebaseUseCase has error then submitLogin should call LoginActionShowMessageErrorSignIn`() { // Given val someEmail = "aosdksoadk@hotmail.com" val somePassword = "13213213412424" val mockThrowable = Throwable(message = "any error") coEvery { loginProvider.signInAuthenticateFirebaseUseCase.invoke(someEmail, somePassword) } returns flow { throw mockThrowable } // When viewModel.submitLogin(someEmail, somePassword) // Then viewModel.action.onChangedTest(LoginAction.ShowMessageErrorSignIn) } }
from django.shortcuts import redirect from django.urls import reverse from django.views.generic import TemplateView from django.http import JsonResponse from django.contrib.auth.mixins import LoginRequiredMixin from ..models import MQTTConfiguration, Device, Room, StateConfig from ..forms import MQTTConfigurationForm, DeviceForm, RoomForm, StateConfigForm import json from rest_framework.authtoken.models import Token from django.http import HttpResponseRedirect import uuid def generate_unique_mqtt_id(): return str(uuid.uuid4()) class ConfigurationView(LoginRequiredMixin, TemplateView): template_name = 'profile/configuration.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Getting or creating a token for the user token, created = Token.objects.get_or_create(user=self.request.user) context['token'] = token context['device_form'] = DeviceForm() context['devices'] = Device.objects.filter(user=self.request.user) context['room_form'] = RoomForm() # Getting or creating the MQTT configuration instance for the user mqtt_config = MQTTConfiguration.objects.filter(user=self.request.user).first() if not mqtt_config: # Generate unique mqtt_id and create a new MQTT configuration unique_mqtt_id = generate_unique_mqtt_id() mqtt_config = MQTTConfiguration.objects.create( user=self.request.user, mqtt_id=unique_mqtt_id, broker_address='localhost', # Default broker address port=1883 # Default port ) context['mqtt_form'] = MQTTConfigurationForm(instance=mqtt_config) rooms = Room.objects.filter(user=self.request.user) context['rooms'] = rooms rooms_data = [{'room_id': str(room.room_id), 'name': room.name, 'position_x': room.position_x, 'position_y': room.position_y} for room in rooms] context['rooms_json'] = json.dumps(rooms_data) room_connections = [] for room in context['rooms']: connected_rooms = room.connected_rooms.all() for connected_room in connected_rooms: room_connections.append({ 'source': str(room.room_id), 'target': str(connected_room.room_id), }) json_rooms = json.dumps(room_connections) context['room_connections_json'] = json_rooms # Ensure default StateConfig exists if not StateConfig.objects.filter(user=self.request.user).exists(): self.create_default_state_configs(self.request.user) state_name = self.request.GET.get('state', 'IDLE') state_config, _ = StateConfig.objects.get_or_create( user=self.request.user, state_name=state_name, defaults={'color_code': '#FFFFFF'} ) context['state_config_form'] = StateConfigForm(instance=state_config) context['current_state'] = state_name context['state_names'] = StateConfig.STATE_NAMES context['state_config'] = state_config return context def create_default_state_configs(self, user): default_configs = [ {'state_name': 'IDLE', 'color_code': '#FFFFFF'}, {'state_name': 'ACTIVE', 'color_code': '#00FF00'}, {'state_name': 'MEDICATION_TAKEN', 'color_code': '#0000FF'}, {'state_name': 'MEDICATION_MISSED', 'color_code': '#FF0000'}, {'state_name': 'ALERT', 'color_code': '#FFFF00'}, ] for config in default_configs: StateConfig.objects.create( user=user, state_name=config['state_name'], color_code=config['color_code'] ) def post(self, request, *args, **kwargs): # Initialize both forms mqtt_config, created = MQTTConfiguration.objects.get_or_create( user=request.user, defaults={'port': 1883, 'broker_address': 'localhost'} ) mqtt_form = MQTTConfigurationForm(request.POST, instance=mqtt_config) device_form = DeviceForm(request.POST or None) room_form = RoomForm(request.POST or None) # Check if MQTT configuration form is submitted if 'mqtt_submit' in request.POST: if mqtt_form.is_valid(): mqtt_form.save() return redirect(reverse('configuration')) # Adjust the redirect as needed # Check if Device form is submitted elif 'device_submit' in request.POST: if device_form.is_valid(): device = device_form.save(commit=False) device.user = request.user device.save() return redirect(reverse('configuration')) # Adjust the redirect as needed # Check if Room form is submitted elif 'room_submit' in request.POST: if room_form.is_valid(): room = room_form.save(commit=False) room.user = request.user room.save() return redirect(reverse('configuration')) # Adjust the redirect as needed elif 'state_config_submit' in request.POST: state_config_form = StateConfigForm(request.POST, request.FILES, instance=StateConfig.objects.get(user=request.user, state_name=request.POST.get('state_name'))) if state_config_form.is_valid(): state_config_form.save() elif 'connect_rooms' in request.POST: room1_id = request.POST.get('room1_id') room2_id = request.POST.get('room2_id') try: room1 = Room.objects.get(pk=room1_id, user=request.user) room2 = Room.objects.get(pk=room2_id, user=request.user) room1.connected_rooms.add(room2) # Add connection room1.save() return JsonResponse({'status': 'success', 'message': 'Rooms connected successfully.'}) except Room.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'Room not found.'}, status=404) elif 'update_device_room' in request.POST: device_id = request.POST.get('update_device_room') device = Device.objects.get(device_id=device_id, user=request.user) room_id = request.POST.get('room') if room_id: device.room = Room.objects.get(room_id=room_id, user=request.user) else: device.room = None device.save() context = self.get_context_data(mqtt_form=mqtt_form, device_form=device_form, room_form=room_form) return self.render_to_response(context)
#include<iostream> using namespace std; class Rectangle{ private: int length; int breadth; public: Rectangle(){ // default constructor --> no parameters and initializes to 1 if you want length = 1; breadth = 1; } Rectangle(int l , int b){ //constructor // --> CONSTRUCTOR OVERLOADING length = l; breadth = b; } int area(){ return length * breadth; } ~Rectangle(){//DESTRUCTOR cout << "Destructor" << endl; } }; int main(){ Rectangle r1(10, 50); int area = r1.area(); cout << area << endl; return 0; }
import { ADD_SHOPPING_LIST, DELETE_SHOPPING_LIST, SET_SHOPPING_LISTS, SET_SHOPPING_LIST_UNITS, UPDATE_SHOPPING_LIST, } from './actionTypes'; import { createShoppingList, getShoppingLists, deleteShoppingList, updateShoppingList, getUnits, createShoppingListItem, deleteShoppingListItem, updateShoppingListItem, } from '../../managers/ShoppingListService'; export const loadLists = () => { return async (dispatch) => { try { const lists = await getShoppingLists(); dispatch({ type: SET_SHOPPING_LISTS, payload: { lists, }, }); } catch (error) { alert(error); } }; }; export const createList = (name) => { return (dispatch) => { createShoppingList(name).then((list) => dispatch({ type: ADD_SHOPPING_LIST, payload: { list: { ...list, products: [], }, }, }), ); }; }; export const updateList = (list) => { return (dispatch) => { updateShoppingList({ id: list.id, name: list.name }).then(() => dispatch({ type: UPDATE_SHOPPING_LIST, payload: { list, }, }), ); }; }; export const removeList = (list) => { return async (dispatch) => { try { await deleteShoppingList(list.id); dispatch({ type: DELETE_SHOPPING_LIST, payload: { list, }, }); } catch (error) { alert(error); throw error; } }; }; export const completeList = (list, completed) => { return (dispatch) => { dispatch({ type: UPDATE_SHOPPING_LIST, payload: { list: { ...list, checked: completed, }, }, }); }; }; export const addProduct = (list, product) => { return (dispatch) => { createShoppingListItem(list.id, product).then((newProduct) => dispatch({ type: UPDATE_SHOPPING_LIST, payload: { list: { ...list, products: [...list.products, newProduct], }, }, }), ); }; }; export const updateProduct = (list, updatedProduct) => { return (dispatch) => { updateShoppingListItem(list.id, updatedProduct).then(() => dispatch({ type: UPDATE_SHOPPING_LIST, payload: { list: { ...list, products: list.products.map((product) => (product.id === updatedProduct.id ? updatedProduct : product)), }, }, }), ); }; }; export const removeProduct = (list, removedProduct) => { return async (dispatch) => { try { await deleteShoppingListItem(list.id, removedProduct.id); dispatch({ type: UPDATE_SHOPPING_LIST, payload: { list: { ...list, products: list.products.filter((product) => product.id !== removedProduct.id), }, }, }); } catch (error) { alert(error); throw error; } }; }; export const loadUnits = () => { return (dispatch) => { getUnits().then((units) => dispatch({ type: SET_SHOPPING_LIST_UNITS, payload: { units, }, }), ); }; };
class Voiture(): def __init__(self,marque="ford",couleur="rouge",pilote="personne",vitesse=0): self.marque=marque self.couleur=couleur self.pilote=pilote self.vitesse=vitesse def __str__(self): return(f"Marque :{self.marque}, Couleur :{self.couleur}, Pilote :{self.pilote}, Vitesse :{self.vitesse}") def Choix_conducteur(self, nom): self.pilote=nom def accelerer(self, taux,durée): if self.pilote != 'personne': gain_vitesse=taux*durée self.vitesse = self.vitesse + gain_vitesse def afficher_tout(self): print(f"La voiture {self.marque} de couleur {self.couleur} est piloté par {self.pilote} avec un vitesse {self.vitesse}") if __name__== "__main__": a1=Voiture('Peugeot','bleue') a2=Voiture(couleur='verte') a3=Voiture('Mercedes') a1.Choix_conducteur('Khalil') a2.Choix_conducteur('Juliette') a2.accelerer(1.8,12) a2.accelerer(1.9,11) a1.afficher_tout() a2.afficher_tout() a3.afficher_tout() a1.accelerer(44,15) ## Affichage avec str print(str(a1))
import React, { useState } from 'react'; import { Button, Modal, Form, Upload } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; const AddImage = ({input,setInput,openimage,setOpenimage}) => { const [form] = Form.useForm(); const [fileName, setFileName] = useState("select a file"); const [selectedFile, setSelectedFile] = useState(new File([], '', { type: 'application/octet-stream' })); const [imageSelected, setImageSelected] = useState(false); const handleOk = () => { // Check if an image is selected if (!imageSelected) { // Display a warning message if no image is selected Modal.warning({ title: 'Warning', content: 'No image selected, Please select an image before clicking "Add".', }); return; } form.validateFields().then((values) => { setInput([...input, { type: 'image', value: URL.createObjectURL(selectedFile) }]); console.log(input); setOpenimage(false); setFileName("select a file"); setImageSelected(false); }); }; const handleCancel = () => { setOpenimage(false); setFileName("select a file") }; const props = { beforeUpload: file => { setSelectedFile(file); setFileName(file.name); setImageSelected(true); return false; }, showUploadList: false, }; return ( <Modal visible={openimage} title="Select image" onCancel={handleCancel} footer={[ <Button key="cancel" onClick={ handleCancel}> Cancel </Button>, <Button key="add" type="primary" onClick={handleOk}> Add </Button>, ]} > <Form form={form} layout="vertical"> <Form.Item name="image" rules={[{ required: true }]}> <Upload {...props}> <Button icon={<UploadOutlined />}>{fileName}</Button> </Upload> </Form.Item> </Form> </Modal> ); }; export default AddImage;
# Ollama handler ## Briefly describe the ML framework this handler integrates with MindsDB, and how? [Ollama](https://ollama.ai/) is a project that enables easy local deployment of Large Language Models (LLMs). All models supported by Ollama are available in MindsDB through this integration. For now, this integration will only work in MacOS, with Linux and Windows to come later. Call this handler by `USING ENGINE="ollama"`, you can see a full example at the end of this readme. ## Why is this integration useful? What does the ideal predictive use case for this integration look like? When would you definitely not use this integration? Locally deployed LLMs can be desirable for a wide variety of reasons. In this case, data privacy, developer feedback-loop speed and inference cost reduction can be powerful reasons to opt for a local LLM. Ideal predictive use cases, as in other LLM-focused integrations (e.g. OpenAI, Anthropic, Cohere), will be anything involving language understanding and generation, including but not limited to: - zero-shot text classification - sentiment analysis - question answering - summarization - translation Some current limitations of local LLMs: - overall weaker performance (ranging from "somewhat" to "a lot") than commercial cloud-based LLMs, particularly GPT-4. Please study options carefully and benchmark thoroughly to ensure your LLM is at the right level of performance for your use case before deploying to production. - steep entry barrier due to required hardware specs (macOS only, M1 chip or greater, a lot of RAM depending on model size) ## Are models created with this integration fast and scalable, in general? Model training is not required, as these are pretrained models. Inference is generally fast, however stream generation is not supported at this time in MindsDB, so completions are only returned once the model has finished generating the entire sequence. ## What are the recommended system specifications? * A macOS machine, M1 chip or greater. * A working Ollama installation. For instructions refer to their [webpage](https://ollama.ai). This step should be really simple. * For 7B models, at least 8GB RAM is recommended. * For 13B models, at least 16GB RAM is recommended. * For 70B models, at least 64GB RAM is recommended. More information [here](https://ollama.ai/library/llama2). Minimum specs can vary depending on the model. ## To what degree can users control the underlying framework by passing parameters via the USING syntax? The prompt template can be overridden at prediction time, e.g.: ```sql -- example: override template at prediction time SELECT text, completion FROM my_llama2 WHERE text = 'hi there!'; USING prompt_template = 'Answer using exactly five words: {{text}}:'; ``` ## Does this integration offer model explainability or insights via the DESCRIBE syntax? It replicates the information exposed by the Ollama API, plus a few additional MindsDB-specific fields. Supported commands are: 1. `DESCRIBE ollama_model;` 2. `DESCRIBE ollama_model.model;` 3. `DESCRIBE ollama_model.features;` ## Does this integration support fine-tuning pre-existing models (i.e. is the update() method implemented)? Are there any caveats? Not at this time. ## Any directions for future work in subsequent versions of the handler? A few are commented in the code: 1. add support for overriding modelfile params (e.g. temperature) 2. add support for storing `context` short conversational memory 3. actually store all model artifacts in the engine storage, instead of the internal Ollama mechanism. This may require upstream changes, though. ## Please provide a minimal SQL example that uses this ML engine (pointers to integration tests in the PR also valid) ```sql CREATE ML_ENGINE ollama FROM ollama; CREATE MODEL my_llama2 PREDICT completion USING model_name = 'llama2', engine = 'ollama'; DESCRIBE my_llama2.model; DESCRIBE my_llama2.features; SELECT text, completion FROM my_llama2 WHERE text = 'hi there!'; ```
"use client"; import React, { useState, FormEvent } from "react"; import Link from "next/link"; import { FaGoogle } from "react-icons/fa"; import { FiGithub } from "react-icons/fi"; import { useRouter } from "next/navigation"; import { useAddUsersMutation } from "@/app/features/bazar/bazarApi"; interface signupInterface { name: string; email: string; password: string; role: string; personalNumber: number; parentNumber: number; religious: string; bloodGroup: string; idCard: number; selectedImage: string; month: string; reportCardStatus: boolean; messMemberStatus: boolean; } const Signup = () => { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [personalNumber, setPersonalNumber] = useState(""); const [parentNumber, setParentNumber] = useState(""); const [religious, setReligious] = useState(""); const [selectedImage, setSelectedImage] = useState<File | null>(null); const [bloodGroup, setBloodGroup] = useState(""); const [idCard, setNationalIdCard] = useState(""); const [month, setMonth] = useState(""); const [error, setError] = useState(""); const [AddUsers] = useAddUsersMutation(); const router = useRouter(); const reset = () => { setName(""); setEmail(""); setPassword(""); setPersonalNumber(""); setParentNumber(""); setReligious(""); setBloodGroup(""); setNationalIdCard(""); }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); if (!name || !email || !password) { setError("All Fields Fillup Needed"); } if (selectedImage) { const formData = new FormData(); formData.append("image", selectedImage); const response = await fetch( "https://api.imgbb.com/1/upload?key=86fe1764d78f51c15b1a9dfe4b9175cf", { method: "POST", body: formData, } ); const imageData = await response.json(); const signupInfo: signupInterface = { name, email, password, role: "user", selectedImage: imageData.data.url, personalNumber: parseFloat(personalNumber), parentNumber: parseFloat(personalNumber), religious, bloodGroup, month, idCard: parseFloat(idCard), reportCardStatus: false, messMemberStatus: false, }; try { const response = await AddUsers(signupInfo); console.log(response); if ("data" in response) { router.push("/login"); reset(); } } catch (error) { console.log(error); } // Continue with the rest of the signup process } else { const signupInfo: signupInterface = { name, email, password, role: "user", selectedImage: "", // or some default value personalNumber: parseFloat(personalNumber), parentNumber: parseFloat(personalNumber), religious, bloodGroup, month, idCard: parseFloat(idCard), reportCardStatus: false, messMemberStatus: false, }; } }; const months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; const bloodGroups = ["A+", "A-", "B+", "B-", "AB+", "AB-", "O+", "O-"]; return ( <div className="h-screen flex justify-center items-center "> <div className=" w-5/6 mx-auto grid grid-cols-2 gap-32 justify-between items-center "> <div className="bg-gradient-to-r from-cyan-500 to-blue-500 text-white h-screen flex items-center justify-center"> <div> <h2 className="text-4xl mb-3 font-semibold"> Welcome To Signup Page </h2> <p className="mb-2">Stay Connected With Us</p> <p className="mb-2">Please Signup With Your Personal Info</p> <div> <Link href={"/"}> <div className=" text-black mt-5 font-semibold bg-white px-6 py-3 rounded-lg"> Go To Home </div> </Link> </div> </div> </div> <div> <div className="text-center mb-8"> <h2 className="mb-2 text-4xl font-semibold">Let's Get Started</h2> {/* <p>Create An Account</p> <div className="flex justify-center gap-5 mt-5"> <FaGoogle className="text-xl "></FaGoogle> <FiGithub className="text-xl "></FiGithub> </div> */} </div> <form onSubmit={handleSubmit}> <div className="grid md:grid-cols-2 gap-5"> <input placeholder="Enter your name" name="name" value={name} required onChange={(e) => setName(e.target.value)} className="border-2 bg-transparent border-gray-200 px-4 py-2 rounded-lg w-full" /> <input type="file" accept="image/*" required onChange={(e) => { const file = e.target.files && e.target.files[0]; setSelectedImage(file); }} className="border-2 border-gray-200 bg-transparent px-4 py-2 rounded-lg w-full" /> <input type="email" name="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Enter your Email" className="border-2 bg-transparent border-gray-200 px-4 py-3 rounded-lg w-full" /> <input type="password" name="password" required value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Enter your Password" className="border-2 bg-transparent border-gray-200 px-4 py-2 rounded-lg w-full" /> <select name="month" value={month} required onChange={(e) => setMonth(e.target.value)} className=" border-2 bg-transparent border-white select select-bordered w-full" > {months.map((month) => ( <option key={month}>{month}</option> ))} </select> <input type="text" name="personalNumber" value={personalNumber} required onChange={(e) => setPersonalNumber(e.target.value)} placeholder="Enter your Personal Number" className="border-2 bg-transparent border-gray-200 px-4 py-2 rounded-lg w-full" /> <input type="text" name="parentNumber" value={parentNumber} required onChange={(e) => setParentNumber(e.target.value)} placeholder="Enter your Parent Number" className="border-2 bg-transparent border-gray-200 px-4 py-2 rounded-lg w-full" /> <input type="text" name="religious" value={religious} required onChange={(e) => setReligious(e.target.value)} placeholder="Enter your Religious" className="border-2 bg-transparent border-gray-200 px-4 py-3 rounded-lg w-full" /> <select name="bloodGroup" required value={bloodGroup} onChange={(e) => setBloodGroup(e.target.value)} className="border-2 border-white select select-bordered w-full" > <option value="">Select Your Blood Group</option> {bloodGroups.map((group) => ( <option key={group} value={group}> {group} </option> ))} </select> <input type="text" name="idCard" value={idCard} required onChange={(e) => setNationalIdCard(e.target.value)} placeholder="Enter your National Id Card Number" className="border-2 bg-transparent border-gray-200 px-4 py-2 rounded-lg w-full" /> </div> <button className="w-full my-5 bg-gradient-to-r from-cyan-500 to-blue-500 px-4 py-2 text-white rounded-lg"> Signup </button> {error && ( <div> <p className="bg-red-600 px-6 py-3 my-5 text-white">{error}</p> </div> )} </form> <div className=" text-end mt-5 "> <Link href="/login">Have An Account ? Login Here</Link> </div> </div> </div> </div> ); }; export default Signup;
import mongoose from "mongoose"; const schema = mongoose.Schema; const cartSchema = new schema( { userId: { type: mongoose.Schema.Types.ObjectId, ref: "users", required: true, }, items: [ { productTitle: { type: String, required: true, }, productPrice: { type: String, required: true, }, productId: { type: mongoose.Schema.Types.ObjectId, ref: "products", }, quantity: { type: Number, min: 1, }, }, ], status: { type: String, default: "Pending", }, }, { timestamps: true, } ); const cartModel = new mongoose.model("cart", cartSchema); export default cartModel;
var obj = { name: "why", age: 18, _address:"北京市" } // 存取属性描述符 // 1.隐藏某一个私有属性被希望直接被外界使用和赋值 // 2.如果我们希望某一个属性他访问和设置值的过程时,也会使用存储属性描述符 Object.defineProperty(obj,"address",{ configurable: false, enumerable: true, get:function(){ foo(); return this._address; }, set:function(value){ bar(); this._address=value; } }) obj.address="上海市" console.log(obj); function foo(){ console.log("获取了一次address的值"); } function bar(){ console.log("设置了address的值"); }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { LivroCreateComponent } from './livro-create/livro-create.component'; import { LivroDeleteComponent } from './livro-delete/livro-delete.component'; import { LivroReadAllComponent } from './livro-read-all/livro-read-all.component'; import { LivroUpdateComponent } from './livro-update/livro-update.component'; import { LivroComponent } from './livro/livro.component'; const livro: Routes = [ { path: "", component: LivroComponent, children:[ { path:"readall", component:LivroReadAllComponent }, { path:"create/:id_cat", component:LivroCreateComponent }, { path:"update/:id", component:LivroUpdateComponent }, { path:"delete/:id", component:LivroDeleteComponent }, { path:"", redirectTo: "livros/:idc_cat/readall", pathMatch: "full"} ]} ]; @NgModule({ imports: [RouterModule.forChild(livro)], exports: [RouterModule] }) export class LivroRoutingModule { }
require_relative "Candidate" class CandidateB < Candidate MON_TOAN = "Toán" MON_HOA = "Hóa" MON_SINH = "Sinh" attr_accessor :block def initialize(id, name, address, priority, block) super(id, name, address, priority) @block = block end def showInfor puts "ID: #{@id}, Name: #{@name}, Address: #{@address}, Priority: #{@priority}, Subject: #{MON_TOAN}, #{MON_HOA}, #{MON_SINH}" end end
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using TFlic.Model.Service; using TFlic.ViewModel.ViewModelClass; using AuthenticationManager = TFlic.Model.Authentication.AuthenticationManager; using ThreadingTask = System.Threading.Tasks.Task; namespace TFlic.Model.Transfer { static class ColumnTransferer { /// <summary> /// Передает файлы с сервера клиенту /// Также производятся некоторые преобразования, т.к. /// клиент имеет свое средство представлния данных /// </summary> /// <param name="columns"> Коллекция колонок </param> /// <param name="idOrganization"> </param> /// <param name="idProjects"></param> /// <param name="idBoard"></param> public static async ThreadingTask GetColumnsDataFromServer( ObservableCollection<Column> columns, long idOrganization, long idProjects, long idBoard) { ICollection<ColumnGET>? columnsDTO = null; try { columnsDTO = await WebClient.Get.ColumnsAllAsync(idOrganization, idProjects, idBoard); } catch (ApiException err) { if (err.StatusCode == (int) HttpStatusCode.Unauthorized) { var account = AccountService.ReadAccountFromJsonFile(); AuthenticationManager.Refresh(account.Tokens.RefreshToken, account.Login); columnsDTO = await WebClient.Get.ColumnsAllAsync(idOrganization, idProjects, idBoard); } } if (columnsDTO is null) { throw new NullReferenceException(); } for (int i = 0; i < columnsDTO.Count; i++) { ObservableCollection<Task> tasksBuffer = new(); await TaskTransferer.GetTasksDataFromServer( tasksBuffer, idOrganization, idProjects, idBoard, columnsDTO.ElementAt(i).Id); columns.Add( new Column() { Id = columnsDTO.ElementAt(i).Id, Title = columnsDTO.ElementAt(i).Name, Tasks = tasksBuffer }); } } public static async ThreadingTask AddColumnAndPutDataToServer( ObservableCollection<Column> columns, long idOrganization, long idProjects, long idBoard) { ColumnDTO newColumn = new() { Name = columns.Last().Title, Position = 0, LimitOfTask = 0, }; ColumnGET? columnGET = null; try { columnGET = await WebClient.Get.ColumnsPOSTAsync(idOrganization, idProjects, idBoard, newColumn); } catch (ApiException err) { if (err.StatusCode == (int) HttpStatusCode.Unauthorized) { var account = AccountService.ReadAccountFromJsonFile(); AuthenticationManager.Refresh(account.Tokens.RefreshToken, account.Login); columnGET = await WebClient.Get.ColumnsPOSTAsync(idOrganization, idProjects, idBoard, newColumn); } } if (columnGET is null) { throw new NullReferenceException(); } columns.Last().Id = columnGET.Id; } public static async ThreadingTask ChangeColumnAndPutDataToServer( ObservableCollection<Column> columns, long idOrganization, long idProjects, long idBoard, long idColumn, string newName, int indexColumn) { Operation replaceNameOperation = new() { Op = "replace", Value = newName, Path = "/Name" }; var requestBody = new List<Operation>() {replaceNameOperation}; try { await WebClient.Get.ColumnsPATCHAsync(idOrganization, idProjects, idBoard, idColumn, requestBody); } catch (ApiException err) { if (err.StatusCode == (int) HttpStatusCode.Unauthorized) { var account = AccountService.ReadAccountFromJsonFile(); AuthenticationManager.Refresh(account.Tokens.RefreshToken, account.Login); await WebClient.Get.ColumnsPATCHAsync(idOrganization, idProjects, idBoard, idColumn, requestBody); } } columns[indexColumn].Title = newName; } public static async ThreadingTask DeleteColumnAndPutDataToServer( long idOrganization, long idProjects, long idBoard, long idColumn) { try { await WebClient.Get.ColumnsDELETEAsync(idOrganization, idProjects, idBoard, idColumn); } catch (ApiException err) { if (err.StatusCode == (int) HttpStatusCode.Unauthorized) { var account = AccountService.ReadAccountFromJsonFile(); AuthenticationManager.Refresh(account.Tokens.RefreshToken, account.Login); await WebClient.Get.ColumnsDELETEAsync(idOrganization, idProjects, idBoard, idColumn); } } } } }
import { observer } from "mobx-react"; import { lobbyWs } from "api"; import { getUser, updateUser } from "ls"; import { Player } from "interfaces/Player"; import { GameStore } from "stores/GameStore"; import { Editable } from "components/Editable"; import { PlayerImage } from "components/PlayerImage"; import { ReactComponent as PictureSvg } from "svg/picture.svg"; import { ReactComponent as KickSvg } from "svg/kick.svg"; import { ReactComponent as MemoSvg } from "svg/notes.svg"; import { ReactComponent as CorrectSvg } from "svg/correct.svg"; import styles from "./styles.module.scss"; interface PlayerSlotProps { player: Player; editingNotes: boolean; setEditingNotes: (v: boolean) => void; } const PlayerSlotComponent = ({ player, editingNotes, setEditingNotes }: PlayerSlotProps) => { const me = getUser().id === player.id; const correct = player.correct === "yes"; const slotStyles = [styles.slot]; if (!me && !player.connected) slotStyles.push(styles.disconnected); const name = player.name ? player.name : "[Имя не задано]"; const nameStyles = [styles.name]; if (me) nameStyles.push(styles.editable); const secret = player.secret ? player.secret : "[Кто он/она?]"; const secretStyles = [styles.secret]; if (!me) secretStyles.push(styles.editable); const onUpdate = (field: string, value: string) => { lobbyWs.emit("player/change", { id: player.id, field, value }); }; const onChangePicture = () => { const value = prompt("Полный url картинки (https://*.*/***/image.jpg)"); if (value !== null) { lobbyWs.emit("player/change", { id: player.id, field: "picture", value }); } }; const onKickPlayer = () => { lobbyWs.emit("player/kick", { id: player.id }); }; return ( <div className={slotStyles.join(" ")}> <span className={nameStyles.join(" ")}> {me ? <Editable value={name} onUpdate={(value) => { const user = getUser(); user.name = value; updateUser(user); onUpdate("name", value) }} /> : <div className={styles.nameDetail}> {player.connected ? <PictureSvg onClick={onChangePicture} /> : <>{!GameStore.state.started && <KickSvg onClick={onKickPlayer}/>}</> } <span>{name}</span> <CorrectSvg onClick={() => onUpdate("correct", "yes")} /> </div> } </span> <span className={secretStyles.join(" ")}> {(!me || correct) && <> {player.connected ? <> {me ? <span>{secret}</span> : <Editable value={secret} onUpdate={(value) => onUpdate("secret", value)} /> } </> : <span>не в сети</span> } </>} </span> <div className={styles.image}> {(me && !correct) ? <div className={styles.notes}> {!editingNotes && <MemoSvg onClick={() => setEditingNotes(true)} />} </div> : <PlayerImage player={player}/> } </div> </div> ); }; export const PlayerSlot = observer(PlayerSlotComponent);
# Import necessary libraries import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt import seaborn as sns # Load and preprocess the Kaggle dataset data = pd.read_csv('Breastcancer.csv') # Update the dataset filename # Replace 'diagnosis' with the actual column name that contains the diagnosis information X = data.drop('diagnosis', axis=1) y = data['diagnosis'] # Feature scaling scaler = StandardScaler() X = scaler.fit_transform(X) # Create and train a Random Forest model model = RandomForestClassifier(n_estimators=100, random_state=42) model.fit(X, y) # Create a function to predict diagnoses for new patient data def predict_diagnosis(new_patient_data): diagnosis = model.predict([new_patient_data]) if diagnosis[0] == 'B': return "Benign" else: return "Malignant" # Command-line interface to take patient data and make predictions while True: print("Enter patient data:") mean_radius = float(input("Mean Radius: ")) mean_texture = float(input("Mean Texture: ")) mean_perimeter = float(input("Mean Perimeter: ")) mean_area = float(input("Mean Area: ")) mean_smoothness = float(input("Mean Smoothness: ")) input_data = [mean_radius, mean_texture, mean_perimeter, mean_area, mean_smoothness] result = predict_diagnosis(input_data) print(f"Predicted Diagnosis: {result}") # Data Visualization for Input sns.set(style="whitegrid") plt.figure(figsize=(8, 6)) plt.title("Input Data Visualization") # Create a bar plot to visualize the entered input data plt.bar( ["Mean Radius", "Mean Texture", "Mean Perimeter", "Mean Area", "Mean Smoothness"], input_data, color=['blue', 'green', 'red', 'purple', 'orange'] ) plt.ylabel("Value") plt.xticks(rotation=45) plt.show()
import { prismaMock } from "../../../helpers/singleton"; import UserModel from "../user.model"; import { User } from "@prisma/client"; const MOCKED_USERS: User[] = [ { id: 1, name: "Caio César", role: "DOCTOR", }, { id: 2, name: "Recepcionista 1", role: "RECEPTIONIST", }, ]; describe("User Model Tests", () => { it("retrieveUsers method should return all registered users", async () => { const userModel = new UserModel(); prismaMock.user.findMany.mockResolvedValue(MOCKED_USERS); const result = await userModel.retrieveUsers(); expect(result).toEqual(MOCKED_USERS); }); it("retrieveUserById should return an user with the selected ID", async () => { const userModel = new UserModel(); prismaMock.user.findUnique.mockResolvedValue(MOCKED_USERS[0]); const result = await userModel.retrieveUserById(MOCKED_USERS[0].id); expect(result).toEqual(MOCKED_USERS[0]); }); it("deleteUser should return the deleted user", async () => { const userModel = new UserModel(); prismaMock.user.delete.mockResolvedValue(MOCKED_USERS[0]); const result = await userModel.deleteUser(MOCKED_USERS[0].id); expect(result).toBe(MOCKED_USERS[0]); }); it("createUser should return the created user", async () => { const userModel = new UserModel(); prismaMock.user.create.mockResolvedValue(MOCKED_USERS[0]); const result = await userModel.createUser(MOCKED_USERS[0]); expect(result).toBe(MOCKED_USERS[0]); }); it("editUser should return the updated user", async () => { const userModel = new UserModel(); const expectedResult = { ...MOCKED_USERS[0], name: "Pedro", }; prismaMock.user.update.mockResolvedValue(expectedResult); const result = await userModel.editUser(1, expectedResult); expect(result).toBe(expectedResult); }); });
import { useState, useEffect } from "react"; import { Route, Switch, useHistory } from "react-router-dom"; import Footer from "./Footer"; import Header from "./Header"; import ImagePopup from "./ImagePopup"; import Main from "./Main"; import PopupWithForm from "./PopupWithForm"; import { Api } from "../utils/Api"; import { authorization, registration, checkToken } from "../utils/auth"; import { CurrentUserContext } from "../contexts/CurrentUserContext"; import EditProfilePopup from "./EditProfilePopup"; import EditAvatarPopup from "./EditAvatarPopup"; import AddPlacePopup from "./AddPlacePopup"; import ProtectedRoute from "./ProtectedRoute"; import SignIn from "./SignIn"; import SignUp from "./SignUp"; import InfoTooltip from "./InfoTooltip"; function App() { const [isInfoTooltipOpen, setIsInfoTooltipOpen] = useState(false); const [isEditProfileOpen, setIsEditProfileOpen] = useState(false); const [isEditAvatarOpen, setIsEditAvatarOpen] = useState(false); const [isAddplaceOpen, setIsAddPlaceOpen] = useState(false); const [isConfirmDeleteOpen, setIsConfirmDeleteOpen] = useState(false); const [selectedCard, setSelectedCard] = useState(null); const [currentUser, setCurrentUser] = useState({}); const [userEmail, setUserEmail] = useState(""); const [cards, setCards] = useState([]); const [loggedIn, setLoggedIn] = useState(false); const [registrationSuccessData, setRegistrationSuccessData] = useState({ status: false, message: "", }); const history = useHistory(); useEffect(() => { handleTokenCheck(); }); //Получение информации о пользователе useEffect(() => { if (loggedIn) Api.getUserInformation() .then((userInformation) => { if (userInformation) setCurrentUser(userInformation); else return Promise.reject(new Error("Sorry, we have problems")); }) .catch((error) => console.error(error)); }, [loggedIn]); //Получение карточек useEffect(() => { if (loggedIn) Api.getInitialCards() .then((cards) => { if (cards) setCards(cards); else return Promise.reject(new Error("Sorry, we have problems")); }) .catch((error) => console.error(error)); }, [loggedIn]); function handleCardLike(card, isLiked) { (isLiked ? Api.removeLike(card._id) : Api.setLike(card._id)) .then((newCard) => { if (newCard) setCards((cards) => cards.map((card) => (card._id === newCard._id ? newCard : card)) ); else return Promise.reject(new Error("Sorry, we have problems")); }) .catch((error) => console.error(error)); } function handleCardDelete(card, isOwn) { if (isOwn) { Api.deleteCard(card._id) .then((answer) => { if (answer) setCards((cards) => cards.filter((item) => item._id !== card._id)); else return Promise.reject(new Error("Sorry, we have problems")); }) .catch((error) => console.error(error)); } } function handleCardClick(card) { setSelectedCard(card); } function handleEditProfileClick() { setIsEditProfileOpen(true); } function handleEditAvatarClick() { setIsEditAvatarOpen(true); } function closeAllPopups() { setIsEditProfileOpen(false); setIsEditAvatarOpen(false); setIsAddPlaceOpen(false); setIsConfirmDeleteOpen(false); setSelectedCard(null); setIsInfoTooltipOpen(false); } function handleAddPlaceClick() { setIsAddPlaceOpen(true); } function handleUpdateUser({ name, description }) { return Api.updateUserInformation(name, description) .then((userInformation) => { if (userInformation) { setCurrentUser(userInformation); closeAllPopups(); } else { return Promise.reject(new Error("Sorry, we have problems")); } }) .catch((error) => console.error(error)); } function handleUpdateAvatar({ avatar }) { return Api.updateAvatar(avatar) .then((userInformation) => { if (userInformation) { setCurrentUser(userInformation); closeAllPopups(); } else { return Promise.reject(new Error("Sorry, we have problems")); } }) .catch((error) => console.error(error)); } function handleAddPlace(placeInfo) { return Api.createCard(placeInfo) .then((newCard) => { if (newCard) { setCards([newCard, ...cards]); closeAllPopups(); } else { return Promise.reject(new Error("Sorry, we have problems")); } }) .catch((error) => console.error(error)); } function handleTokenCheck() { checkToken() .then((res) => { setUserEmail(res.email); setLoggedIn(true); history.push("/"); }) .catch((error) => console.log(error)); } function handleSignOut() { return Api.signOut() .then(() => { setLoggedIn(false); setUserEmail(""); history.push("/sign-in"); }) .catch((error) => console.log(error)); } function handleRegistrationSubmit(formValues, setFormValues) { registration(formValues) .then(() => { setFormValues({ email: "", password: "" }); setRegistrationSuccessData({ ...registrationSuccessData, status: true, message: "Вы успешно зарегестрировались!", }); setIsInfoTooltipOpen(true); if (!isInfoTooltipOpen) history.push("/sign-in"); }) .catch((error) => { error.then((res) => { setRegistrationSuccessData({ ...registrationSuccessData, status: false, message: res.error, }); console.log(res.error); setIsInfoTooltipOpen(true); history.push("/sign-up"); }); }); } function handleLoginSubmit(formValues, setFormValues) { authorization(formValues) .then((result) => { if (result.token) { setFormValues({ email: "", password: "" }); // localStorage.setItem("jwt", result.token); setLoggedIn(true); history.push("/"); } }) .catch((error) => error.then((res) => { setRegistrationSuccessData({ ...registrationSuccessData, status: false, message: res.message, }); console.log(res.message); setIsInfoTooltipOpen(true); }) ); } return ( <CurrentUserContext.Provider value={currentUser}> <div className='page__container'> <Switch> <ProtectedRoute exact path='/' loggedIn={loggedIn} component={() => ( <> <Header title='Выйти' userEmail={userEmail} linkTo='/sign-in' onSignOut={handleSignOut} /> <Main onEditProfileClick={handleEditProfileClick} onEditAvatarClick={handleEditAvatarClick} onAddPlaceClick={handleAddPlaceClick} onCardClick={handleCardClick} onCardLike={handleCardLike} onCardDelete={handleCardDelete} cards={cards} /> </> )} /> <Route path='/sign-in'> <Header title='Регистрация' linkTo='/sign-up' /> <SignIn onSubmit={handleLoginSubmit} /> </Route> <Route path='/sign-up'> <Header title='Войти' linkTo='/sign-in' /> <SignUp onSubmit={handleRegistrationSubmit} /> </Route> </Switch> <Footer /> </div> <InfoTooltip isOpen={isInfoTooltipOpen} onClose={closeAllPopups} successData={registrationSuccessData} /> <EditProfilePopup isOpen={isEditProfileOpen} onUpdateUser={handleUpdateUser} onClose={closeAllPopups} /> <EditAvatarPopup isOpen={isEditAvatarOpen} onUpdateAvatar={handleUpdateAvatar} onClose={closeAllPopups} /> <AddPlacePopup isOpen={isAddplaceOpen} onAddPlace={handleAddPlace} onClose={closeAllPopups} /> <PopupWithForm title='Вы уверены?' name='confirm-delete' isOpen={isConfirmDeleteOpen} onClose={closeAllPopups} > <button type='submit' className='button form__confirm-button'> Да </button> </PopupWithForm> <ImagePopup onClose={closeAllPopups} card={selectedCard} /> </CurrentUserContext.Provider> ); } export default App;
import java.lang.*; import java.util.*; // for input class Number { private int iNo; //java access specifier // in java we have write(public/private) in front of variable every time public void Accept() { Scanner sobj = new Scanner(System.in); // here we have to create variable for input System.out.println("Enter number : "); this.iNo = sobj.nextInt(); // -> is same as . in java } public void Display() { System.out.println("Value is : "+this.iNo); } public int Factorial() { int iFact = 1; int iCnt = 0; for(iCnt=1; iCnt<= iNo; iCnt++) { iFact = iFact*iCnt; } return iFact; } } class program74 { public static void main(String b[]) { int iRet = 0; Number nobj = new Number(); //obj is created nobj.Accept(); nobj.Display(); iRet = nobj.Factorial(); System.out.println("Factorial is : "+ iRet); } }
package com.udacity.project4 import android.app.Application import android.view.View import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.espresso.Espresso import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.action.ViewActions import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.matcher.RootMatchers import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.udacity.project4.locationreminders.RemindersActivity import com.udacity.project4.locationreminders.data.ReminderDataSource import com.udacity.project4.locationreminders.data.local.LocalDB import com.udacity.project4.locationreminders.data.local.RemindersLocalRepository import com.udacity.project4.locationreminders.reminderslist.RemindersListViewModel import com.udacity.project4.locationreminders.savereminder.SaveReminderViewModel import com.udacity.project4.util.DataBindingIdlingResource import com.udacity.project4.util.monitorActivity import com.udacity.project4.utils.EspressoIdlingResource import kotlinx.coroutines.runBlocking import org.hamcrest.Matchers import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module import org.koin.test.KoinTest import org.koin.test.get @RunWith(AndroidJUnit4::class) @LargeTest //END TO END test to black box test the app class RemindersActivityTest : KoinTest {// Extended Koin Test - embed autoclose @after method to close Koin after every test private lateinit var repository: ReminderDataSource private lateinit var appContext: Application private val dataBindingIdlingResource = DataBindingIdlingResource() /** * As we use Koin as a Service Locator Library to develop our code, we'll also use Koin to test our code. * at this step we will initialize Koin related code to be able to use it in out testing. */ @Before fun init() { stopKoin()//Stop the original app koin appContext = getApplicationContext() val myModule = module { viewModel { RemindersListViewModel( appContext, get() as ReminderDataSource ) } single { SaveReminderViewModel( appContext, get() as ReminderDataSource ) } single { RemindersLocalRepository(get()) as ReminderDataSource } single { LocalDB.createRemindersDao(appContext) } } //Declare a new koin module startKoin { modules(listOf(myModule)) } //Get our real repository repository = get() //Clear the data to start fresh runBlocking { repository.deleteAllReminders() } } // TODO: add End to End testing to the app @Before fun registerIdlingResource() { IdlingRegistry.getInstance().register(EspressoIdlingResource.countingIdlingResource) IdlingRegistry.getInstance().register(dataBindingIdlingResource) } @After fun unregisterIdlingResource() { IdlingRegistry.getInstance().unregister(EspressoIdlingResource.countingIdlingResource) IdlingRegistry.getInstance().unregister(dataBindingIdlingResource) } @Test fun remindersActivity_showSnackBarTitleError() { val activityScenario = ActivityScenario.launch(RemindersActivity::class.java) dataBindingIdlingResource.monitorActivity(activityScenario) Espresso.onView(withId(R.id.addReminderFAB)).perform(ViewActions.click()) Espresso.onView(withId(R.id.saveReminder)).perform(ViewActions.click()) val snackBarMessage = appContext.getString(R.string.err_enter_title) Espresso.onView(ViewMatchers.withText(snackBarMessage)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) activityScenario.close() } @Test fun remindersActivity_showSnackBarLocationError() { val activityScenario = ActivityScenario.launch(RemindersActivity::class.java) dataBindingIdlingResource.monitorActivity(activityScenario) Espresso.onView(withId(R.id.addReminderFAB)).perform(ViewActions.click()) Espresso.onView(withId(R.id.reminderTitle)) .perform(ViewActions.typeText("Title")) Espresso.closeSoftKeyboard() Espresso.onView(withId(R.id.saveReminder)).perform(ViewActions.click()) val snackBarMessage = appContext.getString(R.string.err_select_location) Espresso.onView(ViewMatchers.withText(snackBarMessage)) .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) activityScenario.close() } @Test fun remindersActivity_showToastMessage() { val activityScenario = ActivityScenario.launch(RemindersActivity::class.java) dataBindingIdlingResource.monitorActivity(activityScenario) Espresso.onView(withId(R.id.addReminderFAB)).perform(ViewActions.click()) Espresso.onView(withId(R.id.reminderTitle)) .perform(ViewActions.typeText("Title")) Espresso.closeSoftKeyboard() Espresso.onView(withId(R.id.reminderDescription)) .perform(ViewActions.typeText("Description")) Espresso.closeSoftKeyboard() Espresso.onView(withId(R.id.selectLocation)).perform(ViewActions.click()) Espresso.onView(withId(R.id.save_button)).perform(ViewActions.click()) Espresso.onView(withId(R.id.saveReminder)).perform(ViewActions.click()) Espresso.onView(ViewMatchers.withText(R.string.reminder_saved)) .inRoot(RootMatchers.withDecorView(Matchers.not(getDecorView(activityScenario))))// Here we use decorView .check(ViewAssertions.matches(ViewMatchers.isDisplayed())) activityScenario.close() } private fun getDecorView(activityScenario: ActivityScenario<RemindersActivity>): View { lateinit var decorView: View activityScenario.onActivity { decorView = it.window.decorView } return decorView } }
import React, { useEffect, useMemo, useState } from "react"; import * as Yup from "yup"; import { ptForm } from "yup-locale-pt"; Yup.setLocale(ptForm); import { useNavigation } from "@react-navigation/native"; import { KeyboardAvoidingView, Platform, ScrollView, View } from "react-native"; import { showMessage } from "react-native-flash-message"; import { Header } from "../../components/Header"; import { InputSlider } from "../../components/InputSlider"; import { Input } from "../../components/Input"; import { Tag } from "../../components/Tag"; import { ShowResult } from "../../components/ShowResult"; import { InputSliderDecimalNumber } from "../../components/InputSliderDecimalNumber"; import { api } from "../../services/api"; import theme from "../../theme/index"; import { Container, ContainerTag, TitleTag, ButtonAddTag, TitleButtonTag, ButtonHandleSubmit, ContainerTitleTag, ButtonManageTag, TextManageTag, } from "./styles"; export function RegisterCalculation() { const navigation = useNavigation(); const [listTag, setListTag] = useState<any[]>([]); const [selectTag, setSelectTag] = useState(""); const [loading, setLoading] = useState(false); const [title, setTitle] = useState(""); const [entryWeight, setEntryWeight] = useState(0); const [dailyCost, setDailyCost] = useState("0.00"); const [priceAtPurchase, setPriceAtPurchase] = useState(0); const [gmd, setGmd] = useState(0); const [timeOfStay, setTimeOfStay] = useState(0); const [outputWeight, setOutputWeight] = useState(0); const [rcInitial, setRcInitial] = useState<string>("0.0"); const [rcFinal, setRcFinal] = useState<string>("0.0"); const [atSalePrice, setAtSalePrice] = useState(0); const [purchasePrice, setPurchasePrice] = useState(0); const [priceAtProduced, setPriceAtProduced] = useState(0); const [returnOnCapital, setReturnOnCapital] = useState(0); const [result, setResult] = useState(0); const [bash, setBash] = useState(0); const [description, setDescription] = useState(0); const handleTag = (id: string) => { setSelectTag(id); }; const tagSearch = async () => { api .get("/tag-calculations") .then((response) => { setListTag(response.data); }) .catch((err) => { showMessage({ message: "Error!", description: "Ocorreu para carregar as tag personalizadas", type: "danger", icon: "danger", }); }); }; useEffect(() => { tagSearch(); }, [listTag]); async function handleSubmit() { setLoading(true); try { const schema = Yup.object().shape({ title: Yup.string().required("Campo título é obrigatório"), entryWeight: Yup.number() .min(1, "Campo peso de entrada deve ser maior que 0") .required("Campo peso de entrada é obrigatório"), dailyCost: Yup.number() .min(1, "Campo Custo diário deve ser maior que 0") .required("Campo custo diário é obrigatório"), priceAtPurchase: Yup.number() .min(1, "Campo Preço @ compra deve ser maior que 0") .required("Campo preço @ compra é obrigatório"), gmd: Yup.number() .min(1, "Campo GMD deve ser maior que 0") .required("Campo GMD é obrigatório"), timeOfStay: Yup.number() .min(1, "Campo Tempo Permanência deve ser maior que 0") .required("Campo tempo Permanência é obrigatório"), rcInitial: Yup.string() .min(1, "Campo peso de entrada deve ser maior que 0") .required("Campo RC final é obrigatório"), rcFinal: Yup.string() .min(1, "Campo RC final deve ser maior que 0") .required("Campo RC final é obrigatório"), atSalePrice: Yup.number() .min(1, "Campo preço @ de venda deve ser maior que 0") .required("Campo preço @ de venda é obrigatório"), }); await schema.validate({ title, entryWeight, dailyCost, priceAtPurchase, gmd, timeOfStay, rcInitial, rcFinal, atSalePrice, }); const sendValue = { tag: selectTag, title: title, description: description.toString(), bash: bash.toString(), entranceWeight: entryWeight.toString(), dailyCost: `${dailyCost.toString()}-${priceAtPurchase}`, gmd: gmd.toString(), purchasePrice: purchasePrice.toString(), lengthOfStay: timeOfStay.toString(), outputWeight: outputWeight.toString(), rcInitial: rcInitial, rcEnd: rcFinal, salePrice: atSalePrice.toString(), producedPrice: priceAtProduced.toString(), returnOnCapital: returnOnCapital.toString(), result: result.toString(), }; await api.post("/calculations", sendValue); showMessage({ message: "Sucesso!", description: "Cálculo criado com sucesso!", type: "success", icon: "success", }); navigation.navigate("Dashboard", { refreshing: true, }); setLoading(false); } catch (error) { if (error instanceof Yup.ValidationError) { showMessage({ message: "Ops!", description: error.message, type: "danger", }); setLoading(false); } else { showMessage({ message: "Error na autenticação", description: "Ocorreu um erro ao criar cálculo, tente novamente mais tarde!", type: "danger", }); setLoading(false); } } setLoading(false); } useMemo(() => { const calc = (parseFloat(dailyCost) * timeOfStay) / bash; setPriceAtProduced(parseFloat(calc.toFixed(2))); }, [dailyCost, timeOfStay, bash]); useMemo(() => { const calc = ((entryWeight * (parseFloat(rcInitial) / 100)) / 15) * priceAtPurchase; setPurchasePrice(calc); }, [entryWeight, rcInitial, priceAtPurchase]); useMemo(() => { const calc = (outputWeight * (parseFloat(rcFinal) / 100) - entryWeight * (parseFloat(rcInitial) / 100)) / 15; setBash(parseFloat(calc.toFixed(2))); }, [outputWeight, rcFinal, entryWeight, rcInitial]); useMemo(() => { const calc = ((outputWeight * (parseFloat(rcFinal) / 100)) / 15) * atSalePrice; setDescription(calc); }, [outputWeight, rcFinal, atSalePrice]); useMemo(() => { const calc = ((result / (purchasePrice + parseFloat(dailyCost) * timeOfStay)) * 100) / (timeOfStay / 30.41); setReturnOnCapital(parseFloat(calc.toFixed(2))); }, [result, purchasePrice, dailyCost, timeOfStay]); useMemo(() => { const calc = description - (parseFloat(dailyCost) * timeOfStay + purchasePrice); setResult(calc); }, [description, dailyCost, timeOfStay, purchasePrice]); useMemo(() => { const calc = (gmd * timeOfStay) / 1000 + entryWeight; setOutputWeight(calc); }, [gmd, timeOfStay, entryWeight]); return ( <> <Header title="Novo cálculo" /> <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : undefined} keyboardVerticalOffset={Platform.OS === "ios" ? 0 : undefined} enabled style={{ flex: 1, backgroundColor: theme.COLORS.GRAY_50, }} > <ScrollView keyboardShouldPersistTaps="handled" style={{ backgroundColor: "#FCF9F2", flex: 1 }} > <Container> <ContainerTitleTag> <TitleTag>Etiquetas</TitleTag> <ButtonManageTag onPress={() => navigation.navigate("ManageTag")}> <TextManageTag>Gerenciar Etiquetas</TextManageTag> </ButtonManageTag> </ContainerTitleTag> <ContainerTag> {listTag && listTag.map((e) => ( <Tag key={e.id} title={e.title} color={e.color} onPress={() => handleTag(e.id)} id={e.id} selectId={selectTag} /> ))} </ContainerTag> <ButtonAddTag onPress={() => navigation.navigate("CreateTag", { flow: "CreateCalculation" }) } > <TitleButtonTag>Criar nova etiqueta</TitleButtonTag> </ButtonAddTag> <Input title="Título" placeholder="Título" autoCapitalize="none" autoCorrect={false} keyboardAppearance="dark" onChangeText={setTitle} value={title} /> <View style={{ marginTop: 10 }} /> <InputSlider title="Peso de entrada(Kg)" placeholder="Peso de entrada" autoCapitalize="none" autoCorrect={false} keyboardAppearance="dark" keyboardType="numeric" onChangeText={(e) => { if (e === "" || e === "0" || (e.length === 1 && e !== ".")) { setEntryWeight(0); } else { const num = parseFloat(e); if (!isNaN(num) && num <= 1500) { setEntryWeight(num); } } }} value={entryWeight.toString()} sliderValue={(value) => setEntryWeight(value)} isSlide inputValue={entryWeight} maximumValueSlider={1000} /> <InputSliderDecimalNumber keyboardType="numeric" title="Custo diário(R$)" placeholder="Custo diário" autoCorrect={false} keyboardAppearance="dark" onChangeText={(e) => { const regex = /^(\d+(\.\d{0,11})?)?$/; if (regex.test(e)) { setDailyCost(e); } else { setDailyCost(e); } }} value={dailyCost} inputValue={dailyCost ? parseFloat(dailyCost) : 0} sliderValue={(newValue: number) => { setDailyCost(newValue.toFixed(2)); }} maximumValue={50} /> <InputSlider title="Preço @ compra(R$)" placeholder="Preço @ compra" autoCorrect={false} keyboardAppearance="dark" keyboardType="numeric" onChangeText={(e) => { if (e === "" || e === "0" || (e.length === 1 && e !== ".")) { setPriceAtPurchase(0); } else { const num = parseFloat(e); if (!isNaN(num) && num <= 1000) { setPriceAtPurchase(num); } } }} value={priceAtPurchase.toString()} sliderValue={(value) => setPriceAtPurchase(value)} isSlide inputValue={priceAtPurchase} maximumValueSlider={500} /> <InputSlider title="GMD(g)" placeholder="GMD" autoCapitalize="none" autoCorrect={false} keyboardAppearance="dark" keyboardType="numeric" onChangeText={(e) => { if (e === "" || e === "0" || (e.length === 1 && e !== ".")) { setGmd(0); } else { const num = parseFloat(e); if (!isNaN(num) && num <= 3000) { setGmd(num); } } }} value={gmd.toString()} sliderValue={(value) => setGmd(value)} isSlide inputValue={gmd} maximumValueSlider={3000} /> <InputSlider title="Tempo Permanência(dias)" placeholder="Tempo Permanência" autoCapitalize="none" autoCorrect={false} keyboardAppearance="dark" keyboardType="numeric" onChangeText={(e) => { if (e === "" || e === "0" || (e.length === 1 && e !== ".")) { setTimeOfStay(0); } else { const num = parseFloat(e); if (!isNaN(num) && num <= 1000) { setTimeOfStay(num); } } }} value={timeOfStay.toString()} sliderValue={(value) => setTimeOfStay(value)} isSlide inputValue={timeOfStay} maximumValueSlider={1000} /> <ShowResult title="Peso de saída(Kg)" label={outputWeight} /> <View style={{ marginTop: 10 }} /> <InputSliderDecimalNumber keyboardType="numeric" title="RC inicial(%)" placeholder="RC inicial" autoCorrect={false} keyboardAppearance="dark" onChangeText={(e) => { const regex = /^(\d+(\.\d{0,1})?)?$/; if (regex.test(e)) { setRcInitial(e); } else { setRcInitial(e); } }} value={rcInitial} inputValue={rcInitial ? parseFloat(rcInitial) : 0} sliderValue={(newValue: number) => { setRcInitial(newValue.toFixed(1)); }} maximumValue={100} /> <InputSliderDecimalNumber keyboardType="numeric" title="RC final(%)" placeholder="RC final" autoCorrect={false} keyboardAppearance="dark" onChangeText={(e) => { const regex = /^(\d+(\.\d{0,1})?)?$/; if (regex.test(e)) { setRcFinal(e); } else { setRcFinal(e); } }} value={rcFinal} inputValue={rcFinal ? parseFloat(rcFinal) : 0} sliderValue={(newValue: number) => { setRcFinal(newValue.toFixed(1)); }} maximumValue={100} /> <InputSlider title="Preço @ de venda(R$)" placeholder="Preço @" autoCapitalize="none" autoCorrect={false} keyboardAppearance="dark" keyboardType="numeric" onChangeText={(e) => { if (e === "" || e === "0" || (e.length === 1 && e !== ".")) { setAtSalePrice(0); } else { const num = parseFloat(e); if (!isNaN(num) && num <= 1000) { setAtSalePrice(num); } } }} value={atSalePrice.toString()} sliderValue={(value) => setAtSalePrice(value)} isSlide inputValue={atSalePrice} maximumValueSlider={500} /> <ShowResult title="Preço @ produzida(R$)" label={priceAtProduced} isMoney /> <ShowResult title="Valor de compra(R$)" label={purchasePrice} isMoney /> <ShowResult title="Quantidade de @ Produzidas" label={bash} /> <ShowResult title="Preço de venda(R$)" label={description} isMoney /> <ShowResult title="Rendimento do capital(%)/mensal" label={returnOnCapital} /> <ShowResult title="Resultado" label={result} isMoney /> <ButtonHandleSubmit title="Salvar" onPress={handleSubmit} enabled={!loading} loading={loading} /> </Container> </ScrollView> </KeyboardAvoidingView> </> ); }
import React from 'react'; import { Layout } from '../../Components/Layout'; import { Card } from '../../Components/Card'; import { ProductDetail } from '../../Components/ProductDetail'; import { ShoppingCartContext } from '../../Context'; import { data } from 'autoprefixer'; function Home() { const {filteredProducts, setFilteredProducts, setInputValue, category} = React.useContext(ShoppingCartContext); console.log(category); console.log(filteredProducts); const renderProducts = () => { if (filteredProducts?.length == 0) { return ( <div className='w-screen text-3xl '> <h1 >No products related with your search</h1> </div> ) } else { return ( filteredProducts?.map(product => { product.inCart = false; product.price = Math.ceil(product.price); return <Card key={product.id} data={product}/> }) ) } } return ( <Layout> <div className='flex items-center justify-center w-96 mb-8'> <h1 className='font-bold text-3xl'>OUR PRODUCTS</h1> </div> <input type="text" placeholder='Busca lo que tienes en mente...' className='bg-gray-200 w-1/2 py-2 px-1.5 mb-8' onChange={(event) => {setInputValue(event.target.value)}} /> <div className='grid grid-cols-3 gap-8 w-full max-w-screen-xl '> {renderProducts()} </div> <ProductDetail></ProductDetail> </Layout> ) } export default Home;
/*************************************************************************** * Copyright (C) 2004 - 2009 by Matthias Reif, Holger Gerth * * matthias.reif@informatik.tu-chemnitz.de * * holger.gerth@informatik.tu-chemnitz.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, see http://www.gnu.org/licenses/ * ***************************************************************************/ #ifndef QAJSHAREWIDGET_H #define QAJSHAREWIDGET_H #include <QStringList> #include <QFileDialog> #include <QMessageBox> #include <QCheckBox> #include <QSpinBox> #include <QPushButton> #include "modulebase.h" #include "shareitem.h" #include "sharefileitem.h" #include "dirselectiondialog.h" /** @author Matthias Reif */ class ShareModule : public ModuleBase { Q_OBJECT QHash<QString, ShareFileItem*> sharedFiles; public: QLabel* prioLabel; QSpinBox* prioSpin; QPushButton* prioButton; ShareModule(Juicer* juicer); ~ShareModule(); ShareFileItem* findFile(const QString& id); ShareFileItem* findFile(const QString& size, const QString& hash); void insertShare(const QString& path, const QString& shareMode); void insertFile(const QString& id, const QString& hash, const QString& fileName, const QString& size, const QString& priority, const QString& lastAsked, const QString& askCount, const QString& searchCount, const QString& filesystemSeperator); void updateSharedFilesList(); bool isChanged() const { return changed_; } void reset() { sharedFiles.clear(); } public slots: void commitSlot(); void selectionChanged(); void reloadSlot(); protected: ShareItem* findShare(const QString& fileName); QString filesystemSeparator; int prio_; bool changed_; private slots: void insertSlot(); void removeSlot(); void linkSlot(); void setTmpPriority(int prio); void setPriority(); }; #endif
import { useEffect, useRef } from "react"; import { Chart } from "chart.js/auto"; interface BarChartProps { data: number[]; labels: string[]; } export default function BarChart({ data, labels }: BarChartProps) { const chartRef = useRef<HTMLCanvasElement | null>(null); Chart.defaults.font.size = 13; useEffect(() => { if (chartRef.current) { const myChart = new Chart(chartRef.current, { type: "bar", data: { labels: labels, //차트 전체의 datasets -> 범례 datasets: [ { label: "아이템 빌드 수", data: data, //항목별로 다르게 색을 지정해주기 //위한 색 배열(미리 만들어놓고 색 다르게 보이게 함) backgroundColor: [ "#FF6384", "#36A2EB", "#FFCE56", "#5A9A54", "#DE4D4D", "#264DD2", ], borderWidth: 1, // 바의 크기를 조절하는 속성 barThickness: 30, }, ], }, //차트 커스텀 하기 위한 options 설정들 options: { //범례 가리기 plugins: { legend: { display: false, }, }, scales: { //x축 안 보이게 하기 x: { display: false, }, y: { beginAtZero: true, }, }, //가로 차트로 변경 indexAxis: "y", //차트 크기 변경 시 자동 조정 responsive: true, //가로 세로 비율 유지 설정 maintainAspectRatio: true, }, }); return () => { // clean up 함수 myChart.destroy(); }; } }, [chartRef]); return <canvas ref={chartRef} />; }
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { authService } from "../services/index"; import { AppThunk, RootState } from "./index"; import { ProfileInterface, LoginInterface, SigupInterface } from "../types/auth.types"; import { apiConfig } from "../config"; export interface AuthStateInterface { authDone: boolean; accessToken: string; user: ProfileInterface | null; loading: boolean; } const initialState: AuthStateInterface = { accessToken: "", user: null, authDone: false, loading: false, }; const authSlice = createSlice({ name: "auth", initialState, reducers: { loggingIn: state => { state.loading = true; }, loggedIn: (state, action: PayloadAction<ProfileInterface>) => { state.accessToken = action.payload.token; state.user = action.payload; state.loading = false; state.authDone = true; }, loggingInFailed: state => { state.user = null; state.loading = false; }, clearAuthState: state => { state.authDone = false; state.accessToken = ""; state.user = null; state.loading = false; }, }, }); // REDUCER export default authSlice.reducer; const { loggedIn, loggingIn, loggingInFailed, clearAuthState } = authSlice.actions; const signup = ( credentials: SigupInterface ) : AppThunk => async dispatch => { await authService.signup(credentials); } const login = (credentials: LoginInterface ): AppThunk => async dispatch => { try { dispatch(loggingIn()); const { data: loginResponse } = await authService.login(credentials); const profileResponse = await reLogin(loginResponse.token); dispatch(loggedIn({ ...loginResponse, ...profileResponse })); } catch (error) { dispatch(loggingInFailed()); } }; const logout = (): AppThunk => async dispatch => { authService.logout(); dispatch(clearAuthState()); }; const reLogin = async (token: string) => { authService.setAuthToken(token); apiConfig.setAuthToken(token); const { data: profileResponse } = await authService.getProfile(); return profileResponse; }; const fetchUserProfile = (): AppThunk => async dispatch => { const token = authService.getAuthToken(); if (token) try { dispatch(loggingIn()); const profileResponse = await reLogin(token); dispatch(loggedIn(profileResponse)); } catch (error) { dispatch(loggingInFailed()); } }; const selectAuthState = (state: RootState) => state.auth; const selectCurrentUser = () => (state: RootState) => selectAuthState(state).user; const selectLoadingAuth = () => (state: RootState) => selectAuthState(state).loading; const selectInitialAuthDone = () => (state: RootState) => selectAuthState(state).authDone; const selectAccessToken = () => (state: RootState) => selectAuthState(state).accessToken; const selectSignedIn = () => (state: RootState) => selectAccessToken()(state) && selectInitialAuthDone()(state); export { login, logout, signup, selectAuthState, selectCurrentUser, selectLoadingAuth, selectInitialAuthDone, selectAccessToken, selectSignedIn, fetchUserProfile };
import "./PreviewModal.css"; import close from "../../images/close.svg"; import { useEffect } from "react"; const PreviewModal = ({ selectedCard, onClose }) => { useEffect(() => { const close = (e) => { if (e.keyCode === 27) { onClose(); } }; window.addEventListener("keydown", close); return () => window.removeEventListener("keydown", close); }); return ( <div className={`modal`}> <div className="modal__content modal__item"> <button type="button" className="modal__close" onClick={onClose}> <img src={close} alt="Close modal button" /> </button> <img src={selectedCard.images[0].url} alt={selectedCard.name} className="modal__image" /> <div className="modal__item-info"> <div> <div className="modal__item-name">{selectedCard.name}</div> <div className="modal__item-type"></div> </div> </div> </div> </div> ); }; export default PreviewModal;
import 'package:finder_med/pharmacy_details_page.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'Pharmacy.dart'; class PharmaciesPage extends StatefulWidget { const PharmaciesPage({Key? key}) : super(key: key); @override _PharmaciesPageState createState() => _PharmaciesPageState(); } class _PharmaciesPageState extends State<PharmaciesPage> { late TextEditingController _searchController; bool _showMap = true; // Etat pour contrôler l'affichage de la carte final LatLng _yaoundeCenter = const LatLng(3.848, 11.502); // Coordonnées de Yaoundé @override void initState() { super.initState(); _searchController = TextEditingController(); } @override void dispose() { _searchController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Pharmacies'), ), body: Column( children: [ TextField( controller: _searchController, decoration: const InputDecoration( hintText: 'Rechercher une pharmacie...', contentPadding: EdgeInsets.all(16.0), ), onChanged: (value) { setState(() { // Si le champ de recherche n'est pas vide, on ne montre plus la carte _showMap = value.isEmpty; }); }, ), Expanded( child: _showMap ? _buildMap() : _buildPharmaciesList(), ), ], ), ); } Widget _buildMap() { return GoogleMap( initialCameraPosition: CameraPosition( target: _yaoundeCenter, zoom: 12, ), markers: { Marker( markerId: MarkerId('yaounde'), position: _yaoundeCenter, infoWindow: InfoWindow(title: 'Yaoundé'), ), }, ); } Widget _buildPharmaciesList() { return StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('Pharmacies').orderBy('nomPharmacie').snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Center(child: Text('Erreur: ${snapshot.error}')); } final pharmacies = snapshot.data!.docs .where((doc) => doc['nomPharmacie'].toString().toLowerCase().contains(_searchController.text.toLowerCase())) .toList(); if (pharmacies.isEmpty) { return Center(child: Text('Aucune pharmacie trouvée.')); } return ListView.builder( itemCount: pharmacies.length, itemBuilder: (context, index) { var pharmacyData = pharmacies[index]; return ListTile( title: Text(pharmacyData['nomPharmacie']), onTap: () { List<String> contacts = []; if (pharmacyData['contact1'] != null) { contacts.add(pharmacyData['contact1']); } if (pharmacyData['contact2'] != null) { contacts.add(pharmacyData['contact2']); } if (pharmacyData['contact3'] != null) { contacts.add(pharmacyData['contact3']); } final positionGeographique = pharmacyData['positionGeographique']; final double? latitude = positionGeographique != null ? positionGeographique['latitude'] : null; final double? longitude = positionGeographique != null ? positionGeographique['longitude'] : null; var pharmacy = Pharmacy( nomPharmacie: pharmacyData['nomPharmacie'], type: pharmacyData['type'], emplacement: pharmacyData['emplacement'], contacts: contacts, longitude: longitude, latitude: latitude, ); Navigator.push( context, MaterialPageRoute(builder: (context) => PharmacyDetailsPage(pharmacy: pharmacy)), ); }, ); }, ); }, ); } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Sense of Steve - Start Your Coding Engine</title> <link rel="stylesheet" href="/assets/css/main.css"> </link> <base target="_blank"> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-1WREBCPVGJ"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'G-1WREBCPVGJ'); </script> </head> <body> <div class="img-full-screen blog-bg "> <div class="header-container"> <nav class="nav-bar"> <a class="nav-logo" href="/" target="_self"> SENSE <span class="nav-logo inner">OF</span> STEVE </a> <a class="nav-item active " href="/" target="_self"> BLOG </a> </nav> <div class="header-gradient"></div> </div> <div class="main-container"> <div class="content-container"> <div class="content"> <div class="post-container page"> <div class="post-header"> <h1>Start Your Coding Engine</h1> <p>22 Jan 2022 - Steven Koontz</p> </div> <div class="post-body"> <p>How much does it cost to tap on the shoulder of a software developer at work? We know software development takes a lot of mental energy and focus, but surely it can’t be that hard to just “get back into it” after Joe walks by your desk and asks you about your lunch plans.</p> <p>I like to think of the brain as the body’s version of random access memory (RAM). At any given time, you have a finite amount of RAM available for your system. Just as opening and using programs consumes the available RAM on your computer, storing thoughts in your mind uses up your brain’s available “RAM”.<!--more--> When you’re using your computer, and you are done with a program, you close it, and the computer gets some RAM back. Similarly, when you are done considering something in your mind, you release the thought and your brain gets some of its “RAM” back (this is obviously an oversimplification).</p> <p>Now, consider how difficult it is to hold on to your thoughts; all those times where you “just had it”. How much energy do you have to spend to keep a thought in your head? How many thoughts can you keep in your head at once? Imagine trying to construct and keep track of a system of many thoughts that are all interconnected. If you lose focus on any one part of the cohesive concept, the entire idea can be lost. In this way, it would appear that the brain “flushes” its RAM fairly easily when something else demands its attention. This is the reason distractions are so costly for software developers.</p> <p>I’ll use the analogy of starting an engine to illustrate this point. Let’s say you come into the office, fire up your laptop, and open a text editor. You’re not “driving” yet. You’ve put the key in the ignition and you’re trying to get the engine to turn over. Once it does, you naturally accelerate as you “get back into it”. After 30 minutes or so, you’re back up to speed with where you left your code and you’re ready to continue fleshing it out. At this point you are “driving”.</p> <p>Writing enterprise code is mostly describing what should happen in a process if certain logical conditions are met. It’s a lot like writing out the directions for a road trip. There is a notion of, “If I get to this intersection, I turn right. Four blocks down, I make a left if it’s raining.” When a software developer is “driving”, they are able to see the directions in their mind and can continue to describe how to get to their destination. As they build up these directions, they consume more and more mental RAM and it can become difficult to keep track of where they have been and where they are going.</p> <p>So, what happens when Joe asks about lunch plans? Quite simply, the engine stalls and all forward progress is halted. If the interrupting conversation lasts long enough, the solution stored in mental “RAM” could vanish as that RAM is used to hold the conversation. Afterward, this leaves the developer to have to question where they were and stop and ask themselves for directions again. Then, the process starts from the beginning. The engine must be restarted and momentum must be regained. In this modern world full of Zoom meetings, Teams chats, and “quick calls,” it can be very difficult to find the time necessary for sustained, uninterrupted focus, and this process of stalling and restarting the engine can occur multiple times throughout the day. Ideally, after restarting their engine, a developer is able to accelerate back to “cruising speed” and continue moving forward, but if your engine continues to stall just as you get to the point where you can start to accelerate, it is very difficult to move forward.</p> <p>If minimal productivity occurs when the engine is off and maximal productivity occurs at cruising speed, it’s interesting to consider how much time is spent throughout the day simply trying to accelerate to cruising speed. If you have a day with 4 meetings, it is far more efficient to schedule them in a block together, so that the rest of the day can be used as uninterrupted focus time. If you don’t do this, you can end up with 4 meetings spread across your day, and 4 separate 1 hour blocks of “focus” time for development in between. It is very hard (if not impossible) to build software in bursts like this.</p> <p>I used to be guilty of being too available, hopping from chat to chat, call to call, context switching many times throughout the day. When you have so many different things competing for your attention, it’s hard to give any one thing the appropriate care and attention it deserves. If you’re always answering questions or helping someone else, it is very easy to find your day suddenly gone, with little time allocated for the work <em>you</em> need to do. Collaboration is always a good idea, but focus time is equally important. Next time you consider pulling a software developer out of their focus time, consider how important the question is.</p> </div> </div> </div> </div> </div> <div class="footer-container"> <div class="footer-gradient"></div> <div class="footer-bar"> <footer class="footer-content"> <p>All rights reserved &copy; Steven Koontz 2022</p> </footer> </div> </div> </div> </body> </html>
/* eslint-disable react/jsx-props-no-spreading */ import { useForm } from 'react-hook-form' import { useEffect } from 'react' import { yupResolver } from '@hookform/resolvers/yup' import { isEmpty } from 'ramda' import { useNavigate } from 'react-router-dom' import validationSchema from '../validationSchema' import HookInput from '../../../../common/HookInput' import Button from '../../../../common/Button' import { useProducts } from '../../context/ProductContext' import { useAuth } from '../../../../context/AuthContextProvider' export default function ProductForm() { const { handleCreateProduct, updatingProduct, isUpdating, handleUpdateProduct, handleCancelUpdate } = useProducts() const { isAuth, permissionLvl } = useAuth() const { register, handleSubmit, formState: { errors }, reset } = useForm({ resolver: yupResolver(validationSchema) }) const navigate = useNavigate() useEffect(() => { reset(updatingProduct) }, [updatingProduct, reset]) useEffect(() => { reset(handleUpdateProduct) }, [handleUpdateProduct, reset]) useEffect(() => { if (!isAuth || permissionLvl !== 'superadmin') { navigate('/') } }, [isAuth, navigate, permissionLvl]) return ( <div className="w-64"> <div className="fixed w-64 p-4 shadow rounded m-6 bg-gray-800"> <h1 className="text-2xl font-bold mb-2 text-gray-50">{isUpdating ? 'Actualizar' : 'Agregar'} producto</h1> <form className="space-y-4" onSubmit={handleSubmit(isUpdating ? handleUpdateProduct : handleCreateProduct)}> <HookInput name="productName" label="Nombre producto" placeholder="Nombre del producto" register={register} errorMessage={errors.productName?.message} /> <HookInput name="description" label="description" placeholder="description" register={register} errorMessage={errors.category?.message} /> <HookInput name="category" label="category" placeholder="category" register={register} errorMessage={errors.category?.message} /> <HookInput name="price" label="price" placeholder="price" register={register} errorMessage={errors.price?.message} /> <HookInput name="stock" label="stock" placeholder="stock" register={register} errorMessage={errors.stock?.message} /> <HookInput name="image" label="Avatar" placeholder="Url de avatar" register={register} errorMessage={errors.image?.message} /> <Button block className="mr-2" type="submit" disabled={!isEmpty(errors)}>Submit</Button> {isUpdating && <Button block className="mr-2 bg-red-500" type="button" onClick={handleCancelUpdate}>Cancel</Button> } </form> </div> </div> ) }
# ECS tutorial ## Overview > What to expect from this document. This tutorial will guide you step-by-step through the creation of a very simple project that illustrates a range of basic DOTS concepts. In many places, features will be initially used in a non-optimal or incorrect way in order to progressively introduce various concepts. Do not copy parts of this tutorial into other projects without understanding the whole context first. This tutorial is focused on the core entities package, and only makes a very basic use of entities graphics. It does not use any additional packages, like physics or netcode. ![](images/expected_result.gif) The completed project contains the following "features": - A bunch of little colored tanks moving on a flow field and spinning their turrets. - When far enough from the origin, the tanks shoot colored projectiles. - The projectiles bounce on the ground and despawn after a while. - The camera follows a random tank and every press on the space bar switches to another tank. Please report any issue you find with this material. Anything that is confusing, any error you run into, etc. Everything that can help us improve this tutorial is welcome. Use the [DOTS Forum](https://forum.unity.com/forums/data-oriented-technology-stack.147/) to that purpose. ## Required Unity Version This tutorial uses **2022.2.0b8**. Look for that version (or a more recent patch release) in the list of Unity releases from the Unity Hub itself: "Installs" (left menu), "Install Editor" (top right), "Pre-releases" (tab). Alternatively, you can manually download the **2022.2.0b8** version of the Unity editor from those direct links: - [Windows Unity Editor 64-bit](https://beta.unity3d.com/download/9eb452e2ea43/Windows64EditorInstaller/UnitySetup64.exe) - [Mac Unity Editor (Intel)](https://beta.unity3d.com/download/9eb452e2ea43/MacEditorInstaller/Unity.pkg) - [Mac Unity Editor (Apple Silicon)](https://beta.unity3d.com/download/9eb452e2ea43/MacEditorInstallerArm64/Unity.pkg) - [Linux Unity Editor](https://beta.unity3d.com/download/9eb452e2ea43/LinuxEditorInstaller/Unity.tar.xz) ## Using directives and provided code > A remark about code inlined in this tutorial. Every code snippet in this document is automatically extracted from a reference project, and the using directives from the whole file that includes the snippet are copied. As a consequence, note that you will encounter using directives which are not yet necessary at the point where they are introduced. Also, pay close attention to the way we explicitly reference `UnityEngine` types. This is a convention used in this tutorial to clearly delineate the DOTS related types from the classic Unity ones. Some files are provided in full, while some other are modifications of existing files where a `+` line (green) is to be added, a `-` line (red) is to be removed, and the other lines remain unchanged and only provide context. Finally, make sure you read through the comments in the code as you copy the provided source files. Those comments contain a lot of important information about the purpose of each step and are an integral part of this tutorial. ## Project setup > Create a new project, install the packages we need, and tune the settings. ![](images/unity_hub.png) 1. Create a new project in the Unity Hub, using the 3D (URP) template. You will eventually have to download the template if you haven't used it before. Make sure you are using the right Editor version. 1. Once the project is loaded, click the button "Remove Readme Assets" in the "URP Empty Template" inspector. This will get rid of the folder "Assets/TutorialInfo" which we don't need for this tutorial. This inspector should be selected by default, but if it isn't just select `Assets/Readme.asset` in the Project window. 1. Only one package needs to be explicitly installed for this tutorial. The other packages will be pulled into the project as dependencies. Go to `Window > Package Manager`, click the `+` button on the top left and select "Add package by name". Set the "Name" field to "com.unity.entities.graphics" and leave the "Version" field blank then click the "Add" button and wait for the package and its dependencies to install. ![](images/add_package_by_name.png) 1. In `Edit > Project Settings > Editor`, enable "Enter Play Mode Options" but leave the reload sub-options unchecked. For more information about what these options do, please follow these links: * [Unity Manual - Configurable Enter Play Mode](https://docs.unity3d.com/Manual/ConfigurableEnterPlayMode.html) * [Unity Blog - Enter Play Mode faster in Unity 2019.3](https://blog.unity.com/technology/enter-play-mode-faster-in-unity-2019-3) Pay close attention to the implication of those settings on the use of static fields (cf. blog post).<p> ![](images/enter_play_mode_settings.png) 1. In the Project window, create the missing folders from the following list in the Assets folder: * Prefabs * Scenes (already created) * Scripts/Aspects * Scripts/Authoring * Scripts/Components * Scripts/MonoBehaviours * Scripts/Systems * Settings (already created) ![](images/assets_folders.png) ## Conversion settings > Setup the baking pipeline properly. The rest of this tutorial assumes that the "Scene View Mode" (in `Preferences/Entities`) is set to "Runtime Data": ![](images/conversion_settings.png) ## Types accessibility This tutorial takes the convention to make all classes and structs internal. Internal types or members are accessible only within files in the same assembly, and this is the default accessibility level in C#. When working on larger projects which are split over multiple assemblies, explicit accessibility modifiers will be required. Discussing this is out of scope for this tutorial, and isn't specific to DOTS in any way. ## Step 1 - Authoring Scene > Create the scene from which ECS data will be constructed. 1. Make sure the SampleScene from the Scenes folder is currently open. (The following steps will only work on a scene which is saved as a file.) 1. Within the Hierarchy window, right click and select `New Subscene > Empty Scene...`. Name the new scene "EntityScene", and put it in `Scenes/SampleScene`.<p> ![](images/create_subscene.png) 1. Right click "EntityScene" in the Hierarchy window, select `GameObject > 3D Object > Cube` and name the new GameObject "Tank". Set its Position to (0,0,0), Rotation to (0,0,0) and Scale to (1,1,1). 1. Right click "Tank" in the Hierarchy window, select `3D Object > Sphere` and name the new GameObject "Turret". Set its **Position to (0,0.5,0)**, **Rotation to (45,0,0)** and Scale to (1,1,1). 1. Right click "Turret" in the Hierarchy window, select `3D Object > Cylinder` and name the new GameObject "Cannon". Set its **Position to (0,0.5,0)**, Rotation to (0,0,0) and **Scale to (0.2,0.5,0.2)**. 1. Right click "Cannon" in the Hierarchy window, select `Create Empty` and name the new GameObject "SpawnPoint". Set its **Position to (0,1,0)**, **Rotation to (-90,0,0)** and Scale to (1,1,1). 1. You should now have something similar to the following screenshot.<p> ![](images/tank_hierarchy.png) 1. One last thing about that little tank is that each primitive contains by default a collider. We are not going to use those colliders, and they are discarded during baking anyway (conversion to entities) because we don't have a DOTS compatible physics engine in the project. But in the spirit of DOD, let's get rid of useless data: remove the Box Collider component from "Tank", remove the Sphere Collider component from "Turret", and remove the Capsule Collider from "Cannon". There is no collider on "SpawnPoint", so nothing to do there.<p> ![](images/remove_component.png) ## Step 2 - Turret Rotation > Introducing the concepts of unmanaged systems (`ISystem`), queries, idiomatic `foreach`. 1. Create a new file named "TurretRotationSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Burst; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; // Unmanaged systems based on ISystem can be Burst compiled, but this is not yet the default. // So we have to explicitly opt into Burst compilation with the [BurstCompile] attribute. // It has to be added on BOTH the struct AND the OnCreate/OnDestroy/OnUpdate functions to be // effective. [BurstCompile] partial struct TurretRotationSystem : ISystem { // Every function defined by ISystem has to be implemented even if empty. [BurstCompile] public void OnCreate(ref SystemState state) { } // Every function defined by ISystem has to be implemented even if empty. [BurstCompile] public void OnDestroy(ref SystemState state) { } // See note above regarding the [BurstCompile] attribute. [BurstCompile] public void OnUpdate(ref SystemState state) { // The amount of rotation around Y required to do 360 degrees in 2 seconds. var rotation = quaternion.RotateY(SystemAPI.Time.DeltaTime * math.PI); // The classic C# foreach is what we often refer to as "Idiomatic foreach" (IFE). // Aspects provide a higher level interface than directly accessing component data. // Using IFE with aspects is a powerful and expressive way of writing main thread code. foreach (var transform in SystemAPI.Query<TransformAspect>()) { transform.RotateWorld(rotation); } } } ``` 1. Enter play mode and notice that everything is spinning in a funny way (the cannon is progressively detaching from the rest, the animation below shows the situation after letting it run for a bit).<p> ![](images/tank_spin_wrong.gif) | &#x1F4DD; NOTE | | :- | | The problem is that the `foreach` we created matches anything that has a transform, this causes every part of the tank hierarchy to rotate. We need to constrain it to only affect the rotation of the turret. | 1. Leave play mode. 1. Create a new C# source file named "Turret.cs" in the folder "Scripts/Components", put the following contents in there: ```c# using Unity.Entities; // An empty component is called a "tag component". struct Turret : IComponentData { } ``` 1. Create a new C# source file named "TurretAuthoring.cs" in the folder "Scripts/Authoring", put the following contents in there: ```c# using Unity.Entities; // Authoring MonoBehaviours are regular GameObject components. // They constitute the inputs for the baking systems which generates ECS data. class TurretAuthoring : UnityEngine.MonoBehaviour { } // Bakers convert authoring MonoBehaviours into entities and components. class TurretBaker : Baker<TurretAuthoring> { public override void Bake(TurretAuthoring authoring) { AddComponent<Turret>(); } } ``` 1. Add the "TurretAuthoring" component to the "Turret" GameObject, either by drag & dropping the TurretAuthoring.cs file onto the Turret GameObject or by using the "Add Component" button in the GameObject inspector and locating "Turret Authoring". 1. While the "Turret" GameObject is selected, check in the "Entity Conversion" panel (you might have to expand it by dragging it up) that the "Turret" component is now present on the entity.<p> ![](images/turret_tag.png) 1. Modify the contents of the file named "TurretRotationSystem.cs" in the folder "Scripts/Systems" as follows: ```diff using Unity.Burst; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; [BurstCompile] partial struct TurretRotationSystem : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { } [BurstCompile] public void OnDestroy(ref SystemState state) { } [BurstCompile] public void OnUpdate(ref SystemState state) { var rotation = quaternion.RotateY(SystemAPI.Time.DeltaTime * math.PI); + // WithAll adds a constraint to the query, specifying that every entity should have such component. + foreach (var transform in SystemAPI.Query<TransformAspect>().WithAll<Turret>()) - foreach (var transform in SystemAPI.Query<TransformAspect>()) { transform.RotateWorld(rotation); } } } ``` 1. Enter play mode and notice that only the turret is now spinning.<p> ![](images/tank_spin_correct.gif) 1. Leave play mode. ## Step 3 - Tank movement > Introducing `SystemBase` and `Entities.ForEach` parallelism. 1. Create a new C# source file named "Tank.cs" in the folder "Scripts/Components", put the following contents in there: ```c# using Unity.Entities; // Just like we did with the turret, we create a tag component to identify the tank (cube). struct Tank : IComponentData { } ``` 1. Create a new C# source file named "TankAuthoring.cs" in the folder "Scripts/Authoring", put the following contents in there: ```c# using Unity.Entities; class TankAuthoring : UnityEngine.MonoBehaviour { } class TankBaker : Baker<TankAuthoring> { public override void Bake(TankAuthoring authoring) { AddComponent<Tank>(); } } ``` 1. Add the "TankAuthoring" component to the "Tank" GameObject. 1. Create a new C# source file named "TankMovementSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; // Contrarily to ISystem, SystemBase systems are classes. // They are not Burst compiled, and can use managed code. partial class TankMovementSystem : SystemBase { protected override void OnUpdate() { // The Entities.ForEach below is Burst compiled (implicitly). // And time is a member of SystemBase, which is a managed type (class). // This means that it wouldn't be possible to directly access Time from there. // So we need to copy the value we need (DeltaTime) into a local variable. var dt = SystemAPI.Time.DeltaTime; // Entities.ForEach is an older approach to processing queries. Its use is not // encouraged, but it remains convenient until we get feature parity with IFE. Entities .WithAll<Tank>() .ForEach((TransformAspect transform) => { // Notice that this is a lambda being passed as parameter to ForEach. var pos = transform.Position; // Unity.Mathematics.noise provides several types of noise functions. // Here we use the Classic Perlin Noise (cnoise). // The approach taken to generate a flow field from Perlin noise is detailed here: // https://www.bit-101.com/blog/2021/07/mapping-perlin-noise-to-angles/ var angle = (0.5f + noise.cnoise(pos / 10f)) * 4.0f * math.PI; var dir = float3.zero; math.sincos(angle, out dir.x, out dir.z); transform.Position += dir * dt * 5.0f; transform.Rotation = quaternion.RotateY(angle); // The last function call in the Entities.ForEach sequence controls how the code // should be executed: Run (main thread), Schedule (single thread, async), or // ScheduleParallel (multiple threads, async). // Entities.ForEach is fundamentally a job generator, and it makes it very easy to // create parallel jobs. This unfortunately comes with a complexity cost and weird // arbitrary constraints, which is why more explicit approaches are preferred. // Those explicit approaches (IJobEntity) are covered later in this tutorial. }).ScheduleParallel(); } } ``` 1. Enter play mode, the tank should start moving along the flow field.<p> ![](images/tank_movement.gif) 1. Leave play mode. ## Step 4 - Cannon Balls > Creating a prefab, referencing entities from other entities. 1. Create a new C# source file named "CannonBall.cs" in the folder "Scripts/Components", put the following contents in there: ```c# using Unity.Entities; using Unity.Mathematics; // Same approach for the cannon ball, we are creating a component to identify the entities. // But this time it's not a tag component (empty) because it contains data: the Speed field. // It won't be used immediately, but will become relevant when we implement motion. struct CannonBall : IComponentData { public float3 Speed; } ``` 1. Create a new C# source file named "CannonBallAuthoring.cs" in the folder "Scripts/Authoring", put the following contents in there: ```c# using Unity.Entities; using Unity.Rendering; class CannonBallAuthoring : UnityEngine.MonoBehaviour { } class CannonBallBaker : Baker<CannonBallAuthoring> { public override void Bake(CannonBallAuthoring authoring) { // By default, components are zero-initialized. // So in this case, the Speed field in CannonBall will be float3.zero. AddComponent<CannonBall>(); } } ``` 1. Right click "SampleScene" in the Hierarchy window, select `GameObject > 3D Object > Sphere` and name the new GameObject "CannonBall". Set its Position to (0,0,0), Rotation to (0,0,0) and **Scale to (0.2,0.2,0.2)**. 1. Add the "CannonBallAuthoring" component to the "CannonBall" GameObject. 1. Remove the "Sphere Collider" component from the "CannonBall" GameObject. 1. Drag & drop the "CannonBall" GameObject to the "Prefabs" folder in the Project window. 1. Delete the "CannonBall" GameObject (now a prefab instance) from "SampleScene".<p> ![](images/cannon_ball_prefab.png) 1. Modify the contents of the file named "Turret.cs" in the folder "Scripts/Components" as follows: ```diff using Unity.Entities; struct Turret : IComponentData { + // This entity will reference the nozzle of the cannon, where cannon balls should be spawned. + public Entity CannonBallSpawn; + // This entity will reference the prefab to be spawned every time the cannon shoots. + public Entity CannonBallPrefab; } ``` 1. Modify the contents of the file named "TurretAuthoring.cs" in the folder "Scripts/Authoring" as follows: ```diff using Unity.Entities; class TurretAuthoring : UnityEngine.MonoBehaviour { + public UnityEngine.GameObject CannonBallPrefab; + public UnityEngine.Transform CannonBallSpawn; } class TurretBaker : Baker<TurretAuthoring> { public override void Bake(TurretAuthoring authoring) { - AddComponent<Turret>(); + AddComponent(new Turret + { + // By default, each authoring GameObject turns into an Entity. + // Given a GameObject (or authoring component), GetEntity looks up the resulting Entity. + CannonBallPrefab = GetEntity(authoring.CannonBallPrefab), + CannonBallSpawn = GetEntity(authoring.CannonBallSpawn) + }); } } ``` 1. Select the "Turret" GameObject, and set the new fields "CannonBallPrefab" and "CannonBallSpawn" of the "Turret Authoring" component respectively to the "CannonBall" prefab (drag & drop) from the Project folder and to the "SpawnPoint" GameObject (drag & drop from the Hierarchy window).<p> ![](images/turret_authoring.png) 1. Create a new C# source file named "TurretAspect.cs" in the folder "Scripts/Aspects", put the following contents in there: ```c# using Unity.Entities; using Unity.Mathematics; using Unity.Rendering; // Instead of directly accessing the Turret component, we are creating an aspect. // Aspects allows you to provide a customized API for accessing your components. readonly partial struct TurretAspect : IAspect { // This reference provides read only access to the Turret component. // Trying to use ValueRW (instead of ValueRO) on a read-only reference is an error. readonly RefRO<Turret> m_Turret; // Note the use of ValueRO in the following properties. public Entity CannonBallSpawn => m_Turret.ValueRO.CannonBallSpawn; public Entity CannonBallPrefab => m_Turret.ValueRO.CannonBallPrefab; } ``` 1. | &#x1F4DD; NOTE | | :- | | The following step uses `ComponentDataFromEntity<T>` which provides random access to typed components. For more information about this feature, check the [API Documentation](https://docs.unity3d.com/Packages/com.unity.entities@latest/index.html?subfolder=/api/Unity.Entities.ComponentDataFromEntity-1.html). | Create a new C# source file named "TurretShootingSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Rendering; using Unity.Transforms; [BurstCompile] partial struct TurretShootingSystem : ISystem { // A ComponentLookup provides random access to a component (looking up an entity). // We'll use it to extract the world space position and orientation of the spawn point (cannon nozzle). ComponentLookup<LocalToWorldTransform> m_LocalToWorldTransformFromEntity; [BurstCompile] public void OnCreate(ref SystemState state) { // ComponentLookup structures have to be initialized once. // The parameter specifies if the lookups will be read only or if they should allow writes. m_LocalToWorldTransformFromEntity = state.GetComponentLookup<LocalToWorldTransform>(true); } [BurstCompile] public void OnDestroy(ref SystemState state) { } [BurstCompile] public void OnUpdate(ref SystemState state) { // ComponentLookup structures have to be updated every frame. m_LocalToWorldTransformFromEntity.Update(ref state); // Creating an EntityCommandBuffer to defer the structural changes required by instantiation. var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>(); var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged); // Creating an instance of the job. // Passing it the ComponentLookup required to get the world transform of the spawn point. // And the entity command buffer the job can write to. var turretShootJob = new TurretShoot { LocalToWorldTransformFromEntity = m_LocalToWorldTransformFromEntity, ECB = ecb }; // Schedule execution in a single thread, and do not block main thread. turretShootJob.Schedule(); } } [BurstCompile] partial struct TurretShoot : IJobEntity { [ReadOnly] public ComponentLookup<LocalToWorldTransform> LocalToWorldTransformFromEntity; public EntityCommandBuffer ECB; // Note that the TurretAspects parameter is "in", which declares it as read only. // Making it "ref" (read-write) would not make a difference in this case, but you // will encounter situations where potential race conditions trigger the safety system. // So in general, using "in" everywhere possible is a good principle. void Execute(in TurretAspect turret) { var instance = ECB.Instantiate(turret.CannonBallPrefab); var spawnLocalToWorld = LocalToWorldTransformFromEntity[turret.CannonBallSpawn]; var cannonBallTransform = UniformScaleTransform.FromPosition(spawnLocalToWorld.Value.Position); // We are about to overwrite the transform of the new instance. If we didn't explicitly // copy the scale it would get reset to 1 and we'd have oversized cannon balls. cannonBallTransform.Scale = LocalToWorldTransformFromEntity[turret.CannonBallPrefab].Value.Scale; ECB.SetComponent(instance, new LocalToWorldTransform { Value = cannonBallTransform }); ECB.SetComponent(instance, new CannonBall { Speed = spawnLocalToWorld.Value.Forward() * 20.0f }); } } ``` 1. Enter play mode, you should see the tank leaving a trail of cannon balls behind it.<p> ![](images/cannon_ball_trail.gif) ## Step 5 - Cannon ball movement > Introducing parallel jobs. 1. Create a new C# source file named "CannonBallAspect.cs" in the folder "Scripts/Aspects", put the following contents in there: ```c# using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; readonly partial struct CannonBallAspect : IAspect { // An Entity field in an aspect provides access to the entity itself. // This is required for registering commands in an EntityCommandBuffer for example. public readonly Entity Self; // Aspects can contain other aspects. readonly TransformAspect Transform; // A RefRW field provides read write access to a component. If the aspect is taken as an "in" // parameter, the field will behave as if it was a RefRO and will throw exceptions on write attempts. readonly RefRW<CannonBall> CannonBall; // Properties like this are not mandatory, the Transform field could just have been made public instead. // But they improve readability by avoiding chains of "aspect.aspect.aspect.component.value.value". public float3 Position { get => Transform.Position; set => Transform.Position = value; } public float3 Speed { get => CannonBall.ValueRO.Speed; set => CannonBall.ValueRW.Speed = value; } } ``` 1. Create a new C# source file named "CannonBallSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Burst; using Unity.Entities; using Unity.Mathematics; [BurstCompile] // IJobEntity relies on source generation to implicitly define a query from the signature of the Execute function. partial struct CannonBallJob : IJobEntity { // A regular EntityCommandBuffer cannot be used in parallel, a ParallelWriter has to be explicitly used. public EntityCommandBuffer.ParallelWriter ECB; // Time cannot be directly accessed from a job, so DeltaTime has to be passed in as a parameter. public float DeltaTime; // The ChunkIndexInQuery attributes maps the chunk index to an int parameter. // Each chunk can only be processed by a single thread, so those indices are unique to each thread. // They are also fully deterministic, regardless of the amounts of parallel processing happening. // So those indices are used as a sorting key when recording commands in the EntityCommandBuffer, // this way we ensure that the playback of commands is always deterministic. void Execute([ChunkIndexInQuery] int chunkIndex, ref CannonBallAspect cannonBall) { var gravity = new float3(0.0f, -9.82f, 0.0f); var invertY = new float3(1.0f, -1.0f, 1.0f); cannonBall.Position += cannonBall.Speed * DeltaTime; if (cannonBall.Position.y < 0.0f) { cannonBall.Position *= invertY; cannonBall.Speed *= invertY * 0.8f; } cannonBall.Speed += gravity * DeltaTime; var speed = math.lengthsq(cannonBall.Speed); if (speed < 0.1f) ECB.DestroyEntity(chunkIndex, cannonBall.Self); } } [BurstCompile] partial struct CannonBallSystem : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { } [BurstCompile] public void OnDestroy(ref SystemState state) { } [BurstCompile] public void OnUpdate(ref SystemState state) { var ecbSingleton = SystemAPI.GetSingleton<EndSimulationEntityCommandBufferSystem.Singleton>(); var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged); var cannonBallJob = new CannonBallJob { // Note the function call required to get a parallel writer for an EntityCommandBuffer. ECB = ecb.AsParallelWriter(), // Time cannot be directly accessed from a job, so DeltaTime has to be passed in as a parameter. DeltaTime = SystemAPI.Time.DeltaTime }; cannonBallJob.ScheduleParallel(); } } ``` 1. Enter play mode, the cannon balls are now moving away from the tank and bouncing on the ground.<p> ![](images/turret_shoot.gif) ## Step 6 - Spawning many tanks > Dealing with initialization systems that should only run once. 1. Drag & drop the "Tank" GameObject from "EntityScene" to the "Assets/Prefabs" folder in the Project window. 1. Delete the "Tank" GameObject (now a prefab instance) from "EntityScene". 1. Create a new C# source file named "Config.cs" in the folder "Scripts/Components", put the following contents in there: ```c# using Unity.Entities; struct Config : IComponentData { public Entity TankPrefab; public int TankCount; public float SafeZoneRadius; } ``` 1. Create a new C# source file named "ConfigAuthoring.cs" in the folder "Scripts/Authoring", put the following contents in there: ```c# using Unity.Entities; class ConfigAuthoring : UnityEngine.MonoBehaviour { public UnityEngine.GameObject TankPrefab; public int TankCount; public float SafeZoneRadius; } class ConfigBaker : Baker<ConfigAuthoring> { public override void Bake(ConfigAuthoring authoring) { AddComponent(new Config { TankPrefab = GetEntity(authoring.TankPrefab), TankCount = authoring.TankCount, SafeZoneRadius = authoring.SafeZoneRadius }); } } ``` 1. Right click "EntityScene" in the Hierarchy window, select `Create Empty` and name the new GameObject "Config". 1. Add the "ConfigAuthoring" component to the "Config" GameObject. 1. Select the "Config" GameObject, set the new field "TankPrefab" to the "Tank" prefab (drag & drop) from the Project folder, set "TankCount" to 20, and set "SafeZoneRadius" to 15.<p> ![](images/config_authoring.png) | &#x1F4DD; NOTE | | :- | | The "SafeZoneRadius" is not used yet, but will be relevant for a later step. | 1. Create a new C# source file named "TankSpawningSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Rendering; [BurstCompile] partial struct TankSpawningSystem : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { } [BurstCompile] public void OnDestroy(ref SystemState state) { } [BurstCompile] public void OnUpdate(ref SystemState state) { var config = SystemAPI.GetSingleton<Config>(); var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>(); var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged); var vehicles = CollectionHelper.CreateNativeArray<Entity>(config.TankCount, Allocator.Temp); ecb.Instantiate(config.TankPrefab, vehicles); // This system should only run once at startup. So it disables itself after one update. state.Enabled = false; } } ``` | &#x26A0; WARNING | | :- | | If you enter playmode at this point, you might be surprised to only see a single tank. There are actually 20 tanks, but they all spawn at the same location and move in exactly the same way. | 1. Modify the contents of the file named "TankMovementSystem.cs" in the folder "Scripts/Systems" as follows: ```diff using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; partial class TankMovementSystem : SystemBase { protected override void OnUpdate() { var dt = SystemAPI.Time.DeltaTime; Entities .WithAll<Tank>() - .ForEach((TransformAspect transform) => + .ForEach((Entity entity, TransformAspect transform) => { var pos = transform.Position; + // This does not modify the actual position of the tank, only the point at + // which we sample the 3D noise function. This way, every tank is using a + // different slice and will move along its own different random flow field. + pos.y = entity.Index; var angle = (0.5f + noise.cnoise(pos / 10f)) * 4.0f * math.PI; var dir = float3.zero; math.sincos(angle, out dir.x, out dir.z); transform.Position += dir * dt * 5.0f; transform.Rotation = quaternion.RotateY(angle); }).ScheduleParallel(); } } ``` 1. Enter play mode, each of the 20 tanks starts moving along its own flow field.<p> ![](images/lots_of_tanks.gif) 1. Leave play mode. ## Step 7 - Colored tanks and cannon balls > Advanced baking, introducing baking systems. ECS components can control the inputs to the shaders used for rendering. Creating our own shaders (via shadergraph) and mapping custom ECS components to their inputs is out of scope for this tutorial, but we will use an already existing component called `URPMaterialPropertyBaseColor`. As the name implies, it allows controlling the base color of a standard URP material. Our tanks are made of three primitives (tank, turret, cannon), and each of those entities need to have the `URPMaterialPropertyBaseColor` component added. To do so, open the Tank prefab and select all three primitives in the hierarchy (tank, turret, cannon) but not the SpawnPoint transform. Since it doesn't have a renderer, it doesn't need a color. With the three primitives selected, use the "Add Component" button in the inspector to add a `URPMaterialPropertyBaseColorAuthoring` component. 1. Enter play mode, notice that the tanks are now completely black (which is the default 0,0,0,0 value of the authoring component we just added).<p> ![](images/black_tanks.png) 1. Leave play mode. 1. | &#x1F4DD; NOTE | | :- | | The EntityCommandBuffer used by the system below requires a query to specify which entities should be targeted by SetComponentForLinkedEntityGroup.<br>The core of an entity query consists a set of component types, and the query provides a filtered view of only the entities matching that set.<br>For more information about entity queries, see the [package documentation](https://docs.unity3d.com/Packages/com.unity.entities@latest/index.html?subfolder=/manual/ecs_entity_query.html). | Modify the contents of the file named "TankSpawningSystem.cs" in the folder "Scripts/Systems" as follows: ```diff using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Rendering; [BurstCompile] partial struct TankSpawningSystem : ISystem { + // Queries should not be created on the spot in OnUpdate, so they are cached in fields. + EntityQuery m_BaseColorQuery; [BurstCompile] public void OnCreate(ref SystemState state) { + // This system should not run before the Config singleton has been loaded. + state.RequireForUpdate<Config>(); + m_BaseColorQuery = state.GetEntityQuery(ComponentType.ReadOnly<URPMaterialPropertyBaseColor>()); } [BurstCompile] public void OnDestroy(ref SystemState state) { } [BurstCompile] public void OnUpdate(ref SystemState state) { var config = SystemAPI.GetSingleton<Config>(); + // This system will only run once, so the random seed can be hard-coded. + // Using an arbitrary constant seed makes the behavior deterministic. + var random = Random.CreateFromIndex(1234); + var hue = random.NextFloat(); + // Helper to create any amount of colors as distinct from each other as possible. + // The logic behind this approach is detailed at the following address: + // https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ + URPMaterialPropertyBaseColor RandomColor() + { + // Note: if you are not familiar with this concept, this is a "local function". + // You can search for that term on the internet for more information. + // 0.618034005f == 2 / (math.sqrt(5) + 1) == inverse of the golden ratio + hue = (hue + 0.618034005f) % 1; + var color = UnityEngine.Color.HSVToRGB(hue, 1.0f, 1.0f); + return new URPMaterialPropertyBaseColor { Value = (UnityEngine.Vector4)color }; + } var ecbSingleton = SystemAPI.GetSingleton<BeginSimulationEntityCommandBufferSystem.Singleton>(); var ecb = ecbSingleton.CreateCommandBuffer(state.WorldUnmanaged); var vehicles = CollectionHelper.CreateNativeArray<Entity>(config.TankCount, Allocator.Temp); ecb.Instantiate(config.TankPrefab, vehicles); + // An EntityQueryMask provides an efficient test of whether a specific entity would + // be selected by an EntityQuery. + var queryMask = m_BaseColorQuery.GetEntityQueryMask(); + foreach (var vehicle in vehicles) + { + // Every prefab root contains a LinkedEntityGroup, a list of all of its entities. + ecb.SetComponentForLinkedEntityGroup(vehicle, queryMask, RandomColor()); + } state.Enabled = false; } } ``` 1. Enter play mode, notice that the tanks are now randomly colored.<p> ![](images/colored_tanks.png) 1. Leave play mode. 1. Modify the contents of the file named "CannonBallAuthoring.cs" in the folder "Scripts/Authoring" as follows: ```diff using Unity.Entities; using Unity.Rendering; class CannonBallAuthoring : UnityEngine.MonoBehaviour { } class CannonBallBaker : Baker<CannonBallAuthoring> { public override void Bake(CannonBallAuthoring authoring) { AddComponent<CannonBall>(); + AddComponent<URPMaterialPropertyBaseColor>(); } } ``` 1. Modify the contents of the file named "TurretAspect.cs" in the folder "Scripts/Aspects" as follows: ```diff using Unity.Entities; using Unity.Mathematics; using Unity.Rendering; readonly partial struct TurretAspect : IAspect { readonly RefRO<Turret> m_Turret; + readonly RefRO<URPMaterialPropertyBaseColor> m_BaseColor; public Entity CannonBallSpawn => m_Turret.ValueRO.CannonBallSpawn; public Entity CannonBallPrefab => m_Turret.ValueRO.CannonBallPrefab; + public float4 Color => m_BaseColor.ValueRO.Value; } ``` 1. Modify the contents of the file named "TurretShootingSystem.cs" in the folder "Scripts/Systems" as follows: ```diff [BurstCompile] partial struct TurretShoot : IJobEntity { [ReadOnly] public ComponentLookup<LocalToWorldTransform> LocalToWorldTransformFromEntity; public EntityCommandBuffer ECB; void Execute(in TurretAspect turret) { var instance = ECB.Instantiate(turret.CannonBallPrefab); var spawnLocalToWorld = LocalToWorldTransformFromEntity[turret.CannonBallSpawn]; var cannonBallTransform = UniformScaleTransform.FromPosition(spawnLocalToWorld.Value.Position); cannonBallTransform.Scale = LocalToWorldTransformFromEntity[turret.CannonBallPrefab].Value.Scale; ECB.SetComponent(instance, new LocalToWorldTransform { Value = cannonBallTransform }); ECB.SetComponent(instance, new CannonBall { Speed = spawnLocalToWorld.Value.Forward() * 20.0f }); + // The line below propagates the color from the turret to the cannon ball. + ECB.SetComponent(instance, new URPMaterialPropertyBaseColor { Value = turret.Color }); } } ``` 1. Enter play mode, notice that the cannon balls now have the same color as the tank they spawned from.<p> ![](images/colored_cannon_balls.png) 1. Leave play mode. ## Step 8 - Safe zone > Config singleton, live conversion. 1. Create a new C# source file named "Shooting.cs" in the folder "Scripts/Components", put the following contents in there: ```c# using Unity.Entities; // This is a tag component that is also an "enableable component". // Such components can be toggled on and off while remaining present on the entity. // Doing so is a lot more efficient than adding and removing the component. struct Shooting : IComponentData, IEnableableComponent { } ``` 1. Modify the contents of the file named "TurretAuthoring.cs" in the folder "Scripts/Authoring" as follows: ```diff using Unity.Entities; class TurretAuthoring : UnityEngine.MonoBehaviour { public UnityEngine.GameObject CannonBallPrefab; public UnityEngine.Transform CannonBallSpawn; } class TurretBaker : Baker<TurretAuthoring> { public override void Bake(TurretAuthoring authoring) { AddComponent(new Turret { CannonBallPrefab = GetEntity(authoring.CannonBallPrefab), CannonBallSpawn = GetEntity(authoring.CannonBallSpawn) }); + // Enableable components are always initially enabled. + AddComponent<Shooting>(); } } ``` 1. Create a new C# source file named "SafeZoneSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Burst; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; // Requires the Turret type without processing it (it's not part of the Execute method). [WithAll(typeof(Turret))] [BurstCompile] partial struct SafeZoneJob : IJobEntity { // When running this job in parallel, the safety system will complain about a // potential race condition with TurretActiveFromEntity because accessing the same entity // from different threads would cause problems. // But the code of this job is written in such a way that only the entity being currently // processed will be looked up in TurretActiveFromEntity, making this process safe. // So we can disable the parallel safety check. [NativeDisableParallelForRestriction] public ComponentLookup<Shooting> TurretActiveFromEntity; public float SquaredRadius; void Execute(Entity entity, TransformAspect transform) { // The tag component Shooting will be enabled only if the tank is outside the given range. TurretActiveFromEntity.SetComponentEnabled(entity, math.lengthsq(transform.Position) > SquaredRadius); } } [BurstCompile] partial struct SafeZoneSystem : ISystem { // The ComponentLookup random accessors should not be created on the spot. // Just like EntityQuery, they should be created once and stored in a field. ComponentLookup<Shooting> m_TurretActiveFromEntity; [BurstCompile] public void OnCreate(ref SystemState state) { state.RequireForUpdate<Config>(); m_TurretActiveFromEntity = state.GetComponentLookup<Shooting>(); } [BurstCompile] public void OnDestroy(ref SystemState state) { } [BurstCompile] public void OnUpdate(ref SystemState state) { float radius = SystemAPI.GetSingleton<Config>().SafeZoneRadius; const float debugRenderStepInDegrees = 20; // Debug rendering (the white circle). for (float angle = 0; angle < 360; angle += debugRenderStepInDegrees) { var a = float3.zero; var b = float3.zero; math.sincos(math.radians(angle), out a.x, out a.z); math.sincos(math.radians(angle + debugRenderStepInDegrees), out b.x, out b.z); UnityEngine.Debug.DrawLine(a * radius, b * radius); } m_TurretActiveFromEntity.Update(ref state); var safeZoneJob = new SafeZoneJob { TurretActiveFromEntity = m_TurretActiveFromEntity, SquaredRadius = radius * radius }; safeZoneJob.ScheduleParallel(); } } ``` 1. Modify the contents of the file named "TurretShootingSystem.cs" in the folder "Scripts/Systems" as follows: ```diff +// Requiring the Shooting tag component effectively prevents this job from running +// for the tanks which are in the safe zone. +[WithAll(typeof(Shooting))] [BurstCompile] partial struct TurretShoot : IJobEntity { [ReadOnly] public ComponentLookup<LocalToWorldTransform> LocalToWorldTransformFromEntity; public EntityCommandBuffer ECB; void Execute(in TurretAspect turret) { var instance = ECB.Instantiate(turret.CannonBallPrefab); var spawnLocalToWorld = LocalToWorldTransformFromEntity[turret.CannonBallSpawn]; var cannonBallTransform = UniformScaleTransform.FromPosition(spawnLocalToWorld.Value.Position); cannonBallTransform.Scale = LocalToWorldTransformFromEntity[turret.CannonBallPrefab].Value.Scale; ECB.SetComponent(instance, new LocalToWorldTransform { Value = cannonBallTransform }); ECB.SetComponent(instance, new CannonBall { Speed = spawnLocalToWorld.Value.Forward() * 20.0f }); // The line below propagates the color from the turret to the cannon ball. ECB.SetComponent(instance, new URPMaterialPropertyBaseColor { Value = turret.Color }); } } ``` 1. Enter play mode, notice that the tanks are only shooting once they get outside of the safe zone. Make sure the gizmos are enabled in the view options, otherwise you will not see the white circle.<p> ![](images/safe_zone.gif) ![](images/gizmos_enabled.png) 1. Still in play mode, select the "Config" authoring GameObject and modify the "Safe Zone Radius". Notice that the changes are reflected in real time thanks to "Live Baking". 1. Leave play mode. ## Step 9 - Camera follow > Simple interaction between ECS and GameObjects at runtime. 1. Create a new C# source file named "CameraSingleton.cs" in the folder "Scripts/MonoBehaviours", put the following contents in there: ```c# // There are many ways of getting access to the main camera, but the approach using // a singleton (as we use here) works for any kind of MonoBehaviour. class CameraSingleton : UnityEngine.MonoBehaviour { public static UnityEngine.Camera Instance; void Awake() { Instance = GetComponent<UnityEngine.Camera>(); } } ``` 1. Add the "CameraSingleton" MonoBehaviour to the "Main Camera" GameObject in "SampleScene". 1. Create a new C# source file named "CameraSystem.cs" in the folder "Scripts/Systems", put the following contents in there: ```c# using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; // This system should run after the transform system has been updated, otherwise the camera // will lag one frame behind the tank and will jitter. [UpdateInGroup(typeof(LateSimulationSystemGroup))] partial class CameraSystem : SystemBase { Entity Target; Random Random; EntityQuery TanksQuery; protected override void OnCreate() { Random = Random.CreateFromIndex(1234); TanksQuery = GetEntityQuery(typeof(Tank)); RequireForUpdate(TanksQuery); } protected override void OnUpdate() { if (Target == Entity.Null || UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.Space)) { var tanks = TanksQuery.ToEntityArray(Allocator.Temp); Target = tanks[Random.NextInt(tanks.Length)]; } var cameraTransform = CameraSingleton.Instance.transform; var tankTransform = GetComponent<LocalToWorld>(Target); cameraTransform.position = tankTransform.Position - 10.0f * tankTransform.Forward + new float3(0.0f, 5.0f, 0.0f); cameraTransform.LookAt(tankTransform.Position, new float3(0.0f, 1.0f, 0.0f)); } } ``` 1. Enter play mode, look at the Game view (and not the Scene view as before), and notice that the camera is following one of the tanks. Make sure the Game view has input focus (click on it), and repeatedly press the spacebar. The camera should switch to another random tank every time.<p> ![](images/expected_result.gif) 1. Leave play mode. ## Congratulations! You reached the end of this tutorial! Go get some cake and celebrate!
/** * This is not a production server yet! * This is only a minimal backend to get started. */ import {Logger} from '@nestjs/common'; import {NestFactory} from '@nestjs/core'; import {AppModule} from './app/app.module'; import {execSync} from "child_process"; import {DocumentBuilder, SwaggerModule} from "@nestjs/swagger"; import * as fs from "fs"; async function bootstrap() { const app = await NestFactory.create(AppModule); const globalPrefix = 'api'; app.setGlobalPrefix(globalPrefix); const config = new DocumentBuilder() .setTitle("OpenAPI example") .setDescription("OpenAPI example API docs") .setVersion("1.0") .addTag("admin") .setBasePath("admin") .build(); const document = SwaggerModule.createDocument(app, config, {operationIdFactory: (controllerKey: string, methodKey: string) => methodKey}); SwaggerModule.setup("api-docs", app, document); // process.env.ENVIRONMENT === "LOCAL" if (true) { app.enableCors(); Logger.log("CORS enabled!"); const openApiDescriptionPath = "libs/backend-client/src/api-docs.json"; const frontendApiOutputPath = "libs/backend-client/src"; Logger.log("Generating api docs"); fs.writeFileSync( openApiDescriptionPath, JSON.stringify(document) ); execSync(`npx @openapitools/openapi-generator-cli generate -i ${openApiDescriptionPath} -g typescript-axios -o ${frontendApiOutputPath} --type-mappings=DateTime=Date --additional-properties=supportsES6=true`); } const port = process.env.PORT || 3333; await app.listen(port); Logger.log( `🚀 Application is running on: http://localhost:${port}/${globalPrefix}` ); } bootstrap();
// Copyright 2023 ISP RAS // // 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. // #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <Python.h> #define MAX_RE_TEST_SIZE 0x10000 PyObject* sre_compile_method = NULL; PyObject* sre_error_exception = NULL; int SRE_FLAG_DEBUG = 0; int init_sre_compile(void) { /* Import sre_compile.compile and sre.error */ PyObject* sre_compile_module = PyImport_ImportModule("sre_compile"); if (sre_compile_module == NULL) { return 0; } sre_compile_method = PyObject_GetAttrString(sre_compile_module, "compile"); if (sre_compile_method == NULL) { return 0; } PyObject* sre_constants = PyImport_ImportModule("sre_constants"); if (sre_constants == NULL) { return 0; } sre_error_exception = PyObject_GetAttrString(sre_constants, "error"); if (sre_error_exception == NULL) { return 0; } PyObject* debug_flag = PyObject_GetAttrString(sre_constants, "SRE_FLAG_DEBUG"); if (debug_flag == NULL) { return 0; } SRE_FLAG_DEBUG = PyLong_AsLong(debug_flag); return 1; } int fuzz_sre_compile(const char* data, size_t size) { /* Ignore really long regex patterns that will timeout the fuzzer */ if (size > MAX_RE_TEST_SIZE) { return 0; } /* We treat the first 2 bytes of the input as a number for the flags */ if (size < 2) { return 0; } uint16_t flags = ((uint16_t*) data)[0]; /* We remove the SRE_FLAG_DEBUG if present. This is because it prints to stdout which greatly decreases fuzzing speed */ flags &= ~SRE_FLAG_DEBUG; /* Pull the pattern from the remaining bytes */ PyObject* pattern_bytes = PyBytes_FromStringAndSize(data + 2, size - 2); if (pattern_bytes == NULL) { return 0; } PyObject* flags_obj = PyLong_FromUnsignedLong(flags); if (flags_obj == NULL) { Py_DECREF(pattern_bytes); return 0; } /* compiled = _sre.compile(data[2:], data[0:2] */ PyObject* compiled = PyObject_CallFunctionObjArgs( sre_compile_method, pattern_bytes, flags_obj, NULL); /* Ignore ValueError as the fuzzer will more than likely generate some invalid combination of flags */ if (compiled == NULL && PyErr_ExceptionMatches(PyExc_ValueError)) { PyErr_Clear(); } /* Ignore some common errors thrown by sre_parse: Overflow, Assertion, Recursion and Index */ if (compiled == NULL && (PyErr_ExceptionMatches(PyExc_OverflowError) || PyErr_ExceptionMatches(PyExc_AssertionError) || PyErr_ExceptionMatches(PyExc_RecursionError) || PyErr_ExceptionMatches(PyExc_IndexError)) ) { PyErr_Clear(); } /* Ignore re.error */ if (compiled == NULL && PyErr_ExceptionMatches(sre_error_exception)) { PyErr_Clear(); } Py_DECREF(pattern_bytes); Py_DECREF(flags_obj); Py_XDECREF(compiled); return 0; } int main(int argc, char** argv) { // Make initialization if (!Py_IsInitialized()) { Py_InitializeEx(0); } if (!init_sre_compile()) { PyErr_Print(); printf("Failed to initialize sre_compile\n"); return 0; } // Read symbolic file FILE* fd = fopen(argv[1], "rb"); if (!fd) return 1; fseek(fd, 0, SEEK_END); long fsize = ftell(fd); fseek(fd, 0, SEEK_SET); char* buffer = (char*)malloc(fsize); fread(buffer, 1, fsize, fd); fclose(fd); // Run fuzztarget fuzz_sre_compile(buffer, fsize); return 0; }
import axios from "axios"; import { useEffect, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { toast } from "react-toastify"; import FormatDateTime from "../../../utils/FormatDateTime"; import FormatDate from "../../../utils/FormatDate"; import FormatCurrency from "../../../utils/FormatCurrency"; import { Button, Input, Modal, ModalBody, ModalContent, ModalHeader, Table, TableBody, TableCell, TableColumn, TableHeader, TableRow, } from "@nextui-org/react"; import ModalKonfYesNo from "../../../components/ModalKonfYesNo"; const checkOut = async (request, token) => { let res; await axios .post(`/reservasi/kamar/check-out`, request, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) .then((response) => { res = response.data; }) .catch((error) => { res = error.response.data; }); return res; }; function CheckOut() { const [dataDetail, setDataDetail] = useState({}); const [loadSubmit, setLoadSubmit] = useState(false); const [loadCheckOut, setLoadCheckOut] = useState(false); const [konfirmCheckOut, setKonfirmCheckOut] = useState(false); const token = localStorage.getItem("apiKeyAdmin"); const navigation = useNavigate(); const { idReservasi } = useParams(); const [isOpenInputKekurangan, onOpenChangeInputKekurangan] = useState(false); const [inputJumlahUang, setInputJumlahUang] = useState(0); async function getDataTrxCheckOut() { await axios .get(`/transaksi/detail/${idReservasi}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, }) .then((response) => { // res = response; const { data } = response.data; setDataDetail(data); toast.success(response.data.message); }) .catch((error) => { toast.error(error.response.data.message); }); } useEffect(() => { getDataTrxCheckOut(); }, []); async function handleBayarKekurangan(e) { e.preventDefault(); setLoadSubmit(true); setKonfirmCheckOut(true); setLoadSubmit(false); } async function handleCheckOut(e){ e.preventDefault(); setLoadCheckOut(true); const response = await checkOut( { id_trx_reservasi : idReservasi, tgl_lunas : new Date().toLocaleDateString('en-CA', { year: 'numeric', month: '2-digit', day: '2-digit', }).replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2'), total_harga_kamar : dataDetail.totalHargaKamarAll * dataDetail.jumlah_malam, total_harga_layanan : dataDetail.totalHargaLayananAll, pajak_layanan : dataDetail.pajakLayanan, total_semua : dataDetail.total_semua, temp_lebih_kurang : dataDetail.kurang_atau_kembali < 0 ? 1 : 0, total_lebih_kurang : dataDetail.kurang_atau_kembali < 0 ? dataDetail.kurang_atau_kembali * (-1) : dataDetail.kurang_atau_kembali, jumlah_bayar : inputJumlahUang }, token); setLoadCheckOut(false); if(response.status == 'T'){ toast.success(response.message); navigation(`/admin/reservasi`); }else{ console.log(response); toast.error(response.message); } } return ( <div> <div className="flex justify-center"> <p className="text-4xl font-bold pb-4 md:w-3/4 !mb-7 border-b-1 border-gray-400 uppercase text-center"> TRANSAKSI RESERVASI {dataDetail.id_booking} </p> </div> <div className="space-y-2"> <p> Tanggal Pesan :{" "} {dataDetail?.waktu_reservasi && FormatDateTime(new Date(dataDetail?.waktu_reservasi))} </p> {dataDetail.id_booking && <p>ID Booking : {dataDetail?.id_booking}</p>} {dataDetail.id_fo && ( <p> Nama <i>Front Office</i> : {dataDetail.fo.nama_pegawai} </p> )} <p>Jumlah Dewasa : {dataDetail.jumlah_dewasa}</p> <p>Jumlah Anak-anak : {dataDetail.jumlah_anak_anak}</p> <p> Tanggal <i>Check in</i> :{" "} {dataDetail?.waktu_check_in && FormatDate(new Date(dataDetail?.waktu_check_in))} </p> <p> Tanggal <i>Check out</i> :{" "} {dataDetail?.waktu_check_out && FormatDate(new Date(dataDetail?.waktu_check_out))} </p> <p> Total Harga Kamar :{" "} {dataDetail?.total_harga && FormatCurrency(dataDetail?.total_harga)} </p> <div className="space-y-4 !mb-5"> <p>Pemesanan Kamar :</p> <Table aria-label="Tabel Permintaan Layanan"> <TableHeader> <TableColumn>JENIS KAMAR</TableColumn> <TableColumn>JUMLAH KAMAR</TableColumn> <TableColumn>HARGA PER MALAM</TableColumn> {/* <TableColumn>JUMLAH MALAM</TableColumn> <TableColumn>TOTAL HARGA</TableColumn> */} <TableColumn>JUMLAH MALAM</TableColumn> <TableColumn>SUB TOTAL</TableColumn> </TableHeader> <TableBody> {dataDetail["trxKamarPesananPerJenis"] && Object.keys(dataDetail["trxKamarPesananPerJenis"]).map((tl) => { const transaksi = dataDetail["trxKamarPesananPerJenis"][tl]; return ( <TableRow key={tl}> <TableCell>{transaksi.jenis_kamar}</TableCell> <TableCell>{transaksi.jumlah}</TableCell> <TableCell> {transaksi.harga_per_malam && FormatCurrency(transaksi.harga_per_malam)} </TableCell> <TableCell>{dataDetail.jumlah_malam}</TableCell> <TableCell> {transaksi.harga_per_malam && FormatCurrency(transaksi.total_per_jenis)} </TableCell> </TableRow> ); })} <TableRow> <TableCell></TableCell> <TableCell></TableCell> <TableCell></TableCell> <TableCell></TableCell> <TableCell className="font-bold "> {dataDetail.totalHargaKamarAll && FormatCurrency(dataDetail.totalHargaKamarAll)} </TableCell> </TableRow> </TableBody> </Table> </div> <div className="space-y-4"> <p>Permintaan Layanan :</p> <Table aria-label="Tabel Permintaan Layanan"> <TableHeader> <TableColumn>NAMA LAYANAN</TableColumn> <TableColumn>TANGGAL</TableColumn> <TableColumn>JUMLAH</TableColumn> <TableColumn>HARGA</TableColumn> <TableColumn>SUB TOTAL</TableColumn> </TableHeader> <TableBody emptyContent={"Tidak ada Data Permintaan Layanan"}> {dataDetail["trxLayananPesan"] && Object.keys(dataDetail["trxLayananPesan"]).map((tl) => { const transaksiDetail = dataDetail["trxLayananPesan"][tl]; return ( <TableRow key={tl}> <TableCell>{transaksiDetail.nama_layanan}</TableCell> <TableCell> {transaksiDetail.tgl_pemakaian && new Date(transaksiDetail.tgl_pemakaian).toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' }) } </TableCell> <TableCell>{transaksiDetail.jumlah}</TableCell> <TableCell> {transaksiDetail.harga_per_satuan && FormatCurrency(transaksiDetail.harga_per_satuan)} </TableCell> <TableCell> {transaksiDetail.total_per_layanan && FormatCurrency(transaksiDetail.total_per_layanan)} </TableCell> </TableRow> ); })} <TableRow> <TableCell></TableCell> <TableCell></TableCell> <TableCell></TableCell> <TableCell></TableCell> <TableCell className="font-bold "> {dataDetail.totalHargaLayananAll && FormatCurrency(dataDetail.totalHargaLayananAll)} </TableCell> </TableRow> </TableBody> </Table> </div> <div className="pe-10 pt-3"> <table className="w-full"> <thead> <tr className="text-center"> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr className="text-end"> <td colSpan="3" className="w-52"></td> <td>Pajak</td> <td>{FormatCurrency(dataDetail.pajakLayanan)}</td> </tr> <tr className="text-end"> <td colSpan="3"></td> <td className="font-bold">TOTAL</td> <td className="font-bold"> {FormatCurrency(dataDetail.total_semua)} </td> </tr> <tr className="text-end"> <td colSpan="5"></td> </tr> <tr className="text-end"> <td colSpan="3"></td> <td>Jaminan</td> <td>{FormatCurrency(dataDetail.uang_jaminan)}</td> </tr> <tr className="text-end"> <td colSpan="3"></td> <td>Deposit</td> <td>{FormatCurrency(dataDetail.deposit)}</td> </tr> {dataDetail.kurang_atau_kembali < 0 ? ( <tr className="text-end"> <td colSpan="3"></td> <td className="font-bold">Uang Kembali</td> <td className="font-bold"> {FormatCurrency(dataDetail.kurang_atau_kembali * -1)} </td> </tr> ) : ( <tr className="text-end"> <td colSpan="3"></td> <td className="font-bold">Kekurangan</td> <td className="font-bold"> {FormatCurrency(dataDetail.kurang_atau_kembali)} </td> </tr> )} </tbody> </table> </div> </div> <div className="mt-5"> {dataDetail.kurang_atau_kembali < 0 ? <Button fullWidth className="bg-red-600 text-medium text-white hover:bg-red-500 uppercase" onClick={() => {setKonfirmCheckOut(true)}}>Lakukan Check Out</Button> : <Button fullWidth className="bg-green-600 text-medium text-white hover:bg-green-500 uppercase" onClick={() => {onOpenChangeInputKekurangan(true)}}>Input Pembayaran Kekurangan</Button> } </div> <Modal isOpen={isOpenInputKekurangan} onOpenChange={onOpenChangeInputKekurangan} scrollBehavior="inside" placement="center" className="md:max-w-3xl rounded-md" onClose={() => { // setFasilitasSelected({}); }} > <ModalContent className="pb-3 overflow-hidden"> <ModalHeader className="flex flex-col gap-1 uppercase bg-primary text-white"> Input Uang Kekurangan </ModalHeader> <ModalBody> <div> <p className="text-[15px] mb-3">Kekurangan pembayaran : <b>{FormatCurrency(dataDetail?.kurang_atau_kembali)}</b></p> <form onSubmit={(e) => {handleBayarKekurangan(e)}}> <label htmlFor="jmlUang">Masukkan Jumlah Uang Terbayar:</label> <Input type="number" id="jmlUang" variant="bordered" className="w-1/2 m-0" classNames={{ input: ["text-lg"] }} onChange={(e) => setInputJumlahUang(e.target.value)} isInvalid={parseInt(inputJumlahUang) != parseInt(dataDetail.kurang_atau_kembali)} errorMessage={parseInt(inputJumlahUang) < parseInt(dataDetail.kurang_atau_kembali) ? "Uang masih kurang!" : parseInt(inputJumlahUang) > parseInt(dataDetail.kurang_atau_kembali) ? "Uang kelebihan!" : ""} /> <p className="text-xs mt-1 mb-3"> Terbayar :{" "} <span className="font-bold text-sm"> {FormatCurrency(inputJumlahUang)} </span> </p> <Button type="submit" isLoading={loadSubmit} className="bg-primary hover:bg-opacity-90 text-white" fullWidth isDisabled={parseInt(inputJumlahUang) != parseInt(dataDetail.kurang_atau_kembali)} > Konfirmasi </Button> </form> </div> </ModalBody> </ModalContent> </Modal> <ModalKonfYesNo openKonfirm={konfirmCheckOut} setOpenKonfirm={setKonfirmCheckOut} onClickNo={() => setKonfirmCheckOut(false)} onClickYes={(e) => {handleCheckOut(e)}} isLoading={loadCheckOut} pesan="Apakah yakin ingin melakukan check out untuk reservasi ini?"/> </div> ); } export default CheckOut;
import { ArrowRightOutlined } from '@mui/icons-material'; import './flashsales.scss'; import { useEffect, useState } from 'react'; import ProgressBar from './ProgressBar'; import { flashSales } from '../data'; import {Link} from 'react-router-dom' // import ProductCarousel from './ProductCarousel'; import ProductComponent from './ProductComponent'; const FlashSales = () => { const [timeLeft, setTimeLeft] = useState(365 *24 * 60 * 60 *1000); const catLink = flashSales[0].cat; useEffect(()=>{ const timerId = setInterval(()=>{ setTimeLeft((prevTime)=> prevTime - 1000); }, 1000); return () =>{ clearInterval(timerId); }; }, []); const timeLeftDisplay = formatTime(timeLeft); return ( <div className='flashsales'> <div className='flashsale-header'> <h4>Flash Sales</h4> <div className='time-left'> <p>Time left</p> <h4>{timeLeftDisplay}</h4> </div> <Link to={`/products/${catLink}`} className='link'> <div className='see-all'> <span>See All</span> <ArrowRightOutlined/> </div> </Link> </div> <div className='flashsales-wrapper'> <div className='mobile-flash'> <ProductComponent products={flashSales} showProgressBar = {true}/> {/* <ProductCarousel products={flashSales}showProgressBar={true} /> */} </div> { flashSales.map((items)=>( <Link to={`/product/${items.id}`} className='link content-edit' > <div className="content" key={items.id}> <img src={items.img} alt="" /> <p className='title'>{items.title}</p> <p className='price'><span>N</span>{items.price}</p> <p className='initial-pice'><span>N</span>{items.initialPrice}</p> <p>{items.itemLeft} items left</p> <ProgressBar totalItems={items.totalItem} itemsLeft={items.itemLeft}/> </div> </Link> )) } </div> </div> ) }; const formatTime = (time)=>{ const hours = Math.floor(time/(1000 * 60 * 60)); const minutes = Math.floor((time / (1000 * 60)) % 60); const seconds = Math.floor((time / 1000) % 60); return `${hours}h: ${minutes}m: ${seconds}s`; } export default FlashSales
import { Notifications, Search,AccountCircle,KeyboardArrowDown } from "@mui/icons-material"; import "./navbar.scss"; import { useContext } from "react"; import {Link} from "react-router-dom" import { AuthContext } from "../../context/authContext/AuthContext"; import { logout } from "../../context/authContext/AuthActions"; export default function Navbar({setGenre}){ const { dispatch } = useContext(AuthContext); const user = JSON.parse(localStorage.getItem("user")); return ( <div className="navbar"> <div className="container"> <div className="left"> <Link to="/" className="link" onClick={()=>setGenre('')}> <span>HomePage</span> </Link> <Link to="/series" className="link" onClick={()=>setGenre('')}> <span>Series</span> </Link> <Link to="/movies" className="link"onClick={()=>setGenre('')}> <span>Movies</span> </Link> {/* <Link to="/popular" className="link"> <span>Popular</span> </Link> */} <Link to="/myList" className="link"> <span>MyList</span> </Link> </div> <div className="right"> <Notifications className="icon"/> {user.profilePic ? ( <img src={user.profilePic} alt="User Profile Picture" className="icon" /> ) : ( <AccountCircle className="icon" /> )} <span>{user.username}</span> <div className="profile"> <KeyboardArrowDown className="icon"/> <div className="options"> <Link to="/user" className="link"> <span>Setting</span> </Link> <span onClick={() => dispatch(logout())}>Logout</span> </div> </div> </div> </div> </div> ) };
var express = require("express"); var router = express.Router({mergeParams: true}); var Campground = require("../models/campground"); var Comment = require("../models/comment"); var middleware = require("../middleware/index"); //new comment route router.get("/new", middleware.isLoggedIn, function(req, res){ Campground.findById(req.params.id, function(err, foundCampground){ if(err || !foundCampground){ req.flash("error", "Campground not found"); res.redirect("back"); } else { res.render("comments/new", {campground: foundCampground}); } }); }); //create comment route router.post("/", middleware.isLoggedIn, function(req, res){ Campground.findById(req.params.id, function(err, campground){ if(err){ req.flash("error", "Something went wrong"); res.redirect("/campgrounds"); console.log(err); } else { Comment.create(req.body.comment, function(err, comment){ if(err){ req.flash("error", "Something went wrong"); res.redirect("back"); console.log(err); } else { comment.author.id = req.user._id; comment.author.username = req.user.username; comment.save(); campground.comments.push(comment); campground.save(); req.flash("success", "Comment added successfully"); res.redirect("/campgrounds/" + campground._id); } }); } }); }); //edit comment route router.get("/:comment_id/edit", middleware.checkCommentOwnership,function(req, res){ Comment.findById(req.params.comment_id, function(err, foundComment){ if(err||!foundComment){ req.flash("error", err.message); res.redirect("back"); } else{ res.render("comments/edit", {campground_id: req.params.id, comment: foundComment}); } }) }); //update comment route router.put("/:comment_id", middleware.checkCommentOwnership,function(req, res){ Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err, upadatedComment){ if(err||!upadatedComment){ req.flash("error", "Something went wrong"); res.redirect("back"); } else{ res.redirect("/campgrounds/" + req.params.id); } }); }); //delete comment route router.delete("/:comment_id", middleware.checkCommentOwnership,function(req, res){ Comment.findByIdAndRemove(req.params.comment_id, function(err){ if(err){ req.flash("error", "Something went wrong"); res.redirect("/campgrounds/" + req.params.id); } else{ req.flash("success", "Comment deleted"); res.redirect("/campgrounds/" + req.params.id); } }); }); module.exports = router
/* * Copyright 2017-2024 John A. De Goes and the ZIO Contributors * * 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 zio.internal import zio.stacktracer.TracingImplicits.disableAutoTrace import java.util.concurrent.locks.ReentrantLock import java.util.concurrent.locks.Condition /** * A variable that can be set a single time. The synchronous, effectful * equivalent of `Promise`. */ private[zio] final class OneShot[A] private () extends ReentrantLock(false) { @volatile private var value = null.asInstanceOf[A with AnyRef] private final val isSetCondition: Condition = this.newCondition() import OneShot._ /** * Sets the variable to the value. The behavior of this function is undefined * if the variable has already been set. */ def set(v: A): Unit = { if (v == null) throw new Error("Defect: OneShot variable cannot be set to null value") this.lock() try { if (value != null) throw new Error("Defect: OneShot variable being set twice") value = v.asInstanceOf[A with AnyRef] this.isSetCondition.signalAll() } finally { this.unlock() } } /** * Determines if the variable has been set. */ def isSet: Boolean = value != null /** * Retrieves the value of the variable, blocking if necessary. * * @param timeout * The maximum amount of time the thread will be blocked, in milliseconds. * @throws Error * if the timeout is reached without the value being set. */ def get(timeout: Long): A = if (value ne null) value else { this.lock() try { if (value == null) this.isSetCondition.await(timeout, java.util.concurrent.TimeUnit.MILLISECONDS) } finally { this.unlock() } if (value == null) throw new Error("Timed out waiting for variable to be set") value } /** * Retrieves the value of the variable, blocking if necessary. * * This will block until the value is set or the thread is interrupted. */ def get(): A = if (value ne null) value else { this.lock() try { while (value == null) this.isSetCondition.await() } finally { this.unlock() } value } } private[zio] object OneShot { private final val nanosPerMilli = 1000000L /** * Makes a new (unset) variable. */ def make[A]: OneShot[A] = new OneShot() }
<div class="page-header"> <h3>Project #<%= @project.id %></h3> </div> <div class="row"> <div class="col-md-12 mb-2"> <dl class="dl-horizontal"> <dt>Name</dt> <dd><%= @project.name %></dd> <dt>Location</dt> <dd> <% if @project.location.present? %> <a href="/locations/<%= @project.location_id %>"> <%= @project.location.neighborhood %> </a> <% end %> </dd> <dt>Date</dt> <dd> <% if @project.date.present? %> <a href="/days/<%= @project.date_id %>"> <%= @project.date.date %> </a> <% end %> </dd> <dt>Description</dt> <dd><%= @project.description %></dd> <dt>Number of volunteers required</dt> <dd><%= @project.number_of_volunteers_required %></dd> <dt>Organization</dt> <dd> <% if @project.organization.present? %> <a href="/organizations/<%= @project.organization_id %>"> <%= @project.organization.created_at %> </a> <% end %> </dd> </dl> <div class="btn-group btn-group-justified"> <a href="/projects" class="btn btn-primary"> Back </a> <% if current_user == @project.organization %> <a href="/projects/<%= @project.id %>/edit" class="btn btn-warning"> Edit </a> <a href="/delete_project/<%= @project.id %>" class="btn btn-danger" rel="nofollow"> Delete </a> <% end %> </div> </div> </div> <!-- A Project has many project_skills --> <div class="row"> <div class="col-md-12"> <ul class="list-group"> <li class="list-group-item list-group-item-info"> Project_skills </li> <% @project.project_skills.each do |project_skill| %> <li class="list-group-item"> <a href="/project_skills/<%= project_skill.id %>"> <%= project_skill.project_id %> </a> <div class="btn-group btn-group-xs pull-right"> <a href="/project_skills/<%= project_skill.id %>" class="btn btn-primary"> <i class="fa fa-search-plus"></i> </a> <a href="/project_skills/<%= project_skill.id %>/edit" class="btn btn-warning"> <i class="fa fa-edit"></i> </a> <a href="/delete_project_skill/<%= project_skill.id %>" class="btn btn-danger" rel="nofollow"> <i class="fa fa-trash-o"></i> </a> </div> </li> <% end %> <li class="list-group-item"> <form action="/create_project_skill" method="post"> <!-- Hidden input for authenticity token to protect from forgery --> <input name="authenticity_token" type="hidden" value="<%= form_authenticity_token %>"> <!-- Label and input for project_id --> <input type="hidden" name="project_id" value="<%= @project.id %>"> <!-- Label and input for skill_id --> <div class="form-group"> <label for="skill_id" class="control-label"> Skill </label> <%= select_tag(:skill_id, options_from_collection_for_select(Skill.all, :id, :name), :class => "form-control") %> </div> <button class="btn btn-block btn-success"> Create Project Skill </button> </form> </li> </ul> </div> </div>
import React, { useState } from "react"; import SearchList from "./SearchList"; import "../style/search.css"; function Search({ items, onDelete }) { const [searchField, setSearchField] = useState(""); const [sortBy, setSortBy] = useState("none"); const filteredItems = items.filter((item) => item.item_description.toLowerCase().includes(searchField.toLowerCase()) ); let sortedItems = [...filteredItems]; if (sortBy != "none") sortedItems.sort((a, b) => { console.log(typeof a.date_add); switch (sortBy) { case "price_asc": return a.price - b.price; case "price_desc": return b.price - a.price; case "des_asc": return a.item_description.localeCompare(b.item_description); case "des_desc": return b.item_description.localeCompare(a.item_description); case "time_asc": return new Date(a.date_add) - new Date(b.date_add); case "time_desc": return new Date(b.date_add) - new Date(a.date_add); } }); const handleChange = (e) => { setSearchField(e.target.value); }; const handlePriceSortChange = (e) => { setSortBy(e.target.value); }; function searchList() { return <SearchList filteredItems={sortedItems} onDelete={onDelete} />; } return ( <section className="search-section"> <div> <h2 className="search-title">חפש את הפריט האהוב עלייך</h2> </div> <div> <input className="search-input" type="search" placeholder="חפש פריט" onChange={handleChange} /> </div> <div> <label htmlFor="sort-by">מיין לפי: </label> <select id="sort-by" value={sortBy} onChange={handlePriceSortChange}> <option value="none">ללא מיון</option> <option value="price_asc">מחיר מהנמוך לגבוה</option> <option value="price_desc">מחיר מהגבוה לנמוך</option> <option value="des_asc">שם בסדר א"ב</option> <option value="des_desc">שם בסדר א"ב הפוך</option> <option value="time_asc">מהחדש לישן</option> <option value="time_desc">מהישן לחדש</option> </select> </div> {searchList()} </section> ); } export default Search;
package Structs.CasamentoDePadroes; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import Structs.arquivo; import Structs.filme; public class KMP { private static RandomAccessFile arq; public static filme getFilme() throws IOException { if (arq == null) { arq = new RandomAccessFile("Banco/DB.bin", "rw");// arbrir arquivo para leitura. } int tamanhoRegistro, id; boolean lapide; if (arq.getFilePointer() == 0) { arq.seek(4);// pular os 4 bytes do cabeçalho do registro } filme f = null; while (arq.getFilePointer() < arq.length()) { tamanhoRegistro = arq.readInt();// 4 bytes lapide = arq.readBoolean();// 1 byte id = arq.readInt();// 4 bytes if (lapide == false) { f = new filme(lapide, id); arq.readInt();// tamanho do Type f.setType(arq.readUTF());// salvando o Type arq.readInt();// tamanho do Name f.setName(arq.readUTF());// salvando o Nome arq.readInt();// tamanho do Director f.setDirector(arq.readUTF()); // Sanvando o diretor String s = ""; int aux = arq.readInt();// quantidade de pessoas do elenco for (int i = 0; i < aux; i++) { arq.readInt();// tamanho do nome de cada pessoa do elenco s = s + arq.readUTF() + ","; } f.setCast(s.split(","));// salvando cada pessoa do elenco arq.readInt();// tamanho do Country f.setCountry(arq.readUTF()); // salvando o Country arq.readInt();// tamanho da Data f.setDateAdded(arq.readUTF());// salvando a data f.setReleaseYear(arq.readInt());// salvando o ano de lançamento arq.readInt();// tamanho do rating f.setRating(arq.readUTF());// sanlvando o rating f.setDuration(arq.readInt());// savlando a duração String s1 = ""; int aux1 = arq.readInt();// quntidade de generos que tem o registro for (int i = 0; i < aux1; i++) { arq.readInt();// tamanho de cada genero s1 = s1 + arq.readUTF() + ","; } f.setGenres(s1.split(","));// salvando cada genero arq.readInt();// tamanho da descrição f.setDescription(arq.readUTF());// salvando a descrição return f; } else { arq.skipBytes(tamanhoRegistro - 5);// pular o tamanho do registro que é uma lapide - 5 bytes que ja foi // lido } } return null; } private static String listToString(String[] arr) { String resp = ""; for (int i = 0; i < arr.length; i++) { resp += arr[i].trim(); } return resp; } private static boolean kmp(String texto, String padrao) { int[] prefixo = calcularPrefixo(padrao); int j = 0; for (int i = 0; i < texto.length(); i++) { while (j > 0 && texto.charAt(i) != padrao.charAt(j)) { j = prefixo[j - 1]; } if (texto.charAt(i) == padrao.charAt(j)) { j++; } if (j == padrao.length()) { return true; } } return false; } private static int[] calcularPrefixo(String padrao) { int[] prefixo = new int[padrao.length()]; int j = 0; for (int i = 1; i < padrao.length(); i++) { while (j > 0 && padrao.charAt(i) != padrao.charAt(j)) { j = prefixo[j - 1]; } if (padrao.charAt(i) == padrao.charAt(j)) { j++; } prefixo[i] = j; } return prefixo; } public static List<filme> buscarKPM(String key) throws IOException{ List<filme> resultados = new ArrayList<>(); for (int i = 0; i < arquivo.getCont(); i++) { filme filmeAtual = getFilme(); boolean encontrado = false; String nome = filmeAtual.getName(); String tipo = filmeAtual.getType(); String pais = filmeAtual.getCountry(); String descricao = filmeAtual.getDescription(); String generos = listToString(filmeAtual.getGenres()); if(kmp(nome, key) == true){ encontrado = true; }else if(kmp(tipo, key) == true){ encontrado = true; }else if(kmp(pais, key) == true){ encontrado = true; }else if(kmp(descricao, key) == true){ encontrado = true; }else if(kmp(generos, key) == true){ encontrado = true; } if(encontrado){ resultados.add(filmeAtual); } } return resultados; } }
import * as React from "react"; import { styled, useTheme } from "@mui/material/styles"; import Box from "@mui/material/Box"; import Drawer from "@mui/material/Drawer"; import CssBaseline from "@mui/material/CssBaseline"; import MuiAppBar from "@mui/material/AppBar"; import Toolbar from "@mui/material/Toolbar"; import List from "@mui/material/List"; import Typography from "@mui/material/Typography"; import Divider from "@mui/material/Divider"; import IconButton from "@mui/material/IconButton"; import MenuIcon from "@mui/icons-material/Menu"; import InfoIcon from '@mui/icons-material/Info'; import ChevronLeftIcon from "@mui/icons-material/ChevronLeft"; import ChevronRightIcon from "@mui/icons-material/ChevronRight"; import ListItem from "@mui/material/ListItem"; import ListItemButton from "@mui/material/ListItemButton"; import ListItemIcon from "@mui/material/ListItemIcon"; import ListItemText from "@mui/material/ListItemText"; import { Outlet, useLocation, useNavigate } from "react-router-dom"; import { Avatar, Badge, Button, MenuItem } from "@mui/material"; import useMediaQuery from "../../hooks/useMediaQuery.js"; import AccountBoxIcon from '@mui/icons-material/AccountBox'; import { panelChildren } from "../../routes.js"; import { toTitleCase } from "../../utils/tools.js"; import Menu from "@mui/material/Menu"; import AccountCircle from "@mui/icons-material/AccountCircle"; import MailIcon from "@mui/icons-material/Mail"; import NotificationsIcon from "@mui/icons-material/Notifications"; import ArrowDropDownIcon from "@mui/icons-material/ArrowDropDown"; import MoreIcon from "@mui/icons-material/MoreVert"; import CustomSeparator from "../common/BreadCrumbs.jsx"; import { logOut } from "../../features/mainSlice.js"; import LogoutIcon from '@mui/icons-material/Logout'; import { useDispatch, useSelector } from "react-redux"; const drawerWidth = 240; const Main = styled("main", { shouldForwardProp: (prop) => prop !== "open" })( ({ theme, open }) => ({ flexGrow: 1, padding: theme.spacing(3), transition: theme.transitions.create("margin", { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), marginLeft: `-${drawerWidth}px`, ...(open && { transition: theme.transitions.create("margin", { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), marginLeft: 0, }), }) ); const AppBar = styled(MuiAppBar, { shouldForwardProp: (prop) => prop !== "open", })(({ theme, open }) => ({ transition: theme.transitions.create(["margin", "width"], { easing: theme.transitions.easing.sharp, duration: theme.transitions.duration.leavingScreen, }), ...(open && { width: `calc(100% - ${drawerWidth}px)`, marginLeft: `${drawerWidth}px`, transition: theme.transitions.create(["margin", "width"], { easing: theme.transitions.easing.easeOut, duration: theme.transitions.duration.enteringScreen, }), }), })); const DrawerHeader = styled("div")(({ theme }) => ({ display: "flex", alignItems: "center", padding: theme.spacing(0, 1), ...theme.mixins.toolbar, justifyContent: "flex-end", })); export default function Panel() { const theme = useTheme(); const { session } = useSelector((data) => data.mainSlice); const isMobile = useMediaQuery("(max-width: 600px)"); const dispatch = useDispatch(); const [open, setOpen] = React.useState(!isMobile); const navigate = useNavigate(); let location = useLocation(); let currentPath = location?.pathname.split("/"); if (currentPath.length) currentPath = currentPath[currentPath.length - 1]; const [anchorEl, setAnchorEl] = React.useState(null); const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null); const handleDrawerOpen = () => { setOpen(true); }; const handleDrawerClose = () => { isMobile && setOpen(false); }; const isMenuOpen = Boolean(anchorEl); const isMobileMenuOpen = Boolean(mobileMoreAnchorEl); const handleProfileMenuOpen = (event) => { setAnchorEl(event.currentTarget); }; const handleMobileMenuClose = () => { setMobileMoreAnchorEl(null); }; const handleMenuClose = () => { setAnchorEl(null); handleMobileMenuClose(); }; const handleMobileMenuOpen = (event) => { setMobileMoreAnchorEl(event.currentTarget); }; React.useEffect(() => { setOpen(!isMobile); }, [isMobile]); React.useEffect(() => { if (session == null) navigate("/"); }, [session]); const menuId = "primary-search-account-menu"; const renderMenu = ( <Menu anchorEl={anchorEl} anchorOrigin={{ vertical: "bottom", horizontal: "right", }} sx={{top:"40px",minWidth:"300px"}} id={menuId} keepMounted transformOrigin={{ vertical: "bottom", horizontal: "right", }} open={isMenuOpen} onClose={handleMenuClose} > <MenuItem sx={{minWidth:150,py:1}} onClick={() => { navigate("/user_management/profile"); handleMenuClose(); }} > <div style={{ display: "flex", alignItems: "center", gap: "12px" }}> <AccountBoxIcon color="primary"/> <p className="abs" style={{ fontSize: "16px", fontFamily: "sans-serif", }} > Profile </p> </div> </MenuItem> <MenuItem sx={{minWidth:150,py:1}} onClick={() => { navigate('/user_management/about') handleMenuClose(); }} > <div style={{ display: "flex", alignItems: "center", gap: "12px" }}> <InfoIcon color="info"/> <p className="abs" style={{ fontSize: "16px", fontFamily: "sans-serif", }} > About </p> </div> </MenuItem> <MenuItem sx={{minWidth:150,py:1}} onClick={() => { dispatch(logOut()); handleMenuClose(); }} > <div style={{ display: "flex", alignItems: "center", gap: "12px" }}> <LogoutIcon color="error"/> <p className="abs" style={{ fontSize: "16px", fontFamily: "sans-serif", }} > Log Out </p> </div> </MenuItem> </Menu> ); const mobileMenuId = "primary-search-account-menu-mobile"; const renderMobileMenu = ( <Menu anchorEl={mobileMoreAnchorEl} anchorOrigin={{ vertical: "bottom", horizontal: "right", }} id={mobileMenuId} keepMounted transformOrigin={{ vertical: "bottom", horizontal: "right", }} open={isMobileMenuOpen} onClose={handleMobileMenuClose} > <MenuItem> <IconButton size="large" aria-label="show 4 new mails" color="inherit"> <Badge badgeContent={4} color="error"> <MailIcon /> </Badge> </IconButton> <p>Messages</p> </MenuItem> <MenuItem> <IconButton size="large" aria-label="show 17 new notifications" color="inherit" > <Badge badgeContent={17} color="error"> <NotificationsIcon /> </Badge> </IconButton> <p>Notifications</p> </MenuItem> <MenuItem onClick={handleProfileMenuOpen}> <Button size="large" sx={{ marginLeft: 1 }} edge="end" aria-label="account of current user" aria-controls={menuId} aria-haspopup="true" onClick={handleProfileMenuOpen} color="inherit" > <div style={{ display: "flex", alignItems: "center", gap: "8px" }} > <Avatar alt={session?.firstName} src={session?.pic} /> <p className="abs" style={{ fontSize: "16px", fontWeight: 600, fontFamily: "sans-serif", display: "flex", alignItems: "center", textTransform: "capitalize", gap: "5px" }} > <div style={{ display: "flex",flexDirection:"column", alignItems: "center",justifyContent:"center",lineHeight:1.2 }}> <p className="abs" >{toTitleCase(session?.firstName + " " + session?.lastName)}</p> <small style={{fontWeight:400,width:"100%",display:"block",textAlign:"start"}}>{session?.role}</small> </div> <ArrowDropDownIcon /> </p> </div> </Button> </MenuItem> </Menu> ); return ( <Box sx={{ display: "flex" }}> <CssBaseline /> <AppBar position="fixed" open={open} color="inherit" variant="outlined"> <Toolbar> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerOpen} edge="start" sx={{ mr: 2, ...(open && { display: "none" }) }} > <MenuIcon /> </IconButton> <Box sx={{ flexGrow: 1 }} /> <Box sx={{ display: { xs: "none", md: "flex" } }}> <IconButton size="large" aria-label="show 4 new mails" color="inherit" > <Badge badgeContent={4} color="error"> <MailIcon /> </Badge> </IconButton> <IconButton size="large" aria-label="show 17 new notifications" color="inherit" > <Badge badgeContent={17} color="error"> <NotificationsIcon /> </Badge> </IconButton> <Button size="large" sx={{ marginLeft: 1 }} edge="end" aria-label="account of current user" aria-controls={menuId} aria-haspopup="true" onClick={handleProfileMenuOpen} color="inherit" > <div style={{ display: "flex", alignItems: "center", gap: "8px" }} > <Avatar alt={session?.firstName} src={session?.pic} /> <p className="abs" style={{ fontSize: "16px", fontWeight: 600, fontFamily: "sans-serif", display: "flex", alignItems: "center", textTransform: "capitalize", gap: "5px" }} > <div style={{ display: "flex",flexDirection:"column", alignItems: "center",justifyContent:"center",lineHeight:1.2 }}> <p className="abs" >{toTitleCase(session?.firstName + " " + session?.lastName)}</p> <small style={{fontWeight:400,width:"100%",display:"block",textAlign:"start"}}>{session?.role}</small> </div> <ArrowDropDownIcon /> </p> </div> </Button> </Box> <Box sx={{ display: { xs: "flex", md: "none" } }}> <IconButton size="large" aria-label="show more" aria-controls={mobileMenuId} aria-haspopup="true" onClick={handleMobileMenuOpen} color="inherit" > <MoreIcon /> </IconButton> </Box> </Toolbar> </AppBar> {renderMobileMenu} {renderMenu} <Drawer sx={{ width: drawerWidth, flexShrink: 0, "& .MuiDrawer-paper": { width: drawerWidth, boxSizing: "border-box", }, }} variant="persistent" anchor="left" open={open} > <DrawerHeader> <img style={{ height: "60px", width: "80%", margin: "0px 10px",padding: "6px 0px" }} src={"/logo_2.png"} alt="" /> <IconButton onClick={handleDrawerClose}> {theme.direction === "ltr" ? ( <ChevronLeftIcon /> ) : ( <ChevronRightIcon /> )} </IconButton> </DrawerHeader> <Divider /> <List sx={{ pb: 0 }}> <ListItem sx={{ mb: 0, pb: 0, pt: 1 }}> <Typography>User Management</Typography> </ListItem> </List> <List> {panelChildren .filter((item) => item.inNav) .map((item, index) => ( <ListItem key={item.path} className={`${ currentPath === item.path ? "sidenav_active sidebar_element" : "sidebar_element" }`} disablePadding onClick={() => { isMobile && handleDrawerClose(); navigate(item.path); }} > <ListItemButton> <ListItemIcon>{item.icon}</ListItemIcon> <ListItemText primary={toTitleCase(item.path)} /> </ListItemButton> </ListItem> ))} </List> <Divider /> </Drawer> <Main open={open}> <DrawerHeader /> <CustomSeparator location={location?.pathname.split("/")} /> <Outlet /> </Main> </Box> ); }
// import 'package:flutter/material.dart'; // import 'package:get/get.dart'; // import 'package:moto_park/constants/color_constants.dart'; // import 'package:moto_park/pages/Authentication/presentation/controllers/edit_profile_controller.dart'; // import 'package:moto_park/utilities/google_font_text_style.dart'; // // import '../../../../response_model/register_response_model.dart'; // // class DocumentVisible extends GetView<EditProfileController> { // const DocumentVisible({Key? key}) : super(key: key); // // @override // Widget build(BuildContext context) { // double width = MediaQuery.of(context).size.width; // double padding = width * 0.05; // double avatarRadius = width * 0.13; // double textFontSize = width * 0.04; // double labelFontSize = width * 0.04; // double sectionSpacing = width * 0.05; // // return Scaffold( // body: LayoutBuilder( // builder: (context, constraints) { // return Padding( // padding: EdgeInsets.all(padding), // child: Card( // color: Colors.yellow[50], // elevation: 5, // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.circular(15), // ), // child: Padding( // padding: EdgeInsets.all(padding), // child: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Center( // child: Text( // 'User Details', // style: BalooStyles.balooboldTextStyle( // color: blackColor, // size: textFontSize * 1.2 // ), // ), // ), // SizedBox(height: sectionSpacing), // Center( // child: GetBuilder<EditProfileController>( // builder: (controller) { // if (controller.isLoading) { // return const CircularProgressIndicator(); // } // return CircleAvatar( // radius: avatarRadius, // // Display user's profile image if available // backgroundImage: controller.profileImg.isNotEmpty // ? NetworkImage(controller.profileImg) // : null, // child: controller.profileImg.isEmpty // ? Icon(Icons.person, size: avatarRadius) // : null, // ); // }, // ), // ), // SizedBox(height: sectionSpacing), // GetBuilder<EditProfileController>( // builder: (controller) { // if (controller.isLoading) { // return const SizedBox.shrink(); // } // // UserDetails? userDetails = controller.userDetails?.value; // // return Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // TextRow( // label: 'Name:', // value: '${userDetails.firstName ?? ''} ${userDetails.lastName ?? ''}', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // TextRow( // label: 'Email:', // value: userDetails.email ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // TextRow( // label: 'Phone Number:', // value: userDetails.phone ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // TextRow( // label: 'Gender:', // value: userDetails.gender ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // Container( // height: sectionSpacing, // width: double.infinity, // decoration: BoxDecoration( // color: Colors.grey, // borderRadius: BorderRadius.circular(30), // ), // child: Center( // child: Text( // "Emergency Contacts", // style: TextStyle( // fontFamily: 'sans-serif', // fontSize: labelFontSize, // fontWeight: FontWeight.bold, // ), // ), // ), // ), // TextRow( // label: 'Emergency Contact 1:', // value: userDetails.emergencyContact ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // TextRow( // label: 'Emergency Contact 2:', // value: userDetails.emergencyContact2 ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // TextRow( // label: 'Blood Group:', // value: userDetails.bloodGroup ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // TextRow( // label: 'Date of Birth:', // value: userDetails.dateOfBirth ?? '', // labelFontSize: labelFontSize, // valueFontSize: textFontSize, // ), // ], // ); // }, // ), // ], // ), // ), // ), // ); // }, // ), // ); // } // } // // class TextRow extends StatelessWidget { // final String label; // final String value; // final double labelFontSize; // final double valueFontSize; // // const TextRow({ // Key? key, // required this.label, // required this.value, // required this.labelFontSize, // required this.valueFontSize, // }) : super(key: key); // // @override // Widget build(BuildContext context) { // return Padding( // padding: const EdgeInsets.symmetric(vertical: 8.0), // child: Row( // children: [ // Text( // label, // style: TextStyle( // fontSize: labelFontSize, // fontWeight: FontWeight.bold, // ), // ), // const SizedBox(width: 10), // Expanded( // child: Text( // value, // style: TextStyle(fontSize: valueFontSize), // overflow: TextOverflow.ellipsis, // maxLines: 1, // ), // ), // ], // ), // ); // } // } import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:moto_park/constants/color_constants.dart'; import 'package:moto_park/utilities/google_font_text_style.dart'; import '../../../../utilities/helper_widget.dart'; import '../../../Authentication/presentation/controllers/edit_profile_controller.dart'; class DocumentVisible extends StatelessWidget { const DocumentVisible({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final EditProfileController controller = Get.put(EditProfileController()); return Scaffold( body: Padding( padding: EdgeInsets.all(16.0), child: SingleChildScrollView( child: Column( children: [ // Add your existing form fields here GetBuilder<EditProfileController>( builder: (controller) { return Card( color: Colors.yellow[50], elevation: 4, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), ), child: Padding( padding: EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Center( child: CircleAvatar( radius: 50, backgroundImage: NetworkImage("https://randomuser.me/api/portraits/men/22.jpg"), ), ), vGap(20), Row( children: [ Text( 'Name:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.firstNameController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), ], ), vGap(10), Row( children: [ Text( 'Email:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.emailController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), ], ), vGap(10), Row( children: [ Text( 'Phone:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.phoneController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), ], ), vGap(10), Text( 'Address:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), Text( '${controller.addressController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), vGap(10), Row( children: [ Text( 'Date of Birth:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.dobController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), ], ), vGap(10), Row( children: [ Text( 'Blood Group:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.bloodGroupController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), ], ), vGap(10), Row( children: [ Text( 'Emergency Contact 1:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.emergencyContactController.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 14), ), ], ), vGap(10), Row( children: [ Text( 'Emergency Contact 2:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.emergencyContactController2.text}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 14), ), ], ), vGap(10), Row( children: [ Text( 'Gender:', style: BalooStyles.baloomediumTextStyle(color: Color(0xFF808080), size: 18), ), hGap(10), Text( '${controller.dropDownValue}', style: BalooStyles.baloomediumTextStyle(color: blackColor, size: 15), ), ], ), ], ), ), ); }, ), ], ), ), ), ); } }
package com.aliyuncs.aui.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; /** * 课堂成员Entity */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @TableName("class_member") public class ClassMemberEntity implements Serializable { private static final long serialVersionUID = 1L; @TableId(type = IdType.AUTO) private Long id; /** * 课堂Id */ private String classId; /** * 用户Id */ private String userId; /** * 用户名 */ @TableField("user_name") private String userName; @TableField("user_avatar") private String userAvatar; /** * 身份信息。1-学生,2-老师 */ private Integer identity; /** * 状态。1-正常,2-退出, 3-踢出 */ private Integer status; /** * 创建时间 */ @JsonFormat(pattern="yyyy/MM/dd HH:mm:ss",timezone = "GMT+8") private Date createdAt; /** * 修改时间 */ @JsonFormat(pattern="yyyy/MM/dd HH:mm:ss",timezone = "GMT+8") private Date updatedAt; }
import {Injectable} from '@angular/core'; import {Actions, Effect, ofType} from '@ngrx/effects'; import {Action} from '@ngrx/store'; import {Observable} from 'rxjs'; import {catchError, map, mergeMap} from 'rxjs/operators'; import {UserDto} from '../../api/dto/user.dto'; import {UserApiService} from '../../api/user-api.service'; import {convertUserDtoToModel} from '../../api/utils/convert-user-dto-to-model'; import {createCallbackActions, emitErrorActions} from '../store.utils'; import {GetAllUsersAction, GetAllUsersSuccessAction, UsersActionType} from './users.action'; @Injectable() export class UsersEffects { @Effect() public getAll$: Observable<Action> = this.actions$.pipe( ofType<GetAllUsersAction>(UsersActionType.GET_ALL), mergeMap(action => { const {onSuccess, onFailure} = action.payload; return this.userApiService.getAll().pipe( map((dtos: UserDto[]) => dtos.map(dto => convertUserDtoToModel(dto))), mergeMap(users => [new GetAllUsersSuccessAction({users}), ...createCallbackActions(onSuccess, users)]), catchError(error => emitErrorActions(error, onFailure)) ); }) ); constructor(private actions$: Actions, private userApiService: UserApiService) {} }
<?php Block::put('breadcrumb') ?> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="<?= Backend::url('user/users') ?>"><?= __("Users") ?></a></li> <li class="breadcrumb-item active" aria-current="page"><?= e(__($this->pageTitle)) ?></li> </ol> <?php Block::endPut() ?> <?php if ($this->fatalError): ?> <?= $this->formRenderDesign() ?> <?php else: ?> <div class="scoreboard" id="<?= $this->getId('scoreboard') ?>"> <?= $this->makePartial('scoreboard_preview') ?> </div> <?php $canDoGeneralActions = !$formModel->is_guest && !$formModel->is_banned && !$formModel->trashed(); ?> <div class="loading-indicator-container mb-3"> <div class="control-toolbar form-toolbar" data-control="toolbar"> <?= Ui::button("Back", 'user/users')->icon('icon-arrow-left')->outline() ?> <?php if ($canDoGeneralActions): ?> <?php if ($this->user->hasAccess('rainlab.users.impersonate_user')): ?> <div class="toolbar-divider"></div> <?= Ui::ajaxButton("Impersonate", 'onImpersonateUser')->icon('icon-user-secret')->outline() ->confirmMessage("Impersonate this user? You can revert to your original state by logging out.") ?> <?php endif ?> <?php endif ?> <?= Ui::button("Edit", 'user/users/update/'.$formModel->id)->icon('icon-pencil')->outline()->primary() ?> <div class="toolbar-divider"></div> <?= Ui::ajaxButton("Ban", 'onBanUser')->icon('icon-ban')->outline()->danger() ->confirmMessage("Ban this user? It will prevent them from logging in and holding an active session.") ?> <?php if (!$formModel->trashed()): ?> ?> <?= Ui::ajaxButton("Delete", 'onDelete')->icon('icon-delete')->outline()->danger() ->confirmMessage("Are you sure?") ?> <?php endif ?> <?= /** * @event rainlab.user.view.extendPreviewToolbar * Fires when preview user toolbar is rendered. * * Example usage: * * Event::listen('rainlab.user.view.extendPreviewToolbar', function ( * (RainLab\User\Controllers\Users) $controller, * (RainLab\User\Models\User) $record * ) { * return $controller->makePartial('~/path/to/partial'); * }); * */ $this->fireViewEvent('rainlab.user.view.extendPreviewToolbar', [ 'record' => $formModel ]); ?> </div> </div> <?php if ($formModel->is_guest): ?> <?= $this->makePartial('hint_guest') ?> <?php elseif ($formModel->is_banned): ?> <?= $this->makePartial('hint_banned') ?> <?php elseif ($formModel->trashed()): ?> <?= $this->makePartial('hint_trashed') ?> <?php elseif (!$formModel->is_activated): ?> <?= $this->makePartial('hint_activate') ?> <?php endif ?> <?php /** * @event rainlab.user.view.extendPreviewTabs * Provides an opportunity to add tabs to the user preview page in the admin panel. * The event should return an array of `[Tab Name => ~/path/to/partial.php]` * * Example usage: * * Event::listen('rainlab.user.view.extendPreviewTabs', function() { * return [ * "Orders" => '$/acme/shop/partials/_user_orders.php', * ]; * }); * */ $customTabs = array_collapse(Event::fire('rainlab.user.view.extendPreviewTabs')); ?> <div class="control-tabs content-tabs tabs-inset" data-control="tab"> <ul class="nav nav-tabs"> <li class="active"> <a href="#user"> <?= __("User") ?> </a> </li> <li> <a href="#history"> <?= __("History") ?> </a> </li> <?php foreach ($customTabs as $tabName => $tabPartial): ?> <li> <a href="#<?= Str::slug(__($tabName)) ?>"> <?= e(__($tabName)) ?> </a> </li> <?php endforeach ?> </ul> <div class="tab-content"> <div class="tab-pane active"> <div class="row"> <div class="col"> <h4 class="my-3 fw-normal"><?= __("User") ?></h4> <?= $this->formRenderPrimaryTab('User') ?> </div> <div class="col border-start"> <h4 class="my-3 fw-normal"><?= __("Details") ?></h4> <?= $this->formRenderPrimaryTab('Details') ?> </div> </div> </div> <div class="tab-pane"> <h4 class="my-3 fw-normal">Activity Log</h4> <?= $this->relationRender('activity_log') ?> </div> <?php foreach ($customTabs as $tabName => $tabPartial): ?> <div class="tab-pane"> <?= $this->makePartial($tabPartial) ?> </div> <?php endforeach ?> </div> </div> <?php endif ?>
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.operators.resettable; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.memory.MemoryManager; import org.apache.flink.runtime.memory.MemoryManagerBuilder; import org.apache.flink.runtime.operators.testutils.DummyInvokable; import org.apache.flink.runtime.operators.testutils.MutableObjectIteratorWrapper; import org.apache.flink.runtime.testutils.recordutils.RecordSerializer; import org.apache.flink.types.IntValue; import org.apache.flink.types.Record; import org.apache.flink.util.MutableObjectIterator; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; public class SpillingResettableMutableObjectIteratorTest { private static final int NUM_TESTRECORDS = 50000; private static final int MEMORY_CAPACITY = 10 * 1024 * 1024; private IOManager ioman; private MemoryManager memman; private MutableObjectIterator<Record> reader; private final TypeSerializer<Record> serializer = RecordSerializer.get(); @Before public void startup() { // set up IO and memory manager this.memman = MemoryManagerBuilder.newBuilder().setMemorySize(MEMORY_CAPACITY).build(); this.ioman = new IOManagerAsync(); // create test objects final ArrayList<Record> objects = new ArrayList<Record>(NUM_TESTRECORDS); for (int i = 0; i < NUM_TESTRECORDS; ++i) { Record tmp = new Record(new IntValue(i)); objects.add(tmp); } this.reader = new MutableObjectIteratorWrapper(objects.iterator()); } @After public void shutdown() throws Exception { this.ioman.close(); this.ioman = null; if (!this.memman.verifyEmpty()) { Assert.fail( "A memory leak has occurred: Not all memory was properly returned to the memory manager."); } this.memman.shutdown(); this.memman = null; } /** * Tests the resettable iterator with too little memory, so that the data has to be written to * disk. */ @Test public void testResettableIterator() { try { final AbstractInvokable memOwner = new DummyInvokable(); // create the resettable Iterator SpillingResettableMutableObjectIterator<Record> iterator = new SpillingResettableMutableObjectIterator<Record>( this.reader, this.serializer, this.memman, this.ioman, 2, memOwner); // open the iterator iterator.open(); // now test walking through the iterator int count = 0; Record target = new Record(); while ((target = iterator.next(target)) != null) { Assert.assertEquals( "In initial run, element " + count + " does not match expected value!", count++, target.getField(0, IntValue.class).getValue()); } Assert.assertEquals( "Too few elements were deserialzied in initial run!", NUM_TESTRECORDS, count); // test resetting the iterator a few times for (int j = 0; j < 10; ++j) { count = 0; iterator.reset(); target = new Record(); // now we should get the same results while ((target = iterator.next(target)) != null) { Assert.assertEquals( "After reset nr. " + j + 1 + " element " + count + " does not match expected value!", count++, target.getField(0, IntValue.class).getValue()); } Assert.assertEquals( "Too few elements were deserialzied after reset nr. " + j + 1 + "!", NUM_TESTRECORDS, count); } // close the iterator iterator.close(); } catch (Exception ex) { ex.printStackTrace(); Assert.fail("Test encountered an exception."); } } /** * Tests the resettable iterator with enough memory so that all data is kept locally in memory. */ @Test public void testResettableIteratorInMemory() { try { final AbstractInvokable memOwner = new DummyInvokable(); // create the resettable Iterator SpillingResettableMutableObjectIterator<Record> iterator = new SpillingResettableMutableObjectIterator<Record>( this.reader, this.serializer, this.memman, this.ioman, 20, memOwner); // open the iterator iterator.open(); // now test walking through the iterator int count = 0; Record target = new Record(); while ((target = iterator.next(target)) != null) { Assert.assertEquals( "In initial run, element " + count + " does not match expected value!", count++, target.getField(0, IntValue.class).getValue()); } Assert.assertEquals( "Too few elements were deserialzied in initial run!", NUM_TESTRECORDS, count); // test resetting the iterator a few times for (int j = 0; j < 10; ++j) { count = 0; iterator.reset(); target = new Record(); // now we should get the same results while ((target = iterator.next(target)) != null) { Assert.assertEquals( "After reset nr. " + j + 1 + " element " + count + " does not match expected value!", count++, target.getField(0, IntValue.class).getValue()); } Assert.assertEquals( "Too few elements were deserialzied after reset nr. " + j + 1 + "!", NUM_TESTRECORDS, count); } // close the iterator iterator.close(); } catch (Exception ex) { ex.printStackTrace(); Assert.fail("Test encountered an exception."); } } }
package com.primefaces.hibernate.dao; import com.primefaces.hibernate.Idao.ICityDAO; import com.primefaces.hibernate.generic.GenericDaoImpl; import com.primefaces.hibernate.model.Address; import com.primefaces.hibernate.model.City; import com.primefaces.hibernate.model.Country; import com.primefaces.hibernate.util.HibernateUtil; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.apache.log4j.Logger; public class CityDAO extends GenericDaoImpl<City, Short> implements ICityDAO { private static final Logger LOG = Logger.getLogger(CityDAO.class); @Override public void create(Country country, City city) { Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); city.setCountry(country); session.save(city); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("CityDAO - createCity() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } } @Override public City findByName(String name) { List<City> cities = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); cities = session.createQuery("from City c where c.city = :name") .setString("name", name) .list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("CityDAO - findCityByName() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } if(cities.size() > 0) return cities.get(0); return null; } @Override public City findFromAddress(Address address) { City city = null; Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); String hql = "from Address a join fetch a.city where a.addressId = :addressId"; List<Address> addrs = session.createQuery(hql) .setShort("addressId", address.getAddressId()) .list(); if(addrs.size() > 0) { Address addr = addrs.get(0); city = addr.getCity(); } session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("CityDAO - findCityFromAddress() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return city; } @Override public List<City> findOfCountry(Country country) { List<City> cities = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); cities = session.createQuery("from City c where c.country = :country") .setEntity("country", country) .list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("CityDAO - findCityOfCountry() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return cities; } @Override public List<City> list() { List<City> cities = new ArrayList<>(); Session session = HibernateUtil.getSessionFactory().openSession(); try { session.beginTransaction(); cities = session.createQuery("from City c order by c.city").list(); session.getTransaction().commit(); } catch (RuntimeException e) { LOG.error("CityDAO - listCities() failed, " + e.getMessage(), e); } finally { session.flush(); session.close(); } return cities; } }
[![Open in Codespaces](https://classroom.github.com/assets/launch-codespace-f4981d0f882b2a3f0472912d15f9806d57e124e0fc890972558857b51b24a6f9.svg)](https://classroom.github.com/open-in-codespaces?assignment_repo_id=9514048) # Doubly Linked List with Sentinel If you need help running the tests or submitting your code, check out `HELP.md`. ## Instructions Implement a doubly linked list with sentinel. Like an array, a linked list is a simple linear data structure. Several common data types can be implemented using linked lists, like queues, stacks, and associative arrays. A linked list is a collection of data elements called *nodes*. In a *singly linked list* each node holds a value and a link to the next node. In a *doubly linked list* each node also holds a link to the previous node. A *sentinel* is a dummy node that allow us to simplify boundary conditions. In linked list the sentinel is a node that represents `NULL` but has all other attibutes of the other nodes in the list. References to `NULL` are replaced by references to the sentinel. The sentinel lies between the head and the tail. You will write an implementation of a doubly linked list. Implement a Node to hold a value and pointers to the next and previous nodes. Then implement a List which holds references to the first and last node and offers an array-like interface for adding and removing items: * `push_back` (*insert value at back*); * `pop_back` (*remove value at back*); * `push_front` (*insert value at front*); * `pop_front` (*remove value at front*); Also getting the first and last items in the list: * `front` (*gets the value at front*); * `back` (*gets the value at back*); With additional operations to reverse and sort the contents of the list: * `reverse` (*reverses the order of the elements in the list*); * `sort` (*sorts the elements in the list*); To keep your implementation simple, the tests will not cover error conditions. Specifically: `front` or `back` will never be called on an empty list. If you want to know more about linked lists, check [Wikipedia](https://en.wikipedia.org/wiki/Linked_list). ## Source ### Created by - @wolf99 ### Contributed to by - @patricksjackson - @QLaille - @ryanplusplus - @siebenschlaefer ### Modified by - @eloyhz ### Based on Classic computer science topic
import { createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; import { convertRawtoString } from "../../utils/convertRawtoString"; import { timeSince } from "../../utils/timeSince"; const API_KEY = process.env.REACT_APP_YOUTUBE_DATA_API_KEY; export const getVideoDetails = createAsyncThunk( "youtube/App/videoDetails", async (id) => { const { data: { items }, } = await axios.get( `https://youtube.googleapis.com/youtube/v3/videos?key=${API_KEY}&part=snippet,statistics&type=video&id=${id}` ); const parsedData = parseData(items[0]); // console.log(parsedData); return parsedData; } ); const parseData = async (item) => { const channelResponse = await axios.get( `https://youtube.googleapis.com/youtube/v3/channels?part=snippet,statistics&id=${item.snippet.channelId}&key=${API_KEY}` ); const snippet = item.snippet; const id = item.id; const statistics = item.statistics; const channelImage = channelResponse.data.items[0].snippet.thumbnails.default.url; const subscriberCount = channelResponse.data.items[0].statistics.subscriberCount; return { videoId: id, videoTitle: snippet.title, videoDescription: snippet.description, videoViews: convertRawtoString(statistics.viewCount), videoLikes: convertRawtoString(statistics.likeCount), videoAge: timeSince(new Date(snippet.publishedAt)), channelInfo: { id: snippet.channelId, image: channelImage, name: snippet.channelTitle, subscribers: convertRawtoString(subscriberCount, true), }, }; };
const DEFAULT_GATEWAY = "https://arweave.net/{fileId}"; /** * Resolves the scheme of a given Arweave URI and returns the corresponding URL. * @param options - The options object containing the Arweave URI * @returns The resolved URL * @throws Error if the URI scheme is invalid. * @example * ```ts * import { resolveArweaveScheme } from "thirdweb/storage"; * const url = resolveArweaveScheme({ uri: "ar://<fileId>" }); * ``` */ export function resolveArweaveScheme(options) { if (options.uri.startsWith("ar://")) { const fileId = options.uri.replace("ar://", ""); if (options.gatewayUrl) { const separator = options.gatewayUrl.endsWith("/") ? "" : "/"; return `${options.gatewayUrl}${separator}${fileId}`; } return DEFAULT_GATEWAY.replace("{fileId}", fileId); } if (options.uri.startsWith("http")) { return options.uri; } throw new Error(`Invalid URI scheme, expected "ar://" or "http(s)://"`); } //# sourceMappingURL=arweave.js.map
<?php declare(strict_types=1); namespace App\Jobs; use App\Data\Web3\CollectionActivity; use App\Models\Collection; use App\Support\Queues; use DateTime; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Collection as LaravelCollection; use Illuminate\Support\Facades\DB; use RuntimeException; class SyncBurnedNfts implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * @param LaravelCollection<int, CollectionActivity> $activity */ public function __construct( public Collection $collection, public LaravelCollection $activity, ) { $this->onQueue(Queues::SCHEDULED_NFTS); } /** * Execute the job. */ public function handle(): void { if (! config('dashbrd.features.activities') || ! $this->collection->indexesActivities()) { return; } $nfts = $this->collection ->nfts() ->whereIn('token_number', $this->activity->map->tokenId) ->get(); if ($nfts->contains->isBurned()) { report(new RuntimeException( 'There are some NFTs that have been previously burned, yet we got another LABEL_BURN event for them. IDs: '.$nfts->filter->isBurned()->pluck('id')->join(',') )); } $activity = $this->activity->unique('tokenId')->keyBy('tokenId'); DB::transaction(function () use ($nfts, $activity) { $nfts->each(fn ($nft) => $nft->update([ 'burned_at' => $activity[$nft->token_number]->timestamp, ])); }, attempts: 3); } public function retryUntil(): DateTime { // This job only runs database queries, so we don't expect it to fail... However, let's give it some time to run, so we are covered. return now()->addHours(1); } }
Feature: Approve New Faculty Member Accounts Background: Given The following research areas have been created: | title | summary | detailed_overview | | Networks2 | A test networks research area | This research area is made to tests faculty, and it represent a possible networks area | Given There are the following accounts created: | first_name | last_name | email | password | password_confirmation | account_type | research_area | | Jack | Stockley | jnstockley@uiowa.edu | Password123 | Password123 | Faculty | Networks2 | | Kaitlynn | Fuller | kaitfuller@uiowa.edu | password | password | Faculty | Networks2 | | Caleb | Marx | cmarx1@uiowa.edu | Hawkeyes | Hawkeyes | Student | | | Jonah | Terwilleger | jdterwilleger@uiowa.edu | iL0V3iowA | iL0V3iowA | Department Chair | | Scenario: View faculties needing approval without being signed in Given I am on the approve faculty accounts page Then I should be redirected to the login page Scenario: View faculties needing approval without being signed in as a Departmental Chair user Given I am signed with the email "jnstockley@uiowa.edu" and the password "Password123" And I am on the approve faculty accounts page Then I should see a warning message saying "You do not have permission to perform that action" Scenario: View faculties needing approval signed in as a Departmental Chair user Given I am signed with the email "jdterwilleger@uiowa.edu" and the password "iL0V3iowA" And I am on the approve faculty accounts page Then I should see the following faculty accounts: | first_name | last_name | email | password | account_type | research_area | | Jack | Stockley | jnstockley@uiowa.edu | Password123 | Faculty | Networks2 | | Kaitlynn | Fuller | kaitfuller@uiowa.edu | password | Faculty | Networks2 | Scenario: Approve Faculty Member needing approval Given I am signed with the email "jdterwilleger@uiowa.edu" and the password "iL0V3iowA" And I am on the approve faculty accounts page And I should see the following faculty accounts: | first_name | last_name | email | password | account_type | research_area | | Jack | Stockley | jnstockley@uiowa.edu | Password123 | Faculty | Networks2 | | Kaitlynn | Fuller | kaitfuller@uiowa.edu | password | Faculty | Networks2 | When I approve the following faculty account: | first_name | last_name | email | password | account_type | research_area | | Jack | Stockley | jnstockley@uiowa.edu | Password123 | Faculty | Networks2 | Then I should no longer see the following account: | first_name | last_name | email | password | account_type | research_area | | Jack | Stockley | jnstockley@uiowa.edu | Password123 | Faculty | Networks2 |
import React from 'react'; import { TextInput, StyleSheet, Dimensions, View, Image } from 'react-native'; import { SafeAreaView } from 'react-navigation'; import { MaterialCommunityIcons } from '@expo/vector-icons' import WriteHeader from '../components/WriteHeader' import uuid from 'uuid/v1'; import * as ImagePicker from 'expo-image-picker'; const { width, height } = Dimensions.get('window'); export default class WriteScreen extends React.Component { static navigationOptions = { tabBarIcon: ({ tintColor }) => ( <MaterialCommunityIcons name='lead-pencil' size={25} style={{ color: tintColor }} /> ), tabBarOnPress: ({ navigation }) => { navigation.navigate('Write'); } } state = { inputtitle :'', inputcontent : '', imageUrl: '', } _showTitle = (value) => { // console.log(value) this.setState({inputtitle:value}) } _showContent = (value) =>{ // console.log(value) this.setState({inputcontent:value}) } _saveText = () =>{ if(this.state.inputtitle !== ''){ const id = uuid() const date = this._gettoday() const newpost = { id : id, title: this.state.inputtitle, content: this.state.inputcontent, date: date, imageUrl: this.state.imageUrl, } // console.log(newPost) this.setState( { inputtitle: '', inputcontent: '', imageUrl: '', } ) // console.log("***********************") // console.log(newpost) // console.log("**********************") this.props.navigation.navigate('MainScreen',{myparam :newpost}) // console.log(newPost) } else{ this.props.navigation.navigate('MainScreen') // console.log("이건 else") } } _gettoday = () => { tyear = (new Date().getFullYear()).toString() tmonth = (new Date().getMonth() + 1).toString() tday = (new Date().getDate()).toString() if (tmonth < 10) { tmonth = '0' + tmonth } if (tday < 10) { tday = '0' + tday } return (tyear + "-" + tmonth + "-" + tday) // console.log(tyear + "-" + tmonth + "-" + tday) } _selectImage = async() =>{ //안드로이드의 경우 이부분을 아예 지우고 작성해주셔야 합니다 // if (Constants.platform.ios) { // const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL); // if (status !== 'granted') { // alert('Sorry, we need camera roll permissions to make this work!'); // } // } let result = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, }); this.setState({ imageUrl: result.uri }); } render() { return ( <SafeAreaView style={styles.container}> <View style={styles.contentContainer}> <WriteHeader saveProps={this._saveText} selectImage = {this._selectImage}/> <TextInput value = {this.state.inputtitle} onChangeText={this._showTitle} placeholder="제목을 입력하세요" style={styles.title} returnKeyType="done" /> {this.state.imageUrl ? <Image source={{ uri: this.state.imageUrl }} style={{ width: 100, height: 100 }} /> : null} <TextInput value={this.state.inputcontent} onChangeText={this._showContent} placeholder="내용을 입력하세요" multiline={true} style={styles.content} returnKeyType="done" /> </View> </SafeAreaView> ) } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', paddingTop:50, }, contentContainer: { width: width - 60, }, title: { marginVertical: 30, fontSize: 30, paddingBottom: 12, borderBottomWidth: 2, }, content: { fontSize: 20, }, });
package study; import edu.uci.ics.crawler4j.crawler.Page; import edu.uci.ics.crawler4j.crawler.WebCrawler; import edu.uci.ics.crawler4j.parser.HtmlParseData; import edu.uci.ics.crawler4j.url.WebURL; import java.util.regex.Pattern; import static java.lang.System.out; public class SampleCrawler extends WebCrawler { private static final Pattern IMAGE_EXTENSIONS = Pattern.compile(".*\\.(bmp|gif|jpg|png)$"); @Override public boolean shouldVisit(Page referringPage, WebURL url) { // 페이지 방문여 String href = url.getURL().toLowerCase(); if (IMAGE_EXTENSIONS.matcher(href).matches()) { // 일치하는 이미지가 있으 return false; } return href.startsWith("https://en.wikipedia.org/wiki/"); // 해당하는 URL으로 시작한다. } @Override public void visit(Page page) { // 페이지 처리 방법, 방문한 페이지가 전달된다. int docid = page.getWebURL().getDocid(); String url = page.getWebURL().getURL(); if (page.getParseData() instanceof HtmlParseData) { HtmlParseData htmlParseData = (HtmlParseData) page.getParseData(); String text = htmlParseData.getText(); if (text.contains("shipping route")) { out.println("\nURL: " + url); out.println("Text: " + text); out.println("Text length: " + text.length()); } } } }
package com.example.apispringboot.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/api/pessoas/listar","/h2-console/**") .permitAll() .anyRequest() .authenticated() .and().httpBasic() .and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().headers().frameOptions().sameOrigin(); } @Bean public PasswordEncoder passwordEncoder() { return NoOpPasswordEncoder.getInstance(); } }
<template> <div> <TransitionRoot as="template" :show="sidebarOpen"> <Dialog as="div" class="relative z-40 md:hidden" @close="sidebarOpen = false"> <TransitionChild as="template" enter="transition-opacity ease-linear duration-300" enter-from="opacity-0" enter-to="opacity-100" leave="transition-opacity ease-linear duration-300" leave-from="opacity-100" leave-to="opacity-0" > <div class="fixed inset-0 bg-gray-600 bg-opacity-75" /> </TransitionChild> <div class="fixed inset-0 flex z-40"> <TransitionChild as="template" enter="transition ease-in-out duration-300 transform" enter-from="-translate-x-full" enter-to="translate-x-0" leave="transition ease-in-out duration-300 transform" leave-from="translate-x-0" leave-to="-translate-x-full" > <DialogPanel class="relative flex-1 flex flex-col max-w-xs w-full bg-primary-700"> <TransitionChild as="template" enter="ease-in-out duration-300" enter-from="opacity-0" enter-to="opacity-100" leave="ease-in-out duration-300" leave-from="opacity-100" leave-to="opacity-0" > <div class="absolute top-0 right-0 -mr-12 pt-2"> <button type="button" class="ml-1 flex items-center justify-center h-10 w-10 rounded-full focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white" @click="sidebarOpen = false" > <span class="sr-only">Close sidebar</span> <XMarkIcon class="h-6 w-6 text-white" aria-hidden="true" /> </button> </div> </TransitionChild> <div class="flex-1 h-0 pt-5 pb-4 overflow-y-auto"> <div class="flex-shrink-0 flex items-center px-4"> <img class="rounded-full mx-auto h-20 w-auto w-auto" src="@/assets/img/onfly.svg" alt="Workfow" /> </div> <nav class="mt-5 px-2 space-y-1"> <router-link v-for="item in navigation" :key="item.name" :to="item.href" :class="[ 'text-gray-300 hover:bg-gray-700 hover:text-white group flex items-center px-2 py-2 text-sm font-medium rounded-md' ]" > <component :is="item.icon" :class="[ item.current ? 'text-gray-300' : 'text-gray-400 group-hover:text-gray-300', 'mr-3 flex-shrink-0 h-6 w-6' ]" aria-hidden="true" /> {{ item.name }} </router-link> </nav> </div> <div class="flex-shrink-0 flex bg-primary-800 p-4"> <a href="#" class="flex-shrink-0 group block"> <div class="flex flex-col"> <div class="flex"> <div> <img class="inline-block h-10 w-10 rounded-full" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="" /> </div> <div class="ml-3"> <p class="text-base font-medium text-white">{{ userStore?.user?.name }}</p> </div> </div> <div class="pt-2"> <v-button @click="logout"> Sair </v-button> </div> </div> </a> </div> </DialogPanel> </TransitionChild> <div class="flex-shrink-0 w-14"></div> </div> </Dialog> </TransitionRoot> <div class="hidden md:flex md:w-64 md:flex-col md:fixed md:inset-y-0"> <div class="flex-1 flex flex-col min-h-0 bg-primary-700"> <div class="flex-1 flex flex-col pt-5 pb-4 overflow-y-auto"> <div class="flex items-center flex-shrink-0 px-4"> <img class="rounded-full mx-auto h-20 w-auto w-auto" src="@/assets/img/onfly.svg" alt="Workfow" /> </div> <nav class="mt-5 flex-1 px-2 space-y-1"> <router-link v-for="item in navigation" :key="item.name" :to="item.href" :class="[ 'text-gray-300 hover:bg-gray-700 hover:text-white group flex items-center px-2 py-2 text-sm font-medium rounded-md' ]" > <component :is="item.icon" :class="[ item.current ? 'text-gray-300' : 'text-gray-400 group-hover:text-gray-300', 'mr-3 flex-shrink-0 h-6 w-6' ]" aria-hidden="true" /> {{ item.name }} </router-link> </nav> </div> <div class="flex-shrink-0 flex bg-primary-800 p-4"> <a href="#" class="flex-shrink-0 w-full group block"> <div class="flex flex-row justify-between"> <div> <img class="inline-block h-9 w-9 rounded-full" src="https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=2&w=256&h=256&q=80" alt="" /> </div> <div class="ml-3"> <p class="text-sm font-medium text-white">{{ userStore?.user?.name }}</p> </div> <div> <v-button @click="logout"> Sair </v-button> </div> </div> </a> </div> </div> </div> <div class="md:pl-64 flex flex-col flex-1"> <div class="sticky top-0 z-10 md:hidden pl-1 pt-1 sm:pl-3 sm:pt-3 bg-primary-700"> <button type="button" class="-ml-0.5 -mt-0.5 h-12 w-12 inline-flex items-center justify-center rounded-md text-gray-500 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-indigo-500" @click="sidebarOpen = true" > <span class="sr-only">Open sidebar</span> <Bars4Icon class="h-6 w-6 text-gray-100" aria-hidden="true" /> </button> </div> <main class="bg-gray-100 h-screen min-h-full"> <div class="py-6"> <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"></div> <div class="max-w-7xl mx-auto px-4 sm:px-6 md:px-8"> <router-view /> </div> </div> </main> </div> </div> </template> <script setup> import { ref, computed } from 'vue' import { Dialog, DialogPanel, TransitionChild, TransitionRoot } from '@headlessui/vue' import { WalletIcon, Bars4Icon, XMarkIcon, ChartBarIcon } from '@heroicons/vue/24/outline' import useAuth from '../composables/useAuth' import { useUserStore } from '../store/useUserStore' const userStore = useUserStore() const { logout } = useAuth() const navigation = [ { name: 'Home', href: { name: 'home' }, icon: ChartBarIcon, current: true }, { name: 'Despesas', href: { name: 'expense.index' }, icon: WalletIcon, current: false } ] const sidebarOpen = ref(false) </script>
MODULE MPTest; (********************************************************) (* *) (* Test of the "maintenance page" facility *) (* *) (* Programmer: P. Moylan *) (* Last edited: 14 February 1994 *) (* Status: Working *) (* Bugs: *) (* None known at present *) (* Shortcomings: *) (* 1. (Fixed) *) (* 2. Mapping the same window to several *) (* different groups is almost, but not *) (* quite, supported. I think that the *) (* only enhancement needed to support this *) (* is a better way to decide whether to *) (* hide a newly introduced window. *) (* 3. Need to look into whether the order of *) (* Unhide operations is satisfactory. *) (* *) (********************************************************) FROM TaskControl IMPORT (* proc *) CreateTask; FROM Timer IMPORT (* proc *) Sleep; FROM Semaphores IMPORT (* type *) Semaphore, (* proc *) CreateSemaphore, Wait; FROM Keyboard IMPORT (* proc *) HotKey; IMPORT Floppy; (* for the sake of displaying an extra maintenance page *) FROM Windows IMPORT (* type *) Window, Colour, FrameType, DividerType, (* proc *) OpenWindow, ChangeScrollingRegion, CloseWindow, PressAnyKey, WriteChar, WriteString, WriteLn, ShiftWindowRel, ReadChar, ReadCharWithoutEcho; FROM MaintenancePages IMPORT (* type *) MaintenancePage, (* proc *) CreateMaintenancePage, Associate; FROM UserInterface IMPORT (* type *) UIWindow, Capability, CapabilitySet, (* proc *) AllowMouseControl; FROM RandCard IMPORT (* proc *) RandCardinal; (************************************************************************) VAR page1, page2: MaintenancePage; (************************************************************************) PROCEDURE Task1; VAR w1: Window; dummy: UIWindow; BEGIN OpenWindow (w1, blue, cyan, 6, 12, 8, 34, simpleframe, nodivider); Associate (w1, page1); dummy := AllowMouseControl (w1, "Task 1", CapabilitySet {wshow, whide, wmove}); LOOP WriteString (w1, "Message from Task 1 ... "); Sleep (400); END (*LOOP*); PressAnyKey (w1); CloseWindow (w1); END Task1; (************************************************************************) PROCEDURE Task2; VAR w2: Window; dummy: UIWindow; BEGIN OpenWindow (w2, white, magenta, 12, 22, 20, 63, doubleframe, nodivider); Associate (w2, page2); dummy := AllowMouseControl (w2, "Task 2", CapabilitySet {wshow, whide, wmove}); LOOP WriteString (w2, "This is output from Task 2 on Page 2 ... "); Sleep (600); END (*LOOP*); PressAnyKey (w2); CloseWindow (w2); END Task2; (************************************************************************) PROCEDURE Task3; VAR w1: Window; dummy: UIWindow; BEGIN OpenWindow (w1, black, green, 10, 20, 50, 78, doubleframe, nodivider); Associate (w1, page1); dummy := AllowMouseControl (w1, "Task 3", CapabilitySet {wshow, whide, wmove}); LOOP WriteString (w1, "Task 3 also uses page 1 ... "); Sleep (200); END (*LOOP*); PressAnyKey (w1); CloseWindow (w1); END Task3; (************************************************************************) PROCEDURE Random(): INTEGER; (* Returns a small unsigned random number. *) BEGIN RETURN INTEGER (RandCardinal() MOD 3) - 1; END Random; (************************************************************************) PROCEDURE Task4; VAR w1: Window; count: CARDINAL; flip: BOOLEAN; BEGIN OpenWindow (w1, brown, black, 3, 6, 60, 66, simpleframe, nodivider); Associate (w1, page1); count := 0; flip := FALSE; LOOP INC (count); IF count >= 5 THEN ShiftWindowRel (w1, Random(), Random()); count := 0; END (*IF*); flip := NOT flip; IF flip THEN WriteString (w1, "/\/\/") ELSE WriteString (w1, "\/\/\") END (*IF*); Sleep (400); END (*LOOP*); PressAnyKey (w1); CloseWindow (w1); END Task4; (************************************************************************) PROCEDURE InputTask1; VAR w1: Window; dummy: UIWindow; ch: CHAR; BEGIN OpenWindow (w1, black, white, 14, 20, 3, 30, doubleframe, nodivider); Associate (w1, page1); dummy := AllowMouseControl (w1, "Input Task 1", CapabilitySet {wshow, whide, wmove}); LOOP WriteLn (w1); WriteString (w1, "Press any key"); ReadCharWithoutEcho (w1, ch); WriteLn (w1); WriteString (w1, "The key you pressed was "); WriteChar (w1, ch); END (*LOOP*); PressAnyKey (w1); CloseWindow (w1); END InputTask1; (************************************************************************) PROCEDURE InputTask2; VAR w1: Window; dummy: UIWindow; ch: CHAR; BEGIN OpenWindow (w1, magenta, black, 4, 9, 40, 70,simpleframe,simpledivider); Associate (w1, page1); dummy := AllowMouseControl (w1, "Input Task 2", CapabilitySet {wshow, whide, wmove}); WriteString (w1, "You can type into this window"); ChangeScrollingRegion (w1, 3, 4); LOOP ReadChar (w1, ch); END (*LOOP*); PressAnyKey (w1); CloseWindow (w1); END InputTask2; (************************************************************************) PROCEDURE RunTheTest; CONST Esc = CHR(1BH); VAR w0, header1, header2: Window; closedown: Semaphore; BEGIN CreateSemaphore (closedown, 0); HotKey (FALSE, Esc, closedown); OpenWindow (w0, yellow, red, 8, 13, 20, 59, simpleframe, nodivider); WriteString (w0, "TEST OF THE MAINTENANCE PAGE FACILITY"); WriteLn (w0); WriteString (w0, "Type ^P to toggle maintenance function"); WriteLn (w0); WriteString (w0, " Then F6 to cycle through the pages"); WriteLn (w0); WriteString (w0, " Esc to exit program"); CreateMaintenancePage (page1); OpenWindow (header1, white, black, 1, 3, 30, 49, doubleframe, nodivider); Associate (header1, page1); WriteString (header1, "MAINTENANCE PAGE 1"); CreateMaintenancePage (page2); OpenWindow (header2, white, black, 1, 3, 30, 49, doubleframe, nodivider); Associate (header2, page2); WriteString (header2, "MAINTENANCE PAGE 2"); CreateTask (Task1, 2, "Task 1"); CreateTask (Task2, 2, "Task 2"); CreateTask (Task3, 2, "Task 3"); CreateTask (Task4, 2, "Task 4"); CreateTask (InputTask1, 2, "Input Task 1"); CreateTask (InputTask2, 2, "Input Task 2"); Wait (closedown); END RunTheTest; (************************************************************************) (* MAIN PROGRAM *) (************************************************************************) BEGIN RunTheTest; END MPTest. 
package simulator.launcher; import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import simulator.control.Controller; import simulator.factories.*; import simulator.model.DequeuingStrategy; import simulator.model.Event; import simulator.model.LightSwitchingStrategy; import simulator.model.TrafficSimulator; import simulator.view.MainWindow; import simulator.model.Event; import javax.swing.*; public class Main { private final static Integer _timeLimitDefaultValue = 10; private static String _inFile = null; private static String _outFile = null; private static Factory<Event> _eventsFactory = null; private static int simulationTicks; private static boolean enableGUI = true; private static boolean loadEvents = false; private static void parseArgs(String[] args) { // define the valid command line options // Options cmdLineOptions = buildOptions(); // parse the command line as provided in args // CommandLineParser parser = new DefaultParser(); try { CommandLine line = parser.parse(cmdLineOptions, args); parseHelpOption(line, cmdLineOptions); parseInFileOption(line); parseOutFileOption(line); parseTicksOption(line); parseModeOption(line); // if there are some remaining arguments, then something wrong is // provided in the command line! // String[] remaining = line.getArgs(); if (remaining.length > 0) { String error = "Illegal arguments:"; for (String o : remaining) error += (" " + o); throw new ParseException(error); } } catch (ParseException e) { System.err.println(e.getLocalizedMessage()); System.exit(1); } } private static Options buildOptions() { Options cmdLineOptions = new Options(); cmdLineOptions.addOption(Option.builder("i").longOpt("input").hasArg().desc("Events input file").build()); cmdLineOptions.addOption( Option.builder("o").longOpt("output").hasArg().desc("Output file, where reports are written.").build()); cmdLineOptions.addOption(Option.builder("h").longOpt("help").desc("Print this message").build()); cmdLineOptions.addOption(Option.builder("t").longOpt("ticks").hasArg().desc("Ticks to the simulator's main loop" + "default value is 10).").build()); cmdLineOptions.addOption(Option.builder("m").longOpt("mode").hasArg().desc("Type of simulation").build()); return cmdLineOptions; } private static void parseHelpOption(CommandLine line, Options cmdLineOptions) { if (line.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(Main.class.getCanonicalName(), cmdLineOptions, true); System.exit(0); } } private static void parseInFileOption(CommandLine line) throws ParseException { if (line.hasOption("i")) { Main._inFile = line.getOptionValue("i"); Main.loadEvents = true; } } private static void parseOutFileOption(CommandLine line) throws ParseException { _outFile = line.getOptionValue("o"); } private static void parseTicksOption(CommandLine line) throws ParseException { if (line.hasOption("t")) { Main.simulationTicks = Integer.parseInt(line.getOptionValue("t")); } else { Main.simulationTicks = Main._timeLimitDefaultValue; } } private static void parseModeOption(CommandLine line) throws ParseException { if (line.hasOption("m") && line.getOptionValue("m").equals("console")) { // Console mode Main.enableGUI = false; } else if (line.hasOption("m") && !line.getOptionValue("m").equals("gui")) { // option -m used with invalid value throw new ParseException("Unkown mode type"); } else { // GUI Mode DEFAULT if (line.hasOption("i")) { // load events into the sim Main.loadEvents = true; } } } private static void initFactories() { List<Builder<LightSwitchingStrategy>> lsbs = new ArrayList<>(); lsbs.add( new RoundRobinStrategyBuilder()); lsbs.add( new MostCrowdedStrategyBuilder()); Factory<LightSwitchingStrategy> lssFactory = new BuilderBasedFactory<>(lsbs); List<Builder<DequeuingStrategy>> dqbs = new ArrayList<>(); dqbs.add( new MoveFirstStrategyBuilder()); dqbs.add( new MoveAllStrategyBuilder()); Factory<DequeuingStrategy> dqsFactory = new BuilderBasedFactory<>(dqbs); List<Builder<Event>> ebs = new ArrayList<>(); ebs.add( new NewJunctionEventBuilder(lssFactory, dqsFactory)); ebs.add( new NewCityRoadEventBuilder()); ebs.add( new NewInterCityRoadEventBuilder()); ebs.add( new NewVehicleEventBuilder()); ebs.add( new SetWeatherEventBuilder()); ebs.add( new SetContClassEventBuilder()); Main._eventsFactory = new BuilderBasedFactory<>(ebs); } private static void startBatchMode() throws IOException { // TODO complete this method to start the simulation TrafficSimulator sim = new TrafficSimulator(); Controller controller = new Controller(sim, Main._eventsFactory); InputStream is = new FileInputStream(Main._inFile); controller.loadEvents(is); is.close(); // close input stream // Create output stream OutputStream out; if (Main._outFile == null) { out = System.out; } else { out = new FileOutputStream(Main._outFile); } controller.run(Main.simulationTicks, out); // run simulation out.close(); // close output stream } private static void startGUIMode() { TrafficSimulator sim = new TrafficSimulator(); Controller ctrl = new Controller(sim, Main._eventsFactory); SwingUtilities.invokeLater(() -> new MainWindow(ctrl)); } private static void start(String[] args) throws IOException { initFactories(); parseArgs(args); if (Main.enableGUI) { startGUIMode(); } else { startBatchMode(); } } // example command lines: // // -i resources/examples/ex1.json // -i resources/examples/ex1.json -t 300 // -i resources/examples/ex1.json -o resources/tmp/ex1.out.json // --help public static void main(String[] args) { try { start(args); } catch (Exception e) { e.printStackTrace(); } } }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' EXPOsan: Exposition of sanitation and resource recovery systems This module is developed by: Yalin Li <mailto.yalin.li@gmail.com> Hannah Lohman <hlohman94@gmail.com> This module is under the University of Illinois/NCSA Open Source License. Please refer to https://github.com/QSD-Group/EXPOsan/blob/main/LICENSE.txt for license details. ''' import os, qsdsan as qs from qsdsan import ImpactItem, StreamImpactItem from exposan.utils import ( get_decay_k, get_generic_scaled_capital, get_generic_tanker_truck_fee as get_tanker_truck_fee, ) # Module-wise setting on whether to allow resource recovery INCLUDE_RESOURCE_RECOVERY = False # Check if has access to the private repository from qsdsan.utils import data_path as qs_data_path if not os.path.isdir(os.path.join(qs_data_path, 'sanunit_data/ng')): raise ModuleNotFoundError( 'Files associated with the NEWgenerator system (under non-disclosure agreement) ' 'cannot be found, ' 'please set path to use the QSDsan-private repository if you have access.' ) ng_path = os.path.dirname(__file__) data_path = os.path.join(ng_path, 'data') results_path = os.path.join(ng_path, 'results') # To save simulation data if not os.path.isdir(results_path): os.mkdir(results_path) # %% # Unit parameters # Number of people served by the one NEWgenerator100 default_ppl = 100 discount_rate = 0.05 # Time take for full degradation, [yr] tau_deg = 2 # Log reduction at full degradation log_deg = 3 max_CH4_emission = 0.25 emptying_fee = 0.15 # Nutrient loss during application app_loss = dict.fromkeys(('NH3', 'NonNH3', 'P', 'K', 'Mg', 'Ca'), 0.02) app_loss['NH3'] = 0.05 # Energetic content of the biogas biogas_energy = 803 # kJ/mol CH4 LPG_energy = 50 # MJ/kg get_biogas_factor = lambda: biogas_energy/cmps.CH4.MW/LPG_energy # Prices and GWP CFs # Recycled nutrients are sold at a lower price than commercial fertilizers price_factor = 0.25 # Should be changed based on country price_ratio = 1 EcosystemQuality_factor = 29320 * (2.8e-09+7.65e-14) # (pt/species.yr) * (species.yr/kgCO2eq) HumanHealth_factor = 436000 * 9.28e-07 # (pt/DALY) * (DALY/kgCO2eq) def update_resource_recovery_settings(): global INCLUDE_RESOURCE_RECOVERY global price_dct, GWP_dct, H_Ecosystems_dct, H_Health_dct, H_Resources_dct RR_factor = int(bool(INCLUDE_RESOURCE_RECOVERY)) price_dct = { 'Electricity': 0.13, 'N': 1.507*price_factor*RR_factor, 'P': 3.983*price_factor*RR_factor, 'K': 1.333*price_factor*RR_factor, 'conc_NH3': 1.333*(14/17)*price_factor*RR_factor, 'biogas': 0, 'GAC': 1.1*price_ratio, 'zeolite': 0.23*price_ratio, 'NaCl': 0.2758*price_ratio, 'NaCl1': 0.2758*price_ratio, 'NaOH': 0.16*price_ratio, 'LPG': 1.3916, # USD/kg, 0.710 USD/L global average, 0.51 kg = 1 L 'wages': 3.64, } GWP_dct = { 'Electricity': 0.69, 'CH4': 34, 'N2O': 298, # # Below are for comparison with old NEWgen codes # 'CH4': 28, # 'N2O': 265, 'N': -5.4*RR_factor, 'P': -4.9*RR_factor, 'K': -1.5*RR_factor, 'conc_NH3': -5.4*(14/17)*RR_factor, 'biogas': 0, 'GAC': 8.388648277, 'zeolite': 5.175, 'NaCl': 0.266695553, 'NaOH': 1.228848922, 'LPG': 0.714219323022122, # 2.93, 3.05 Bwaise } H_Ecosystems_dct = { 'Electricity': 0.002456338, 'CH4': 34 * EcosystemQuality_factor, 'N2O': 298 * EcosystemQuality_factor, 'N': -0.0461961*RR_factor, 'P': -0.093269908*RR_factor, 'K': -0.01895794*RR_factor, 'conc_NH3': -0.0461961*(14/17)*RR_factor, 'biogas': 0, 'GAC': 0.000437915, 'zeolite': 0.020161669, 'NaCl': 0.001166777, 'NaOH': 0.005304792, 'LPG': 0.003610414, } H_Health_dct = { 'Electricity': 0.040824307, 'CH4': 34 * HumanHealth_factor, 'N2O': 298 * HumanHealth_factor, 'N': -0.637826734*RR_factor, 'P': -1.774294425*RR_factor, 'K': -0.116067637*RR_factor, 'conc_NH3': -0.637826734*(14/17)*RR_factor, 'biogas': 0, 'GAC': 0.003448424, 'zeolite': 0.36462721, 'NaCl': 0.020900452, 'NaOH': 0.092927677, 'LPG': 0.044654087, } H_Resources_dct = { 'Electricity': 0.027825633, 'CH4': 0, # no GWP to Resource Depletion pathway 'N2O': 0, # no GWP to Resource Depletion pathway 'N': -0.259196888*RR_factor, 'P': -1.084191599*RR_factor, 'K': -0.054033438*RR_factor, 'conc_NH3': -0.259196888*(14/17)*RR_factor, 'biogas': 0, 'GAC': 0.002986373, 'zeolite': 0.224590444, 'NaCl': 0.013404934, 'NaOH': 0.052849392, 'LPG': 0.178274445, } return price_dct, GWP_dct, H_Ecosystems_dct, H_Health_dct, H_Resources_dct update_resource_recovery_settings() # %% # Load components and systems from . import _components from ._components import * _components_loaded = False def _load_components(reload=False): global components, _components_loaded if not _components_loaded or reload: components = create_components() qs.set_thermo(components) _components_loaded = True _impact_item_loaded = False def _load_lca_data(reload=False): ''' Load impact indicator and impact item data. Parameters ---------- reload : bool Whether to force reload LCA data. ''' global _impact_item_loaded if not _impact_item_loaded or reload: indicator_path = os.path.join(data_path, 'impact_indicators.csv') qs.ImpactIndicator.load_from_file(indicator_path) item_path = os.path.join(data_path, 'impact_items.xlsx') qs.ImpactItem.load_from_file(item_path) price_dct, GWP_dct, H_Ecosystems_dct, H_Health_dct, H_Resources_dct = update_resource_recovery_settings() # Impacts associated with streams and electricity def create_stream_impact_item(item_ID, dct_key=''): dct_key = dct_key or item_ID.rsplit('_item')[0] # `rstrip` will change "struvite_item" to "struv" StreamImpactItem(ID=item_ID, GWP=GWP_dct[dct_key], H_Ecosystems=H_Ecosystems_dct[dct_key], H_Health=H_Health_dct[dct_key], H_Resources=H_Resources_dct[dct_key]) create_stream_impact_item(item_ID='CH4_item') create_stream_impact_item(item_ID='N2O_item') create_stream_impact_item(item_ID='N_item') create_stream_impact_item(item_ID='P_item') create_stream_impact_item(item_ID='K_item') create_stream_impact_item(item_ID='conc_NH3_item') create_stream_impact_item(item_ID='biogas_item') create_stream_impact_item(item_ID='GAC_item') create_stream_impact_item(item_ID='zeolite_item') create_stream_impact_item(item_ID='NaCl_item') create_stream_impact_item(item_ID='NaCl1_item', dct_key='NaCl') create_stream_impact_item(item_ID='NaOH_item') create_stream_impact_item(item_ID='LPG_item') ImpactItem(ID='e_item', functional_unit='kWh', GWP=GWP_dct['Electricity'], H_Ecosystems=H_Ecosystems_dct['Electricity'], H_Health=H_Health_dct['Electricity'], H_Resources=H_Resources_dct['Electricity']) _impact_item_loaded = True return _impact_item_loaded from . import systems from .systems import * _system_loaded = False def _load_system(): qs.currency = 'USD' qs.PowerUtility.price = price_dct['Electricity'] global sysA, sysB, teaA, teaB, lcaA, lcaB, _system_loaded sysA = create_system('A') teaA = sysA.TEA lcaA = sysA.LCA sysB = create_system('B') teaB = sysB.TEA lcaB = sysB.LCA _system_loaded = True def load(): if not _components_loaded: _load_components() if not _system_loaded: _load_system() dct = globals() for sys in (sysA, sysB): dct.update(sys.flowsheet.to_dict()) def __getattr__(name): if not _components_loaded or not _system_loaded: raise AttributeError(f'module "{__name__}" not yet loaded, ' f'load module with `{__name__}.load()`.') # %% # Util functions ##### Recoveries ##### # Calculate recoveries as in kg N/P/K per yr hr_per_yr = 365 * 24 get_N = lambda stream: stream.TN*stream.F_vol/1e3*hr_per_yr get_P = lambda stream: stream.TP*stream.F_vol/1e3*hr_per_yr get_K = lambda stream: stream.TK*stream.F_vol/1e3*hr_per_yr # Only for `sysA` or `sysB` def get_recoveries(system, ppl=default_ppl, include_breakdown=False): AB = system.ID[-1] u_reg = system.flowsheet.unit dct = globals() dct['N_dct'] = N_dct = {} dct['P_dct'] = P_dct = {} dct['K_dct'] = K_dct = {} ##### Unique to A or B ##### if AB == 'A': toilet = u_reg.A2 sludge_pasteurization = u_reg.A4 ion_exchange = u_reg.A5 else: # unique to sysB toilet = u_reg.B2 sludge_pasteurization = u_reg.B4 ion_exchange = u_reg.B5 ##### Applicable for both A and B ##### # In N_dct['urine'] = get_N(toilet.ins[0]) * ppl N_dct['feces'] = get_N(toilet.ins[1]) * ppl N_dct['input'] = N_dct['urine'] + N_dct['feces'] P_dct['urine'] = get_P(toilet.ins[0]) * ppl P_dct['feces'] = get_P(toilet.ins[1]) * ppl P_dct['input'] = P_dct['urine'] + P_dct['feces'] K_dct['urine'] = get_K(toilet.ins[0]) * ppl K_dct['feces'] = get_K(toilet.ins[1]) * ppl K_dct['input'] = K_dct['urine'] + K_dct['feces'] # Sludge Pasteurization N_dct['treated_sludge'] = get_N(sludge_pasteurization.outs[3]) P_dct['treated_sludge'] = get_P(sludge_pasteurization.outs[3]) K_dct['treated_sludge'] = get_K(sludge_pasteurization.outs[3]) # Ion Exchange N_dct['NH3'] = ion_exchange.outs[3].imol['NH3'] * 14 * hr_per_yr # % N, P, and K recovered as a usable fertilizer product, # for model metrics and also the Resource Recovery criterion in DMsan analysis functions = [ lambda: (N_dct['treated_sludge']+N_dct['NH3']) / N_dct['input'] * 100, # total_N_recovery lambda: P_dct['treated_sludge'] / P_dct['input'] * 100, # total_P_recovery lambda: K_dct['treated_sludge'] / K_dct['input'] * 100, # total_K_recovery ] if not include_breakdown: return functions return [ *functions, lambda: N_dct['treated_sludge'] / N_dct['input'] * 100, # N_sludge_pasteurization lambda: N_dct['NH3'] / N_dct['input'] * 100, # N_ion_exchange lambda: P_dct['treated_sludge'] / P_dct['input'] * 100, # P_sludge_pasteurization lambda: K_dct['treated_sludge'] / K_dct['input'] * 100, # K_sludge_pasteurization ] ##### Costs ##### # Learning curve assumptions percent_CAPEX_to_scale = 0.65 number_of_units = 100000 percent_limit = 0.015 learning_curve_percent = 0.925 def get_scaled_capital(tea): return get_generic_scaled_capital( tea=tea, percent_CAPEX_to_scale=percent_CAPEX_to_scale, number_of_units=number_of_units, percent_limit=percent_limit, learning_curve_percent=learning_curve_percent ) def get_TEA_metrics(system, ppl=default_ppl, include_breakdown=False): tea = system.TEA get_annual_electricity = lambda system: system.power_utility.cost*system.operating_hours functions = [lambda: (get_scaled_capital(tea)-tea.net_earnings) / ppl] if not include_breakdown: return functions # net cost return [ *functions, lambda: get_scaled_capital(tea) / ppl, # CAPEX lambda: get_annual_electricity()/ppl, # energy (electricity) lambda: tea.annual_labor/ppl, # labor lambda: (tea.AOC-get_annual_electricity()-tea.annual_labor)/ppl, # OPEX (other than energy and labor) lambda: tea.sales / ppl, # sales ] def get_normalized_CAPEX(units, ppl=default_ppl): '''Get the CAPEX of a unit/units normalized to per capita per day.''' system = units[0].system return system.TEA.get_unit_annualized_equipment_cost(units)/365/ppl def get_noramlized_electricity_cost(units, ppl=default_ppl): '''Get the energy (electricity) cost of a unit/units normalized to per capita per day.''' return sum(u.power_utility.cost for u in units)/ppl def get_normalized_OPEX(units, ppl=default_ppl): ''' Get the OPEX of a unit/units normalized to per capita per day, energy (electricity) cost is not included. ''' OPEX = sum(u.add_OPEX.values() for u in units) streams = sum([u.ins for u in units], []) OPEX += sum(s.cost for s in streams) return OPEX * 24 / ppl # convert to per capita per day ##### Emissions ##### def get_LCA_metrics(system, ppl=default_ppl, include_breakdown=False): lca = system.LCA functions = [ lambda: lca.total_impacts['GlobalWarming']/lca.lifetime/ppl, # annual GWP # ReCiPe LCA functions lambda: lca.total_impacts['H_Ecosystems']/lca.lifetime/ppl, lambda: lca.total_impacts['H_Health']/lca.lifetime/ppl, lambda: lca.total_impacts['H_Resources']/lca.lifetime/ppl, ] if not include_breakdown: return functions return [ *functions, lambda: lca.total_construction_impacts['GlobalWarming']/lca.lifetime/ppl, # construction lambda: lca.total_transportation_impacts['GlobalWarming']/lca.lifetime/ppl, # transportation lambda: lca.total_stream_impacts['GlobalWarming']/lca.lifetime/ppl, # stream (including fugitive gases and offsets) lambda: lca.total_other_impacts['GlobalWarming']/lca.lifetime/ppl, ] def print_summaries(systems): try: iter(systems) except: systems = (systems, ) for sys in systems: sys.simulate() print(f'\n---------- Summary for {sys.ID} ----------\n') if sys.ID in ('sysA', 'sysB'): recovery_functions = get_recoveries(sys) print(f'\nTotal N recovery: {recovery_functions[0]():.1f} %.') print(f'\nTotal P recovery: {recovery_functions[1]():.1f} %.') print(f'\nTotal K recovery: {recovery_functions[2]():.1f} %.') TEA_functions = get_TEA_metrics(sys) unit = f'{qs.currency}/cap/yr' print(f'\nTotal cost: {TEA_functions[0]():.2f} {unit}.') LCA_functions = get_LCA_metrics(sys) print(f'\nNet emission: {LCA_functions[0]():.2f} kg CO2-eq/cap/yr.') unit = 'points/cap/yr' print(f'\nNet ecosystems damage: {LCA_functions[1]():.2f} {unit}.') print(f'\nNet health damage: {LCA_functions[2]():.2f} {unit}.') print(f'\nNet resources damage: {LCA_functions[3]():.2f} {unit}.') else: sys.TEA.show() print('\n') sys.LCA.show() from . import models from .models import * from . import country_specific from .country_specific import * __all__ = ( 'ng_path', 'data_path', 'results_path', *_components.__all__, *systems.__all__, *models.__all__, *country_specific.__all__, )
const { log } = require("console"); var pandoc = require("node-pandoc"); const fs = require("fs") var config = JSON.parse(fs.readFileSync('config.json')); var src = config.src var args = "-f docx -t html5"; var outputString = ""; var callback = function (err, result) { if (err) { console.error("Oh Nos: ", err); return; } // Regular expressions to match ul, li, h1, h2, h3 tags var ulLiRegex = /<ul>[\s\S]*?<\/ul>|<li>[\s\S]*?<\/li>/g; var h1H2H3Regex = /<h[1-3][^>]*>[\s\S]*?<\/h[1-3]>/g; // Extract ul, li, h1, h2, h3 matches var ulLiMatches = result.match(ulLiRegex); var h1H2H3Matches = result.match(h1H2H3Regex); // Concatenate matches into a single string outputString = ulLiMatches.join("") + " " + h1H2H3Matches.join(""); // Remove whitespace characters and line breaks outputString = outputString.replace(/\s+/g, ""); // Remove id attributes from the output string outputString = outputString.replace(/id="[^"]*"/g, ""); // Print the cleaned output console.log(outputString); // Call the second pandoc inside this callback var args2 = "-f html -t docx -o word1.docx"; var callback2 = function (err2, result2) { if (err2) console.error("Oh Nos: ", err2); // Without the -o arg, the converted value will be returned. console.log(result2); }; pandoc(outputString, args2, callback2); }; // Call the first pandoc pandoc(src, args, callback); console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$44"); var cheerio = require("cheerio"); var src = "./word1.docx"; var args = "-f docx -t html5"; // Set your callback function var callback = function (err, result) { if (err) { console.error("Oh Nos: ", err); } else { // Call the function to process the result processHtml(result); } }; // Call pandoc pandoc(src, args, callback); var cheerio = require("cheerio"); const PPTX = require('nodejs-pptx'); var src = "./word1.docx"; var args = "-f docx -t html5"; // Set your callback function var callback = function (err, result) { if (err) { console.error("Oh Nos: ", err); } else { // Call the function to process the result processHtml(result); } }; // Call pandoc pandoc(src, args, callback); // Function to process the HTML result function processHtml(result) { var $ = cheerio.load(result); var ulElements = []; $("ul").each(function () { var lis = []; $(this) .find("li") .each(function () { var text = $(this).find("p").text(); lis.push(text); }); ulElements.push(lis); }); var h1Headings = []; $("h1").each(function () { var text = $(this).text().trim(); if (text !== "") { h1Headings.push(text); } }); // Call the function to add elements to the PowerPoint addElements(ulElements, h1Headings); } // Function to add elements to PowerPoint async function addElements(ulElements, h1Headings){ let pptx = new PPTX.Composer(); await pptx.load(config.pptxTemplate); for(const [i, header] of h1Headings.entries()){ await pptx.compose(async pres => { await pres.getSlide(i + 1).addText(text => { text .value(header) .x(config.x) .y(config.y) .fontFace(config.fontFace) .fontSize(config.fontSize) .textColor(config.textColor) .textWrap(config.textWrap) .textAlign(config.textAlign) .textVerticalAlign(config.textVerticalAlign) .line(config.line) .margin(config.margin); }); }); } for(const [i, body] of ulElements.entries()){ await pptx.compose(async pres => { await pres.getSlide(i + 1).addText(text => { text .value(body) .x(config.xbody) .y(config.ybody) .fontFace(config.fontFacebody) .fontSize(config.fontSizebody) .textColor(config.textColorbody) .textWrap(config.textWrapbody) .textAlign(config.textAlignbody) .textVerticalAlign(config.textVerticalAlignbody) .line(config.linebody) .margin(config.marginbody); }); }); } await pptx.save(config.savingPath); console.log('New presentation with headers saved!'); }
const empleados = [ { id: 1, nombre: "felipe", }, { id: 2, nombre: "andres", }, { id: 3, nombre: "jessica", }, { id: 4, nombre: "daniel", }, ]; const salarios = [ { id: 1, salario: 3000, }, { id: 2, salario: 1000, }, { id: 3, salario: 4000, }, ]; const getEmpleado = (id, callback) => { return new Promise((resolve, reject) => { const empleado = empleados.find((e) => e.id === id)?.nombre; empleado ? resolve(empleado) : reject(`no existe el empleado con id ${id}`); }); }; const getSalario = (id, callback) => { return new Promise((resolve, reject) => { const salario = salarios.find((e) => e.id === id)?.salario; // .? es un null check operator salario ? resolve(salario) : reject(`no existe el salario con id ${id}`); }); }; const id = 4; const getInfoEmpleado = async (id)=>{ try { const empleado = await getEmpleado(id); const salario = await getSalario(id) return `el salario de ${empleado} es ${salario}` } catch (error) { throw error; } } getInfoEmpleado(id).then((msg) => { console.log(msg) }).catch(error => console.log(error))
import React, { useState, useEffect } from 'react'; import './Second.css' import ProductTable from './ProductTable'; const Second = () => { const [file, setfile] = useState(''); const [fileContent, setFileContent] = useState({}); const [fileType, setFileType] = useState('json'); // Default to text file const [encoding, setEncoding] = useState('utf-8'); // Default to UTF-8 const [delimiter, setDelimiter] = useState(','); const [hasHeader, setHasHeader] = useState(true); // const availableProperties = ['subcategory', 'title', 'price', 'popularity']; const [selectedProperties, setSelectedProperties] = useState([]); const [displaytable, setdisplaytable] = useState(false) const handlePropertySelect = (property) => { if (!selectedProperties.includes(property)) { setSelectedProperties([...selectedProperties, property]); } }; const handlePropertyRemove = (property) => { const updatedProperties = selectedProperties.filter((selected) => selected !== property); setSelectedProperties(updatedProperties); }; const resetAllStates=()=>{ setHasHeader(false); setFileContent({}); setFileType(''); setEncoding('utf8'); setDelimiter(','); } const handleFileChange = () => { if (file) { const reader = new FileReader(); reader.onload = (e) => { const content = e.target.result; // If fileType is JSON, parse the content as JSON if (fileType === 'json') { try { const parsedContent = JSON.parse(content); setFileContent(parsedContent); // Beautify JSON setdisplaytable(true); } catch (error) { console.error('Error parsing JSON:', error); setFileContent('Error parsing JSON'); } } else if (fileType === 'csv') { // Parse CSV based on specified delimiter and hasHeader const rows = content.split('\n'); const headers = hasHeader ? rows[0].split(delimiter) : null; const parsedContent = rows .slice(hasHeader ? 1 : 0) .map((row) => row.split(delimiter)); setFileContent(parsedContent); setdisplaytable(true); // Display the parsed content } else { // For other file types, display the content as is setFileContent(content); } }; // Set the specified encoding and read the file reader.readAsText(file, encoding); }else{ alert("File not found"); } }; return ( <> <div className='Second' > <h4>Import products</h4> <div className='importgrid'> <div className='grid'> <p>Type 1: Select File</p> <input type="file" onChange={(e)=>{setfile(e.target.files[0])}} /> <p>supported File Types(s): CSV, .json</p> </div> <div className='grid'> <p>step 2: specify format</p> <label> File type: <select value={fileType} onChange={(e) => setFileType(e.target.value)} > <option value="json">json</option> <option value="csv">csv</option> </select> </label> <label> Character encoding: <select value={encoding} onChange={(e) => setEncoding(e.target.value)}> <option value="utf-8">UTF-8</option> <option value="iso-8859-1">ISO-8859-1</option> </select> </label> <label> Delimeter: <select value={delimiter} onChange={(e) => setDelimiter(e.target.value)} > <option value="comma">comma</option> <option value="option2">Option 2</option> <option value="option3">Option 3</option> </select> </label> <label htmlFor="">Has Header</label> <input type="checkbox" checked={hasHeader} onChange={() => setHasHeader(!hasHeader)}/> </div> <div className='grid'> <p>step 3: Display Handling</p> <p>Select the fields to be displayed</p> <div className="property-selector-container"> <div className="properties-box"> <h2>Available Properties</h2> <ul> {availableProperties.map((property) => ( <li key={property} onClick={() => handlePropertySelect(property)}> {property} </li> ))} </ul> </div> <div className="properties-box"> <h2>Selected Properties</h2> <ul> {selectedProperties.map((property) => ( <li key={property} onClick={() => handlePropertyRemove(property)}> {property} </li> ))} </ul> </div> </div> </div> </div> <button className='btn1' onClick={handleFileChange}>next</button> <button className='btn2' >Cancel</button> {displaytable ? <ProductTable data={fileContent} selectedProperties = {selectedProperties}/>:null} </div> </> ); }; export default Second;
#!/usr/bin/python import io # used to create file streams from io import open import fcntl # used to access I2C parameters like addresses import time # used for sleep delay and timestamps import string # helps parse strings import os import sys class AtlasI2C: long_timeout = 2 # the timeout needed to query readings and calibrations short_timeout = 1 # timeout for regular commands default_bus = 1 # the default bus for I2C on the newer Raspberry Pis, certain older boards use bus 0 default_address = 99 # the default address for the sensor current_addr = default_address def __init__(self, address=default_address, bus=default_bus): # open two file streams, one for reading and one for writing # the specific I2C channel is selected with bus # it is usually 1, except for older revisions where its 0 # wb and rb indicate binary read and write self.file_read = io.open("/dev/i2c-"+str(bus), "rb", buffering=0) self.file_write = io.open("/dev/i2c-"+str(bus), "wb", buffering=0) # initializes I2C to either a user specified or default address self.set_i2c_address(address) def set_i2c_address(self, addr): # set the I2C communications to the slave specified by the address # The commands for I2C dev using the ioctl functions are specified in # the i2c-dev.h file from i2c-tools I2C_SLAVE = 0x703 fcntl.ioctl(self.file_read, I2C_SLAVE, addr) fcntl.ioctl(self.file_write, I2C_SLAVE, addr) self.current_addr = addr def write(self, cmd): # appends the null character and sends the string over I2C cmd += "\00" self.file_write.write(cmd.encode('latin-1')) def read(self, num_of_bytes=31): # reads a specified number of bytes from I2C, then parses and displays the result res = self.file_read.read(num_of_bytes) # read from the board if res[0] == 1: # change MSB to 0 for all received characters except the first and get a list of characters # NOTE: having to change the MSB to 0 is a glitch in the raspberry pi, and you shouldn't have to do this! char_list = list(map(lambda x: chr(x & ~0x80), list(res[1:]))) place = 0 for i in char_list: if i != "\x00": place = place + 1 else: break char_list_edit = char_list[:-(len(char_list)-(place))] value= ''.join(char_list_edit) return "Command succeeded " + ''.join(char_list) # convert the char list to a string and returns it else: return "Error " + str(res[0]) def query(self, string): # write a command to the board, wait the correct timeout, and read the response self.write(string) # the read and calibration commands require a longer timeout if((string.upper().startswith("R")) or (string.upper().startswith("CAL"))): time.sleep(self.long_timeout) elif string.upper().startswith("SLEEP"): return "sleep mode" else: time.sleep(self.short_timeout) return self.read() def close(self): self.file_read.close() self.file_write.close() def list_i2c_devices(self): prev_addr = self.current_addr # save the current address so we can restore it after i2c_devices = [] for i in range (0,128): try: self.set_i2c_address(i) self.read(1) i2c_devices.append(i) except IOError: pass self.set_i2c_address(prev_addr) # restore the address we were using return i2c_devices def select(self,string): if string == "ph": self.set_i2c_address(99) elif string == "orp": self.set_i2c_address(98) elif string == "do": self.set_i2c_address(97) elif string == "ec": self.set_i2c_address(100) elif string == "rtd": self.set_i2c_address(102) elif string == "pmp": self.set_i2c_address(103) elif string == "flow": self.set_i2c_address(104) else: print("Error, invalid chip name entered") return string + " selected for modification.\n" def main(): device = AtlasI2C() # creates the I2C port object, specify the address or bus if necessary real_raw_input = vars(__builtins__).get('raw_input', input) #Calibration Loops and Instructions for each. while True: print( "This script will loop forever. Exit with ^C or Close the window. \n") print("Type the name of chip to modify below. Choices: ph, orp, do, ec, rtd, pmp, flow. \nIf An invalid name is entered, ph will be modified.") cmd = real_raw_input("Chip Name: ") device.select(str(cmd)) exit = 'Y' while exit == 'N': print("Calibration can now be performed using the Cal command. \nAll other valid Atlas Chip Commands can also be used. \n") brd_cmd = real_raw_input("Enter Command: ") if len(brd_cmd) == 0: print("No command entered, please try again. \n") else: try: print(device.query(brd_cmd)) except IOError: print("Failed Device query ") exit = real_raw_input("Enter Y to issue more commands, or N if you wish to enter a new chip name: ") if __name__ == "__main__": main()
import { Meta, Canvas, Source, Title, Controls } from '@storybook/blocks' import * as TagStories from './Tag.stories' <Meta of={TagStories} /> <Title children='Tag'/> <Canvas of={TagStories.Default} sourceState='none'/> <Source code={ `import { Tag } from 'star-components-library'; const MyComponents = () => <Tag /> ` } of={TagStories.Default} language="tsx"/> <Controls /> <Title children='Close'/> <Canvas of={TagStories.Close} sourceState='none'/> <Source code={ `import { Tag } from 'star-components-library'; const MyComponents = () => ( <Tag closeIcon onClose={() => alert('you closed the tag')}> Close me </Tag> ) ` } of={TagStories.Close} language="tsx"/> <Title children='PreventDefault'/> <Canvas of={TagStories.PreventDefault} sourceState='none'/> <Source code={ `import { Tag } from 'star-components-library'; const MyComponents = () => ( <Tag closeIcon preventDefault onClose={() => alert("you won't shut me out")}> Close me </Tag> ) ` } of={TagStories.PreventDefault} language="tsx"/>
import { Lesson, Course, CourseProps } from "../../src" import { faker } from "@faker-js/faker" import LessonBuilder from "./LessonBuilder" import CourseNames from "./CourseNames" export default class CourseBuilder { private constructor(private props: CourseProps) {} static create(lessonsQuantity: number = 10) { return new CourseBuilder({ name: CourseNames.random(), description: "Course description", imageUrl: faker.image.url(), price: 100, duration: 100, lessonsQuantity, lessons: LessonBuilder.createListWith(lessonsQuantity).map((lesson) => lesson.props), }) } withId(id: string): CourseBuilder { this.props.id = id return this } withoutId(): CourseBuilder { this.props.id = undefined as any return this } withName(name: string): CourseBuilder { this.props.name = name return this } withoutName(): CourseBuilder { this.props.name = undefined as any return this } withDescription(description: string): CourseBuilder { this.props.description = description return this } withoutDescription(): CourseBuilder { this.props.description = undefined as any return this } withPrice(price: number): CourseBuilder { this.props.price = price return this } withoutPrice(): CourseBuilder { this.props.price = undefined as any return this } withDuration(duration: number): CourseBuilder { this.props.duration = duration return this } withoutDuration(): CourseBuilder { this.props.duration = undefined as any return this } withNumberOfLessons(lessonsQuantity: number): CourseBuilder { this.props.lessonsQuantity = lessonsQuantity return this } withoutNumberOfLessons(): CourseBuilder { this.props.lessonsQuantity = undefined as any return this } withLessons(lessons: Lesson[]): CourseBuilder { this.props.lessons = lessons.map((l) => l.props) return this } withoutLessons(): CourseBuilder { this.props.lessons = undefined as any return this } published(): CourseBuilder { this.props.published = true return this } draft(): CourseBuilder { this.props.published = false return this } now(): Course { return new Course(this.props) } }
import React from 'react'; import { render, screen } from '@testing-library/react'; import { Provider } from 'react-redux'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import ProtectedRoute from '../components/ProtectedRoute'; import { store } from '../store'; import { RootState } from '../store'; const renderWithProviders = (ui: React.ReactElement, initialState: Partial<RootState>) => { return render( <Provider store={{ ...store, preloadedState: initialState }}> <Router>{ui}</Router> </Provider> ); }; test('redirects to /signin if not authenticated', () => { renderWithProviders( <Routes> <Route path="/protected" element={<ProtectedRoute />} /> <Route path="/signin" element={<div>Sign In Page</div>} /> </Routes>, { auth: { isAuthenticated: false, user: null, loading: false, error: null } } ); expect(screen.getByText(/Sign In Page/i)).toBeInTheDocument(); }); test('renders protected route if authenticated', () => { renderWithProviders( <Routes> <Route path="/protected" element={<ProtectedRoute />} /> </Routes>, { auth: { isAuthenticated: true, user: {}, loading: false, error: null } } ); expect(screen.queryByText(/Sign In Page/i)).not.toBeInTheDocument(); });
# Old School Grid For this Bonus Challenge, practice your CSS skills by making your own "old-school" grid system from scratch. You'll be "re-implementing" a fictional "Boopstrap" grid, a grid system similar to the original Bootstrap v1. - Note: This activity is intended to build up your knowledge of how CSS frameworks are built, but *is not* the correct way to do things! We'll learn that soon, with Grid and Flexbox. For now, we'll use the old hack of using "float: left" for our grid. - Note: If you've never used a grid system (such as Bootstrap's grid) this exercise might lack context. If so, feel free to read up on Bootstrap's (modern) grid here: <https://getbootstrap.com/docs/4.5/layout/grid/> Steps: 1. First, see if you can understand the existing HTML & CSS code 2. Second, fill in the TODO's in the CSS with what you think might go there 3. If successful, you should see a layout like the mockup.png 4. Finally, finish the media query, to make your grid system "responsive", or make all the columns with "md" in the class name "collapse" on smaller screens (e.g. they should only behave as columns for screens larger than 960px) Hints: - Do not change the HTML for this activity. - Boostrap has a "Base 12" column system. Every column gets a percentage based the number in its name, as a fraction of 12 (e.g. 3/12, 5/12, 12/12 and so on, with 1/12 being the narrowest, and 12/12 being a full width) - A "container" has already been implemented for you, but commented out, with a max-width and auto margins (causing it to be centered -- another older hack!) - Boostrap has a "Base 12" column system. The percentages can be calculated by the following math: `100 / 12 * number` (e.g. 3 is then 100 / 12 * 3) - You might want to round down , to prevent columns from being too wide and overflowing (Pixel rounding: The curse of the old-school grids!) - To make the "md" columns appear to "collapse" on smaller devices, make them full width (100%) on those devices
import React, { useState, useEffect, useRef } from "react"; const SearchBar = ({ componentId, data, setStock }) => { const [itemOptions, setItemOptions] = useState([]); const searchInput = useRef(""); const handleSearchInputChange = (e) => { console.log("handleSearchInput", searchInput.current.value); const jsonData = Array.isArray(data) ? data : JSON.parse(data); const filteredData = jsonData .filter((stock) => stock.company_name.includes(searchInput.current.value.toUpperCase()) ) .map((stock, index) => { return { name: stock.company_name, index: index, id: stock.id, ticker: stock.ticker, }; }) .slice(0, 10); setItemOptions(filteredData); setStock(e.target.value); }; useEffect(() => { //console.log("useEffect", searchInput.current.value); }, [searchInput.current.value]); return ( <div className="mb-4 relative w-full"> <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> <svg className="w-5 h-5 text-gray-500" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" > <path fillRule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clipRule="evenodd" ></path> </svg> </div> <div className={`search-bar w-full`}> <input type="text" ref={searchInput} name={componentId} list={componentId} className="w-full bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-cyan-600 focus:border-cyan-600 block pl-10 p-2.5" placeholder="Search" autoComplete="off" onChange={(e) => handleSearchInputChange(e)} /> <datalist id={componentId}> {itemOptions.map((stock) => ( <option key={stock.index} value={stock.name}> {`${stock.ticker} - ${stock.name}`} </option> ))} </datalist> </div> </div> ); }; export default SearchBar;