text
stringlengths
184
4.48M
#%% # Exercise 1 # Using basic Python, write a program that receives two objects, a function and a list of numbers. # The function needs to return the minimum, and the maximum of the function. # You cannot use the built-in functions min and max. def min_max(func, numbers): min_ = numbers[0] max_ = numbers[0] for number in numbers: result = func(number) if min_ is None or result < min_: min_ = result if max_ is None or result > max_: max_ = result return min_, max_ # Create a test assert min_max(lambda x: x**2, [1, 2, 3, 4, 5]) == (1, 25) # %% # Exercise 2 # Create a function that sorts a list of numbers in ascending order. # You can sort a list by swapping elements one by one until the list is sorted. def sort_list(numbers): for i in range(len(numbers)): for j in range(i + 1, len(numbers)): if numbers[i] > numbers[j]: numbers[i], numbers[j] = numbers[j], numbers[i] return numbers # Create a test assert sort_list([3, 1, 2, 4, 5]) == [1, 2, 3, 4, 5] # %% # Exercise 3 # In this exercise you will perform a binary search on a sorted list of numbers. # Given a list and a number you need to return the index # The binary search algorithm works as follows: # 1. Find the middle element in the list. # 2. If the middle element is the number you are looking for, return it. # 3. If the middle element is greater than the number you are looking for, repeat the process on the left half of the list. # 4. If the middle element is smaller than the number you are looking for, repeat the process on the right half of the list. # 5. If the number is not in the list, return None. def binary_search(numbers, number): left = 0 right = len(numbers) - 1 while left <= right: middle = (left + right) // 2 if numbers[middle] == number: return middle elif numbers[middle] > number: right = middle - 1 else: left = middle + 1 return None # Create a test assert binary_search([1, 2, 3, 4, 5], 3) == 2 # %%
use serde::Deserialize; /** * Register Request */ #[derive(Debug, Deserialize)] pub struct RegisterRequest { pub nickname: String, pub email: String, pub password: String, } /** * Login Request */ #[derive(Debug, Deserialize)] pub struct LoginRequest { pub email: String, pub password: String, } /** * Refresh Token Request */ #[derive(Debug, Deserialize)] pub struct RefreshTokenRequest { pub refresh_token: String, }
/* eslint-disable */ import { batch, createMemo, createSignal, For, JSX } from "solid-js"; import { Show, SwitchKind } from "tmeta-util-solid"; import { InputHandler } from "./Exploration"; import { unreachable } from "./guards"; const idStr = <T,>() => <W extends string>(w: W): W & {__is: T} => { return w as W & {__is: T}; }; // a simple thing to make with this would be lisp // - it has pretty uniform syntax. basically json but without even having object field/value which means // we can handle all cursor movement inside the list type JObject = { kind: "JObject@-N0gk9Mfm2iXGUkeWUMS", fields: JField[], multiline: boolean, mode: "array" | "object", }; type JField = { kind: "JField@-N0gkJ4N6etM-Md1KiyT", key?: JString | JSlot | undefined, value: JValue, // enables copy/pasting between objects and arrays eg // if you paste from an array to an object, it will put a bunch of fields with a slot for the key // if you paste into an array, it will error at all the keys // ok there's no reason to do this, we can just have seperate objectfield/arrayfield and handle // that on paste }; type JString = { kind: "JString@-N0gkxU5wAjciRZnERvO", text: Uint8Array, }; type JNumber = { kind: "JNumber@-N0gkzBWv3Cx0Ryyouky", num: number, }; type JBoolean = { kind: "JBoolean@-N0gl-Obi0cyd58QHO85", value: true | false, }; type JNull = { kind: "JNull@-N0l0aP4SXjljg-GoC-S", }; type JSlot = { // a slot doesn't really need a kind, it shouldn't be a real node kind: "JSlot@-N0gpdqw6BjkuWrRqqTG", value?: JValue | undefined, }; type SysText = { kind: "@systext", text: string, }; type JValue = JObject | JString | JNumber | JBoolean | JNull | JSlot; const colors: {white: string, dark: string, light: string}[] = [ {white: "text-red-100", dark: "text-red-400", light: "text-red-200"}, {white: "text-orange-100", dark: "text-orange-400", light: "text-orange-200"}, {white: "text-yellow-100", dark: "text-yellow-400", light: "text-yellow-200"}, {white: "text-green-100", dark: "text-green-400", light: "text-green-200"}, {white: "text-blue-100", dark: "text-blue-400", light: "text-blue-200"}, {white: "text-purple-100", dark: "text-purple-400", light: "text-purple-200"}, ]; const colrfor = (depth: number) => colors[(depth + colors.length - 1) % colors.length]!; function JField(props: { vc: VisualCursor | null, field: JField, depth: number, }): JSX.Element { // cursor positions: // []"key"[: ]"value"[] // note that these indices do not change if the key is not set. instead, the function should handle that. return <span> <span class="text-gray-500">{false ? "(" : null}</span> {props.field.key != null ? <> <TempCrs vc={props.vc} idx={0} covers={""} view="vertical" /> <span class={colrfor(props.depth).dark}> <JSONValueRender vc={subvc(props.vc, 0)} val={props.field.key} depth={props.depth} /> </span> </> : <></>} <TempCrs vc={props.vc} idx={1} covers={props.field.key != null ? ": " : ""} view={props.field.key != null ? "covers" : "vertical"} /> <span class={colrfor(props.depth).light}> <JSONValueRender vc={subvc(props.vc, 1)} val={props.field.value} depth={props.depth} /> </span> <TempCrs vc={props.vc} idx={2} covers={""} view="vertical" /> <span class="text-gray-500">{false ? ")" : null}</span> </span>; } function TempCrs(props: { vc: VisualCursor | null, idx: number, covers: JSX.Element, view: "horizontal" | "vertical" | "covers", }) { const match = createMemo(() => { return props.vc?.path.length === 0 ? ( props.vc.value.focus === props.idx ? "focus" as const : props.vc.value.anchor === props.idx ? "anchor" as const : null ) : null; }); return <>{props.view === "horizontal" ? <> {props.covers} <span class="block relative">{match() != null ? ( <div class={[ "absolute top-0 left-0 w-full h-[2px] transform translate-y-[-50%]", "rounded", match() === "focus" ? "bg-blue-400" : "bg-gray-400", ].join(" ")}></div> ) : null}</span> </> : props.view === "vertical" ? <> {props.covers} <div class="inline relative"> <Show if={match() != null}> <div class={` absolute inline-block w-[2px] text-transparent select-none transform translate-x-[-50%] rounded-md ${match() === "focus" ? "bg-blue-400" : "bg-gray-400"} `}>.</div> </Show> </div> </> : ( <span class={({ 'focus': "bg-blue-400 text-blue-900 rounded", 'anchor': "bg-gray-400 text-gray-900 rounded", 'none': "", } as const)[match() ?? "none"]}>{props.covers}</span> )}</>; } function subvc(vc: VisualCursor | null, i: number): VisualCursor | null { if(vc == null) return null; if(vc.path[0] !== i) return null; return { path: vc.path.slice(1), value: vc.value, }; } function JObjectContent(props: { vc: VisualCursor | null, obj: JObject, depth: number, }): JSX.Element { // v return <span class={props.obj.multiline ? "block pl-2 w-full border-l border-gray-700" : ""}> <TempCrs vc={props.vc} idx={0} covers={ props.obj.fields.length === 0 ? "…" : "" } view={props.obj.multiline ? "horizontal" : "vertical"} /> <>{props.obj.multiline ? "" : " "}</> <For each={props.obj.fields}>{(field, i) => { const last = createMemo(() => i() === props.obj.fields.length - 1); return <span class={props.obj.multiline ? "block" : ""}> <JField vc={subvc(props.vc, i())} field={field} depth={props.depth + 1} /> {props.obj.multiline || !last() ? "," : ""} {props.obj.multiline || !last() ? "" : " "} <TempCrs vc={props.vc} idx={i() + 1} covers={null} view={props.obj.multiline ? "horizontal" : "vertical"} /> {props.obj.multiline || last() ? "" : " "} </span> }}</For> </span>; } function JSONValueRender(props: { vc: VisualCursor | null, val: JValue, depth: number, }): JSX.Element { return <SwitchKind item={props.val}>{{ 'JObject@-N0gk9Mfm2iXGUkeWUMS': jobj => <span class={colrfor(props.depth).white}> <span>{jobj.mode === "object" ? "{" : "["}</span> <JObjectContent vc={props.vc} obj={jobj} depth={props.depth} /> <span>{jobj.mode === "object" ? "}" : "]"}</span> </span>, // we could even do jnum.toLocaleString() or Intl.NumberFormat // also note: consider making numbers, booleans, and null a different color // https://github.com/th00ber/atom-json-color 'JNumber@-N0gkzBWv3Cx0Ryyouky': jnum => <>{JSON.stringify(jnum.num)}</>, 'JBoolean@-N0gl-Obi0cyd58QHO85': jbool => <>{jbool.value.toString()}</>, 'JNull@-N0l0aP4SXjljg-GoC-S': () => <>{"null"}</>, 'JString@-N0gkxU5wAjciRZnERvO': jstr => { const halfwayPoint = createMemo(() => props.vc === null ? 0 : props.vc.path.length === 0 ? props.vc.value.focus : unreachable()); return <> <span class={colrfor(props.depth).dark}>"</span> <span class={ jstr.text.includes("\n".codePointAt(0)!) ? "block pl-2 "+colrfor(props.depth + 1).light : "" }> <TempCrs vc={props.vc} idx={0} covers={""} view={"vertical"} /> {new TextDecoder().decode(jstr.text.subarray(0, halfwayPoint()))} <TempCrs vc={props.vc} idx={halfwayPoint()} covers={""} view={"vertical"} /> {new TextDecoder().decode(jstr.text.subarray(halfwayPoint()))} </span> <span class={colrfor(props.depth).dark}>"</span> </>; }, ["JSlot@-N0gpdqw6BjkuWrRqqTG"]: () => <> <span class="bg-gray-600 px-1 rounded-md"> <TempCrs vc={props.vc} idx={0} covers={" "} view={"covers"} /> </span> </>, }}</SwitchKind>; } function TextNodeRaw(props: {children: JSX.Element, [key: string]: unknown}): JSX.Element { //@todo // also we can use display="contents" here, it's supported in browsers now return <>{props.children}</>; } type ObjHandlers<T> = { move(itm: T, vc: VisualCursor, stop: StopOpts): null | CursorMoveRes, side(itm: T, side: -1 | 1): null | CursorMoveRes, child(itm: T, idx: number): Obj, asText(itm: T): string, // we could have this return {remainder: Obj, value: T} // that way we can bubble events up // eg if you try to insert an image in a text node, it can say it doesn't accept it and then the parent has to // deal with it. not sure if we want to do this but we could. insert(obj: T, insert: Obj, at: {path: NodePath, index: number}): T, cut(obj: T, range: {start: number, end: number}): {node: T, removed: Obj[]}, }; const handlers_map = new Map<string, Partial<ObjHandlers<Obj>>>(); function register<T extends Obj>(kind: T["kind"], handlers: Partial<ObjHandlers<T>>): void { handlers_map.set(kind, handlers); // wow that's not typesafe, ts is lying. it's nice that it pretends // it's okay for me though. } let dbprefix = 0; function debugprint<T>(msg: unknown[], cb: () => T): T { let res; const pfx = "[dbg] " + "| ".repeat(dbprefix); // console.log(pfx, msg); dbprefix++; try { res = cb(); return res; }catch(e) { res = e; throw e; }finally{ dbprefix--; // console.log(pfx + "→ ", [res]); } } function anyhandler<Method extends keyof ObjHandlers<Obj>>( method: Method, args: Parameters<ObjHandlers<Obj>[Method]>, defaultval: () => ReturnType<ObjHandlers<Obj>[Method]>, ): ReturnType<ObjHandlers<Obj>[Method]> { const itm = args[0]; return debugprint([method, itm, ...args], (): ReturnType<ObjHandlers<Obj>[Method]> => { const ih = handlers_map.get(itm.kind); const ihm = ih?.[method]; if(ihm == null) { console.warn("missing "+method+" handler for "+itm.kind); return defaultval(); } // @ts-expect-error return ihm(...args); }); } // isn't this literally what interfaces are for? // like you would have the objects themselves have a prototype with all these methods on them already? // and then you don't have to do this manual dispatch? // yeah, it is. const any: ObjHandlers<Obj> = { move(...a) {return anyhandler("move", a, () => null)}, side(...a) {return anyhandler("side", a, () => null)}, child(...a) {return anyhandler("child", a, () => unreachable())}, asText(...a) {return anyhandler("asText", a, () => "[EUNSUPPORTED STRINGIFY "+a[0].kind+"]")}, insert(...a) {return anyhandler("insert", a, () => unreachable())}, cut(...a) {return anyhandler("cut", a, () => unreachable())}, }; type StopOpts = { dir: -1 | 1, selecting: boolean, // ← can't we just check if focus equals anchor? no need for this }; // function jStringMove(str: JString, vc: VisualCursor, stop: StopOpts): null | CursorMoveRes { // if(vc.path.length !== 0) unreachable(); // const svcdup = {...svc}; // svcdup.focus += stop.dir; // if(svcdup.focus < 0) return null; // if(svcdup.focus < str.text.length) return null; // return {path: [], index: svcdup.focus}; // } function defaultSubMove(obj: Obj, vc: VisualCursor, stop: StopOpts): { kind: "update", vc: VisualCursor, } | { kind: "return", res: CursorMoveRes, } { if(vc.path.length !== 0) { const idx = vc.path[0]!; const res = any.move(any.child(obj, idx), { path: vc.path.slice(1), value: vc.value, }, stop); if(res != null) { return {kind: "return", res: { path: [idx, ...res.path], index: res.index, }}; } const nq = stop.dir < 0 ? idx : idx + 1; // idx + + (stop.dir > 0) return {kind: "return", res: { path: [], index: nq, }}; } return {kind: "update", vc}; } register<JString>("JString@-N0gkxU5wAjciRZnERvO", { move(field, vc, stop) { const idx = vc.value.focus; const res = idx + stop.dir; // TODO Intl.Segmenter if(res < 0) return null; if(res > field.text.length) return null; return { path: [], index: res, }; }, side(field, dir) { return {path: [], index: dir === -1 ? 0 : field.text.length}; }, child(field, idx) { throw new Error("no children in text"); }, asText(str) { return JSON.stringify(new TextDecoder().decode(str.text)); }, insert(str, item, at) { if(at.path.length !== 0) unreachable(); // hmm. if we copy fields and paste them in a text, it won't keep the commas. // we'll have to solve that. later. // ^ maybe: rather than cut() returning an array of objects, have it return a single holder object // then, that object can say "the items in here should be multiline fields seperated by commas" // but it can be interpreted differently based on where it's being pasted. I think that's good. do that. const insert_text = new TextEncoder().encode(any.asText(item)); const new_val = new Uint8Array(str.text.length + insert_text.length); new_val.set(str.text.subarray(0, at.index), 0); new_val.set(insert_text, at.index); new_val.set(str.text.subarray(at.index), at.index + insert_text.length); // manual string concatenation in javascript. fun. return { kind: "JString@-N0gkxU5wAjciRZnERvO", text: new_val, }; }, }); register<JNumber>("JNumber@-N0gkzBWv3Cx0Ryyouky", { move(field, vc, stop) { // we're actually going to pop out a little number editor so we're treating all numbers as if // they have two positions const idx = vc.value.focus; const res = idx + stop.dir; // TODO Intl.Segmenter if(res < 0) return null; if(res > 1) return null; return { path: [], index: res, }; }, side(field, dir) { return {path: [], index: dir === -1 ? 0 : 1}; }, child(field, idx) { throw new Error("no children in number"); }, asText(num) { return JSON.stringify(num.num); }, }); // deleting a slot: // - select left and delete range // - this is default behaviour, the slot doesn't have to define it // - the field will then detect if a slot is deleted, it wlil put the key in the value or something // - not sure about how this will be implemented yet but the interaction is simple // → "key": [|] // ⌫ → "key" // just the question is how to implement that // and what does deleting right do inside there? // and do we really need to have all these cursor positions? []"key"[: |]{[]}[] // seems like we should just have []"key"[: ]{[]} register<JSlot>("JSlot@-N0gpdqw6BjkuWrRqqTG", { move(field, vc, stop) { return null; }, side(field, dir) { return {path: [], index: 0}; }, child(field, idx) { throw new Error("no children in slot"); }, asText(num) { return "<slot />"; }, insert(obj, item, at) { alert("E-SLOT-INSERT-ATTEMPT"); unreachable(); }, }); function slotInsert(item: Obj, at: {path: NodePath, index: number}): JValue { // ok I think we're handling this wrong // ! when you press a key in a slot, we need to show a suggestions list // your typing will filter that suggestions list and also offer up dynamic suggestions // we can have a few hotkeys that will insert a node directly instead of opening up the suggestions // list: `"`, `{`, `[` // that seems like a much better method than what we're trying to do here if(is<SysText>(item, "@systext")) { const text = item.text; // if someone eg pastes `"test"` this won't work // or if they use an ime and input that // TODO: more robust handling here^^^ // maybe we could loop over each byte and call slotInsert? // that requires that we make sure typing the exact conetnt should always // create the same thing. eg typing "{"a": "b"}" should create that structure // exactly. // but the problem is it doesn't - typing \" doesn't break you out of a string, you // have to move your cursor to get out of a string if(text === "\"") { const res: JString = { kind: "JString@-N0gkxU5wAjciRZnERvO", text: new Uint8Array([]), }; return res; } if(text === "{" || text === "[") { const res: JObject = { kind: "JObject@-N0gk9Mfm2iXGUkeWUMS", fields: [], multiline: false, mode: text === "[" ? "array" : "object", }; return res; } // when your cursor is inside a slot, we should show that listbox // something we could do is if you type something in the listbox that isn't // true, false, or null, we can detect if it's a string/number and offer up suggestions // makes typing json nicer - you don't need the quotes when typing the string key, you just // have to accept the suggestion // TODO: make a headlessui listbox or whatever it is that lets you search for a thing and // press enter to insert it alert("TODO support that character"); unreachable(); } alert("TODO support paste into slot"); unreachable(); } // booleans don't actually need any selection points. you delete and retype. // deleting turns the node into a slot and then the slot shows one of those fancy headless ui comboboxes // to pick the value register<JBoolean>("JBoolean@-N0gl-Obi0cyd58QHO85", { move() {return null}, side() {return null}, child() {unreachable()}, asText(bool) { return JSON.stringify(bool.value); }, }); register<JField>("JField@-N0gkJ4N6etM-Md1KiyT", { move(field, vc, stop) { const dsmres = defaultSubMove(field, vc, stop); if(dsmres.kind === "return") return dsmres.res; vc = dsmres.vc; const idx = vc.value.focus; // || if the actual selection start point is in here if(!stop.selecting) do { const nidx = idx + (stop.dir < 0 ? -1 : 0); const item = nidx === 0 ? field.key : nidx === 1 ? field.value : null; if(item == null) break; const val = any.side(item, -stop.dir as -1 | 1); if(val == null) break; return { path: [nidx, ...val.path], index: val.index, }; } while(false); const res = idx + stop.dir; // my favourite js operator, the <+! operator if(res <+! field.key || res > 2) return null; return { path: [], index: res, } }, side(field, dir) { if(dir === 1) return {path: [], index: 2}; return {path: [], index: field.key != null ? 0 : 1}; }, child(field, idx) { if(idx === 1) return field.value; if(idx === 0) return field.key!; unreachable(); }, asText(field) { return (field.key != null ? any.asText(field.key) + ": " : "") + any.asText(field.value); }, insert(obj, item, at) { if(at.path.length === 0) { if(!is<SysText>(item, "@systext")) { alert("not supported paste arbitrary in field"); return obj; } if(item.text !== ":") { alert("not supported type anything other than ':'"); return obj; } // 0 - only exists if there is a key // 1 - // 2 if(at.index === 0) { alert("not supported here"); return obj; } if(at.index === 1) { if(obj.key != null) { alert("not supported here"); return obj; } return { ...obj, key: {kind: "JSlot@-N0gpdqw6BjkuWrRqqTG"}, }; } if(at.index === 2) { if(obj.key != null) { alert("not supported here"); return obj; } if(obj.value.kind !== "JString@-N0gkxU5wAjciRZnERvO" && obj.value.kind !== "JSlot@-N0gpdqw6BjkuWrRqqTG") { alert("not supported non-string key"); return obj; } return { ...obj, key: obj.value, value: {kind: "JSlot@-N0gpdqw6BjkuWrRqqTG"}, }; } unreachable(); } const at0 = at.path[0]!; const atr = at.path.slice(1); const upd = {...obj}; const chv = any.child(obj, at0); const chp = {path: atr, index: at.index}; const nch = any.insert(chv, item, chp); if(at0 === 0) upd.key = nch as typeof upd.key; else if(at0 === 1) upd.value = nch as typeof upd.value; else unreachable(); return upd; }, }); register<SysText>("@systext", { asText(srt) { return srt.text; }, }); register<JObject>("JObject@-N0gk9Mfm2iXGUkeWUMS", { move(obj, vc, stop) { // cursor positions: // inline: // {field, field, field} // {|field, |field, |field|} // multiline: // {field,field,field,} // {|field,|field,|field,|} // display: // - multiline will use horizontal cursors // - inline have saces before, after, and between where vertical cursors will go const dsmres = defaultSubMove(obj, vc, stop); if(dsmres.kind === "return") return dsmres.res; vc = dsmres.vc; const idx = vc.value.focus; const stops = obj.fields.length; // || if the actual selection start point is in here if(!stop.selecting) do { const nidx = idx + (stop.dir < 0 ? -1 : 0); const field = obj.fields[nidx]; if(field == null) break; const val = any.side(field, -stop.dir as -1 | 1); if(val == null) break; return { path: [nidx, ...val.path], index: val.index, }; } while(false); const res = idx + stop.dir; if(res < 0 || res > stops) return null; return { path: [], index: res, } }, side(obj, dir) { if(dir == -1) return {path: [], index: 0}; return {path: [], index: obj.fields.length}; }, child(obj, idx) { return obj.fields[idx]!; }, insert(obj, item, at) { if(at.path.length === 0) { // systext.is(item)? if(is<SysText>(item, "@systext")) { if(item.text === "\n") { return {...obj, multiline: true}; } } // create a slot // type in the slot const newchild: JField = { kind: "JField@-N0gkJ4N6etM-Md1KiyT", value: slotInsert(item, {path: [], index: 0}), }; const updfields = [...obj.fields]; updfields.splice(at.index, 0, newchild); return { ...obj, fields: updfields, }; } const at0 = at.path[0]!; const atr = at.path.slice(1); const updfields = [...obj.fields]; updfields.splice(at0, 1, any.insert(any.child(obj, at0), item, {path: atr, index: at.index}) as typeof obj.fields[number]); return { ...obj, fields: updfields, }; }, asText(itm) { return (itm.mode === "object" ? "{" : "[") + itm.fields.map(field => any.asText(field)).join(",") + (itm.mode === "object" ? "}" : "]" ); }, }); function is<T extends Obj>(item: Obj, kind: T["kind"]): item is T { return item.kind === kind; } type userstr = string | JString; type usernum = number | JNumber; type userbool = boolean | JBoolean; type useractualobj = {[key: string]: userval | JSlot}; type userobj = useractualarr | useractualobj | JObject; type useractualarr = (userval | JSlot)[]; type useronefield = [value: userval | JSlot]; type userfield = [key: userstr | JSlot, value: userval | JSlot] | useronefield; type userval = userstr | usernum | userbool | userobj; type sources = userval | JSlot; type targetsof<T extends sources> = T extends { kind: string, } ? T : T extends string ? JString : T extends number ? JNumber : T extends boolean ? ( JBoolean ) : T extends useractualobj ? JObject : T extends useractualarr ? JObject : never; type test = targetsof<userstr | JSlot>; const a = { auto<T extends sources>(val: T): targetsof<T> { if(typeof val === "string") { const res: JString = {kind: "JString@-N0gkxU5wAjciRZnERvO", text: new TextEncoder().encode(val)}; return res as targetsof<T>; }; if(typeof val === "number") { const res: JNumber = {kind: "JNumber@-N0gkzBWv3Cx0Ryyouky", num: val}; return res as targetsof<T>; }; if(typeof val === "boolean") { const res: JBoolean = {kind: "JBoolean@-N0gl-Obi0cyd58QHO85", value: val}; return res as targetsof<T>; }; if(typeof val === "object") { if('kind' in val && [ "JObject@-N0gk9Mfm2iXGUkeWUMS", "JString@-N0gkxU5wAjciRZnERvO", "JNumber@-N0gkzBWv3Cx0Ryyouky", "JBoolean@-N0gl-Obi0cyd58QHO85", "JSlot@-N0gpdqw6BjkuWrRqqTG", "JNull@-N0l0aP4SXjljg-GoC-S" as unknown, ].includes(val.kind as unknown)) { return val as targetsof<T>; } } throw new Error("TODO typeof:"+(typeof val)); }, jfield(field: userfield): JField { const guarda = (a: userfield): a is useronefield => a.length === 1; if(guarda(field)) { return { kind: "JField@-N0gkJ4N6etM-Md1KiyT", value: a.auto(field[0]), }; }else{ return { kind: "JField@-N0gkJ4N6etM-Md1KiyT", key: a.auto(field[0]), value: a.auto(field[1]), }; } }, obj(v: "inline" | "multiline", ...obj: userfield[]): JObject { return { kind: "JObject@-N0gk9Mfm2iXGUkeWUMS", multiline: v === "multiline", fields: obj.map(o => a.jfield(o)), mode: "object", }; }, arr(v: "inline" | "multiline", ...obj: userfield[]): JObject { return { kind: "JObject@-N0gk9Mfm2iXGUkeWUMS", multiline: v === "multiline", fields: obj.map(o => a.jfield(o)), mode: "array", }; }, // v this is misleading. a slot should be handled by its parent node because of how cusor // movement works around it slot(): JSlot { return {kind: "JSlot@-N0gpdqw6BjkuWrRqqTG"}; }, }; type NodePath = number[]; type SubVC = { focus: number, anchor: number, anchor_sub: null | VisualCursor }; type VisualCursor = { path: NodePath, value: SubVC, }; type CursorMoveRes = { path: NodePath, index: number, }; export default function ExplorationEditor2(): JSX.Element { const [visualCursor, setVisualCursor] = createSignal<VisualCursor>({ path: [], value: { focus: 0, anchor: 0, anchor_sub: null, }, }); const [jsonObj, setJsonObj] = createSignal<JValue>(a.obj("multiline", ["types", a.obj("multiline", ["string", "hi! this is a test string"], ["escapes string", "woah, this \"string\" includes\nmultiple lines. pretty fancy"], ["number", 25], ["boolean", true], ["array", a.arr("multiline", ["My numbers:"], [a.arr("inline", [1], [2], [3])], [a.obj("inline", ["an", "inline object"], ["pretty", "fancy"])], )], ["object", a.obj("inline", ["type", "message"], ["value", a.obj("multiline", ["sender", "Jalak"], ["content", "Welcome!"], )], )], ["empty inline object", a.obj("inline")], ["empty multiline object", a.obj("multiline")], )], ["slots", a.obj("multiline", ["key", "value"], ["slot value", a.slot()], [a.slot(), "slot key"], ["missing key"], [a.slot()], )], )); return <><InputHandler onKeyDown={e => { if(e.code.startsWith("Arrow")) { e.preventDefault(); e.stopPropagation(); const lr = e.code === "ArrowLeft" || e.code === "ArrowUp" ? -1 : 1; const vc = visualCursor(); const nv = any.move(jsonObj(), vc, {dir: lr, selecting: e.shiftKey || e.code === "ArrowUp" || e.code === "ArrowDown"}); if(nv) setVisualCursor({ path: nv.path, value: { focus: nv.index, anchor: nv.index, anchor_sub: null, }, }); } }} onBeforeInput={(e) => { const insert = (val: Obj) => { const vc = visualCursor(); const nobj = any.insert(jsonObj(), val, { path: vc.path, index: vc.value.focus, }) as ReturnType<typeof jsonObj>; batch(() => { setJsonObj(() => nobj); }); } if(e.inputType === "insertText") { e.preventDefault(); e.stopPropagation(); const systext: SysText = { kind: "@systext", text: e.data ?? "", }; insert(systext); }else if(e.inputType === "insertLineBreak") { const systext: SysText = { kind: "@systext", text: "\n", }; insert(systext); // deleteContentBackward // deleteContentForward }else{ console.log(e); } }} > <div class="border border-gray-600 rounded-md p-2 whitespace-pre-wrap" style="overflow-wrap: anywhere" > <JSONValueRender vc={visualCursor()} val={jsonObj()} depth={0} /> </div> </InputHandler><div> <div class="border border-gray-600 rounded-md p-2 whitespace-pre-wrap select-text" style="overflow-wrap: anywhere" > {any.asText(jsonObj())} </div> </div></>; } export type Obj = { kind: string, };
<template> <div class="signup_wrapper"> <div class="container"> <h2>Qiitaへようこそ</h2> <p>新規登録して利用を開始しましょう。</p> <Notification :message="error" v-if="error" class="mb-4 pb-3" /> <div class="signup_form"> <div class="signup_form_left"> <img src="https://placehold.jp/300x300.png" alt="" /> <p> もしQiitaのアカウントを持っている場合は <NuxtLink to="/login">ログイン</NuxtLink>から </p> </div> <div class="signup_form_right"> <form @submit.prevent="signup"> <div class="form_container"> <ul> <li> <input type="text" placeholder="ユーザー名" required v-model="name" /> </li> <li> <input type="email" placeholder="メールアドレス" required v-model="email" /> </li> <li> <input type="password" placeholder="パスワード" required v-model="password" /> </li> <li> <input type="password" placeholder="パスワード確認用" required v-model="password_confirmation" /> </li> </ul> </div> <button class="resister_button" type="submit" variant="primary"> 登録する </button> </form> </div> </div> </div> </div> </template> <script> export default { layout: "auth", data: function () { return { name: "", email: "", password: "", password_confirmation: "", error: null, }; }, methods: { async signup() { try { await this.$axios.post("/api/auth", { name: this.name, email: this.email, password: this.password, password_confirmation: this.password_confirmation, }); await this.$auth.loginWith("local", { data: { password: this.password, email: this.email, }, }); if (this.$auth.loggedIn) { this.$router.push("/sample"); } } catch (e) { this.error = e.response.data.errors.full_messages; } }, }, }; </script> <style></style>
<?php /** * @package Controller * @author Rupert Brasil Lustosa <rupertlustosa@gmail.com> * @date 09/12/2019 09:48:30 */ declare(strict_types=1); namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Type extends Model { use SoftDeletes; const ADMIN = 1; const CLIENTE = 2; /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = true; /** * The table associated with the model. * * @var string */ protected $table = 'types'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', ]; /** * The attributes that aren't mass assignable. * * @var array */ /*protected $guarded = [ 'name', ];*/ /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = []; /** * The attributes that should be visible in arrays. * * @var array */ protected $visible = []; /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = []; # Query Scopes # Relationships # Accessors & Mutators public static function typesBasics() { return Type::query()->whereNotIn('id', [self::CLIENTE, self::ADMIN])->get(); } }
import React from "react"; import { useForm, Controller } from "react-hook-form"; import error_icon from "../assets/images/icon-error.svg"; function FormSection() { return ( <section className="flex flex-col items-center justify-center gap-[2.25rem] w-full bg-soft-blue pt-[4.625rem] pb-[4.5rem] px-[2rem]"> <FormText /> <Form /> </section> ); } function FormText() { return ( <div className="flex flex-col justify-center items-center gap-[1.5rem]"> <p className="text-xs text-white">35,000+ already joined</p> <h2 className="text-[2rem] text-white font-medium max-w-[22ch] text-center"> Stay up-to-date with what we’re doing </h2> </div> ); } function Form() { const { control, register, handleSubmit, formState: { errors }, } = useForm({ defaultValues: { email: '', // Aquí establece un valor inicial vacío para el campo de correo electrónico }, }); const onSubmit = (data) => {}; return ( <div className="flex flex-col items-center mx-auto max-w-[27.625rem] w-full"> <form onSubmit={handleSubmit(onSubmit)} className="w-full"> <div className="grid items-center gap-8 md:grid-cols-[2.4fr_1fr] md:flex-row md:justify-between md:gap-4"> <div className="w-full relative"> <Controller name="email" control={control} rules={{ required: "The email is required", pattern: { value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i, message: "Whoops, make sure it's an valid email", }, }} render={({ field }) => ( <input {...field} id="email" type="email" className={`h-[3rem] w-full relative z-[4] rounded-lg border-2 border-very-dark-blue/10 px-4 py-3 text-very-dark-blue focus:border-very-dark-blue/50 bg-white ${ errors.email ? "!border-red-500 focus-visible:!outline-red-500" : "" }`} placeholder="Enter your email address" name="mail" /> )} /> <label className="sr-only">Input your email</label> {errors.email && ( <> <img src={error_icon} alt="error-icon" className="absolute right-3 top-1/2 z-[4] -translate-y-1/2 transform" /> <div className="w-full"> <span className="z-1 absolute -bottom-[1.75rem] left-0 w-full rounded-md bg-red-500 px-2 pb-1 pt-3 text-sm text-white transition-all duration-300 ease-in-out italic">{errors.email.message}</span> </div> </> )} </div> <button type="submit" className="flex-1 rounded-lg border-[0.188rem] border-soft-red bg-soft-red py-[0.6558rem] text-white transition duration-300 hover:bg-white hover:text-soft-red" > Contact Us </button> </div> </form> </div> ); } export default FormSection;
import 'package:flutter/material.dart'; import 'package:stock_alert/database_repository.dart'; class ClearWatchlist extends StatelessWidget { const ClearWatchlist({super.key}); /* clears the watchlist of stocks */ clearWatchlistHandler() async { final DatabaseRepository repo = DatabaseRepository.instance; repo.clearWatchlist(); } @override Widget build(BuildContext context) { return ElevatedButton( onPressed: () => showDialog( context: context, builder: (_) => AlertDialog( backgroundColor: Theme.of(context).scaffoldBackgroundColor, title: Text( 'Clear Watchlist', textScaler: TextScaler.noScaling, textAlign: TextAlign.center, style: TextStyle( color: Theme.of(context).textTheme.headlineMedium!.color, fontSize: 28, fontWeight: FontWeight.w700, ), ), content: Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.fromLTRB(10, 10, 10, 20), child: Text( 'Are you sure?', textScaler: TextScaler.noScaling, style: TextStyle( color: Theme.of(context).colorScheme.tertiary, fontSize: 30, fontWeight: FontWeight.w600, fontStyle: FontStyle.italic, ), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ GestureDetector( onTap: () => { clearWatchlistHandler(), Navigator.pop(context), // close alert window }, child: Icon( Icons.check_circle_outline, size: 55, color: Theme.of(context).iconTheme.color, ), ), GestureDetector( onTap: () => Navigator.pop(context), child: Icon( Icons.cancel_outlined, size: 55, color: Theme.of(context).iconTheme.color, ), ), ], ), ], ), ), ), style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFFFF0000), foregroundColor: const Color(0xFF800000)), child: const Padding( padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), child: Text( 'Clear\nWatchlist', textScaler: TextScaler.noScaling, textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600, ), ), ), ); } }
// // PumpMessageSender.swift // RileyLink // // Created by Jaim Zuber on 3/2/17. // Copyright © 2017 LoopKit Authors. All rights reserved. // import Foundation import RileyLinkBLEKit public protocol PumpMessageSender { /// - Throws: LocalizedError func resetRadioConfig() throws /// - Throws: LocalizedError func updateRegister(_ address: CC111XRegister, value: UInt8) throws /// - Throws: LocalizedError func setBaseFrequency(_ frequency: Measurement<UnitFrequency>) throws /// - Throws: LocalizedError func listen(onChannel channel: Int, timeout: TimeInterval) throws -> RFPacket? /// - Throws: LocalizedError func send(_ msg: PumpMessage) throws /// - Throws: LocalizedError func getRileyLinkStatistics() throws -> RileyLinkStatistics /// Sends a message to the pump, expecting a PumpMessage with specific response body type /// /// - Parameters: /// - message: The message to send /// - responseType: The expected response message type /// - repeatCount: The number of times to repeat the message before listening begins /// - timeout: The length of time to listen for a pump response /// - retryCount: The number of times to repeat the send & listen sequence /// - Returns: The expected response message body /// - Throws: /// - PumpOpsError.couldNotDecode /// - PumpOpsError.crosstalk /// - PumpOpsError.deviceError /// - PumpOpsError.noResponse /// - PumpOpsError.pumpError /// - PumpOpsError.unexpectedResponse /// - PumpOpsError.unknownResponse func getResponse<T: MessageBody>(to message: PumpMessage, responseType: MessageType, repeatCount: Int, timeout: TimeInterval, retryCount: Int) throws -> T /// Sends a message to the pump, listening for a any known PumpMessage in reply /// /// - Parameters: /// - message: The message to send /// - repeatCount: The number of times to repeat the message before listening begins /// - timeout: The length of time to listen for a pump response /// - retryCount: The number of times to repeat the send & listen sequence /// - Returns: The message reply /// - Throws: An error describing a failure in the sending or receiving of a message: /// - PumpOpsError.couldNotDecode /// - PumpOpsError.crosstalk /// - PumpOpsError.deviceError /// - PumpOpsError.noResponse /// - PumpOpsError.unknownResponse func sendAndListen(_ message: PumpMessage, repeatCount: Int, timeout: TimeInterval, retryCount: Int) throws -> PumpMessage // Send a PumpMessage, and listens for a packet; used by callers who need to see RSSI /// - Throws: /// - PumpOpsError.noResponse /// - PumpOpsError.deviceError func sendAndListenForPacket(_ message: PumpMessage, repeatCount: Int, timeout: TimeInterval, retryCount: Int) throws -> RFPacket /// - Throws: PumpOpsError.deviceError func listenForPacket(onChannel channel: Int, timeout: TimeInterval) throws -> RFPacket? }
.TH hsh 1 2022-04-15 "0x16. C - Simple Shell ver. 1.0" "Holberton Simple Shell Manual" .SH NAME .SH "" .B Simple_Shell - holberton shell project .PP - Command line interpreter or (hsh) .SH SYNOPSIS .SH "" .B hsh [No options yet] .SH DESCRIPTION .SH "" .B The [\fIhsh\fR] is a Simple Shell Project to built by the Students at Holberton School. \ The hsh DON´T pretends to be a functionally complete shell, .br besides the current version is in constant process of being changed to conform \ with the specifications for Holberton School project, so .br this man page is not intended to be a tutorial or a complete specification about of hsh. .B The simple_shell is a command line interpreter, that includes the basic \ functionality of a traditional Unix-like command line interface. .br The [\fIhsh\fR] is designed to run on the linux environment. .br .B \fIInvocation:\fR .SH "" .in +4n Compile simple_shell with the GNU Compiler Collection, preferably using gcc plus the below \ specified flags, as per this example .br (note the use of the * wildcard which enables all related \ .c files to be compiled concurrently): .P .RS .B $ gcc -Wall -Werror -Wextra -pedantic *.c -o hsh .P .SH OPTIONS .SH "" Simple_shell can be run in interactive mode by entering the below command on the \ command line followd by 'ENTER' Note that the prompt ('hsh$ ') .br will appear and you will then be in interactive mode and able to enter commands \ followed by 'ENTER'. .P .RS .B hsh$ ./hsh .P .RE You can handle multiple commands using ';' '&&' '||' specifiers. Once you have \ entered the commands you execute the commands by pressing .br 'ENTER' or 'RETURN' on your keyboard. .P Besides the [\fbhsh\fR] can be run in non-interactive mode through the use of shell scripts. This can involve the use of pipeline ('|'): .P .RS .B echo 'pwd' | ./hsh .P .SH ENVIRONMENT .SH "" .B \fbReserved Words:\fR .SH "" .in +4n .B exit: Quit the program, exits the hsh. .B env: Prints the environment variables .B history: Displays the history list, one command per line, preceded with line numbers, starting with 0. .P .B \fbThe commands:\fR .SH "" .in +4n .B exit , .B env and .B echo are handled automatically by .B hsh. .SH FILES .P .SH "" .SH BUGS No known bugs at this time. See status widget in the repositories 'README' for\ updates though. If you spot a bug please feel free to create an issue .br or contact the AUTHORS via email. .SH EXAMPLE(S) .P .SH "" .SH AUTHOR(S) .P .SH "" Jesús Macías <@holbertonschool.com> .br Marco Antonio Ordóñez <3917@holbertonschool.com> .br .SH SEE ALSO .P .SH "" .BR access(2), bash(1), chdir(2), execve(2), _exit(2), exit(3), fflush(3), fork(2), free(3), .br isatty(3), malloc(3), open(2), read(2), sh(1), signal(2), stat(2), wait(2), write(2) .P .P
import { withStyles, StyledComponentProps, Theme } from "@material-ui/core/styles"; import React from 'react'; import { meanBy } from 'lodash' import App from "./App"; const styles = (theme: Theme) => ({ root: { backgroundColor: theme.palette.background.default, letterSpacing: 0.001 } }); type Coord = {x: number; y: number} type SvgMoveEvent = React.MouseEvent<SVGSVGElement, MouseEvent> | React.TouchEvent<SVGSVGElement> interface Props extends StyledComponentProps {app: App} interface State {} class DraggableSvg extends React.PureComponent<Props, State> { svgRef = React.createRef<SVGSVGElement>(); transformRef = React.createRef<SVGGElement>(); draggedElement? : SVGSVGElement transform = { scale: 0.012828952955767671, pos_x: 0.23271609882570168, pos_y: 0.18932110016807063 } offset? : Coord prevTouchDist = 0 constructor(props : Props) { super(props) //USe ref for perfomance purpose } startDrag(e: SvgMoveEvent, cursor: Coord) { if (!e.currentTarget.closest(".undraggable")) { //Fix drag weird behavior when text is selected inside a foreignObject this.draggedElement = e.currentTarget; window.getSelection()?.removeAllRanges(); if (this.svgRef.current) this.svgRef.current.style.cursor = "grabbing" this.offset = cursor this.offset.x -= this.transform.pos_x; this.offset.y -= this.transform.pos_y; } } drag(e: SvgMoveEvent, cursor: Coord) { if (this.draggedElement && this.offset) { //console.log({ drag: e }) //if (e.type === 'touchmove') debugger; this.transform.pos_x = cursor.x - this.offset.x this.transform.pos_y = cursor.y - this.offset.y this.transformRef.current?.setAttribute("transform", this.getTransformString()); } } endDrag(e: SvgMoveEvent) { if (this.svgRef.current) this.svgRef.current.style.cursor = "grab" this.draggedElement = undefined } zoom(e: SvgMoveEvent, cursor: Coord, scalefactor: number) { const x = (cursor.x - this.transform.pos_x) const y = (cursor.y - this.transform.pos_y) const newscale = this.transform.scale * scalefactor if (newscale <= 0.5 && newscale >= 0.022 * 0.50) { this.transform.scale = newscale this.transform.pos_x = cursor.x - x * scalefactor this.transform.pos_y = cursor.y - y * scalefactor this.offset = cursor this.offset.x -= this.transform.pos_x; this.offset.y -= this.transform.pos_y; this.transformRef.current?.setAttribute("transform", this.getTransformString()); } } getCurrentViewBoxStr() { const screenRatio = 2 const width = screenRatio const height = 1 const viewBox = { min_x: -width / 2, min_y: -height / 2, width: width, height: height } const viewBoxStr = viewBox.min_x + " " + viewBox.min_y + " " + viewBox.width + " " + viewBox.height //console.log(viewBoxStr) return viewBoxStr } getTransformString() { return `translate(${this.transform.pos_x}, ${this.transform.pos_y}) scale(${this.transform.scale})` } clientCordToSvgCord(clientX : number, clientY : number, relativeTo:React.RefObject<SVGSVGElement>) { if (!relativeTo.current) throw Error("Should not be empty") const CTM = relativeTo.current.getScreenCTM(); if (!CTM) throw Error("Should not be empty") return { x: (clientX - CTM.e) / CTM.a, y: (clientY - CTM.f) / CTM.d }; } // const clientX = evt.clientX || meanBy(evt.touches, t => t.clientX) // const clientY = evt.clientY || meanBy(evt.touches, t => t.clientY) render() { const { classes } = this.props const html = <svg className={`main ${classes?.root}`} id="mainsvg" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox={this.getCurrentViewBoxStr()} ref={this.svgRef} onWheel={e => { const cursor = this.clientCordToSvgCord(e.clientX, e.clientY, this.svgRef) this.zoom(e, cursor,e.deltaY < 0 ? 1 * 1.10 : 1 / 1.10) }} onMouseDown={e => { const cursor = this.clientCordToSvgCord(e.clientX, e.clientY, this.svgRef) this.startDrag(e, cursor) }} onMouseMove={e => { const cursor = this.clientCordToSvgCord(e.clientX, e.clientY, this.svgRef) this.drag(e, cursor) }} onMouseLeave={e => this.endDrag(e)} onMouseUp={e => this.endDrag(e)} onTouchStart={e => { const clientX = meanBy(e.touches, t => t.clientX) const clientY = meanBy(e.touches, t => t.clientY) const cursor = this.clientCordToSvgCord(clientX, clientY, this.svgRef) this.startDrag(e, cursor) if (e.touches.length >= 2) { this.prevTouchDist = norm( e.touches[1].clientX - e.touches[0].clientX, e.touches[1].clientY - e.touches[0].clientY, ) } }} onTouchMove={e => { const clientX = meanBy(e.touches, t => t.clientX) const clientY = meanBy(e.touches, t => t.clientY) const cursor = this.clientCordToSvgCord(clientX, clientY, this.svgRef) this.drag(e, cursor) if (e.touches.length >= 2) { const currentTouchDist = norm( e.touches[1].clientX - e.touches[0].clientX, e.touches[1].clientY - e.touches[0].clientY, ) this.zoom(e, cursor, currentTouchDist / this.prevTouchDist) this.prevTouchDist = currentTouchDist } }} onTouchEnd={e => { const clientX = meanBy(e.touches, t => t.clientX) const clientY = meanBy(e.touches, t => t.clientY) const cursor = this.clientCordToSvgCord(clientX, clientY, this.svgRef) if (e.touches.length > 0) { this.startDrag(e, cursor) if (e.touches.length >= 2) { this.prevTouchDist = norm( e.touches[1].clientX - e.touches[0].clientX, e.touches[1].clientY - e.touches[0].clientY, ) } } else { this.endDrag(e) } }} > <g ref={this.transformRef} transform={this.getTransformString()} > <g> {this.props.children} </g> </g> </svg> return html } } function norm(x: number, y: number) { return Math.sqrt(x * x + y * y) } export default withStyles(styles, { withTheme: true })(DraggableSvg)
// Relança uma exceção public class Rethrow { public static void genException() { // aqui, numer é mais longo do que denom int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 }; int denom[] = { 2, 0, 4, 4, 0, 8 }; for(int i = 0; i < numer.length; i++) { try { System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i] / denom[i]); } catch(ArithmeticException exc) { // captura a exceção System.out.println("Can't divide by Zero!"); } catch(ArrayIndexOutOfBoundsException exc) { // captura a exceção System.out.println("No matching element found."); throw exc; // relança a exceção } } } } class RethrowDemo { public static void main(String[] args) { try { Rethrow.genException(); } catch(ArrayIndexOutOfBoundsException exc) { // recaptura a execução System.out.println("Fatal error - " + "program terminated."); } } }
Train/test/dev -same distribution -small amount of data --> 60/20/20 -large amount of data --> 99/0.6/0.4 High Bias - Undertraining the training data (high cost on train set) - Bigger network - Train longer - Different network structure High Variance -Rule of thumb: First try to get as low Cost on train set as you can by finding the best hyperparameters (learn_rate, nodes, n_layers, structure of network, initalization, cost function, layer activation functions, (L2 lambda), (itterations), ...). Then avoid overfititng by regulazation, more data... -Overfiting the train set (high cost on test set) - More Data - For images --> flip image horizantally --> more data. Get random parts of the image. - Regulazation -L2 Regulazation -Wights -= (dW + Lamdba/m * W) -Reduces complexity when Lambda is a big number -Simplier modell -Drop out -Upon each train you drop out nodes randomly thus network becomes smaller -At train you define a probability (0.8 for example). And based on that pobability you change each node's (A1, A2...) value to 0. --> doA2 (0 if the random value is less than the probability, else 1) * A2. Z3 = W3 @ A2 / drop-out + B3 (dividing in order to ignore the drop out at forward prop) -At test you don't use the drop out method. -Probabilities can differ for each layer. layers with more nodes have lower prob. -Early stoping -Monitor dev cost upon training as well. Once dev cost starts to increase stop iterrating. - Different network structure -Normalization -Subtract mean (1/m * Sum(X)) from each training set to set the mean to zero -Normalize Variance: Divide each training set by (1/m * sum(x^2) which is now the variance (after already previously subtructing mean)) -Use same Mean and Variance to scale test set. .Vanishing/Exploding gradient descent -When you have a deep network. Big init weights cause the network to explode --> y= w^l where w is greater than 1, small weight cause it to vanish --> y= w^l where w is less that 1. -The more nodes a layer have the smaller the weights should be --> W_l = np.random.rand(l_n, l_n-1) * np.sqrt(1/n_l-1) for Relu better = np.random.rand(l_n, l_n-1) * np.sqrt(2/n_l-1) -Gradient checking -Only use to debug the program. Two sided gradient check. Gradient = F[x+E] - F[x-E]/2E = dprob -Concatenate Weights and biases to a large vector. Calculate the previous for each element. (E=10^-7) then check ||d0-dprob0|| / (||d0|| + ||dprob0||). If this equals around 10^-7 then the gradient descent alogrithm is ok. bigger than 10^-3 means there is a bug. -Remeber regulazation check as well. Batches - 1 itteration over all mini batch is an epoch -If M is small (<2000) use Batch gradient descand (no mini batches) -If M is greated (>2000) use mini-batch 2^6, 2^7,2^8,2^9...2000 Gradient descent with momentum - using the VdWt = Beta * VdWt-1 + (1-Beta) * dWt foruma Use ADam optimiser!!! Learning rate decay -The more you learn, the smaller the learning_rate is -1/(1+decay-rate*epochs) * learning_rate_0 where decay-rate is a hyper parameter (1 e.g) Batch normalization -Normalize hidden network activations - go to course
/* * Copyright (c) 2015-2999 广州朗尊软件科技有限公司<www.legendshop.cn> All rights reserved. * * https://www.legendshop.cn/ * * 版权所有,并保留所有权利 * */ package com.legendshop.order.excel; import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadRowHeight; import com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 商家订单结算订单 * * @author legendshop */ @Data @HeadRowHeight(20) @ContentRowHeight(20) @Schema(description = "商家积分订单结算订单") public class ShopOrderBillOrderIntegralExportDTO implements Serializable { private static final long serialVersionUID = -2251647664322031168L; @ExcelIgnore @Schema(description = "订单ID") private Long orderId; @ColumnWidth(30) @ExcelProperty("订单编号") @Schema(description = "订单编号") private String orderNumber; @ColumnWidth(30) @ExcelProperty("下单时间") @Schema(description = "下单时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date orderTime; @ColumnWidth(30) @ExcelProperty("支付时间") @Schema(description = "支付时间") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date payTime; @ColumnWidth(20) @ExcelProperty("订单金额") @Schema(description = "订单金额") private BigDecimal orderAmount; @ColumnWidth(20) @ExcelProperty("运费金额") @Schema(description = "运费金额") private BigDecimal freightAmount; @ColumnWidth(20) @ExcelProperty("红包金额") @Schema(description = "红包金额") private BigDecimal redpackAmount; @ColumnWidth(20) @ExcelProperty("退款金额") @Schema(description = "退款金额") private BigDecimal refundAmount; @ColumnWidth(20) @ExcelProperty("抵扣金额") @Schema(description = "抵扣金额") private BigDecimal totalDeductionAmount; @ColumnWidth(20) @ExcelProperty("使用积分") @Schema(description = "使用积分") private BigDecimal totalIntegral; @ColumnWidth(20) @ExcelProperty("积分结算金额") @Schema(description = "积分结算金额") private BigDecimal settlementPrice; @ColumnWidth(20) @ExcelProperty("兑换积分比例") @Schema(description = "兑换积分,比例 x:1") private String proportion; }
<script setup> import EventCreateForm from '../../components/Event/EventCreateForm.vue' import { ref, computed } from 'vue' import { useRouter } from 'vue-router' import { onBeforeMount } from '@vue/runtime-core' import ApiService from '../../composables/ApiService' import { parseJwt } from '../../utils' const router = useRouter() const events = ref([]) const categories = ref([]) const token = ref(localStorage.getItem('accessToken')) //get current Date const currentDateTime = computed(() => new Date()) //get all events const getEvents = async () => { const res = await ApiService.getAllEventsWithoutAuth() if (res.status === 200) { let data = await res.data events.value = data } else { console.log('error, cannot get data') } } //create new event const createEvent = async (newEvent, file) => { if (validateEmail(newEvent.bookingEmail)) { if (checkLengthNote(newEvent.eventNotes)) { if (checkLengthName(newEvent.bookingName)) { if ( validateEventStartTime( newEvent.eventStartTime, newEvent.eventCategoryId, newEvent.bookingName ) ) { let event = JSON.stringify({ eventStartTime: newEvent.eventStartTime, bookingName: newEvent.bookingName, bookingEmail: newEvent.bookingEmail, eventNotes: newEvent.eventNotes, eventCategoryId: newEvent.eventCategoryId, }) const blob = new Blob([event], { type: 'application/json' }) const formData = new FormData() if ( file !== null || file !== undefined || file !== '<input type="file" id="file">' ) { formData.append('event', blob) if (file == isNaN) { formData.delete(file) } else { formData.append('file', file) } } else { formData.append('event', blob) } const res = await fetch( `${import.meta.env.VITE_SERVER_URL}/api/events`, { method: 'POST', headers: { // 'content-type': 'application/json', Authorization: `Bearer ${token.value}`, }, body: formData, } ) if (res.status === 201) { let data = await res.json() alert('Created event successfully') router.push({ name: 'eventDetail', query: { id: data.id } }) } else if (res.status === 403) { alert(`Lecturer can't create event`) } } } } } } //get all categories const getCategories = async () => { const res = await ApiService.getCategories() if (res.status === 200) { let data = await res.data categories.value = data } else { console.log('Error, cannot get categories data') } } //validate email https://www.simplilearn.com/tutorials/javascript-tutorial/email-validation-in-javascript function validateEmail(email) { var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ if (email.length <= 100) { if (email.match(validRegex)) { return true } else { alert('Invalid email address!') } } else { alert('bookingEmail must have length 1-100') } } //validate eventStartTime (future and overlap) function validateEventStartTime(eventStartTime, categoryId, name) { if (eventStartTime < currentDateTime.value) { alert('Invalid Date! Date must be future') return false } else if (checkOverlap(eventStartTime, categoryId, name)) { alert('Invalid Date! Date is overlap') return false } else { return true } } //check overlap in event function checkOverlap(getStartTime, categoryId, name) { let status = false let b_start = getStartTime let b_duration = categories.value.filter((c) => c.id == categoryId)[0] .eventDuration let b_end = getEndDate(getStartTime, b_duration) events.value .filter( (e) => e.eventCategory.id == categoryId && e.bookingName != name && getDate(e.eventStartTime) == getDate(getStartTime) ) .forEach((e) => { let a_start = new Date(e.eventStartTime) let a_end = getEndDate(e.eventStartTime, e.eventDuration) if (dateRangeOverlaps(a_start, a_end, b_start, b_end)) { status = true } }) return status } //validate Note function checkLengthNote(note) { if (note == undefined) { note = '' } if (note.length > 500) { alert('eventNotes must have length between 0-500') } else { return true } } //validate Name function checkLengthName(name) { if (name.length > 100 || name.length < 1) { alert('bookingName must have length between 1-100') } else { return true } } //function getDate function getDate(date) { return new Date(date).toLocaleDateString() } //function plus minutes with duration function getEndDate(date, duration) { let dateFormat = new Date(date) return new Date(dateFormat.getTime() + duration * 60 * 1000) } function dateRangeOverlaps(a_start, a_end, b_start, b_end) { if (a_start <= b_start && b_start < a_end) return true // b starts in a if (a_start < b_end && b_end <= a_end) return true // b ends in a if (b_start <= a_start && a_end <= b_end) return true // a in b if (a_start <= b_start && b_end <= a_end) return true // b in a if (b_start <= a_start && b_end > a_start) return true // a starts in b return false } onBeforeMount(async () => { await getEvents() await getCategories() }) </script> <template> <div> <div class="text-center rounded-lg p-100 justify-center items-center max-w-6xl mx-auto sm:px-6 lg:px-4 py-10 font-bold text-4xl md:text-4xl lg:text-5xl font-heading text-color-500" > <div class="bg-blue-600 text-white rounded-xl py-7 shadow-lg w-full max-w-xl mx-auto px-3 md:mb-0" > Create Event </div> </div> <EventCreateForm :categories="categories" :event="events" @createEvent="createEvent" /> </div> </template> <style></style>
import React, { useState } from 'react' import './News.css' import NewsCard from './NewsCard/NewsCard' import newsDatas from './newsData'; import { Swiper, SwiperSlide } from "swiper/react"; // Import Swiper styles import "swiper/css"; import "swiper/css/navigation"; // import required modules import { Navigation } from "swiper"; function News() { const [newsInfos, setNewsInfos] = useState(newsDatas) return ( <div className="news"> <div className="news-body container"> <div className="news-title"> <h5>بلاگ هتل</h5> <h3>اخبار ما</h3> </div> <div className="news-boxes"> <Swiper slidesPerView={1} spaceBetween={30} slidesPerGroup={3} loop={true} loopFillGroupWithBlank={true} navigation={true} modules={[Navigation]} className="mySwiper" breakpoints={{ 768: { slidesPerView: 1, spaceBetween: 20, }, 992: { slidesPerView: 2, spaceBetween: 40, }, 1024: { slidesPerView: 3, spaceBetween: 50, }, }} > { newsInfos.map(newsInfo => ( <SwiperSlide key={newsInfo.id}> <NewsCard {...newsInfo} key={newsInfo.id} /> </SwiperSlide> )) } </Swiper> </div> </div> </div> ) } export default News
clc, clearvars, close all % Read the features data data = readtable('Features.xlsx'); % Extract predictors and response variables predictors = data.Properties.VariableNames(1:end-1); X = data(:, predictors); response = data.Properties.VariableNames(end); Y = table2array(data(:, response)); % Shuffle the data rng(394) idx = randperm(size(data, 1)); X = X(idx, :); Y = Y(idx, :); % Set up holdout validation cvp = cvpartition(Y, 'Holdout', 0.3); % Partition the data X_train = X(cvp.training, :); Y_train = Y(cvp.training, :); X_test = X(cvp.test, :); Y_test = Y(cvp.test, :); % Create decision trees template template = templateTree('MaxNumSplits', length(Y)-1); % Fit k-fold ensemble of learners for classification k = 10; iterations = 100; model = fitcensemble(X_train, Y_train, ... 'Method', 'Bag', ..., 'Type', 'classification', ... 'NumLearningCycles', iterations, ... 'Learners', template, ... 'ClassNames', unique(Y), ... 'KFold', k); % Classification loss cost = kfoldLoss(model, 'Mode', 'cumulative'); % Plot the cumulative, 10-fold cross-validated, misclassification rate. figure; plot(cost) grid on xlabel('Learning cycle') ylabel('10-fold Misclassification rate') title(['Generalization error: ', num2str(cost(end))]) legend('Model performance') % Export trained model to local directory save('model.mat', 'model') % Make predictions Y_pred = predict(model.Trained{1}, X_test); % Compute model accuracy p = Y_pred == Y_test; accuracy = sum(p) / numel(p); % Plot confusion matrix figure; C = confusionchart(Y_test, Y_pred, ... 'RowSummary','row-normalized', ... 'ColumnSummary','column-normalized'); title({'Confusion matrix - Bagged Trees', ['Accuracy: ', num2str(accuracy*100), '%']})
import React, { useEffect } from 'react'; import { StyleSheet, useWindowDimensions, View } from 'react-native'; import Animated, { Easing, useAnimatedStyle, useDerivedValue, useSharedValue, withRepeat, withTiming, } from 'react-native-reanimated'; import { Defs, LinearGradient, Path, Rect, Stop, Svg } from 'react-native-svg'; import { useTheme } from '../../contexts/themeContext/ThemeContext'; const paddingLarge = 16; const paddingMedium = 12; const paddingSmall = 8; const styles = StyleSheet.create({ background: { height: 64, position: 'absolute', width: '100%', }, container: { borderBottomWidth: 1, flexDirection: 'row', }, }); export const Skeleton: React.FC = () => { const width = useWindowDimensions().width; const startOffset = useSharedValue(-width); const { theme: { channelListSkeleton: { animationTime = 1800, background, container, gradientStart, gradientStop, height = 64, maskFillColor, }, colors: { border, grey_gainsboro, white_snow }, }, } = useTheme(); useEffect(() => { startOffset.value = withRepeat( withTiming(width, { duration: animationTime, easing: Easing.linear, }), -1, ); }, []); const animatedStyle = useAnimatedStyle( () => ({ transform: [{ translateX: startOffset.value }], }), [], ); const d = useDerivedValue(() => { const useableHeight = height - paddingMedium * 2; const boneHeight = (useableHeight - 8) / 2; const boneRadius = boneHeight / 2; const circleRadius = useableHeight / 2; const avatarBoneWidth = circleRadius * 2 + paddingSmall * 2; const detailsBonesWidth = width - avatarBoneWidth; return `M0 0 h${width} v${height} h-${width}z M${paddingSmall} ${ height / 2 } a${circleRadius} ${circleRadius} 0 1 0 ${ circleRadius * 2 } 0 a${circleRadius} ${circleRadius} 0 1 0 -${circleRadius * 2} 0z M${ avatarBoneWidth + boneRadius } ${paddingMedium} a${boneRadius} ${boneRadius} 0 1 0 0 ${boneHeight}z M${ avatarBoneWidth - boneRadius + detailsBonesWidth * 0.25 } ${paddingMedium} h-${detailsBonesWidth * 0.25 - boneRadius * 2} v${boneHeight} h${ detailsBonesWidth * 0.25 - boneRadius * 2 }z M${avatarBoneWidth - boneRadius + detailsBonesWidth * 0.25} ${ paddingMedium + boneHeight } a${boneRadius} ${boneRadius} 0 1 0 0 -${boneHeight}z M${avatarBoneWidth + boneRadius} ${ paddingMedium + boneHeight + paddingSmall } a${boneRadius} ${boneRadius} 0 1 0 0 ${boneHeight}z M${ avatarBoneWidth + detailsBonesWidth * 0.8 - boneRadius } ${paddingMedium + boneHeight + paddingSmall} h-${ detailsBonesWidth * 0.8 - boneRadius * 2 } v${boneHeight} h${detailsBonesWidth * 0.8 - boneRadius * 2}z M${ avatarBoneWidth + detailsBonesWidth * 0.8 - boneRadius } ${height - paddingMedium} a${boneRadius} ${boneRadius} 0 1 0 0 -${boneHeight}z M${ avatarBoneWidth + detailsBonesWidth * 0.8 + boneRadius + paddingLarge } ${ paddingMedium + boneHeight + paddingSmall } a${boneRadius} ${boneRadius} 0 1 0 0 ${boneHeight}z M${width - paddingSmall - boneRadius} ${ paddingMedium + boneHeight + paddingSmall } h-${ width - paddingSmall - boneRadius - (avatarBoneWidth + detailsBonesWidth * 0.8 + boneRadius + paddingLarge) } v${boneHeight} h${ width - paddingSmall - boneRadius - (avatarBoneWidth + detailsBonesWidth * 0.8 + boneRadius + paddingLarge) }z M${width - paddingSmall * 2} ${ height - paddingMedium } a${boneRadius} ${boneRadius} 0 1 0 0 -${boneHeight}z`; }, []); return ( <View style={[styles.container, { borderBottomColor: border }, container]} testID='channel-preview-skeleton' > <View style={[styles.background, { backgroundColor: white_snow }, background]} /> <Animated.View style={[animatedStyle, styles.background]}> <Svg height={height} width={width}> <Rect fill='url(#gradient)' height={height} width={width} x={0} y={0} /> <Defs> <LinearGradient gradientUnits='userSpaceOnUse' id='gradient' x1={0} x2={width} y1={0} y2={0} > <Stop offset={1} stopColor={grey_gainsboro} {...gradientStart} /> <Stop offset={0.5} stopColor={grey_gainsboro} {...gradientStop} /> <Stop offset={0} stopColor={grey_gainsboro} {...gradientStart} /> </LinearGradient> </Defs> </Svg> </Animated.View> <Svg height={height} width={width}> <Path d={d.value} fill={maskFillColor || white_snow} /> </Svg> </View> ); }; Skeleton.displayName = 'Skeleton{channelListSkeleton}';
using Discord; using Discord.Commands; using Discord.Rest; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using PKHeX.Core; using SysBot.Base; using System; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using static Discord.GatewayIntents; namespace SysBot.Pokemon.Discord { public static class SysCordSettings { public static DiscordManager Manager { get; internal set; } = default!; public static DiscordSettings Settings => Manager.Config; public static PokeRaidHubConfig HubConfig { get; internal set; } = default!; } public sealed class SysCord<T> where T : PKM, new() { public static PokeBotRunner<T> Runner { get; private set; } = default!; public static RestApplication App { get; private set; } = default!; public static SysCord<T> Instance { get; private set; } public static ReactionService ReactionService { get; private set; } private readonly DiscordSocketClient _client; private readonly DiscordManager Manager; public readonly PokeRaidHub<T> Hub; // Keep the CommandService and DI container around for use with commands. // These two types require you install the Discord.Net.Commands package. private readonly CommandService _commands; private readonly IServiceProvider _services; // Track loading of Echo/Logging channels so they aren't loaded multiple times. private bool MessageChannelsLoaded { get; set; } public SysCord(PokeBotRunner<T> runner) { Runner = runner; Hub = runner.Hub; Manager = new DiscordManager(Hub.Config.Discord); SysCordSettings.Manager = Manager; SysCordSettings.HubConfig = Hub.Config; _client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Info, GatewayIntents = GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.DirectMessages | GatewayIntents.GuildMembers | GatewayIntents.MessageContent | GatewayIntents.GuildMessageReactions, MessageCacheSize = 100, AlwaysDownloadUsers = true, }); _commands = new CommandService(new CommandServiceConfig { // Again, log level: LogLevel = LogSeverity.Info, // This makes commands get run on the task thread pool instead on the websocket read thread. // This ensures long running logic can't block the websocket connection. DefaultRunMode = Hub.Config.Discord.AsyncCommands ? RunMode.Async : RunMode.Sync, // There's a few more properties you can set, // for example, case-insensitive commands. CaseSensitiveCommands = false, }); // Subscribe the logging handler to both the client and the CommandService. _client.Log += Log; _commands.Log += Log; // Setup your DI container. _services = ConfigureServices(); Instance = this; ReactionService = new ReactionService(_client); } public DiscordSocketClient GetClient() { return _client; } // If any services require the client, or the CommandService, or something else you keep on hand, // pass them as parameters into this method as needed. // If this method is getting pretty long, you can separate it out into another file using partials. private static IServiceProvider ConfigureServices() { var map = new ServiceCollection();//.AddSingleton(new SomeServiceClass()); // When all your required services are in the collection, build the container. // Tip: There's an overload taking in a 'validateScopes' bool to make sure // you haven't made any mistakes in your dependency graph. return map.BuildServiceProvider(); } // Example of a logging handler. This can be reused by add-ons // that ask for a Func<LogMessage, Task>. private static Task Log(LogMessage msg) { var text = $"[{msg.Severity,8}] {msg.Source}: {msg.Message} {msg.Exception}"; Console.ForegroundColor = GetTextColor(msg.Severity); Console.WriteLine($"{DateTime.Now,-19} {text}"); Console.ResetColor(); LogUtil.LogText($"SysCord: {text}"); return Task.CompletedTask; } private static ConsoleColor GetTextColor(LogSeverity sv) => sv switch { LogSeverity.Critical => ConsoleColor.Red, LogSeverity.Error => ConsoleColor.Red, LogSeverity.Warning => ConsoleColor.Yellow, LogSeverity.Info => ConsoleColor.White, LogSeverity.Verbose => ConsoleColor.DarkGray, LogSeverity.Debug => ConsoleColor.DarkGray, _ => Console.ForegroundColor, }; public async Task MainAsync(string apiToken, CancellationToken token) { // Centralize the logic for commands into a separate method. await InitCommands().ConfigureAwait(false); // Login and connect. await _client.LoginAsync(TokenType.Bot, apiToken).ConfigureAwait(false); await _client.StartAsync().ConfigureAwait(false); var app = await _client.GetApplicationInfoAsync().ConfigureAwait(false); Manager.Owner = app.Owner.Id; App = app; // Wait infinitely so your bot actually stays connected. await MonitorStatusAsync(token).ConfigureAwait(false); } public async Task InitCommands() { var assembly = Assembly.GetExecutingAssembly(); await _commands.AddModulesAsync(assembly, _services).ConfigureAwait(false); var genericTypes = assembly.DefinedTypes.Where(z => z.IsSubclassOf(typeof(ModuleBase<SocketCommandContext>)) && z.IsGenericType); foreach (var t in genericTypes) { var genModule = t.MakeGenericType(typeof(T)); await _commands.AddModuleAsync(genModule, _services).ConfigureAwait(false); } var modules = _commands.Modules.ToList(); foreach (var module in modules) { var name = module.Name; name = name.Replace("Module", ""); var gen = name.IndexOf('`'); if (gen != -1) name = name[..gen]; } // Subscribe a handler to see if a message invokes a command. _client.Ready += LoadLoggingAndEcho; _client.MessageReceived += HandleMessageAsync; _client.ReactionAdded += ExtraCommandUtil<T>.HandleReactionAsync; } private async Task HandleMessageAsync(SocketMessage arg) { // Bail out if it's a System Message. if (arg is not SocketUserMessage msg) return; // We don't want the bot to respond to itself or other bots. if (msg.Author.Id == _client.CurrentUser.Id || msg.Author.IsBot) return; // Create a number to track where the prefix ends and the command begins int pos = 0; if (msg.HasStringPrefix(Hub.Config.Discord.CommandPrefix, ref pos)) { bool handled = await TryHandleCommandAsync(msg, pos).ConfigureAwait(false); if (handled) return; } } private async Task<bool> TryHandleCommandAsync(SocketUserMessage msg, int pos) { // Create a Command Context. var context = new SocketCommandContext(_client, msg); // Check Permission var mgr = Manager; if (!mgr.CanUseCommandUser(msg.Author.Id)) { await msg.Channel.SendMessageAsync("You are not permitted to use this command.").ConfigureAwait(false); return true; } if (!mgr.CanUseCommandChannel(msg.Channel.Id) && msg.Author.Id != mgr.Owner) { await msg.Channel.SendMessageAsync("You can't use that command here.").ConfigureAwait(false); return true; } // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully). var guild = msg.Channel is SocketGuildChannel g ? g.Guild.Name : "Unknown Guild"; await Log(new LogMessage(LogSeverity.Info, "Command", $"Executing command from {guild}#{msg.Channel.Name}:@{msg.Author.Username}. Content: {msg}")).ConfigureAwait(false); var result = await _commands.ExecuteAsync(context, pos, _services).ConfigureAwait(false); if (result.Error == CommandError.UnknownCommand) return false; // Uncomment the following lines if you want the bot // to send a message if it failed. // This does not catch errors from commands with 'RunMode.Async', // subscribe a handler for '_commands.CommandExecuted' to see those. if (!result.IsSuccess) await msg.Channel.SendMessageAsync(result.ErrorReason).ConfigureAwait(false); return true; } private async Task MonitorStatusAsync(CancellationToken token) { UserStatus state = UserStatus.Idle; while (!token.IsCancellationRequested) { var active = UserStatus.Online; if (active != state) { state = active; await _client.SetStatusAsync(state).ConfigureAwait(false); } await Task.Delay(20_000, token).ConfigureAwait(false); } } private async Task LoadLoggingAndEcho() { if (MessageChannelsLoaded) return; // Restore Echoes EchoModule.RestoreChannels(_client, Hub.Config.Discord); // Restore Logging LogModule.RestoreLogging(_client, Hub.Config.Discord); // Don't let it load more than once in case of Discord hiccups. await Log(new LogMessage(LogSeverity.Info, "LoadLoggingAndEcho()", "Logging and Echo channels loaded!")).ConfigureAwait(false); MessageChannelsLoaded = true; var game = Hub.Config.Discord.BotGameStatus; if (!string.IsNullOrWhiteSpace(game)) await _client.SetGameAsync(game).ConfigureAwait(false); } } }
import { Injectable, Inject} from '@angular/core'; import { DOCUMENT } from '@angular/common'; interface Scripts { name: string; src: string; type : string } export const ScriptStore: Scripts[] = [ { name: 'Jvectorjs', src: 'assets/js/jquery-jvectormap-2.0.5.min.js', type: 'javascript' }, { name: 'dtmin', src: 'assets/covid/assets/js/datatables.min.js', type: 'javascript' }, { name: 'dtreorder', src: 'assets/js/dataTables.rowReorder.min.js', type: 'javascript' }, { name: 'dteresponsive', src: 'assets/js/dataTables.responsive.min.js', type: 'javascript' }, { name: 'World', src: 'assets/js/jquery-jvectormap-world-mill.js', type: 'javascript' }, { name: 'dtmincss', src: 'assets/covid/assets/css/datatables.min.css', type: 'css' }, { name: 'jqdtmincss', src: 'assets/css/jquery.dataTables.min.css', type: 'css' }, { name: 'dtreordercss', src: 'assets/css/rowReorder.dataTables.min.css', type: 'css' }, { name: 'dteresponsivecss', src: 'assets/css/responsive.dataTables.min.css', type: 'css' }, { name: 'Jvectorjscss', src: 'assets/css/jquery-jvectormap-2.0.5.css', type: 'css' }, { name: 'India', src: 'assets/js/India.js', type: 'javascript' }, { name: 'US', src: 'assets/js/US.js', type: 'javascript' }, { name: 'Australia', src: 'assets/js/Australia.js', type: 'javascript' }, { name: 'Canada', src: 'assets/js/Canada.js', type: 'javascript' }, { name: 'China', src: 'assets/js/China.js', type: 'javascript' }, { name: 'Colombia', src: 'assets/js/Colombia.js', type: 'javascript' }, { name: 'Germany', src: 'assets/js/Germany.js', type: 'javascript' }, { name: 'Italy', src: 'assets/js/Italy.js', type: 'javascript' } ]; @Injectable({ providedIn: 'root' }) export class ScriptService { private scripts: any = {}; constructor(@Inject(DOCUMENT) private dom : any) { ScriptStore.forEach((script: any) => { let element = ""; let srcType = ""; if(script.type === "javascript"){ element = "script"; srcType = "src"; } else { element = "link"; srcType = "href"; } this.scripts[script.name] = { loaded: false, src: script.src, type: script.type, element: element, srcType: srcType }; }); } load(...scripts: string[]) { const promises: any[] = []; scripts.forEach((script) => promises.push(this.loadScript(script))); return Promise.all(promises); } loadScript(name: string) { return new Promise((resolve, reject) => { // resolve if already loaded if (this.scripts[name].loaded) { resolve({ script: name, loaded: true, status: 'Already Loaded' }); } else { // load script const script = document.createElement(this.scripts[name].element); script.type = 'text/'+this.scripts[name].type; script[this.scripts[name].srcType] = this.scripts[name].src; script.rel="stylesheet"; script.onload = () => { this.scripts[name].loaded = true; resolve({ script: name, loaded: true, status: 'Loaded' }); }; script.onerror = (error: any) => resolve({ script: name, loaded: false, status: 'Loaded' }); document.getElementsByTagName('head')[0].appendChild(script); } }); } // loadScript(name: string) { // return new Promise((resolve, reject) => { // // resolve if already loaded // if (this.scripts[name].loaded) { // resolve({ script: name, loaded: true, status: 'Already Loaded' }); // } else { // // load script // const script = document.createElement('script'); // script.type = 'text/javascript'; // script.src = this.scripts[name].src; // script.onload = () => { // this.scripts[name].loaded = true; // resolve({ script: name, loaded: true, status: 'Loaded' }); // }; // script.onerror = (error: any) => resolve({ script: name, loaded: false, status: 'Loaded' }); // document.getElementsByTagName('head')[0].appendChild(script); // } // }); // } createCanonicalURL(url?:string) { let canURL = url == undefined ? this.dom.URL : url; let canLink = this.dom.querySelector("link[rel='canonical']"); if(canLink){ canLink.setAttribute('href', canURL); } else { let link: HTMLLinkElement = this.dom.createElement('link'); link.setAttribute('rel', 'canonical'); this.dom.head.appendChild(link); link.setAttribute('href', canURL); } } createMetaTag(name:any,content:any){ let metaLink = this.dom.querySelector("meta[name='"+name+"']"); if(metaLink){ metaLink.setAttribute('content', content); } else { let link: HTMLLinkElement = this.dom.createElement('meta'); link.setAttribute('name', name); this.dom.head.appendChild(link); link.setAttribute('content', content); } return this.dom.querySelector("meta[name='"+name+"']").getAttribute('content'); } }
import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import * as moment from 'moment'; import { SERVER_API_URL } from 'app/app.constants'; import { createRequestOption } from 'app/shared/util/request-util'; import { IDemande } from 'app/shared/model/demande.model'; type EntityResponseType = HttpResponse<IDemande>; type EntityArrayResponseType = HttpResponse<IDemande[]>; @Injectable({ providedIn: 'root' }) export class DemandeService { public resourceUrl = SERVER_API_URL + 'api/demandes'; constructor(protected http: HttpClient) {} create(demande: IDemande): Observable<EntityResponseType> { const copy = this.convertDateFromClient(demande); return this.http .post<IDemande>(this.resourceUrl, copy, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } update(demande: IDemande): Observable<EntityResponseType> { const copy = this.convertDateFromClient(demande); return this.http .put<IDemande>(this.resourceUrl, copy, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } find(id: number): Observable<EntityResponseType> { return this.http .get<IDemande>(`${this.resourceUrl}/${id}`, { observe: 'response' }) .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } query(req?: any): Observable<EntityArrayResponseType> { const options = createRequestOption(req); return this.http .get<IDemande[]>(this.resourceUrl, { params: options, observe: 'response' }) .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res))); } delete(id: number): Observable<HttpResponse<{}>> { return this.http.delete(`${this.resourceUrl}/${id}`, { observe: 'response' }); } protected convertDateFromClient(demande: IDemande): IDemande { const copy: IDemande = Object.assign({}, demande, { dateInspection: demande.dateInspection && demande.dateInspection.isValid() ? demande.dateInspection.toJSON() : undefined, }); return copy; } protected convertDateFromServer(res: EntityResponseType): EntityResponseType { if (res.body) { res.body.dateInspection = res.body.dateInspection ? moment(res.body.dateInspection) : undefined; } return res; } protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType { if (res.body) { res.body.forEach((demande: IDemande) => { demande.dateInspection = demande.dateInspection ? moment(demande.dateInspection) : undefined; }); } return res; } }
# ⚛️React x 🔥Firebase Workshop > A workshop to explain how to go about integrating Firebase into your React application. We'll be implementing Authentication, Firestore, Remote Config, Cloud Functions and Hosting. ## Table of Contents * [🎯 Goals](#goals) * [⚡ Get Started](#get-started) * [📚 Projects](#projects) * [🤖 Deployments](#deployments) * [🚀 Libraries Used](#libraries-used) ## 🎯 Goals - Learn how we can use Firebase Authentication to manage our users - Learn how we can use Firebase Cloud Firestore to store data and receive it in real time - Learn how we can use Firebase Remote Config to receive configuration variables from the cloud - Learn how we can use Cloud Functions to handle further business operations ## ⚡ Get Started ### Clone Repo ``` # clone the repo $ git clone git@github.com:askharley/react-x-firebase-workshop.git # navigate into the repo root $ cd react-x-firebase-workshop # go into the start project $ cd start ``` ### Environmental Variables Add your Firebase project's web config to a `.env` file in the root of the application. ```js REACT_APP_API_KEY= REACT_APP_AUTH_DOMAIN= REACT_APP_DATABASE_URL= REACT_APP_PROJECT_ID= REACT_APP_STORAGE_BUCKET= REACT_APP_MESSAGING_SENDER_ID= REACT_APP_APP_ID= ``` ### Install ``` # install the dependencies $ npm i # start the application $ npm start ``` ## 📚 Projects * [start](https://github.com/askharley/react-x-firebase-workshop/tree/main/start) - a starting place to begin your work * [final](https://github.com/askharley/react-x-firebase-workshop/tree/main/final) - an example of what a final implementation using Firebase would look like ## 🤖 Deployments * [start](https://react-x-firebase-workshop-start.netlify.app/) - [![Netlify Status](https://api.netlify.com/api/v1/badges/71a180da-fc6f-414d-8cb8-201cb7d9e161/deploy-status)](https://app.netlify.com/sites/react-x-firebase-workshop-start/deploys) * [final](https://react-x-firebase-workshop-final.netlify.app/) - [![Netlify Status](https://api.netlify.com/api/v1/badges/71a180da-fc6f-414d-8cb8-201cb7d9e161/deploy-status)](https://app.netlify.com/sites/react-x-firebase-workshop-final/deploys) ## 🚀 Libraries Used * [AntD](https://ant.design/components) - Components * [Firebase](https://www.npmjs.com/package/firebase) - Our complete backend-as-a-service implementation * [dayjs](https://www.npmjs.com/package/dayjs) - Helpers methods for some date utils * [prop-types](https://www.npmjs.com/package/prop-types) - Runtime type checking for React props * [use-ekko](https://github.com/askharley/use-ekko) - Persist state to the local storage
import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Experience } from 'src/app/models/experience'; import { CompanyService } from 'src/app/service/company.service'; import { Company } from 'src/app/models/company'; @Component({ selector: 'app-form-update-experience', templateUrl: './form-update-experience.component.html', styleUrls: ['./form-update-experience.component.css'], }) export class FormUpdateExperienceComponent implements OnInit { @Output() onUpdateExperience: EventEmitter<Experience> = new EventEmitter(); @Input() currentExperienceForm: any; companyList: Company[] = []; showAddCompany: boolean = false; form: FormGroup = this.formBuilder.group({ name: ['', [Validators.required]], description: [ '', [ Validators.required, Validators.minLength(10), Validators.maxLength(250), ], ], company: [null, [Validators.required]], start_date: ['', [Validators.required]], end_date: ['', []], is_current: [false, []], }); constructor( private formBuilder: FormBuilder, private companyService: CompanyService ) {} ngOnInit(): void { this.getCompanies(); this.updateFormValues(); } onSubmit(event: Event) { event.preventDefault; if (this.form.valid) { let { name, company, description, start_date, end_date, is_current } = this.form.value; let id = this.currentExperienceForm.id; const updatedExperience = { id, name, company, description, start_date, end_date, is_current, }; this.onUpdateExperience.emit(updatedExperience); this.form.reset(); return; } else { this.form.markAllAsTouched(); } } toggleAddCompany() { this.showAddCompany = !this.showAddCompany; this.getCompanies(); } toggleIsCurrentJob() { if (this.form.controls['end_date'].status === 'DISABLED') { this.form.controls['end_date'].enable(); return; } else { this.form.controls['end_date'].reset(); this.form.controls['end_date'].disable(); this.form.controls['is_current'].setValue(true); return; } } updateFormValues() { let { name, description, company, start_date, end_date } = this.currentExperienceForm; let company_id = company.id; this.form.patchValue({ name: name, description: description, company: company_id, start_date: start_date, end_date: end_date, }); } /* Services */ getCompanies() { this.companyService.getCompanies().subscribe({ next: (data) => { this.companyList = data; }, }); } get Name() { return this.form.get('name'); } get Description() { return this.form.get('description'); } get Company() { return this.form.get('company'); } get Start_date() { return this.form.get('start_date'); } get End_date() { return this.form.get('end_date'); } get Is_current() { return this.form.get('is_current'); } }
/* * Copyright (C) 2023 Huawei Device Co., Ltd. * 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. */ /** * @file * @kit NetworkKit */ import type { AsyncCallback, Callback } from './@ohos.base'; import type connection from './@ohos.net.connection'; import type _AbilityContext from './application/UIAbilityContext'; /** * Provides VPN related interfaces. * @namespace vpn * @syscap SystemCapability.Communication.NetManager.Vpn * @since 10 */ declare namespace vpn { /** * Get network link information. * @syscap SystemCapability.Communication.NetManager.Core * @since 10 */ export type LinkAddress = connection.LinkAddress; /** * Get network route information. * @syscap SystemCapability.Communication.NetManager.Core * @since 10 */ export type RouteInfo = connection.RouteInfo; /** * The context of an ability. It allows access to ability-specific resources. * @syscap SystemCapability.Ability.AbilityRuntime.Core * @since 10 */ export type AbilityContext = _AbilityContext; /** * Create a VPN connection using the AbilityContext. * @param { AbilityContext } context - Indicates the context of application or capability. * @returns { VpnConnection } the VpnConnection of the construct VpnConnection instance. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ function createVpnConnection(context: AbilityContext): VpnConnection; /** * Defines a VPN connection. * @interface VpnConnection * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ export interface VpnConnection { /** * Create a VPN network using the VpnConfig. * @permission ohos.permission.MANAGE_VPN * @param { VpnConfig } config - Indicates the {@link VpnConfig} configuration of the VPN network. * @param { AsyncCallback<number> } callback - The callback is used to return file descriptor of VPN interface. * @throws { BusinessError } 201 - Permission denied. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @throws { BusinessError } 2200001 - Invalid parameter value. * @throws { BusinessError } 2200002 - Operation failed. Cannot connect to service. * @throws { BusinessError } 2200003 - System internal error. * @throws { BusinessError } 2203001 - VPN creation denied. Check the user type. * @throws { BusinessError } 2203002 - VPN already exists. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ setUp(config: VpnConfig, callback: AsyncCallback<number>): void; /** * Create a VPN network using the VpnConfig. * @permission ohos.permission.MANAGE_VPN * @param { VpnConfig } config - Indicates the {@link VpnConfig} configuration of the VPN network. * @returns { Promise<number> } The promise returns file descriptor of VPN interface. * @throws { BusinessError } 201 - Permission denied. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @throws { BusinessError } 2200001 - Invalid parameter value. * @throws { BusinessError } 2200002 - Operation failed. Cannot connect to service. * @throws { BusinessError } 2200003 - System internal error. * @throws { BusinessError } 2203001 - VPN creation denied. Check the user type. * @throws { BusinessError } 2203002 - VPN already exists. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ setUp(config: VpnConfig): Promise<number>; /** * Protect a socket from VPN connections. After protecting, data sent through this socket will go directly to the * underlying network so its traffic will not be forwarded through the VPN. * @permission ohos.permission.MANAGE_VPN * @param { number } socketFd - File descriptor of socket, this socket from @ohos.net.socket. * @param { AsyncCallback<void> } callback - The callback of protect. * @throws { BusinessError } 201 - Permission denied. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @throws { BusinessError } 2200001 - Invalid parameter value. * @throws { BusinessError } 2200002 - Operation failed. Cannot connect to service. * @throws { BusinessError } 2200003 - System internal error. * @throws { BusinessError } 2203004 - Invalid socket file descriptor. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ protect(socketFd: number, callback: AsyncCallback<void>): void; /** * Protect a socket from VPN connections. After protecting, data sent through this socket will go directly to the * underlying network so its traffic will not be forwarded through the VPN. * @permission ohos.permission.MANAGE_VPN * @param { number } socketFd - File descriptor of socket, this socket from @ohos.net.socket. * @returns { Promise<void> } The promise returned by the function. * @throws { BusinessError } 201 - Permission denied. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @throws { BusinessError } 2200001 - Invalid parameter value. * @throws { BusinessError } 2200002 - Operation failed. Cannot connect to service. * @throws { BusinessError } 2200003 - System internal error. * @throws { BusinessError } 2203004 - Invalid socket file descriptor. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ protect(socketFd: number): Promise<void>; /** * Destroy the VPN network. * @permission ohos.permission.MANAGE_VPN * @param { AsyncCallback<void> } callback - The callback of destroy. * @throws { BusinessError } 201 - Permission denied. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @throws { BusinessError } 2200002 - Operation failed. Cannot connect to service. * @throws { BusinessError } 2200003 - System internal error. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ destroy(callback: AsyncCallback<void>): void; /** * Destroy the VPN network. * @permission ohos.permission.MANAGE_VPN * @returns { Promise<void> } The promise returned by the function. * @throws { BusinessError } 201 - Permission denied. * @throws { BusinessError } 202 - Non-system applications use system APIs. * @throws { BusinessError } 401 - Parameter error. * @throws { BusinessError } 2200002 - Operation failed. Cannot connect to service. * @throws { BusinessError } 2200003 - System internal error. * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ destroy(): Promise<void>; } /** * Define configuration of the VPN network. * @interface VpnConfig * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ export interface VpnConfig { /** * The array of addresses for VPN interface. * @type {Array<LinkAddress>} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ addresses: Array<LinkAddress>; /** * The array of routes for VPN interface. * @type {?Array<RouteInfo>} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ routes?: Array<RouteInfo>; /** * The array of DNS servers for the VPN network. * @type {?Array<string>} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ dnsAddresses?: Array<string>; /** * The array of search domains for the DNS resolver. * @type {?Array<string>} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ searchDomains?: Array<string>; /** * The maximum transmission unit (MTU) for the VPN interface. * @type {?number} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ mtu?: number; /** * Whether ipv4 is supported. The default value is true. * @type {?boolean} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ isIPv4Accepted?: boolean; /** * Whether ipv6 is supported. The default value is false. * @type {?boolean} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ isIPv6Accepted?: boolean; /** * Whether to use the built-in VPN. The default value is false. * @type {?boolean} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ isLegacy?: boolean; /** * Whether the VPN interface's file descriptor is in blocking/non-blocking mode. The default value is false. * @type {?boolean} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ isBlocking?: boolean; /** * The array of trustlist for the VPN network. The string indicates package name. * @type {?Array<string>} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ trustedApplications?: Array<string>; /** * The array of blocklist for the VPN network. The string indicates package name. * @type {?Array<string>} * @syscap SystemCapability.Communication.NetManager.Vpn * @systemapi Hide this for inner system use. * @since 10 */ blockedApplications?: Array<string>; } } export default vpn;
package com.yuan.guli.guliproduct.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import com.yuan.common.valid.AddGroup; import com.yuan.common.valid.ListValue; import com.yuan.common.valid.UpdateGroup; import com.yuan.common.valid.UpdateStatusGroup; import lombok.Data; import org.hibernate.validator.constraints.URL; import javax.validation.constraints.*; /** * 品牌 * * @author lzy * @email 1716827691@qq.com * @date 2022-03-07 21:33:41 */ @Data @TableName("pms_brand") public class BrandEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 品牌id */ @TableId @NotNull(message = "id无法被指定",groups = {UpdateGroup.class}) @Null(message = "id已存在",groups = {AddGroup.class}) private Long brandId; /** * 品牌名 * @NotNull 不能为空 * @NotEntity 不能为null,且不能为空串 * @NotBlank 不能为null,且不能为空串 */ @NotBlank(message = "品牌名称不能为空",groups = {AddGroup.class,UpdateGroup.class}) private String name; /** * 品牌logo地址 */ @URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class, UpdateGroup.class}) //@NotEmpty(message = "地址不能为空",groups = {AddGroup.class}) private String logo; /** * 介绍 */ private String descript; /** * 显示状态[0-不显示;1-显示] */ @NotNull(groups = {AddGroup.class,UpdateStatusGroup.class}) @ListValue(values = {0,1},message = "数值范围不正确",groups = {AddGroup.class,UpdateStatusGroup.class}) private Integer showStatus; /** * 检索首字母 */ @Size(max = 1,message = "检索字母只能是一个数量的字母",groups = {AddGroup.class,UpdateGroup.class}) //设置最大长度,最小长度默认为0 @Pattern(regexp = "^[a-zA-Z]$",message = "检索字母必须为英文",groups = {AddGroup.class,UpdateGroup.class}) //自定义规则注解,传入正则表达式 //@NotBlank(message = "不能为空") private String firstLetter; /** * 排序 */ @Min(value = 0 ,message = "最小排序只能为大于等于0",groups = {AddGroup.class,UpdateGroup.class}) //最小排序设置为0 //@NotNull(message = "不能为空",groups = {AddGroup.class,UpdateGroup.class}) private Integer sort; }
import express, { Request, Response } from 'express'; import { body } from 'express-validator'; import { BadRequestError, validateRequest } from '@ms-ticketing/common'; import { User } from '../models/user'; import { Password } from '../services/password'; import jwt from 'jsonwebtoken'; const router = express.Router(); router.post('/api/users/signin', [ body('email') .isEmail() .withMessage('Email Must be Valid!'), body('password') .trim() .notEmpty() .withMessage('You must provide a password.') ], validateRequest, async (req: Request, res: Response) => { const { email, password } = req.body; const existingUser = await User.findOne({ email }); if(!existingUser) { throw new BadRequestError('Invalid credentials!'); } const passwordMatch = await Password.compare(existingUser.password, password); if(!passwordMatch) { throw new BadRequestError('Invalid credentials!'); } // Generate JWT const userJwt = jwt.sign({ id: existingUser.id, email: existingUser.email, }, process.env.JWT_KEY! // Here ! tells to typescript compiler not to worry about this value being null or undefined. ); // Store it on session object // req.session.jwt = userJwt; // We can't do live above as Typescript definition file for cookie-session // does not have information req.session = { jwt: userJwt }; res.status(200).send(existingUser); }); export { router as signinRouter };
import React from 'react' import { useState } from 'react'; import Button from 'react-bootstrap/Button'; import Form from 'react-bootstrap/Form'; import { db } from '../firebase'; import {addDoc, collection, updateDoc,query, where,getDocs,documentId} from 'firebase/firestore'; function UpdateNotifications() { const [number, setNumber] = useState(''); const [subject, setSubject] = useState(''); const [content, setContent] = useState(''); const today = new Date(); const day = today.getDate(); const month = today.getMonth() + 1; const year = today.getFullYear(); const addNotification = async (e) => { try { const docRef =await addDoc(collection(db, "Notifications"), { number:number, subject: subject, content: content, date:`${day}-${month}-${year}`, }); console.log('Document written with ID: ', docRef.id); alert('Document added to Notificatons'); } catch (e) { console.error('Error adding document: ', e); alert('Error adding document: ', e); } }; return ( <div className='body' > <div className='containerStaff'> <Form> <Form.Group className='mb-1' controlId='formBasicEmail'> <Form.Control size='sm' type='text' placeholder='Notification No' value={number} onChange={(e) => setNumber(e.target.value)} /> </Form.Group> <Form.Group className='mb-1' controlId='formBasicPassword'> <Form.Control size='sm' type='text' placeholder='Subject' value={subject} onChange={(e) => setSubject(e.target.value)} /> </Form.Group> <Form.Group className='mb-1' controlId='formBasicPassword'> <Form.Control size='sm' type='text' placeholder='Write Content' value={content} onChange={(e) => setContent(e.target.value)} /> </Form.Group> <a onClick={addNotification} > <Button size='sm' variant='primary' > Submit </Button> </a> </Form> </div> </div> ) } export default UpdateNotifications
import React, { useState } from "react"; import { Redirect, Route, Switch } from "react-router-dom"; import Customers from "./components/customers"; import Rentals from "./components/rentals"; import notFound from "./components/notFound"; import NavBar from "./common/navBar"; import Movies from "./components/movies"; import "./App.css"; import MovieForm from "./components/movieForm"; import LoginForm from "./components/loginForm"; function App(props) { return ( <React.Fragment> <NavBar /> <main className="container"> <Switch> <Route path="/movies/:id" component={MovieForm} /> <Route path="/movies" component={Movies} /> <Route path="/customers" component={Customers} /> <Route path="/rentals" component={Rentals} /> <Route path="/login-form" component={LoginForm} /> <Route path="/not-found" component={notFound} /> <Redirect from="/" exact to="/movies"></Redirect> <Redirect to="/not-found"></Redirect> </Switch> </main> </React.Fragment> ); } export default App;
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="../global.css"> <title>Modelo de Objeto de Documento (DOM)</title> </head> <body> <h1>Modelo de Objeto de Documento (DOM)</h1> <ul class="assuntos"> <li>Objeto window</li> <li>Objeto document</li> <li>Manipulação de elementos HTML</li> <li>Manipulação de estilos CSS</li> <li>Exemplo Lista</li> <li>Exemplo Calculadora</li> </ul> <h2>Visualização dos testes</h2> <p>Acesse as Ferramentas de Desenvolvedor ou Desenvolvimento (F12)<br> Guia console, para vizualizar as saídas com a função console.log()</p> <h2>Materiais de apoio</h2> <a href="https://developer.mozilla.org/pt-BR/docs/Web/API/Document_Object_Model/Introduction" target="_blank">Introdução ao DOM</a><br> <a href="https://developer.mozilla.org/pt-BR/docs/Web/API/Window" target="_blank">Window</a><br> <a href="https://developer.mozilla.org/pt-BR/docs/Web/API/Document" target="_blank">Document</a><br> <h2 id="exemplos">Integração do JS com HTML e CSS</h2> <fieldset class="conteiner-exemplos"> <div class="conteiner-mensagem"> <h2 id="exemplo-lista">Lista</h2> <label for="nome" class="item label">Nome</label> <input id="nome" class="item campo" type="text" /> <button id="btn-mensagem" class="item botao">Enviar</button> <label for="mensagem" class="item label">Mensagem</label> <p id="mensagem" class="item saida"></p> <ol id="lista" class="item"></ol> </div> <div class="conteiner-calculadora"> <h2 id="exemplo-calculadora">Calculadora</h2> <label for="n1" class="item label">Primeiro número</label> <input id="n1" class="item campo" type="text" /> <label for="n2" class="item label">Segundo número</label> <input id="n2" class="item campo" type="text" /> <p class="label">Operações</p> <div> <input type="radio" id="somar" name="operacoes" value="somar" checked/> <label for="somar">Somar</label> </div> <div> <input type="radio" id="subtrair" name="operacoes" value="subtrair" /> <label for="subtrair">Subtrair</label> </div> <div> <input type="radio" id="multiplicar" name="operacoes" value="multiplicar" /> <label for="multiplicar">Multiplicar</label> </div> <div> <input type="radio" id="dividir" name="operacoes" value="dividir" /> <label for="dividir">Dividir</label> </div> <button id="btn-calcular" class="item botao">Calcular</button> <button id="btn-limpar" class="item botao">Limpar</button> <label for="resultado" class="item label">Resultado</label> <p id="resultado" class="item saida"></p> </div> </fieldset> <h2>Exercícios</h2> <a href="./controleEscolar.html" target="_blank">Controle escolar</a><br> <a href="/" target="_blank">Lista 07</a><br> <a href="../index.html"> <div class="botao"> <p>Voltar</p> </div> </a> <p class="rodape">Prof. Ralfe Della Croce Filho</p> <script src="dom.js"></script> </body> </html>
import { NextFunction, Request, Response } from "express"; import Errors from "../errors/errors"; import Card from "../models/card"; import { AuthRequest } from '../middlewares/auth'; import { ERROR } from '../constants/errors'; export const getCards = (req: Request, res: Response, next: NextFunction) => { Card.find({}) .select("-__v") .then((cards) => { res.send(cards); }) .catch(next); }; export const postCard = ( req: AuthRequest, res: Response, next: NextFunction ) => { const userId = req.user?._id; const { name, link } = req.body; Card.create({ name, link, owner: userId, }) .then((card) => { res.send(card); }) .catch((err) => { if (err.name === "ValidationError") { next(Errors.badRequest(ERROR.message.BAD_REQUEST)); } else { next(err); } }); }; export const deleteCard = ( req: AuthRequest, res: Response, next: NextFunction ) => { const userId = req.user?._id; Card.findById(req.params.cardId) .then((card) => { if (!card) { throw Errors.notFound(ERROR.message.NOT_FOUND_REQUEST); } if (card.owner.toString() !== userId) { throw Errors.forbiddenError(); } return Card.findByIdAndRemove(req.params.cardId); }) .then((card) => { res.send({ message: "Карточка удалена", data: card, }); }) .catch((err) => { if (err.name === "CastError") { next(Errors.badRequest(ERROR.message.INVALID_ID_ERROR)); } else { next(err); } }); }; export const likeCard = ( req: AuthRequest, res: Response, next: NextFunction ) => { const userId = req.user?._id; Card.findByIdAndUpdate( req.params.cardId, { $addToSet: { likes: userId } }, { new: true } ) .then((card) => { if (!card) { throw Errors.notFound(ERROR.message.NOT_FOUND_REQUEST); } res.send({ message: "Лайк поставлен", }); }) .catch((err) => { if (err.name === "CastError") { next(Errors.badRequest(ERROR.message.INVALID_ID_ERROR)); } else { next(err); } }); }; export const dislikeCard = ( req: AuthRequest, res: Response, next: NextFunction ) => { const userId = req.user?._id || {}; Card.findByIdAndUpdate( req.params.cardId, { $pull: { likes: userId } }, { new: true } ) .then((card) => { if (!card) { throw Errors.notFound(ERROR.message.NOT_FOUND_REQUEST); } res.send( // card { message: "Лайк удален" } ); }) .catch((err) => { if (err.name === "CastError") { next(Errors.badRequest(ERROR.message.INVALID_ID_ERROR)); } else { next(err); } }); };
import type { AppName, Formatter, Lang, OnLanguageChange, Translate, TranslationConstructor, TranslationContructorProps, TranslateFunction, TranslationObject, TranslationOptions, Translator } from "./t.types"; const variableRegex = /(?:{{(.+?)}})/g; const recursiveRegex = /(?:\$t\((.+?)\))/g; const Translationary = function Translationary( props: TranslationContructorProps ): Translator { const { appName, lang, onLanguageChange, formatter, fetchTranslations } = props; /** . * Main translation function. Also defers to test when applicable. * * @param rawKey string * @param rawOptions TranslationOptions | string * @returns string */ const translate: TranslateFunction = (rawKey, rawOptions = {}) => { let options = rawOptions; if (typeof rawOptions === "string") { options = { defaultValue: rawOptions }; } const { count, context, defaultValue, plural } = options as TranslationOptions; let key = rawKey; key = context ? `${key}_${context}` : key; key = plural || (typeof count === "number" && count > 1) ? `${key}_plural` : key; let translation = key .split(".") .reduce( (tr, k) => tr?.[k] || defaultValue, this.translations as TranslationObject ); if (this.testEnabled && !translation) { throw new Error( `[ERR] translation ${key} is missing in ${this.lang} ${this.appName}` ); } // this is separated so test mode has a chance to throw an error translation = (translation || key) as string; /** * this grabs variable calls from inside the strings and replaces * them with the variable value. if no match is found, the variable is * not replaced * * in test mode a missing variable throws an error. outside test it will * return thge defaultValue on error (if available), or the key */ let variableError = false; (translation.match(variableRegex) || []).forEach((match) => { const [variableString, format] = match.slice(2, -2).split(", "); const variable = variableString .split(".") .reduce((opt: TranslationOptions, v: string) => opt[v], options); if (variable) { translation = (translation as string).replace( match, this.formatter(variable, format) ); } else if (this.testEnabled) { throw new Error( `[ERR] translation ${key} is missing variable ${variableString}` ); } else { variableError = true; } }); if (variableError) { return defaultValue || key; } (translation.match(recursiveRegex) || []).forEach((match) => { const args = match.slice(3, -1).split(", "); const opt = args[1] ? JSON.parse(args.slice(1).join(", ")) : undefined; const translationKey = translate(args[0], opt); translation = (translation as string).replace(match, translationKey); }); return translation; }; /** * Gets the current language. */ this.getLanguage = () => { return this.lang; }; /** * Gets the full translations object. Only works when test mode is enabled * It is intended for testing as well as generating types. */ this.getTranslations = () => { if (this.testEnabled) { return this.translations; } console.error("[ERR] getTranslations only works when test mode is enabled"); return null; }; /** . * Handles setup of the variables and the retrieves initial translations * * @param appName string * @param lang string * @param onLanguageChange (lang) => void * @param formatter */ this.init = ( app: AppName, language: Lang, formatterFunction: Formatter, onLanguageChangeFunction?: OnLanguageChange ) => { this.appName = app; this.lang = language; this.formatter = formatterFunction; this.onLanguageChange = onLanguageChangeFunction; return this.setTranslations(lang); }; /** . * Sets the language internally, grabs the translations, * then fires the onLanguageChange * * @param lang */ this.setLanguage = (newLanguage: Lang): Promise<TranslationObject> => { this.lang = newLanguage; return this.setTranslations(newLanguage); }; /** . * Enables or disables test mode * * @param test boolean */ this.setTest = (test = true) => { this.testEnabled = test; }; /** . * Grabs the translations from s3 * * @param lang * @returns Promise<translations> */ this.setTranslations = (newLanguage: string): Promise<TranslationObject> => { const setTranslation = (translations: TranslationObject) => { this.translations = translations; }; return new Promise<TranslationObject>((resolve) => { resolve( fetchTranslations({ appName, lang: newLanguage }) ); }) .then((res: TranslationObject) => setTranslation(res)) .then(() => this.onLanguageChange?.(newLanguage)); }; this.init(appName, lang, formatter, onLanguageChange); return Object.assign(translate, { getLanguage: this.getLanguage, getTranslations: this.getTranslations, setLanguage: this.setLanguage, setTest: this.setTest } as Translate); } as TranslationConstructor<Translator>; export default Translationary;
import { StaticImageData } from "next/image" import p5Types from "p5" import * as previews from "./previews" import * as sketches from "./sketches" export interface Infos { id: string title: string desc: string href: string preview: StaticImageData sketch: (p: p5Types, parentId: string) => void } const infos: Infos[] = [ { id: "UnifiedRupture", title: "Unified Rupture", desc: "Unified Rupture aims to create a visual experience where fusion and fragmentation coexist harmoniously. Employing noise to warp conical gradients, it presents visual elements with a sense of interconnectedness amid fractured segments.", href: "https://openprocessing.org/sketch/1898796", preview: previews.UnifiedRupture, sketch: sketches.UnifiedRupture, }, // { // id: "Travel", // title: "Travel", // desc: "Travel is essentially a photo slideshow that utilizes noise to create domain warping effects, resulting in a marble-like, flowing appearance.", // href: "https://openprocessing.org/sketch/1826376", // preview: previews.Travel, // sketch: sketches.Travel, // }, { id: "DraculaAndTheUndead", title: "Dracula and the Undead", desc: "As the title suggests, I aim to encapsulate the atmosphere of fresh blood akin to Dracula with vibrant red hues, while cyan tones represent the icy chill of the undead. Deliberately contrasting the two, I've created a vivid interplay symbolizing their inherent conflict.", href: "https://openprocessing.org/sketch/1891135", preview: previews.DraculaAndTheUndead, sketch: sketches.DraculaAndTheUndead, }, { id: "SHUTTLE", title: "SHUTTLE !", desc: "Inspired by Ryoji Ikeda, this generative art piece aims to create visual effects of interweaving, shuttling, and cycling on the screen after initializing random data points.", href: "https://openprocessing.org/sketch/1828512", preview: previews.SHUTTLE, sketch: sketches.SHUTTLE, }, { id: "Naraka", title: "Naraka", desc: "In Sanskrit, Naraka translates to 'hell'. In the pitch-black environment, the incessant white mist creeping out in the background represents the whispers of the dead. From the top, white spider silk descends, repeatedly breaking and falling, symbolizing the cycle of reincarnation.", href: "https://openprocessing.org/sketch/1914052", preview: previews.Naraka, sketch: sketches.Naraka, }, ] export default infos
/* Hero Styles to make big full width mastheads or sections Usage: <section class="hero"> <div class="hero__body"> <div class="container"> <h1 class="hero__heading"></h1> <p></p> </div> </div> </section> */ .hero { background-size: cover; // The hero is ready to have a full size background image by default background-position: center; overflow: hidden; position: relative; z-index: 0; padding-top: $section-spacing-unit / 2; padding-bottom: $section-spacing-unit / 2; @include mq-min($bp-sm) { padding-top: $section-spacing-unit; padding-bottom: $section-spacing-unit; } .hero__heading, p { } } .hero--standard { padding-bottom: $section-spacing-unit / 4; @include mq-min($bp-sm) { padding-bottom: $section-spacing-unit / 2; } } .hero--listing { padding-bottom: 0; background-color: $lighter-grey; } .hero__subtitle { @include font-size($h2-font-size, $h2-line-height); margin-bottom: $base-spacing-unit * 2; @include mq-max($bp-md-lg) { @include font-size($h2-font-size-sm, false); } @include mq-max($bp-md) { @include font-size($h2-font-size-xs, false); } @include mq-max($bp-sm) { @include font-size($h4-font-size, false); } @include mq-max($bp-xs) { @include font-size($h5-font-size, false); } } .hero__body { @include z-index(3); margin:auto; > *:last-child, > * > *:last-child { margin-bottom: 0; } } @keyframes fadeIn { 0 { opacity: 0 } 100% { opacity: 1 } } // Add this element parallel to the hero__body to separate the background from the content of the hero .hero__bg { @include z-index(1, absolute); width:100%; height:100%; top:50%; left:0; background-size: cover; opacity: 1; // The hero is ready to have a full size background image by default background-position: center; transform: translate(0,-50%); transition: all $transition-slow; &.is-active { opacity: 1 } } canvas.hero__bg { width: 100%; } .hero__heading { } // add a color overlay to the background-image .hero--overlay { // The overlay &:before { @include z-index(2, absolute); @extend %full-cover; content: ''; background-color: $hero-overlay-color; opacity: $hero-overlay-opacity; } } // Hero Vert // Use table positioning to allow the content of the hero to be vertically centered // You can then either set a height in pixels, or if it's placed inside an element with a // set height, the hero will stretch to the full height of it's parent // IMPORTANT: if setting a height on hero--vert or hero--full, use height not min-height. // min-height don't play well with table elements .hero--vert { width: 100%; min-height:30rem; display: flex; align-items:center; min-height:100vh; .hero__body { width:100%; } } .hero--dark { background:$dark-grey; color:white; } .hero--darker { background:$darker-grey; color:white; } .hero--cta { @extend .hero--dark; z-index: 200; margin-top: -1px; // *hack to make sure it overlaps the bottom of the content area (subpixel rendering) } .hero--fluid { padding: 15% 0; @include mq-min($bp-lg) { padding: 10% 0; } } .hero--tight { padding-top: $section-spacing-unit/2; padding-bottom: $section-spacing-unit/2; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 原型式继承 function inheritObject(o) { function F(){} F.prototype = o return new F() } // 寄生式继承 // 声明基对象 var book = { name: 'js book', alikeBook: ['css book', 'html book'] } function createBook(obj) { // 通过原型式继承创建对象 const o = new inheritObject(obj) // 拓展新对象 o.getName = function() { console.log(name) } return o } // 寄生式继承就是对原型式继承的第二次封装,并且在这第二次封装过程中对继承的对象进行了扩展,这样新创建的对象不仅仅有父类中的属性和方法而且还添加新的属性和方法 </script> </body> </html>
def contar_vocales(palabra): """ Función para contar el número de veces que aparece cada vocal en una palabra. Args: - palabra: Una cadena que representa la palabra de la cual se contarán las vocales. Returns: - Un diccionario donde las claves son las vocales ('a', 'e', 'i', 'o', 'u') y los valores son los conteos de cada vocal. """ palabra = palabra.lower() # Convertir la palabra a minúsculas para asegurar la comparación vocales = ['a', 'e', 'i', 'o', 'u'] # Lista de vocales # Crear un diccionario con comprensión de diccionarios donde las claves son las vocales y los valores son los conteos conteo_vocales = {vocal: palabra.count(vocal) for vocal in vocales} return conteo_vocales # Ejercicio 9 palabra = input("Ingrese una palabra: ") # Solicitar al usuario ingresar una palabra conteo_vocales = contar_vocales(palabra) # Contar las vocales en la palabra print(conteo_vocales) # Imprimir el conteo de las vocales
/* eslint-disable prettier/prettier */ import { IsNumber, // IsNotEmpty, IsEnum, // Allow, IsArray, // ValidateIf, IsString, ArrayUnique, ArrayNotEmpty, IsNotEmpty, IsOptional, } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export enum BookGenres { Action = 'Action', Fantasy = 'Fantasy', Romance = 'Romance', Mystery = 'Mystery', ScienceFiction = 'ScienceFiction', } export class CreateBookDTO { @ApiProperty({ description: 'Name of the book', example: 'Default book name', // readOnly: true, }) @IsNotEmpty() @IsString() name: string; /** * @example 'A simple description on a book' */ @IsString() @IsOptional() description: string; // @IsDateString( // { strict: true, strictSeparator: true }, // { // message: // 'createDate must be a valid ISO 8601 date string eg: 2023-01-15T14:30:00.000Z or yyyy-mm-dd or yyyy-mm or yyyy - slashes not accepted', // }, // ) // @Transform(({ value }) => { // console.log('Transforming Date', value, new Date(value)); // if (isDateString(value)) { // return new Date(value).toISOString(); // } // return value; // }) // @IsDate() // @ApiProperty({ format: 'date-time' }) // createDate: string; @IsNumber() @ApiProperty() sales: number; @ApiProperty({ minimum: 1, default: 1, required: false, }) @IsNumber() likes: number; @ApiProperty({ enum: BookGenres, enumName: 'Book Genre', isArray: true, uniqueItems: true, // enum: ['Admin', 'Moderator', 'User'], example: [BookGenres.Romance, BookGenres.Action], // enum: [BookGenres.ACTION, BookGenres.ROMANCE], type: [String], // description: 'Specify an array of genre', }) @IsArray() @ArrayNotEmpty() @ArrayUnique() @IsEnum(BookGenres, { each: true }) genre: BookGenres[]; // @ApiProperty({ readOnly: true }) // @IsEmpty() // test: string; } // export class UpdateBookDTO extends P
import mongoose, { PipelineStage, Types } from 'mongoose'; import { paginationHelper } from '../../../helper/paginationHelper'; import { IGenericResponse } from '../../interface/common'; import { IPaginationOption } from '../../interface/pagination'; import { ENUM_STATUS, ENUM_YN } from '../../../enums/globalEnums'; import ApiError from '../../errors/ApiError'; import { RESOURCE_SEARCHABLE_FIELDS } from './resource.constant'; import { IResource, IResourceFilters } from './resource.interface'; import { Resource } from './resource.model'; const { ObjectId } = mongoose.Types; const createResourceByDb = async (payload: IResource): Promise<IResource> => { const result = await Resource.create(payload); return result; }; //getAllResourceFromDb const getAllResourceFromDb = async ( filters: IResourceFilters, paginationOptions: IPaginationOption ): Promise<IGenericResponse<IResource[]>> => { //****************search and filters start************/ const { searchTerm, select, ...filtersData } = filters; filtersData.status= filtersData.status ? filtersData.status : ENUM_STATUS.ACTIVE // Split the string and extract field names const projection: { [key: string]: number } = {}; if (select) { const fieldNames = select?.split(',').map(field => field.trim()); // Create the projection object fieldNames.forEach(field => { projection[field] = 1; }); } const andConditions = []; if (searchTerm) { andConditions.push({ $or: RESOURCE_SEARCHABLE_FIELDS.map(field => //search array value field === 'tags' ? { [field]: { $in: [new RegExp(searchTerm, 'i')] } } : { [field]: new RegExp(searchTerm, 'i'), } ), }); } if (Object.keys(filtersData).length) { andConditions.push({ $and: Object.entries(filtersData).map(([field, value]) => field === 'module' ? { [field]: new Types.ObjectId(value) } : { [field]: value } ), }); } //****************search and filters end**********/ //****************pagination start **************/ const { page, limit, skip, sortBy, sortOrder } = paginationHelper.calculatePagination(paginationOptions); const sortConditions: { [key: string]: 1 | -1 } = {}; if (sortBy && sortOrder) { sortConditions[sortBy] = sortOrder === 'asc' ? 1 : -1; } //****************pagination end ***************/ const whereConditions = andConditions.length > 0 ? { $and: andConditions } : {}; /* const result = await Milestone.find(whereConditions) .sort(sortConditions) .skip(Number(skip)) .limit(Number(limit)); */ const pipeline: PipelineStage[] = [ { $match: whereConditions }, { $sort: sortConditions }, { $skip: Number(skip) || 0 }, { $limit: Number(limit) || 15 }, { $lookup: { from: 'modules', let: { id: '$module' }, pipeline: [ { $match: { $expr: { $eq: ['$_id', '$$id'] }, // Additional filter conditions for collection2 }, }, // Additional stages for collection2 // প্রথম লুকাপ চালানোর পরে যে ডাটা আসছে তার উপরে যদি আমি যেই কোন কিছু করতে চাই তাহলে এখানে করতে হবে |যেমন আমি এখানে project করেছি { $project: { title: 1, }, }, ], as: 'moduleDetails', }, }, // { // $project: { module: 0 }, // }, // { // $addFields: { // module: { // $cond: { // if: { $eq: [{ $size: '$moduleDetails' }, 0] }, // then: [{}], // else: '$moduleDetails', // }, // }, // }, // }, // { // $project: { moduleDetails: 0 }, // }, // { // $unwind: '$module', // }, ]; let result = null; if (select) { result = await Resource.find(whereConditions) .sort({ ...sortConditions }) .skip(Number(skip)) .limit(Number(limit)) .select({ ...projection }); } else { result = await Resource.aggregate(pipeline); } const total = await Resource.countDocuments(whereConditions); return { meta: { page, limit, total, }, data: result, }; }; // get single e form db const getSingleResourceFromDb = async ( id: string ): Promise<IResource | null> => { const result = await Resource.aggregate([ { $match: { _id: new ObjectId(id) } }, { $lookup: { from: 'modules', let: { id: '$module' }, pipeline: [ { $match: { $expr: { $eq: ['$_id', '$$id'] }, // Additional filter conditions for collection2 }, }, { $project: { title: 1, }, }, ], as: 'moduleDetails', }, }, // { // $project: { module: 0 }, // }, // { // $addFields: { // module: { // $cond: { // if: { $eq: [{ $size: '$moduleDetails' }, 0] }, // then: [{}], // else: '$moduleDetails', // }, // }, // }, // }, // { // $project: { moduleDetails: 0 }, // }, // { // $unwind: '$module', // }, ]); return result[0]; }; // update e form db const updateResourceFromDb = async ( id: string, payload: Partial<IResource> ): Promise<IResource | null> => { const { demo_video, ...otherData } = payload; const updateData = { ...otherData }; if (demo_video && Object.keys(demo_video).length > 0) { Object.keys(demo_video).forEach(key => { const demo_videoKey = `demo_video.${key}`; // `demo_video.status` (updateData as any)[demo_videoKey] = demo_video[key as keyof typeof demo_video]; }); } const result = await Resource.findOneAndUpdate({ _id: id }, updateData, { new: true, runValidators: true, }); if (!result) { throw new ApiError(500, 'Resource update fail!!😪😭😰'); } return result; }; // delete e form db const deleteResourceByIdFromDb = async ( id: string, query: IResourceFilters ): Promise<IResource | null> => { let result; if (query.delete === ENUM_YN.YES) { result = await Resource.findByIdAndDelete(id); } else { result = await Resource.findOneAndUpdate( { _id: id }, { status: ENUM_STATUS.DEACTIVATE, isDelete: ENUM_YN.YES } ); } return result; }; // set user reviews e form db const ResourceReviewsByUserFromDb = async (): Promise<IResource | null> => { return null; }; export const ResourceService = { createResourceByDb, getAllResourceFromDb, getSingleResourceFromDb, updateResourceFromDb, deleteResourceByIdFromDb, ResourceReviewsByUserFromDb, };
import React, { useState, useEffect } from 'react' import { Link, useNavigate} from 'react-router-dom' import { Form, Button, Row, Col} from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { register } from '../reduxState/actions/userActions' // components import Loader from '../components/Loader' import Message from '../components/Message' import FormContainer from '../components/FormContainer' function RegisterView() { const [name, setName] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [confirmPassword, setConfirmPassword] = useState('') const [message, setMessage] = useState('') let navigate = useNavigate() const dispatch = useDispatch() /* getting userData from redux state */ const userRegister = useSelector(state => state.userRegister) const { error, loading, userData } = userRegister /* redirect the user if they are already logged in */ useEffect(() => { if(userData) { navigate(-1) } }, [navigate, userData]) const submitHandler = (e) => { e.preventDefault() setMessage('') if(password !== confirmPassword) { setMessage('Passwords do not match.') } else if (password.length < 8){ setMessage('Password must be at least 8 characters long.') } else { dispatch(register(name, email, password)) } } return ( <FormContainer> <h1>Create New Account</h1> { message && <Message variant='warning'>{message}</Message>} { error && <Message variant='warning'>{error}</Message> } { loading && <Loader /> } <Form onSubmit={submitHandler}> <Form.Group className='my-4' controlId='name'> <Form.Label>Name</Form.Label> <Form.Control required type='name' placeholder='Enter Name' value={name} onChange={(e) => setName(e.target.value)} /> </Form.Group> <Form.Group className='my-4' controlId='email'> <Form.Label>Email Address</Form.Label> <Form.Control required type='email' placeholder='Enter Email' value={email} onChange={(e) => setEmail(e.target.value)} /> </Form.Group> <Form.Group className='my-4' controlId='password'> <Form.Label>Password</Form.Label> <Form.Control required type='password' placeholder='Enter Password' value={password} onChange={(e) => setPassword(e.target.value)} /> </Form.Group> <Form.Group className='my-4' controlId='confirmPassword'> <Form.Label>Confirm Password</Form.Label> <Form.Control required type='password' placeholder='Enter Password Again' value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} /> </Form.Group> <Button type='submit' variant='primary'> Register </Button> </Form> <Row className='py-3'> <Col> Already Registered? <Link className='px-1' to={'/login'}>Sign In</Link> </Col> </Row> </FormContainer> ) } export default RegisterView
/********************************************************************* * * Treeler - Open-source Structured Prediction for NLP * * Copyright (C) 2014 TALP Research Center * Universitat Politecnica de Catalunya * * This file is part of Treeler. * * Treeler is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Treeler 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Treeler. If not, see <http://www.gnu.org/licenses/>. * * contact: Xavier Carreras (carreras@lsi.upc.edu) * TALP Research Center * Universitat Politecnica de Catalunya * 08034 Barcelona * ********************************************************************/ /** * \file parser-projdep2.h * \brief Declaration of ProjDep2 * \author Xavier Carreras */ #ifndef TREELER_PROJDEP2_H #define TREELER_PROJDEP2_H #include "treeler/dep/dep-tree.h" #include "treeler/dep/dep-symbols.h" #include "treeler/base/label.h" #include "treeler/dep/part-dep2.h" #include "treeler/io/io-basic.h" #include<map> using namespace std; namespace treeler { /** * \brief An second-order projective dependency parser * \ingroup dep * \author Xavier Carreras, Terry Koo * */ class ProjDep2 { public: typedef PartDep2 R; struct Configuration { int L; /* number of edge labels */ bool multiroot; /* whether parsing is multiroot or not */ }; template <typename X, typename S> static double argmax(const Configuration& c, const X& x, S& scores, Label<PartDep2>& y); template <typename X, typename S> static double argmax(const Configuration& c, const X& x, S& scores, DepVector<int>& y) { // a factored label Label<PartDep2> fy; double s = argmax(c,x,scores,fy); convert(x,fy, y); return s; } protected: Configuration _config; const DepSymbols& _symbols; public: ProjDep2(const DepSymbols& sym0) : _symbols(sym0) { _config.L = _symbols.d_syntactic_labels.size(); } Configuration& configuration() { return _config; } template <typename X, typename Y> void decompose(const X& x, const Y& y, Label<R>& parts) const { R::decompose(_symbols, x, y, parts); } template <typename X, typename Y> void compose(const X& x, const Label<R>& parts, Y& y) const { R::compose(_symbols, x, parts, y); } template <typename X, typename S> double argmax(const X& x, S& scores, Label<PartDep2>& y) { return argmax(_config, x, scores, y); } template <typename X, typename S, typename LabelT> double argmax(const X& x, S& scores, DepVector<LabelT>& y) { Label<PartDep2> parts; double s = argmax(_config, x, scores, parts); compose(x, parts, y); return s; } protected: /* nested datatypes for inference routines */ /* struct U_signature; */ /* struct C_signature; */ /* struct U_backpointer; */ /* struct C_backpointer; */ class outside_scores; /* chart entry for uncomplete dependency structures */ /* defined by: head, modifier and label of dominating depencency */ struct U_signature { int _h, _m, _l; bool operator< (const U_signature & s2) const { if (_h<s2._h) return true; else if (_h==s2._h) { if (_m<s2._m) return true; else if (_m==s2._m) { return (_l<s2._l); } } return false; } U_signature(int h0, int m0, int l0) : _h(h0), _m(m0), _l(l0) {} int head() const { return _h; } int mod() const { return _m; } int label() const { return _l; } }; /* the value of a U_signature chart entry */ /* contains: splitting point, and positions of head's child and inner modifier's child */ struct U_backpointer { int _r,_ch,_cm; U_backpointer(int r0, int ch0, int cm0) : _r(r0), _ch(ch0), _cm(cm0) {} }; /* chart entry for uncomplete dependency structures */ /* defined by: head, modifier of dominating dependency, and end point of the sentence span */ struct C_signature { int _h, _e, _m; bool operator< (const C_signature & s2) const { if (_h<s2._h) return true; else if (_h==s2._h) { if (_e<s2._e) return true; else if (_e==s2._e) { return (_m<s2._m); } } return false; } C_signature(int h0, int e0, int m0) : _h(h0), _e(e0), _m(m0) {} int head() const { return _h; } int end() const { return _e; } int mod() const { return _m; } }; /* the value of a C_signature chart entry */ /* contains: label of dominating dependency and outer child of modifier */ struct C_backpointer { int _l, _cm; C_backpointer(int l0, int cm0) : _l(l0), _cm(cm0) {} }; /* Structure of back pointers in the chart * The pointers are indexed by head and modifier * Internally, pointers for head=-1 (root) are stored in the [m,m] position */ struct chart_values { map<C_signature,C_backpointer> CBP; map<U_signature,U_backpointer> UBP; chart_values() {} ~chart_values() {} void set_cbp(int h, int e, int m, int l, int cm); void set_ubp(int h, int m, int l, int r, int ch, int cm); bool get_cbp(int h, int e, int m, int *l, int *cm) const; bool get_ubp(int h, int m, int l, int *r, int *ch, int *cm) const; }; struct chart_scores { double *_CS; // scores for complete structures double *_US; // scores for uncomplete structures const int _N, _L, _NL, _N2, _N2L; chart_scores (int N0, int L0); ~chart_scores(); double cscore (int h, int e, int m) const; void cscore_set (int h, int e, int m, double sco); double uscore (int h, int m, int l) const; void uscore_set (int h, int m, int l, double sco); }; /* walk the path of backpointers to recover the viterbi tree */ static void unravel_tree(const int N, Label<PartDep2>& y, const struct chart_values& CV, const int h, const int e, const int m); /* TERRY: I changed this to use templated functors instead of a function; I think the use of a function with conditional if statements might be marginally slower than templated functors, which can be inlined */ /* argmax parsing */ /* template<class PartScorer> */ /* double argmax_impl(const Pattern* const x, */ /* PartScorer& part_score, */ /* Label<PartDep2>& y); */ /* /\* inside pass: fills IS with inside scores and returns logZ *\/ */ /* template<class PartScorer> */ /* double inside(const Pattern* const x, */ /* chart_scores& IS, */ /* PartScorer& part_scorer); */ /* /\* outside pass: takes IS as input and fills ret_M with */ /* marginals *\/ */ /* template<class PartScorer> */ /* void outside(const Pattern* const x, */ /* const chart_scores& IS, */ /* const double logZ, */ /* PartScorer& part_scorer, */ /* double* const ret_M); */ /* test the parser's inference routines against a brute-force method */ template<class UseTree, class PartScorer> void bruteforce(const int N, UseTree& use, PartScorer& part_score); void testinf(); protected: int _L; /* number of edge labels */ bool _multiroot; /* whether parsing is multiroot or not */ /* whether to use a deptree-based method to construct labels */ bool _use_deptree_labels; public: /* helper function that converts a first-order deptree representation to a second-order label */ static void deptree2label(const bool multiroot, const int N, const DepTree<int>* const root, Label<PartDep2>& y); }; } #include "treeler/dep/parser-projdep2.tcc" #endif /* TREELER_PROJDEP2_H */
import React, {useEffect, useState} from "react"; import Layout from './Layout' import {Row, Col, Card, Button, Form} from "react-bootstrap"; import {AreaChart, Area, XAxis, YAxis, Legend, CartesianGrid, Tooltip, ResponsiveContainer} from 'recharts'; import {FaDroplet} from "react-icons/fa6"; import {HiSave} from "react-icons/hi"; import { humProcessDataForCustomDate, humProcessDataForToday, humProcessDataForMonth, humProcessDataForYear, } from './processDataForChart'; import * as XLSX from 'xlsx'; import {getHumidity, getTemperature} from "../network/dataset_api"; function Humidity() { const [latestHumidity, setLatestHumidity] = useState(null); const [selectedButton, setSelectedButton] = useState('today'); const [selectedDate, setSelectedDate] = useState(new Date().toISOString().slice(0, 10)); const [humidity, setHumidity] = useState([]); const [selectedTimeframe, setSelectedTimeframe] = useState('today'); const [chartData, setChartData] = useState([]); const [isLoadingHum, setIsLoadingHum] = useState(true); const exportToExcel = (data, fileName) => { const worksheet = XLSX.utils.json_to_sheet(data.map(item => ({ Zeit: item.name, Wert: item.humidity }))); const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "Feuchtigkeitswerte"); XLSX.writeFile(workbook, `${fileName}.xlsx`); }; useEffect(() => { async function loadHumidity() { try { const hum = await getHumidity(); setHumidity(hum); if (hum.length > 0) { const latestHum = hum[hum.length - 1]; setLatestHumidity(latestHum); } updateChartData(hum, 'today'); } catch (error) { console.error(error); }finally { setIsLoadingHum(false); } } async function loadData() { await loadHumidity(); } //loading data when componenet gets mounted loadData(); //updating data interval const interval = setInterval(() => { loadData(); }, 5000); return () => clearInterval(interval); }, []); function handleExcelClick() { let fileName; let dataToExport = []; switch (selectedTimeframe) { case 'today': fileName = `Feuchtigkeit_Today_${new Date().toISOString().slice(0, 10)}`; dataToExport = humProcessDataForToday(humidity); break; case 'month': fileName = `Feuchtigkeit_Month_${new Date().getFullYear()}_${new Date().getMonth() + 1}`; dataToExport = humProcessDataForMonth(humidity); break; case 'year': fileName = `Feuchtigkeit_Year_${new Date().getFullYear()}`; dataToExport = humProcessDataForYear(humidity); break; case 'custom': fileName = `Feuchtigkeit_${selectedDate}`; dataToExport = humProcessDataForCustomDate(humidity, selectedDate); break; default: return; } exportToExcel(dataToExport, fileName); } const updateChartData = (hum, timeframe, date = null) => { let processedData; switch (timeframe) { case 'today': processedData = humProcessDataForToday(hum); break; case 'month': processedData = humProcessDataForMonth(hum); break; case 'year': processedData = humProcessDataForYear(hum); break; case 'custom': processedData = humProcessDataForCustomDate(hum, date); break; default: processedData = []; } setChartData(processedData); }; const handleDateChange = (event) => { setSelectedDate(event.target.value); setSelectedTimeframe('custom'); updateChartData(humidity, 'custom', event.target.value); }; const handleButtonClick = (buttonName) => { setSelectedButton(buttonName); setSelectedTimeframe(buttonName); updateChartData(humidity, buttonName); }; const getButtonClassName = (buttonName) => { return selectedButton === buttonName ? 'chartButton' : 'chartButton grayedOut'; }; return ( <Layout> <Row style={{display: 'flex', flexGrow: '1', alignItems: 'center', margin: '40px'}}> <Col> <div style={{ opacity: '1', borderRadius: '25px', background: 'white', height: '80vH', width: '99%', display: 'flex', justifyContent: 'center' }}> <div style={{ display: 'flex', alignItems: 'center', marginLeft: '0%', width: '20%', height: '100%' }}> {/* Content for the left side */} <Card className="card-shadow2"> <Card.Body className="text-center"> <Card.Title className='card-content'>Humidity</Card.Title> <FaDroplet className='card-content1 temp-icon'/> <Card.Text className='card-content1'> {isLoadingHum ? ( <p>Loading...</p> ) : latestHumidity ? ( `${latestHumidity.humidity} %` ) : ( "Data not available" )} </Card.Text> <Card.Text className='sensorText'> Hum-Sensor </Card.Text> <Button className="align-icon-text" onClick={() => handleExcelClick()}> <HiSave/> <span className="button-text">Download Sensor data history</span> </Button> </Card.Body> </Card> </div> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', marginLeft: '4%' }}> {/* vertical line for separation */} <div className='vl'></div> </div> {/* Area for chart */} <div style={{ display: 'flex', alignItems: 'center', marginLeft: '0%', marginRight: '0%', width: '70%', height: '100%' }}> <ResponsiveContainer width="100%" height="80%"> <div style={{ display: 'flex', justifyContent: 'start', alignItems: 'center', marginLeft: '11%', marginRight: '0%', width: '100%' }}> <Button className={getButtonClassName('today')} onClick={() => handleButtonClick('today')}>Today</Button> <Button className={getButtonClassName('month')} onClick={() => handleButtonClick('month')}>This month</Button> <Button className={getButtonClassName('year')} onClick={() => handleButtonClick('year')}>This year</Button> <Form.Control className='chartDateForm' type="date" value={selectedDate} onChange={handleDateChange} /> </div> <AreaChart width={500} height={300} data={chartData} margin={{ top: 5, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3"/> <XAxis dataKey="name" label={{value: 'Time', position: 'insideBottomRight', offset: -17}}/> <YAxis label={{value: 'Humidity in %', angle: -90, position: 'insideLeft'}}/> <Tooltip/> <Legend></Legend> <Area type="monotone" dataKey="humidity" name='Hum-Sensor' stroke="rgba(33,81,95,1)" fill="rgba(42,113,140,1)" activeDot={{r: 8}}/> </AreaChart> </ResponsiveContainer> </div> </div> </Col> </Row> </Layout> ); } export default Humidity;
import React from "react"; import { render, fireEvent, screen, waitFor } from "@testing-library/react"; import { BrowserRouter } from "react-router-dom"; import { signInWithEmailAndPassword } from "firebase/auth"; import { auth } from "../firebase"; import Login from "../components/Login"; // Mocking Firebase Auth method jest.mock("firebase/auth", () => ({ signInWithEmailAndPassword: jest.fn(), })); // Render with routing context const renderWithRouter = (component) => { return render(<BrowserRouter>{component}</BrowserRouter>); }; describe("Login Component", () => { test("renders correctly", () => { renderWithRouter(<Login />); // Check if components are rendered expect(screen.getByText(/Lama Chat/i)).toBeInTheDocument(); expect(screen.getByText(/Login/i)).toBeInTheDocument(); expect( screen.getByPlaceholderText(/email/i) ).toBeInTheDocument(); expect( screen.getByPlaceholderText(/password/i) ).toBeInTheDocument(); expect(screen.getByText(/Sign in/i)).toBeInTheDocument(); expect(screen.getByText(/Register/i)).toBeInTheDocument(); }); test("calls signInWithEmailAndPassword on form submission", async () => { renderWithRouter(<Login />); const emailInput = screen.getByPlaceholderText(/email/i); const passwordInput = screen.getByPlaceholderText(/password/i); const submitButton = screen.getByText(/Sign in/i); // Fill inputs fireEvent.change(emailInput, { target: { value: "test@example.com" }, }); fireEvent.change(passwordInput, { target: { value: "password123" }, }); // Submit the form fireEvent.click(submitButton); // Check if signInWithEmailAndPassword is called with correct parameters await waitFor(() => { expect(signInWithEmailAndPassword).toHaveBeenCalledWith( auth, "test@example.com", "password123" ); }); }); test("displays error message when login fails", async () => { renderWithRouter(<Login />); const emailInput = screen.getByPlaceholderText(/email/i); const passwordInput = screen.getByPlaceholderText(/password/i); const submitButton = screen.getByText(/Sign in/i); // Mock signInWithEmailAndPassword to throw an error signInWithEmailAndPassword.mockImplementation(() => { throw new Error("Login failed"); }); // Fill inputs and submit the form fireEvent.change(emailInput, { target: { value: "invalid@example.com" }, }); fireEvent.change(passwordInput, { target: { value: "wrongpassword" }, }); fireEvent.click(submitButton); // Wait for error message to be displayed await waitFor(() => { expect( screen.getByText(/Something went wrong/i) ).toBeInTheDocument(); }); }); });
-- this is data retrival USE store; SELECT * FROM customers; -- Retrieving a specific data from the data SELECT customer_id, first_name, city, points FROM customers; -- sorting the table in ascending order SELECT customer_id, first_name, city, points FROM customers ORDER BY points; -- sorting the table in descending order SELECT customer_id, first_name, city, points FROM customers ORDER BY points desc; -- Retrieve customer who live in chicago SELECT * FROM customers WHERE city = 'chicago'; -- Retrieve customer who live in chicago, orlando, hampton SELECT * FROM customers WHERE city in ('chicago', 'orlando', 'hampton'); -- Aggregate Function min, max, count, count distinct, sum, avg -- retrieve minimum points SELECT min(points) as minimum_points FROM customers; -- retrieve maximum point SELECT max(points) as Maximum_points FROM customers; -- retrieve the count in point SELECT count(points) as Count FROM customers; -- Retrieve the average number SELECT avg(points) as Average FROM customers; -- Retrieve the sum of the point SELECT sum(points) as Sum FROM customers; -- Retrieve the distinct points SELECT count(distinct points) as distinct_points FROM customers; -- which customers are born in the year 1986 select * from customers where birth_date LIKE '1986%'; -- which customer doesnt have phone number in the records select * from customers where phone IS NULL; -- calculate the total amount of each product that is been procces in the company. select o.order_id, p.name, oi.quantity, oi.unit_price, oi.quantity * oi.unit_price as total_amount, os.name from products p join order_items oi on p.product_id = oi.product_id join orders o on o.order_id = oi.order_id join order_statuses os on o.status = os.order_status_id where os.order_status_id = 1; -- what is the total amount of all the goods shipped select os.name, sum(oi.quantity * oi.unit_price) as Total_amount from products p join order_items oi on p.product_id = oi.product_id join orders o on o.order_id = oi.order_id join order_statuses os on o.status = os.order_status_id where os.order_status_id = 2 group by os.name; -- how much did the company generate in the year 2017 select os.name, sum(oi.quantity * oi.unit_price) as Total_Revenue from shippers sh join orders o on sh.shipper_id = o.shipper_id join order_statuses os on os.order_status_id = o.status join order_items oi on oi.order_id = o.order_id where (shipped_date between '2017-01-01' and '2017-12-31') and os.order_status_id = 2 group by os.name; -- what the total cost of goods in the company and how many quantity remains select sum(quantity_in_stock) as total_quantity_in_stock, sum(quantity_in_stock * unit_price) as total_cost from products; -- JOINING THE CUSTOMERS TABLES WITH ORDERS TABLE USE store; SELECT * FROM customers JOIN orders ON customers.customer_id = orders.customer_id; -- RETRIEVE THE CUSTOMER FIRST_NAME THAT PLACED ORDER AND THEIR ORDERS DATE SELECT orders.customer_id, first_name, order_date FROM customers JOIN orders ON customers.customer_id = orders.customer_id; -- RETRIEVE THE CUSTOMER NAME AND THE PRODUCT THEY PURCHASE SELECT customers.first_name, products.name FROM customers JOIN orders ON customers.customer_id = orders.customer_id JOIN order_items ON orders.order_id = order_items.order_id JOIN products ON order_items.product_id = products.product_id; -- RETRIEVE THE CUSTOMER FIRST_NAME, THEIR ORDER DATE, THE QUANTITY OF PRODUCT THEY PURCHASE AND THE SHIPPER NAME FOR THE PRODUCT SELECT first_name, order_date, quantity, shippers.name FROM customers JOIN orders ON customers.customer_id = orders.customer_id JOIN order_items ON orders.order_id = order_items.order_id JOIN products ON order_items.product_id = products.product_id JOIN shippers ON orders.shipper_id = shippers.shipper_id; -- RETRIEVE THE PRODUCT THAT HAS BEEN SHIPPED SELECT products.name, order_statuses.name FROM customers JOIN orders ON customers.customer_id = orders.customer_id JOIN order_items ON orders.order_id = order_items.order_id JOIN products ON order_items.product_id = products.product_id JOIN shippers ON orders.shipper_id = shippers.shipper_id JOIN order_statuses ON order_statuses.order_status_id = orders.status; -- RETRIEVE THE CUSTOMER FIRST_NAME THAT PLACED ORDER WHOSE GOODS HAVE BEEN SHIPPED AND THE SHIPPED DATE SELECT first_name, products.name, shipped_date, order_statuses.name FROM customers JOIN orders ON customers.customer_id = orders.customer_id JOIN order_items ON orders.order_id = order_items.order_id JOIN order_statuses ON order_statuses.order_status_id = orders.status JOIN products ON order_items.product_id = products.product_id WHERE order_statuses.order_status_id = 2;
/** @format */ import React from "react"; import { t } from "i18next"; import { Button, Section } from "@/library/core"; import { Modal } from "@/library/modals"; import { Form } from "@/library/form"; import { useDeleteTeamForm } from "../../hooks"; import { DeleteTeamModalProps } from "./types"; export const DeleteTeamModal: React.FC<DeleteTeamModalProps> = ({ team }) => { // Initializes component's states, hooks and etc. const form = useDeleteTeamForm({ team }); return ( <Modal.Init size="small" disabled={form.isSubmitting}> <Modal.Header title={t("Delete team")} description={team.name} /> <Modal.Body> <Form.Init form={form}> <Form.Field> <Form.Input name="name" label={t("Name")} asterisk placeholder={t("Enter team's name")} spellCheck={false} maxLength={64} autoComplete="off" autoFocus /> </Form.Field> <Section.Helper variant="danger"> {t( `This action cannot be undone. This will permanently deletes team's ({{name}}) data. Trainers and athletes of the team will be removed from this team`, { name: team.name } )} </Section.Helper> </Form.Init> </Modal.Body> <Modal.Footer> <Button type="submit" form={form.id} variant="danger" loading={form.isSubmitting} disabled={!form.isValid}> {t("Delete")} </Button> </Modal.Footer> </Modal.Init> ); };
<h2 align="center">SpringBoot Student API </h2> `Java SpringBoot`, `Spring Data JPA`, `Postgresql` ## Motivation In my previous experience, I worked with relational databases using JDBC, which is a Java API for interacting with databases. However, in this project, I made the decision to use Hibernate, which is an implementation of the Java Persistence API (JPA). Hibernate simplifies the mapping of object data to the database schema using annotations. Unlike JDBC, which requires manual mapping code, Hibernate automatically handles the mapping based on the provided annotations. This approach reduces boilerplate code and enables a more object-oriented database interaction. Hibernate also offers advanced features, including caching, lazy loading, and transaction management, enhancing performance and reliability in Java applications. ## Project Overview <h2 align="center"> <img src="images/architecture.png" width="190"> </h2> The Spring Boot project is an API that handles CRUD (Create, Read, Update, Delete) requests for managing students. The project is structured into different layers, including the API layer, service layer, and data access layer. It utilizes various technologies such as Hibernate, JPA (Java Persistence API), and PostgreSQL as the underlying database. ### Key Components and Features: 1. **API Layer**: The API layer handles incoming HTTP requests and maps them to corresponding methods in the controller classes. It defines endpoints for creating, reading, updating, and deleting student records. 2. **Service Layer**: The service layer contains the business logic of the application. It encapsulates the operations and rules related to managing students. The services communicate with the data access layer to perform CRUD operations. 3. **Data Access Layer**: The data access layer is responsible for interacting with the database. It utilizes Hibernate as the ORM (Object-Relational Mapping) framework and JPA for database persistence. The layer includes JPA repositories, which provide an interface to perform database operations. 4. **Hibernate and JPA**: Hibernate is used as the ORM framework to map Java objects to database tables. It simplifies database operations and provides features such as automatic schema generation, caching, and lazy loading. JPA, which is a specification for ORM in Java, is used in conjunction with Hibernate to define entities, relationships, and perform CRUD operations. 5. **PostgreSQL Database**: The project connects to a PostgreSQL database, which serves as the persistent data storage. PostgreSQL is a popular open-source relational database management system known for its reliability and compatibility with Java applications. - Build API that will receive CRUD requested - Service Layer - Data Acccess Layer (connecting to any database) ## Learned 1. Spring Data JPA - abstraction on top of JPA & Hibernate -> easy to work with db. 2. Class = db 3. Hibernate -> Object -> ORM 4. JPA -> Generated queries (SQL) 5. API for CRUD operations on student records. 6. Implemented layers including API, service, and data access. 7. Utilized Hibernate and JPA for object-relational mapping. 8. Connected to a PostgreSQL database for data storage. 9. Learned to build an API, use Hibernate for mapping, and connect to databases. 10. How to package up your application and then from a jar spin up an instance that contains your application. 11. You can basically take the jar, deploy it to a server or dockerize it, do anything you want with your jar. ## Run Locally > java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8081 - Specify your own server ## Author - [@ayazhankadessova](https://github.com/ayazhankadessova) - [Linkedin](https://www.linkedin.com/in/ayazhankad/) ## 👩‍💻 About Me I'm an aspiring Software Developer/Site Reliability Engineer from Kazakhstan, studying in Hong Kong. ## ✍️ Project Steps & Notes - Saved My Steps & Notes [here](https://github.com/ayazhankadessova/springboot-student-api/blob/main/Notes.md).
@extends('layouts.app') @section('page-header') <!-- breadcrumb --> <link rel="shortcut icon" href="{{ URL::asset('assets/images/fiv.png') }}" type="image/x-icon" /> @endsection @section('css') <style> body{ background-image: url({{ asset('assets/images/bg2.png') }}); } </style> @endsection @section('content') <div class="container" > <div class="row justify-content-center"> <div class="col-md-8"> <div class="card " style="margin-top: 10%"> <div class="card-header bg-success text-white"> {{trans('register_page.Student Register')}}</div> <div class="card-body"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif <form method="POST" action="{{ route('register') }}"> @csrf <div class="form-group row"> <label for="name_en" class="col-md-4 col-form-label text-md-right">{{trans('register_page.Name')}}</label> <div class="col-md-6"> <input id="name_en" type="text" class="form-control @error('name_en') is-invalid @enderror" name="name_en" value="{{ old('name_en') }}" autocomplete="name_en" autofocus> @error('name_en') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="name_ar" class="col-md-4 col-form-label text-md-right">{{trans('register_page.Arabic Name')}}</label> <div class="col-md-6"> <input id="name_ar" type="text" class="form-control @error('name_ar') is-invalid @enderror" name="name_ar" value="{{ old('name_ar') }}" autocomplete="name_ar"> @error('name_ar') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="email" class="col-md-4 col-form-label text-md-right">{{trans('register_page.E-Mail Address')}}</label> <div class="col-md-6"> <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email"> @error('email') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="departments" class="col-md-4 col-form-label text-md-right">{{trans('teacher_courses.Department')}}</label> <div class="col-md-6"> <select class="custom-select mr-sm-2 @error('departments') is-invalid @enderror" name="departments"> <option selected disabled>{{trans('teacher_courses.Choose from the list')}}...</option> @foreach($departments as $department) <option value="{{ $department->id }}">{{ $department->Name }}</option> @endforeach </select> @error('departments') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="years" class="col-md-4 col-form-label text-md-right">{{trans('teacher_courses.Years')}}</label> <div class="col-md-6"> <select class="custom-select mr-sm-2 @error('years') is-invalid @enderror" name="years"> <option selected disabled>{{trans('teacher_courses.Choose from the list')}}...</option> @foreach($years as $year) <option value="{{ $year->id }}">{{ $year->Name }}</option> @endforeach </select> @error('years') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password" class="col-md-4 col-form-label text-md-right">{{trans('register_page.Password')}}</label> <div class="col-md-6"> <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="new-password"> @error('password') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{trans('register_page.Confirm Password')}}</label> <div class="col-md-6"> <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password"> </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-success"> {{trans('register_page.Register')}} </button> <a href="{{ route('login.show', 'student') }}" class="btn btn-link"> {{trans('register_page.Have an account? Login')}} </a> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; abstract contract StoringDepositOptions { struct Option { uint256 lockPeriod; uint256 numOfPurchases; uint256 rewardBonusInTenthPerc; } Option[] private options; constructor(Option[] memory _options) { for (uint256 i = 0; i < _options.length; i++) { options.push(_options[i]); } } modifier validOption(uint256 _option) { require(_option < options.length, "Invalid option"); _; } /** * @dev Returns the option at the given index. */ function getOption(uint256 index) public view validOption(index) returns (uint256, uint256, uint256) { Option memory _option = options[index]; return (_option.lockPeriod, _option.numOfPurchases, _option.rewardBonusInTenthPerc); } /** * @dev Returns all options. */ function getOptions() public view returns (Option[] memory) { return options; } }
import React, { useState, useEffect } from "react"; import UserCard from "./UserCard"; import { useAuthContext } from "../hooks/useAuthContext"; import { HiOutlineSearch, HiOutlineFilter } from "react-icons/hi"; import CreateUser from "./CreateUser"; import UserDetails from "./UserDetails"; function Users({ setMenu }) { const [users, setUsers] = useState([]); const [edit, setEdit] = useState({ open: false, data: null }); const { admin } = useAuthContext(); const [showModal, setShowModal] = useState(false); const [userid, setUserid] = useState(""); const fetchAllUsers = async () => { const response = await fetch("https://hospitalapi.vercel.app/users"); const json = await response.json(); if (response.ok) { setUsers(json); } }; const searchUser = async () => { const response = await fetch( `https://hospitalapi.vercel.app/users/${userid}` ); const json = await response.json(); if (response.ok) { setUsers([json]); } }; useEffect(() => { if (admin) { fetchAllUsers(); } }, [edit]); return ( <div className="flex flex-col w-full"> {showModal && ( <CreateUser setShowModal={setShowModal} setEdit={setEdit} /> )} <div className="flex w-full justify-between items-center p-3"> <h1>Users</h1> <button className="w-20 bg-[#0198A5] rounded-md active:scale-95" onClick={() => setShowModal(true)} > Add </button> <div className="flex bg-white w-[35%] p-2 items-center rounded-lg justify-center"> <div className="flex w-full gap-2 px-2 items-center"> <HiOutlineSearch className="relative left-8 text-[#0198A5]" /> <input type="text" value={userid} className=" focus:outline-[#0198A5] bg-[#F7F7F7] w-[80%] pl-8" onChange={(e) => setUserid(e.target.value)} /> <div className="bg-[#F7F7F7] h-6 flex items-center justify-center rounded-md w-6 active:scale-95" onClick={searchUser} > <HiOutlineFilter className="text-[#0198A5]" /> </div> </div> <button className="md:hidden bg-[#0198A5] w-6 h-5 rounded-md" onClick={() => setMenu((prevstate) => !prevstate)} > = </button> </div> </div> {!edit.open ? ( <div className="flex flex-wrap gap-5 h-full w-full p-5 overflow-scroll no-scrollbar "> {users.map((user) => { return ( <UserCard hospitaldata={user} key={user._id} setEdit={setEdit} /> ); })} </div> ) : ( <UserDetails edit={edit} setEdit={setEdit} /> )} </div> ); } export default Users;
# Load the reshape2 package if not already loaded if (!require(reshape2)) { install.packages("reshape2") library(reshape2) } # (i) Get the summary statistics of the air quality dataset summary(airquality) # (ii) Melt airquality dataset and display as long-format data melted_data <- melt(airquality) # (iii) Melt airquality data and specify month and day to be "ID variables" melted_data_with_id <- melt(airquality, id.vars = c("Month", "Day")) # (iv) Cast the molten airquality data set with respect to month and date features casted_data <- dcast(melted_data_with_id, Month + Day ~ variable) # (v) Compute the average of Ozone, Solar.R, Wind, and Temperature per month averages_per_month <- dcast(melted_data, Month ~ variable, fun.aggregate = mean) # Print the results print(averages_per_month)
# 滑动窗口 滑动窗口是一种常用的算法技巧,用于解决一类涉及连续子数组或子字符串的问题。滑动窗口通常适用于以下情况: 1. 字符串或数组中的连续子串/子数组问题:当需要处理连续的子串或子数组,并且需要在该子串/子数组上进行操作(如求和、求平均值、查找最大/最小值等)时,滑动窗口是一种常见的解决方法。比如求解最长连续不重复子串、找到满足特定条件的最小/最大子数组等问题。 2. 固定窗口大小问题:当需要在固定大小的窗口上进行操作,并且需要在窗口滑动过程中维护某种状态或性质时,滑动窗口也是一个有效的技巧。这种情况下,窗口通常由两个指针(左指针和右指针)确定,通过移动指针来滑动窗口,同时更新窗口内的状态。例如,在一个数组中找到满足特定条件的子数组,且该子数组的长度固定为某个值。 3. 寻找最优解问题:滑动窗口在某些情况下可以用于寻找最优解。通过在滑动过程中根据问题要求更新窗口,可以找到满足最优条件的窗口。例如,求解最小覆盖子串、找到最长连续递增子数组等问题。 滑动窗口的核心思想是通过调整窗口的起始位置和终止位置来滑动窗口,以有效地处理子串或子数组的问题。使用滑动窗口可以在时间复杂度为 O(n) 的情况下解决许多与连续子串/子数组相关的问题,提高算法的效率。 需要注意的是,滑动窗口并非适用于所有问题,因此在解决具体问题时,仍需结合实际情况进行分析和判断是否适合使用滑动窗口。
# Día 4 En el día 4 trabajamos lo que son Arrays y Objetos en JavaScript, a continaución un resumen de lo que se vio: ## Array Los Arrays son estructuras de datos que permiten almacenar varios valores de diferentes tipos, veamos algunos ejemplos: - Como declarar un Array: ```javascript let my_array = [valor1, valor2, valor3, valor4, valor5]; ``` - Añadir elementos a un array ```javascript countries.push(valor6); ``` - Eliminar el último elemento de un array ```javascript countries.pop(); ``` - Metodo map, permite recorrer un array y modificar sus elementos ```javascript const numbers = [1, 2, 3, 4, 5]; const squareNumbers = numbers.map(function (number) { return number * number; }); ``` - Metodo reduce permite recorrer un array y devolver un solo valor ```javascript const suma = numeros.reduce(function(acumulador, numero) { return acumulador + numero; }, 0); ``` ## Objetos Los objetos son otra estructura de datos muy importante que permite almacenar valores siguiendo el patron clave valor, veamos algunas utilidades - Como declarar un objeto: ```javascript const miObjeto = { clave1: valor1, clave2: valor2, clave3: valor3 }; ``` - Declarar un objeto con otro objeto como valor ```javascript const curso = { nombre: "30 días de JS", duración: "20 horas", clases: 100, detalles: { tecnologias: ["js", "node", "web browser"], calificacion: 5, }, comentarios: ["¡Excelente curso!", "Javscript no es lo mismo que Java", "hola"] }; ``` - Acceder a las propiedades de un objeto ```javascript curso.nombre; // "30 días de JS" curso["nombre"]; // "30 días de JS" ``` - Un objeto con un método ```javascript let carro = { marca: "Toyota", encender: function() { console.log("El carro ha sido encendido"); } }; ``` - Llamar al método del objeto ```javascript carro.encender(); // "El carro ha sido encendido" ```
package com.ericksantos.todolist.errors; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ExceptionHandlerController { // Handle HttpMessageNotReadableException by returning a ResponseEntity with a // status of BAD_REQUEST @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity<String> httpMessageNotReadable(HttpMessageNotReadableException e) { // Extract the most specific cause message from the exception String errorMessage = e.getMostSpecificCause().getMessage(); // Return a ResponseEntity with the extracted error message and a status of // BAD_REQUEST return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage); } }
// --- Directions // Check to see if two provided strings are anagrams of eachother. // One string is an anagram of another if it uses the same characters // in the same quantity. Only consider characters, not spaces // or punctuation. Consider capital letters to be the same as lower case // --- Examples // anagrams('rail safety', 'fairy tales') --> True // anagrams('RAIL! SAFETY!', 'fairy tales') --> True // anagrams('Hi there', 'Bye there') --> False function anagrams(stringA, stringB) { // ehllo === ehllo // ahhiow === ahhiow // eennoo === oootttwww return cleanString(stringA) === cleanString(stringB); } function cleanString(str) { // The sort() method sorts an array alphabetically: return str.replace(/[^\w]/g, '').toLowerCase().split('').sort().join(''); } // ----------------- Second Way --------------------------- // Low performance function anagrams2(stringA, stringB) { const aCharMap = buildCharMap(stringA); const bCharMap = buildCharMap(stringB); if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) { return false; } // Array --> For-Of && Object --> For-In for (let char in aCharMap) { if (aCharMap[char] !== bCharMap[char]) { return false; } } return true; } function buildCharMap(str) { const charMap = {}; // A regular expression is an object that describes a pattern of characters. for (let char of str.replace(/[^\w]/g, '').toLowerCase()) { // remove space with RegEx charMap[char] = charMap[char] + 1 || 1; } return charMap; // { o: 2, n: 2, e: 2, c: 1 } } module.exports = anagrams;
import 'package:flutter/material.dart'; import 'package:possapp/core/assets/assets.gen.dart'; import 'package:possapp/core/constants/colors.dart'; import 'package:possapp/presentation/history/pages/history_page.dart'; import 'package:possapp/presentation/home/pages/home_page.dart'; import 'package:possapp/presentation/home/widgets/nav_item.dart'; import 'package:possapp/presentation/orders/pages/orders_page.dart'; import 'package:possapp/presentation/setting/pages/setting_page.dart'; class DashboardPageState extends StatefulWidget { const DashboardPageState({super.key}); @override State<DashboardPageState> createState() => _DashboardPageStateState(); } class _DashboardPageStateState extends State<DashboardPageState> { int _selectedIndex = 0; final List<Widget> _pages = [ const HomePage(), const OrdersPage(), const HistoryPage(), const SettingPage(), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: _pages[_selectedIndex], bottomNavigationBar: Container( padding: const EdgeInsets.all(20.0), decoration: BoxDecoration( borderRadius: const BorderRadius.vertical( top: Radius.circular(30), ), color: AppColors.white, boxShadow: [ BoxShadow( offset: const Offset(0, -2), blurRadius: 30.0, blurStyle: BlurStyle.outer, spreadRadius: 0, color: AppColors.black.withOpacity(0.08), ), ], ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ NavItem( iconPath: Assets.icons.home.path, label: 'Home', isActive: _selectedIndex == 0, onTap: () => _onItemTapped(0), ), NavItem( iconPath: Assets.icons.orders.path, label: 'Orders', isActive: _selectedIndex == 1, onTap: () { _onItemTapped(1); }), NavItem( iconPath: Assets.icons.history.path, label: 'History', isActive: _selectedIndex == 2, onTap: () => _onItemTapped(2), ), NavItem( iconPath: Assets.icons.dashboard.path, label: 'Kelola', isActive: _selectedIndex == 3, onTap: () => _onItemTapped(3), ), ], ), ), ); } }
import { Controller, UseGuards, Req, ForbiddenException, BadRequestException } from '@nestjs/common'; import { ApiTags, ApiBearerAuth } from '@nestjs/swagger'; import { AuthGuard } from '@nestjs/passport'; import { Crud, CrudController, Override, ParsedRequest, CrudRequest, ParsedBody } from '@nestjsx/crud'; import { Queue } from 'bull'; import { InjectQueue } from '@nestjs/bull'; import { User } from '../_helpers/decorators/user.decorator'; import { AccessLevel } from '../permissions/entity/access-level.enum'; import { ExerciseService } from '../exercises/exercise.service'; import { TESTSET_SYNC_QUEUE, TESTSET_SYNC_CREATE, TESTSET_SYNC_UPDATE, TESTSET_SYNC_DELETE } from './testset.constants'; import { TestSetService } from './testset.service'; import { TestSetEntity } from './entity/testset.entity'; @Controller('testsets') @ApiTags('testsets') @ApiBearerAuth() @UseGuards(AuthGuard('jwt')) @Crud({ model: { type: TestSetEntity }, params: { id: { field: 'id', type: 'uuid', primary: true } }, routes: { getManyBase: { interceptors: [], decorators: [] }, getOneBase: { interceptors: [], decorators: [] }, createOneBase: { interceptors: [], decorators: [] }, updateOneBase: { interceptors: [], decorators: [] }, deleteOneBase: { interceptors: [], decorators: [], returnDeleted: true } } }) export class TestSetController implements CrudController<TestSetEntity> { constructor( readonly service: TestSetService, @InjectQueue(TESTSET_SYNC_QUEUE) private readonly testsetSyncQueue: Queue, readonly exerciseService: ExerciseService ) {} get base(): CrudController<TestSetEntity> { return this; } @Override() async getOne( @User() user: any, @Req() req, @ParsedRequest() parsedReq: CrudRequest ) { const accessLevel = await this.exerciseService.getAccessLevel(req.params.exercise_id, user.id); if (accessLevel < AccessLevel.VIEWER) { throw new ForbiddenException('You do not have sufficient privileges'); } return this.base.getOneBase(parsedReq); } @Override() async getMany( @User() user: any, @ParsedRequest() parsedReq: CrudRequest ) { const exerciseFilterIndex = parsedReq.parsed.filter .findIndex(f => f.field === 'exercise_id' && f.operator === 'eq'); if (exerciseFilterIndex < 0) { throw new BadRequestException('Test sets must be listed per exercise'); } const accessLevel = await this.exerciseService.getAccessLevel( parsedReq.parsed.filter[exerciseFilterIndex].value, user.id); if (accessLevel < AccessLevel.VIEWER) { throw new ForbiddenException(`You do not have sufficient privileges`); } return this.base.getManyBase(parsedReq); } @Override() async createOne( @User() user: any, @Req() req, @ParsedRequest() parsedReq: CrudRequest, @ParsedBody() dto: TestSetEntity ) { const accessLevel = await this.exerciseService.getAccessLevel(dto.exercise_id, user.id); if (accessLevel < AccessLevel.CONTRIBUTOR) { throw new ForbiddenException(`You do not have sufficient privileges`); } const testset = await this.base.createOneBase(parsedReq, dto); this.testsetSyncQueue.add( TESTSET_SYNC_CREATE, { user, testset } ); return testset; } @Override() async updateOne( @User() user: any, @Req() req, @ParsedRequest() parsedReq: CrudRequest, @ParsedBody() dto: TestSetEntity ) { const accessLevel = await this.service.getAccessLevel(req.params.id, user.id); if (accessLevel < AccessLevel.CONTRIBUTOR) { throw new ForbiddenException(`You do not have sufficient privileges`); } const testset = await this.base.updateOneBase(parsedReq, dto); this.testsetSyncQueue.add( TESTSET_SYNC_UPDATE, { user, testset } ); return testset; } @Override() async deleteOne( @User() user: any, @Req() req, @ParsedRequest() parsedReq: CrudRequest ) { const accessLevel = await this.service.getAccessLevel(req.params.id, user.id); if (accessLevel < AccessLevel.CONTRIBUTOR) { throw new ForbiddenException( `You do not have sufficient privileges`); } const testset = await this.base.deleteOneBase(parsedReq); if (testset) { this.testsetSyncQueue.add( TESTSET_SYNC_DELETE, { user, testset } ); } return testset; } }
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { map, Subject ,catchError,throwError, Subscription} from 'rxjs'; import { AuthService } from '../auth.service'; import { Post } from './post.model'; import { PostsService } from './posts.service'; @Component({ selector: 'app-http-req', templateUrl: './http-req.component.html', styleUrls: ['./http-req.component.css'] }) export class HttpReqComponent implements OnInit { loadedPosts: Post[] = []; isFetching = false; error = ""; token!:string; private errorSub!: Subscription; constructor(private http: HttpClient, private postsService: PostsService,private authService:AuthService) { this.token=this.authService.getToken(); // console.log(this.token); } ngOnInit() { this.errorSub = this.postsService.error.subscribe(errorMessage => { this.error = errorMessage; }); this.isFetching = true; this.postsService.fetchPosts(this.token).subscribe( posts => { this.isFetching = false; this.loadedPosts = posts; }, error => { this.isFetching = false; this.error = error.message; } ); } onCreatePost(postData: Post) { // Send Http request this.postsService.createAndStorePost(postData.title, postData.content,this.token); } onFetchPosts() { // Send Http request this.isFetching = true; this.postsService.fetchPosts(this.token).subscribe( posts => { this.isFetching = false; this.loadedPosts = posts; }, error => { this.isFetching = false; this.error = error.message; console.log(error); } ); } onClearPosts() { // Send Http request this.postsService.deletePosts().subscribe(() => { this.loadedPosts = []; }); } onHandleError() { this.error = ""; } ngOnDestroy() { this.errorSub.unsubscribe(); } delete(id:any){ console.log(id); } }
- Joins in SQL allow you to combine data from multiple tables based on related columns. They are used to retrieve data that is distributed across different tables and establish relationships between them. - SQL supports different types of joins, including: - **INNER JOIN**: Returns only the rows where there is a match between the joining columns of the two tables. It combines the matching rows from both tables into a single result set. - **LEFT JOIN (or LEFT OUTER JOIN)**: Returns all rows from the left table and the matching rows from the right table. If there is no match, it includes NULL values for the right table columns. - **RIGHT JOIN (or RIGHT OUTER JOIN)**: Returns all rows from the right table and the matching rows from the left table. If there is no match, it includes NULL values for the left table columns. - **FULL JOIN (or FULL OUTER JOIN)**: Returns all rows from both tables. It includes all matching rows as well as the unmatched rows from both tables. If there is no match, it includes NULL values for the non-matching table columns. - **CROSS JOIN**: Returns the Cartesian product of the two tables, meaning it combines every row from the first table with every row from the second table. It does not require any specific join conditions. - Joining tables requires specifying the join conditions using the ON keyword or the WHERE clause: - **ON**: Specifies the columns or expressions to join the tables. It defines the relationship between the tables based on the equality of the specified columns. - **WHERE**: Specifies the join conditions using the WHERE clause. It allows you to define additional filtering criteria for the join. - Joining multiple tables can involve chaining multiple join operations. For example, you can join Table A with Table B using an INNER JOIN, and then join the result with Table C using another INNER JOIN. - When joining tables, it is important to ensure that the join conditions are properly defined and that the related columns have appropriate indexes for performance optimization. - Joins can be used in various scenarios: - **Retrieving Related Data**: Joins are commonly used to retrieve data from multiple tables that have a relationship defined by foreign keys. For example, you can retrieve customer information along with their corresponding orders from separate customer and order tables. - **Combining Data**: Joins are used to combine data from different tables to create a unified view or report. This is particularly useful when data is spread across multiple tables and needs to be consolidated. - **Data Analysis and Aggregation**: Joins are essential for performing data analysis and aggregation operations, such as calculating sums, averages, or counts across multiple related tables. - Joins play a crucial role in SQL queries, allowing you to leverage the relationships between tables and retrieve data from multiple sources. Understanding the different join types and their usage is important for working with complex database schemas.
package com.example.t2; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.DatePickerDialog; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import androidx.appcompat.widget.SearchView; import android.widget.Spinner; import android.widget.Toast; import com.example.t2.model.CauThuAdapter; import com.example.t2.model.CauThu; import com.example.t2.model.CauThuAdapter; import com.example.t2.model.SpinnerAdapter; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener,CauThuAdapter.CauThuItemListener,SearchView.OnQueryTextListener { private RecyclerView recyclerView; private CauThuAdapter adapter; private EditText edTen,edNgay; private CheckBox cb1,cb2,cb3; private RadioButton rg1,rg2; private Button add,update; private SearchView searchView; private int pcur; private Spinner sp; private int[]imgs={R.drawable.car,R.drawable.xemay,R.drawable.maybay}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); adapter=new CauThuAdapter(this); LinearLayoutManager manager=new LinearLayoutManager(this,RecyclerView.VERTICAL,false); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(adapter); edNgay.setOnClickListener(this); adapter.setClickListener(this); searchView.setOnQueryTextListener(this); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CauThu cauThu = new CauThu(); String i=sp.getSelectedItem().toString(); int img=R.drawable.car; String ten=edTen.getText().toString(); String ngay=edNgay.getText().toString(); String gioitinh=""; boolean rg11 = rg1.isChecked(); boolean rg21 = rg2.isChecked(); boolean cb11 = cb1.isChecked(); boolean cb21 = cb2.isChecked(); boolean cb31 = cb3.isChecked(); if(!ten.isEmpty() && !ngay.isEmpty()){ if(rg11){ gioitinh="Nam"; } if(rg21){ gioitinh="Nu"; } img=imgs[Integer.parseInt(i)]; cauThu.setImg(img); cauThu.setTen(ten); cauThu.setGioitinh(gioitinh); cauThu.setNgaysinh(ngay); cauThu.setHauve(cb11); cauThu.setTienve(cb21); cauThu.setTiendao(cb31); adapter.add(cauThu); edTen.setText(""); edNgay.setText(""); rg1.setChecked(false); rg2.setChecked(false); cb1.setChecked(false); cb2.setChecked(false); cb3.setChecked(false); } else { Toast.makeText(getApplicationContext(),"Nhap data",Toast.LENGTH_LONG).show(); } } }); update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CauThu cauThu = new CauThu(); String ten=edTen.getText().toString(); String ngay=edNgay.getText().toString(); String gioitinh=""; String i=sp.getSelectedItem().toString(); int img=R.drawable.maybay; boolean rg11 = rg1.isChecked(); boolean rg21 = rg2.isChecked(); boolean cb11 = cb1.isChecked(); boolean cb21 = cb2.isChecked(); boolean cb31 = cb3.isChecked(); if(!ten.isEmpty() && !ngay.isEmpty()){ if(rg11){ gioitinh="Nam"; } if(rg21){ gioitinh="Nu"; } img=imgs[Integer.parseInt(i)]; cauThu.setImg(img); cauThu.setTen(ten); cauThu.setGioitinh(gioitinh); cauThu.setNgaysinh(ngay); cauThu.setHauve(cb11); cauThu.setTienve(cb21); cauThu.setTiendao(cb31); adapter.update(pcur,cauThu); add.setEnabled(true); update.setEnabled(false); } else { Toast.makeText(getApplicationContext(),"Nhap data",Toast.LENGTH_LONG).show(); } } }); } private void initView() { sp=findViewById(R.id.img); SpinnerAdapter spinnerAdapter=new SpinnerAdapter(this); sp.setAdapter(spinnerAdapter); edTen = findViewById(R.id.edTen); edNgay = findViewById(R.id.edNgay); rg1 = findViewById(R.id.rg1); rg2 = findViewById(R.id.rg2); cb1 = findViewById(R.id.cb1); cb2 = findViewById(R.id.cb2); cb3 = findViewById(R.id.cb3); add = findViewById(R.id.btadd); update = findViewById(R.id.btupdate); recyclerView = findViewById(R.id.recyclerView); update.setEnabled(false); searchView=findViewById(R.id.search); } @Override public void onClick(View view) { if(view==edNgay){ Calendar c= Calendar.getInstance(); int y=c.get(Calendar.YEAR); int m=c.get(Calendar.MONTH); int d=c.get(Calendar.DAY_OF_MONTH); DatePickerDialog dialog= new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker datePicker, int yy, int mm, int dd) { edNgay.setText(yy+"/"+(mm+1)+"/"+dd); } },y,m,d); dialog.show(); } } @Override public void onItemClick(View view, int position) { add.setEnabled(false); update.setEnabled(true); pcur=position; CauThu cauThu=adapter.getItem(position); edTen.setText(cauThu.getTen()); int img=cauThu.getImg(); int p=0; for (int i=0;i<imgs.length;i++){ if (img==imgs[i]){ p=i; break; } } sp.setSelection(p); edNgay.setText(cauThu.getNgaysinh()); String gioitinh=cauThu.getGioitinh(); if (gioitinh.contains("Nam")){ rg1.setChecked(true); } else{ rg2.setChecked(true); } if(cauThu.isHauve()){ cb1.setChecked(true); } else{ cb1.setChecked(false); } if(cauThu.isTienve()){ cb2.setChecked(true); } else{ cb2.setChecked(false); } if(cauThu.isTiendao()){ cb3.setChecked(true); } else{ cb3.setChecked(false); } } @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { filter(s); return false; } private void filter(String s){ List<CauThu> filterlist=new ArrayList<>(); for (CauThu c:adapter.getBackup()){ if(c.getTen().toLowerCase().contains(s.toLowerCase())){ filterlist.add(c); } } if(filterlist.isEmpty()){ Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show(); }else{ adapter.filterList(filterlist); } } }
import 'package:flutter/material.dart'; class InputWidget extends StatelessWidget { final String? hintText; final IconData? prefixIcon; final double height; final String topLabel; final bool obscureText; InputWidget({ this.hintText, this.prefixIcon, this.height = 48.0, this.topLabel = "", this.obscureText = false, }); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( this.topLabel, style: TextStyle( fontFamily: "Sofia", fontSize: 18.0, fontWeight: FontWeight.w600), ), SizedBox(height: 5.0), Container( height: height, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(8.0), ), child: TextFormField( obscureText: this.obscureText, decoration: InputDecoration( prefixIcon: this.prefixIcon == null ? this.prefixIcon as Widget? : Icon( this.prefixIcon, color: Color.fromRGBO(105, 108, 121, 1), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide( color: Color(0xFF999B84), ), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide( color: Color(0xFF999B84), ), ), hintText: this.hintText, hintStyle: TextStyle( fontFamily: "Sofia", fontSize: 14.0, color: Color.fromRGBO(105, 108, 121, 0.7), ), ), ), ) ], ); } }
Turret This is a python program control automatic turret with termal camera through Raspberry Pi ## Matirial single-board computers : [Raspberry Pi 4 model b](https://piepie.com.tw/product/raspberry-pi-4-model-b-4gb) Motors : [K-Power Hb200t * 2](https://www.made-in-china.com/showroom/servo-kyra/product-detailTyEQoAuWXwhO/China-K-Power-Hb200t-12V-200kg-Torque-Steel-Gear-Digital-Industrial-Servo.html) Thermal Camera: [MLX90640-BAA IR Thermal Camera](https://twarm.com/commerce/product_info.php?products_id=7218) ## Raspberry Pi Setup [How to set up a Raspberry Pi](https://www.raspberrypi.com/tutorials/how-to-set-up-raspberry-pi/) ## Installation ### Using `pip` Use the package manager [pip](https://pip.pypa.io/en/stable/) to install python package. Install the dependencies from `requirements.txt` ```bash pip install ``` If the `requirements.txt` not found or outdated, you may have to use `pipenv` ### Using `pipenv` Using Python virtualenv management tool [pipenv](https://pipenv.pypa.io/en/latest/) to install and isolate python packages from other projects. > To install `pipenv` > ```bash > pip install --user pipenv > ``` Install the dependencies from `pipfile` ```bash pipenv install ``` Install the dependencies from `requirements.txt` ```bash pipenv install -r path/to/requirements.txt ``` If the `requirements.txt` not found or outdated, you may recreate it with `pipfile` from `pipenv`: ```bash pipenv lock -r > requirements.txt ``` ### Error installing opencv-python Sometime opencv-python couldn't be installed on Raspberry Pi. The installation will stuck in likely the last step, pending something forever. In this case, you may install the older version of opencv-python. e.g.: ```bash pip install opencv-python==4.4.0.46 ``` ### Adafruit_CircuitPython_MLX90640 **Original Repository** : [Adafruit_CircuitPython_MLX90640](https://github.com/adafruit/Adafruit_CircuitPython_MLX90640.git) The original repository (python) is unable to use the frequency above 8 Hz with thermal camera. To make is work on 8 Hz and above, it is needed to make some changes in the original repository. **Edited Repository ( 8 Hz and above frequency enable )** : [Adafruit_CircuitPython_MLX90640](https://github.com/seantjjd4/Adafruit_CircuitPython_MLX90640.git) ```bash git clone https://github.com/seantjjd4/Adafruit_CircuitPython_MLX90640.git # in your project enviroment pip install -e /path/to/Adafruit_CircuitPython_MLX90640/ ``` ## Usage ```bash cd /path/to/project_folder python3 main.py ``` ### To Run Test ```bash python3 -m unittest # to run specific test file python3 -m unittest test/test_file ``` ## Set Auto Start There are serveral autostart methods in raspberry pi. ### Systemd service setting Using systemd service unit for auto start raspberry pi project 1. Create a systemd service unit file ```bash sudo nano /etc/systemd/system/turret-autostart.service ``` 2. Add the following content to the turret-autostart.service file ```bash [Unit] Description=Turret program autostart service [Service] ExecStart=/bin/bash /path/to/turret/autostart.sh Restart=on-failure User=${user-name} [Install] WantedBy=multi-user.target ``` 3. Reload systemd to read the new service unit after save the file ```bash sudo systemctl daemon-reload ``` 4. Enable the service to your project ```bash sudo systemctl enable turret-autostart.service ``` 5. Start your service ```bash sudo systemctl start turret-autostart.service ``` ### Restart and check the status! Restart: ```bash sudo reboot ``` Check service status and log: ```bash sudo systemctl status turret-autostart.service ``` Check python program: ```bash ps aux | grep python ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/)
""" Flask Application for Sentiment Comparison -------------------------------------------- Developer: Nick Gambirasi Date: 02 September 2023 Purpose -------------------------------------------- This script is for the flask app. The purpose of the flask app is to employ the model on a "production" dataset to evaluate which airlines have the best customer satisfaction rates. The application begins with the screen that is contains a single button. When the user clicks this button, they will be redirected to the main application page. In the meantime, the program will read in the production dataset and make all of the predictions on the production data. After the predictions are made, then the user will be redirected again to a page that shows the comparisons of the airlines in some graphics. """ from flask import Flask, render_template import os from app_utils import collect_and_predict, plot_data APP_ROOT = os.path.abspath(os.path.dirname(__file__)) app = Flask(__name__) global pred_data global airlines pred_data = None airlines = [] @app.route("/") def redirect(): return render_template("loading.html") @app.route("/select-airline") def select_airline(): global pred_data global airlines if pred_data is None: pred_data = collect_and_predict() if not airlines: with open(os.path.join(APP_ROOT, os.pardir, "data/airlines.txt")) as f: for line in f.readlines(): airlines.append(line.strip().replace(" ", "_")) context = {"airlines": airlines} return render_template("homepage.html", **context) @app.route("/analysis/<airline_name>") def results(airline_name: str): """ Queries the production data for the first airline selected from the initial webpage. """ global pred_data global airlines airlines_copy = airlines.copy() try: airlines_copy.remove(airline_name) except ValueError as e: pass airline_data = pred_data.query("airline==@airline_name.replace('_', ' ')") context = { "graphJSON": plot_data(data_df=airline_data), "airline": airline_name, "unselected_airlines": airlines_copy, } return render_template("results.html", **context) @app.route("/analysis/compare/<airline1_name>+<airline2_name>") def compare(airline1_name: str, airline2_name: str): global pred_data # airline1_name = airline1_name.replace("_", " ") # airline2_name = airline2_name.replace("_", " ") airline1_data = pred_data.query("airline==@airline1_name.replace('_', ' ')") airline2_data = pred_data.query("airline==@airline2_name.replace('_', ' ')") context = { "airline1_name": airline1_name, "airline2_name": airline2_name, "airline1_graphJSON": plot_data(data_df=airline1_data), "airline2_graphJSON": plot_data(data_df=airline2_data), } return render_template("compare.html", **context) if __name__ == "__main__": app.run(debug=True)
import {Component, Inject, OnInit, ViewEncapsulation} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog"; import {ScheduleService} from 'app/shared/services/schedule.service'; import {fuseAnimations} from "../../../../../@fuse/animations"; @Component({ selector: 'app-schedule-create', templateUrl: './schedule-create.component.html', styleUrls: ['./schedule-create.component.scss'], encapsulation: ViewEncapsulation.None, animations: fuseAnimations }) export class ScheduleCreateComponent implements OnInit { action: any; dialogTitle: any; scheduleForm: FormGroup; isSubmitted = false; updateData: any; constructor(public matDialogRef: MatDialogRef<ScheduleCreateComponent>, @Inject(MAT_DIALOG_DATA) private _data: any, private fb: FormBuilder, private scheduleService: ScheduleService) { this.action = _data.action; if (this.action === 'EDIT') { this.dialogTitle = 'Edit Schedule'; if (_data.schedule) { this.updateData = _data; } } else { this.dialogTitle = 'Add Schedule'; } } ngOnInit(): void { this.refresh(); this.checkForUpdate(); } refresh() { this.scheduleForm = this.fb.group({ 'name': ['', Validators.required], 'isActive': [true, Validators.required] }); } checkForUpdate() { if (this.updateData) { this.scheduleForm.patchValue({ 'name': this.updateData.schedule.name, 'isActive': this.updateData.schedule.isActive }); } } saveSchedule() { this.isSubmitted = true; if (!this.scheduleForm.valid) { this.isSubmitted = false; return; } if (this.isSubmitted) { this.scheduleService.addSchedule(this.scheduleForm.value).subscribe(data => { this.scheduleForm.reset(); this.isSubmitted = false; }); } } updateSchedule() { this.isSubmitted = true; if (!this.scheduleForm.valid) { this.isSubmitted = false; return; } if (this.isSubmitted) { this.scheduleService.updateSchedule(this.updateData.schedule.id, this.scheduleForm.value).subscribe(data => { this.updateData = undefined; this.scheduleForm.reset(); this.isSubmitted = false; }); } } }
@extends('layouts.app', ['class' => 'g-sidenav-show bg-gray-100']) @section('content') @include('layouts.navbars.auth.topnav', ['title' => 'Arsip Surat']) <div class="container-fluid py-4"> <div class="row"> <div class="col-12"> <div class="card mb-4"> <div class="card-header pb-0"> <h2>Arsip Surat</h2> <div class="d-flex align-items-center mt-4"> <span class="me-2">Cari Surat:</span> <div class="col-6"> <input type="text" class="form-control" id="searchJudul" placeholder="Masukkan Judul Surat"> </div> <button class="btn btn-primary ms-2 my-auto" id="btnSearchJudul">Cari</button> </div> </div> <div class="card-body "> @if (session('success')) <div class="alert alert-success"> {{ session('success') }} </div> @endif <div class="table-responsive p-0"> <table class="table align-items-center mb-0"> <thead> <tr> <th>Nomor Surat</th> <th>Kategori</th> <th>Judul</th> <th>Waktu Pengarsipan</th> <th>Aksi</th> </tr> </thead> <tbody> @foreach ($data as $row) <tr> <th>{{ $row->nomor_surat }}</th> <td>{{ optional($row->kategori)->nama_kategori }}</td> <td>{{ $row->judul }}</td> <td>{{ $row->waktu_arsip }}</td> <td> <a href="{{ route('arsip.hapus', ['id' => $row->id]) }}" class="btn btn-danger" onclick="return confirm('Anda yakin ingin menghapus data kategori surat ini?');"><i class="fas fa-trash"></i> Hapus</a> <a href="{{ asset('storage/file_surat/' . $row->file_surat) }}" download="{{ $row->judul }}.pdf" class="btn btn-kuning"><i class="fas fa-download"></i> Unduh</a> <a href="{{ route('arsip.lihat', $row->id) }}" class="btn btn-info"><i class="fas fa-eye"></i> Lihat</a> </td> </tr> @endforeach </tbody> </table> </div> </div> <div class="card-footer"> <a href="{{ route('arsip.tambah') }}" class="btn btn-success">Arsipkan Surat</a> </div> </div> </div> </div> </div> <style> .table th, .table td { text-align: center; } .table thead th { vertical-align: middle; } </style> <script> document.getElementById('btnSearchJudul').addEventListener('click', function() { var searchValue = document.getElementById('searchJudul').value.toLowerCase(); var rows = document.querySelectorAll('.table tbody tr'); rows.forEach(function(row) { var name = row.children[2].textContent.toLowerCase(); if (name.includes(searchValue)) { row.style.display = ''; } else { row.style.display = 'none'; } }); }); </script> <!-- Tambahkan di bagian head atau sebelum penutup tag body --> <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script> <script> document.addEventListener('DOMContentLoaded', function() { var downloadButtons = document.querySelectorAll('.btn-download'); downloadButtons.forEach(function(button) { button.addEventListener('click', function(event) { event.preventDefault(); // Dapatkan URL file dari atribut data var fileUrl = this.getAttribute('data-file-url'); // Minta pengguna untuk memilih direktori penyimpanan var directoryPath = prompt( 'Masukkan direktori penyimpanan (cth: /path/to/directory)'); if (directoryPath) { // Gunakan FileSaver.js untuk menyimpan file ke direktori yang dipilih fetch(fileUrl) .then(response => response.blob()) .then(blob => saveAs(blob, directoryPath + '/' + fileUrl.split('/') .pop())); } }); }); }); </script> @include('layouts.footers.auth.footer') @endsection
# Depth Stencil View ![image-20231211181118793](../../../image/image-20231211181118793.png) ## DSV Depth Stencil View (DSV)는 그래픽 프로그래밍에서 깊이(depth)와 스텐실(stencil) 정보를 담고 있는 텍스처를 나타내는 개체이다. 주로 3D 그래픽스에서 깊이 버퍼 (depth buffer)를 사용하여 깊이 정보를 저장하고, 스텐실 버퍼 (stencil buffer)를 사용하여 렌더링 동작을 제어한다. DSV는 이러한 깊이와 스텐실 정보를 GPU에서 사용할 수 있도록 만들어주는 중요한 개념이다. ## 스텐실? 스텐실이란 그래픽스 및 이미지 프로세싱에서 사용되는 기술 중 하나로, 특정한 영역의 픽셀을 제어하고 수정하는 데 사용된다. 이 스텐실은 깊이 버퍼와 함께 사용되어 복잡한 렌더링 및 영상처리 기술을 구현하는 데 도움이 된다. 예를 들어, 스텐실을 사용하여 반투명한 물체를 렌더링하거나, 특정 부분에 대한 그림자 효과를 추가하는 등의 작업이 가능하다. ## 스텐실의 주요역할은 다음과 같다. 1. 영역 제어 : 특정한 조건을 만족하는 픽셀들만을 선택하여 처리할 수 있다. 이를 통해 특정한 부분에 대한 처리를 제한하거나 강조할 수 있다. 2. 렌더링 명령의 조건부 실행 : 스텐실 값을 기반으로 렌더링 명령을 조건부로 수행하거나 건너뛸 수 있다. 3. 마스킹 및 클리핑 : 특정 영역을 마스크 (mask)하여 해당 영역만을 보존하고 나머지를 무시할 수 있다. 또한, 스텐실을 사용하여 특정 영역을 클리핑하여 화면에 그려지지 않도록 할 수 있다. ## 다시 돌아와서 DSV의 역할과 사용 방법에 대해 1. **깊이 스텐실 텍스쳐 생성 및 설정** : 먼저, 깊이와 스텐실 정보를 담을 텍스처를 생성하고 설정한다. 이 텍스처는 주로 깊이 버퍼와 스텐실 버퍼의 역할을 수행한다. ```c++ D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {}; dsvHeapDesc.NumDescriptors = 1; dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV; dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; ID3D12DescriptorHeap* dsvHeap; device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&dsvHeap)); D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {}; dsvDesc.Format = DXGI_FORMAT_D32_FLOAT; // 깊이 형식 dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; // 2D 텍스처 device->CreateDepthStencilView(depthStencilBuffer, &dsvDesc, dsvHeap->GetCPUDescriptorHandleForHeapStart());xxxxxxxxxx D3D12_DESCRD3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};dsvHeapDesc.NumDescriptors = 1;dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;ID3D12DescriptorHeap* dsvHeap;device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&dsvHeap));D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = {};dsvDesc.Format = DXGI_FORMAT_D32_FLOAT; // 깊이 형식dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D; // 2D 텍스처device->CreateDepthStencilView(depthStencilBuffer, &dsvDesc, dsvHeap->GetCPUDescriptorHandleForHeapStart()); ``` 깊이 형식과 텍스처의 차원 등을 지정하여 DSV를 생성한다. 2. **렌더링 파이프라인에서 DSV 설정** : 렌더링 파이프라인 설정 중에 DSV를 사용할 수 있도록 설정해야한다. 이는 주로 렌더 타겟 뷰 (RTV)와 함께 렌더링 명령 리스트에 설정 된다. ```c++ commandList->OMSetRenderTargets(1, &rtvDescriptor, true, &dsvDescriptor); ``` RTV는 색상 정보를, DSV는 깊이와 스텐실 정보를 나타낸다. 이 정보들은 렌더 타겟으로 사용되어 화면에 렌더링되는 씬의 모습을 결정한다. 3. **깊이 테스트와 스텐실 테스트** : DSV는 렌더링 중에 깊이 테스트와 스텐실 테스트와 함께 사용된다. 깊이 테스트는 픽셀의 깊이 값을 기준으로 픽셀을 그릴지 말지를 결정하고, 스텐실 테스트는 스텐실 값을 기준으로 픽셀을 그릴지를 결정한다. ```c++ // 깊이 테스트와 스텐실 테스트 설정 D3D12_DEPTH_STENCIL_DESC depthStencilDesc = {}; depthStencilDesc.DepthEnable = TRUE; depthStencilDesc.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DetphFunc = D3D12_COMPARISON_FUNC_LESS; depthStencilDesc.StencilEnable = FALSE; // 스텐실 테스트를 사용할지 여부 device->CreateDepthStencilState(&depthStencilDesc, &depthStencilState); commandList->OMSetDepthStencilState(depthStencilState, 0); ``` ​ 깊이 테스트와 스텐실 테스트를 설정하기 위해 `D3D12_DEPTH_STENCIL_DESC`구조체를 사용한다. Depth Stencil View는 3D 그래픽 애플리케이션에서 깊이와 스텐실 처리에 필수적인 요소 중 하나이며, 올바르게 설정되어야 올바른 렌더링 동작을 보장할 수 있다.
package com.example.a7mintuesworkout import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = [HistoryEntity::class], version = 1) abstract class HistoryDatabase: RoomDatabase() { abstract fun historyDao():HistoryDao companion object{ @Volatile private var INSTANCE:HistoryDatabase? = null fun getInstance(context: Context):HistoryDatabase{ synchronized(this){ var instance = INSTANCE if (instance== null){ instance = Room.databaseBuilder( context.applicationContext, HistoryDatabase::class.java, "history_database" ).fallbackToDestructiveMigration() .build() INSTANCE = instance } return instance } } } }
<!DOCTYPE html> <html lang="ko" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <header class="p-3 bg-dark text-white"> <div class="container"> <div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start"> <ul class="nav col-12 col-lg-auto me-lg-auto mb-2 justify-content-center mb-md-0"> <li><a id="home" class="header-nav nav-link px-2 text-secondary" th:href="@{/}">Home</a></li> <li><a id="hashtag" class="header-nav nav-link px-2 text-secondary" th:href="@{/posts/search-hashtag}" >Hashtags</a></li> <li><a id="my_posts" class="header-nav nav-link px-2 text-secondary" th:href="@{/posts/my}" >My Posts</a></li> <li> <a id="notifications" class="header-nav nav-link px-2 text-secondary" th:href="@{/users/alarm}">Notifications <span id="notification-count" style="display: none;"></span> </a> </li> </ul> <div class="text-end"> <span id="username" class="text-white me-2" sec:authorize="isAuthenticated()" sec:authentication="principal.nickname"></span> <a role="button" id="login" class="btn btn-outline-light me-2" sec:authorize="!isAuthenticated()" th:href="@{/users/login}">Login</a> <a role="button" id="signup" class="btn btn-outline-light me-2" sec:authorize="!isAuthenticated()" th:href="@{/users/signup}">Signup</a> <a role="button" id="logout" class="btn btn-outline-light me-2" sec:authorize="isAuthenticated()" th:href="@{/logout}">Logout</a> </div> </div> </div> <link rel="stylesheet" href="/css/header.css"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="/js/header.js"></script> </header> </body> </html>
--- id: 657d0a5bf57d5c721d5e82e4 title: ステップ 38 challengeType: 0 dashedName: step-38 --- # --description-- Next, create another `for...of` loop that loops through the `arr`. The variable name for the `for...of` loop should be called `num`. # --hints-- You should have a `for...of` loop with a variable named `num`. ```js assert.match(code, /for\s*\(\s*(const|let|var)\s+num\s+of\s+arr\s*\)\s*{\s*}/); ``` # --seed-- ## --seed-contents-- ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Advanced Dice Game</title> <link rel="stylesheet" href="styles.css" /> </head> <body> <header> <h1>Advanced Dice Game</h1> <button class="btn" id="rules-btn" type="button">Show rules</button> <div class="rules-container"> <h2>Rules</h2> <ul> <li>There are total of six rounds</li> <li>You can only roll the dice three times per round</li> <li>To start the game, roll the dice</li> <li> Then, choose from one of the selected scores or roll the dice again </li> <li> If you choose a selected score, then you will move to the next round </li> <li> If you decline to choose a selected score, then you can roll the dice again two more times </li> </ul> <h2 class="points">Points</h2> <ul> <li>Three of a kind: Sum of all five dice</li> <li>Four of a kind: Sum of all five dice</li> <li>Full house: Three of a kind and a pair - 25 points</li> <li> Small straight: Four of the dice have consecutive values - 30 points </li> <li> Large straight: All five dice have consecutive values - 40 points </li> </ul> </div> </header> <main> <form id="game"> <div id="dice"> <div class="die"></div> <div class="die"></div> <div class="die"></div> <div class="die"></div> <div class="die"></div> </div> <p class="rounds-text"> <strong>Rolls:</strong> <span id="current-round-rolls">0</span> | <strong>Round:</strong> <span id="current-round">1</span> </p> <div id="score-options"> <div> <input type="radio" name="score-options" id="three-of-a-kind" value="three-of-a-kind" disabled /> <label for="three-of-a-kind">Three of a kind<span></span></label> </div> <div> <input type="radio" name="score-options" id="four-of-a-kind" value="four-of-a-kind" disabled /> <label for="four-of-a-kind">Four of a kind<span></span></label> </div> <div> <input type="radio" name="score-options" id="full-house" value="full-house" disabled /> <label for="full-house">Full house<span></span></label> </div> <div> <input type="radio" name="score-options" id="small-straight" value="small-straight" disabled /> <label for="small-straight">Small straight<span></span></label> </div> <div> <input type="radio" name="score-options" id="large-straight" value="large-straight" disabled /> <label for="large-straight">Large straight<span></span></label> </div> <div> <input type="radio" name="score-options" id="none" value="none" disabled /> <label for="none">None of the above<span></span></label> </div> </div> <button class="btn" id="keep-score-btn" type="button"> Keep the above selected score </button> <button class="btn" id="roll-dice-btn" type="button"> Roll the dice </button> </form> <div id="scores"> <h3>Score history (Total score: <span id="total-score">0</span>)</h3> <ol id="score-history"></ol> </div> </main> <script src="./script.js"></script> </body> </html> ``` ```css *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } :root { --dark-grey: #1b1b32; --light-grey: #f5f6f7; --black: #000; --white: #fff; --grey: #3b3b4f; --golden-yellow: #fecc4c; --yellow: #ffcc4c; --gold: #feac32; --orange: #ffac33; --dark-orange: #f89808; } body { background-color: var(--dark-grey); } header { color: var(--light-grey); text-align: center; } h1 { font-size: 2.5rem; margin: 25px 0; } .rules-container { display: none; background-color: var(--light-grey); color: var(--black); width: 50%; margin: 20px auto; height: 300px; border-radius: 10px; overflow-y: scroll; } .rules-container ul { list-style-type: none; } .points { margin-top: 15px; } main { background-color: var(--light-grey); padding: 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(500px, 1fr)); gap: 1rem; margin: auto; justify-items: center; width: 50%; border-radius: 10px; } #dice { display: flex; justify-content: space-around; margin-bottom: 15px; } .die { width: 40px; height: 40px; text-align: center; margin-right: 15px; border: 4px solid var(--black); padding: 10px; } .rounds-text { text-align: center; } input[type="radio"]:disabled + label { color: var(--grey); } #score-history { margin-top: 15px; text-align: center; list-style-position: inside; } .btn { cursor: pointer; width: 200px; margin: 10px 0 10px 0.5rem; color: var(--black); background-color: var(--gold); background-image: linear-gradient(var(--golden-yellow), var(--orange)); border-color: var(--gold); border-width: 3px; } .btn:hover:enabled { background-image: linear-gradient(var(--yellow), var(--dark-orange)); } @media (max-width: 992px) { main { width: 100%; } } @media (max-width: 500px) { .btn { width: 120px; } } ``` ```js const listOfAllDice = document.querySelectorAll(".die"); const scoreInputs = document.querySelectorAll("#score-options input"); const scoreSpans = document.querySelectorAll("#score-options span"); const currentRoundText = document.getElementById("current-round"); const currentRoundRollsText = document.getElementById("current-round-rolls"); const totalScoreText = document.getElementById("total-score"); const scoreHistory = document.getElementById("score-history"); const rollDiceBtn = document.getElementById("roll-dice-btn"); const keepScoreBtn = document.getElementById("keep-score-btn"); const rulesContainer = document.querySelector(".rules-container"); const rulesBtn = document.getElementById("rules-btn"); let diceValuesArr = []; let isModalShowing = false; let score = 0; let totalScore = 0; let round = 1; let rolls = 0; const rollDice = () => { diceValuesArr = []; for (let i = 0; i < 5; i++) { const randomDice = Math.floor(Math.random() * 6) + 1; diceValuesArr.push(randomDice); }; listOfAllDice.forEach((dice, index) => { dice.textContent = diceValuesArr[index]; }); }; const updateStats = () => { currentRoundRollsText.textContent = rolls; currentRoundText.textContent = round; }; const updateRadioOption = (optionNode, score) => { scoreInputs[optionNode].disabled = false; scoreInputs[optionNode].value = score; scoreSpans[optionNode].textContent = `, score = ${score}`; }; const getHighestDuplicates = (arr) => { const counts = {}; for (const num of arr) { if (counts[num]) { counts[num]++; } else { counts[num] = 1; } } let highestCount = 0; --fcc-editable-region-- --fcc-editable-region-- }; rollDiceBtn.addEventListener("click", () => { if (rolls === 3) { alert("You have made three rolls this round. Please select a score."); } else { rolls++; rollDice(); updateStats(); } }); rulesBtn.addEventListener("click", () => { isModalShowing = !isModalShowing; if (isModalShowing) { rulesBtn.textContent = "Hide Rules"; rulesContainer.style.display = "block"; } else { rulesBtn.textContent = "Show Rules"; rulesContainer.style.display = "none"; } }); ```
import React, { lazy, useEffect } from 'react'; import { Suspense } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Navigate, Route, Routes } from 'react-router-dom'; import { useMediaQuery } from 'react-responsive'; import { ThemeProvider } from 'styled-components'; import { selectTheme } from 'redux/global/global-selectors'; import { ReactComponent as EllipsePink } from 'assets/bg/Ellipse_pink_2.svg'; import { ReactComponent as EllipsePurple } from 'assets/bg/Ellipse_purple_2.svg'; import Layout from 'components/Layout/Layout'; import { routes } from 'routes'; import { getUserInfoRequest } from 'redux/auth/auth-operations'; // import RegisterPage from 'pages/RegisterPage/RegisterPage'; // import LoginPage from 'pages/LoginPage/LoginPage'; import { Loader } from 'components'; import { Toaster } from 'components/Toaster/Toaster'; import { theme } from 'styles/theme'; import { colors } from 'styles/colors'; import GlobalStyles from 'styles/GlobalStyles/GlobalStyles.styled'; import { Background } from 'components/Layout/Layout.styled'; const HomePage = lazy(() => import('pages/HomePage/HomePage')); const CurrencyPage = lazy(() => import('pages/CurrencyPage/CurrencyPage')); const LoginPage = lazy(() => import('pages/LoginPage/LoginPage')); const RegisterPage = lazy(() => import('pages/RegisterPage/RegisterPage')); const StatisticsPage = lazy(() => import('pages/StatisticsPage/StatisticsPage') ); export function App() { const dispatch = useDispatch(); const isMobile = useMediaQuery({ maxWidth: 767 }); const themeTitle = useSelector(selectTheme); const normalizedTheme = { ...theme, ...colors[themeTitle] }; useEffect(() => { dispatch(getUserInfoRequest()); }, [dispatch]); return ( <ThemeProvider theme={normalizedTheme}> <GlobalStyles /> <Suspense fallback={<Loader />}> <Routes> <Route path={routes.HOME} element={<Layout />}> <Route index element={<HomePage />} /> {isMobile && ( <Route path={routes.CURRENCY_PAGE} element={<CurrencyPage />} ></Route> )} <Route path={routes.STATISTICS_PAGE} element={<StatisticsPage />} /> <Route path="*" element={<Navigate to={routes.HOME} />} /> </Route> <Route path={routes.REGISTER_PAGE} element={<RegisterPage />} /> <Route path={routes.LOGIN_PAGE} element={<LoginPage />} /> </Routes> </Suspense> <Background> <EllipsePink className="ellipse_pink" /> <EllipsePurple className="ellipse_purple" /> <div className="blur" /> </Background> <Toaster /> </ThemeProvider> ); }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent\Uuid; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->uuid('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); $table->primary('id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hot-Gadgets</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> <link rel="shortcut icon" href="./images/fav.png" type="image/x-icon"> </head> <body> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand " href="#"> <img src="./images/logo.png" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home </a> </li> <li class="nav-item"> <a class="nav-link" href="#phone">Smart-Phone</a> </li> <li class="nav-item"> <a class="nav-link" href="#laptop">Laptop</a> </li> <li class="nav-item"> <a class="nav-link" href="#catagories">Catagories</a> </li> </ul> </div> </nav> </div> <header id="header"> <div class="header container"> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <div class="row d-flex justify-content-center align-items-center"> <div class="col-xl-5 col-lg-5 col-md-5 col-sm-10 col-10"> <h1><span class="common-color">Macbook-Pro</span></h1> <p class="common-color">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem repellendus officia nesciunt illum odio optio maxime voluptates cumque laborum. Aliquam?</p> <button class="btn-style">Buy Now>></button> </div> <div class=" col-xl-1 col-lg-1 col-md-1 col-sm-2 col-2"> <img src="./images/bg-1.png" alt=""> </div> <div class="col-xl-5 col-lg-5 col-md-5 col-sm-12 col-12"> <img src="./images/banner-products/product-1.png" class="d-block w-100" alt="..."> </div> </div> </div> <div class="carousel-item"> <div class="row d-flex justify-content-center align-items-center"> <div class="head-text col-xl-5 col-lg-5 col-md-5 col-sm-10 col-10 "> <h1><span class="another-color">Macbook-Pro</span></h1> <p class="another-color">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem repellendus officia nesciunt illum odio optio maxime voluptates cumque laborum. Aliquam?</p> <button class="btn-style">Buy Now>></button> </div> <div class=" col-xl-1 col-lg-1 col-md-1 col-sm-2 col-2"> <img src="./images/bg-1.png" alt=""> </div> <div class="col-xl-5 col-lg-5 col-md-5 col-sm-12 col-12"> <img src="./images/banner-products/slider-1.png" class="d-block w-100" alt="..."> </div> </div> </div> <div class="carousel-item"> <div class="row d-flex justify-content-center align-items-center"> <div class="col-xl-5 col-lg-5 col-md-5 col-sm-10 col-10"> <h1><span class="common-color">Macbook-Pro</span> </h1> <p class="common-color">Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptatem repellendus officia nesciunt illum odio optio maxime voluptates cumque laborum. Aliquam?</p> <button class="btn-style">Buy Now>></button> </div> <div class=" col-xl-1 col-lg-1 col-md-1 col-sm-2 col-2"> <img src="./images/bg-1.png" alt=""> </div> <div class="col-xl-5 col-lg-5 col-md-5 col-sm-12 col-12"> <img src="./images/banner-products/slider-3.png" class="d-block w-100" alt="..."> </div> </div> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </header> <section id="phone"> <div class="phone container"> <div class="d-flex justify-content-between"> <h3>Smart-Phone</h3> <p class="pt-3"> <span>See all</span> </p> </div> <div class="card-group"> <div class="card"> <img class="card-img-top" src="./images/phone/phone-1.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <h3> $540 </h3> <button class="btn-style">Buy Now>></button> </div> </div> <div class="card"> <img class="card-img-top" src="./images/phone/phone-2.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <h3> $540 </h3> <button class="btn-style">Buy Now>></button> </div> </div> <div class="card"> <img class="card-img-top" src="./images/phone/phone-3.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <h3> $540 </h3> <button class="btn-style">Buy Now>></button> </div> </div> </div> </div> </section> <section id="laptop"> <div class="laptop container"> <div class="d-flex justify-content-between"> <h3>Smart-Phone</h3> <p class="pt-3"> <span>See all</span> </p> </div> <div class="card-group"> <div class="card"> <img class="card-img-top" src="./images/laptop/product-1.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <button class="btn-style justify-content-center">Buy Now>></button> </div> </div> <div class="card"> <img class="card-img-top" src="./images/laptop/product-2.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <button class="btn-style">Buy Now>></button> </div> </div> <div class="card"> <img class="card-img-top" src="./images/laptop/product-3.png" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p> <button class="btn-style justify-content-center">Buy Now>></button> </div> </div> </div> </div> </section> <section id="catagories"> <div class="container catagories"> <h3 class="text-center">Catagories</h3> <div class="d-flex justify-content-center"> <div class="bottom-style"></div> </div> <div class="row "> <div class="col-xl-6 col-lg-6 col-sm-6 col-12 d-flex justify-content-center align-items-center mt-5"> <div class="mr-5"> <img class="left-img img-fluid w-100" src="./images/Categories/bag.png" alt=""> </div> <div class="d-flex flex-column ml-5"> <img class="left-img img-fluid w-100" src="./images/Categories/perfume.png" alt=""> <img class="left-img img-fluid w-100" src="./images/Categories/shoe.png" alt=""> </div> </div> <div class="col-xl-6 col-lg-6 col-sm-6 col-12 mt-5"> <img class="img-fluid w-100" src="./images/Categories/pale-order.png" alt=""> </div> </div> </div> </section> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> </body> </html>
169. 求众数 给定一个大小为 *n* 的数组,找到其中的众数。众数是指在数组中出现次数**大于** `⌊ n/2 ⌋` 的元素。 你可以假设数组是非空的,并且给定的数组总是存在众数。 **示例 1:** ``` 输入: [3,2,3] 输出: 3 ``` **示例 2:** ``` 输入: [2,2,1,1,1,2,2] 输出: 2 ``` 解题思路: 本题对于众数的定义,和常规不一样。出现次数大于n/2,认为是众数。那么很容易想到,对于排好序之后的数组,众数一定占据一多半,即中间位置出现的数一定是众数。 ```python class Solution: def majorityElement(self, nums: List[int]) -> int: m=len(nums) nums.sort() return nums[m//2] ```
const { Card } = require('../models/models') const sequelize = require('../db') const apiError = require('../error/apiError'); function getRandomInt(min, max) { min = Math.ceil(min) max = Math.floor(max) return Math.floor(Math.random() * (max - min) + min); } class CardController { async create(req, res, next) { const { personId, cardTypeId } = req.body let number = '' for (let i = 0; i < 4; i++) { number = number + getRandomInt(1000, 10000).toString() } const cvv = getRandomInt(100, 1000) const request_date = new Date() const expire_date = new Date(`${request_date.getFullYear() + 4}-${request_date.getMonth()}`) const person = await Card.create({ number, expire_date, cvv, personId, cardTypeId }) return res.json(person) } async getAll(req, res) { const { personId, typeId } = req.query let cards; if (!personId && !typeId) { cards = await Card.findAll() } else if (!personId) { cards = await Card.findAll({ where: { cardTypeId: typeId } }) } else if (!typeId) { cards = await Card.findAll({ where: { personId } }) } else { cards = await Card.findAll({ where: { cardTypeId: typeId, personId } }) } return res.json(cards) } async getCountByCardId(req, res) { const cards = await Card.findAll({ attributes: ['cardTypeId', [sequelize.fn('COUNT', sequelize.col('id')), 'count']], group: ['cardTypeId'] }) return res.json(cards) } async getOne(req, res) { const { id } = req.params const card = Card.findOne({ where: { id } }) return res.json(card) } async export(req, res) { await sequelize.query("COPY cards TO '/tmp/cards.csv' DELIMITER ',' CSV HEADER", { model: Card, mapToModel: true }) return res.json({ message: 'Export successed' }) } } module.exports = new CardController()
<?php namespace App\Http\Controllers; use App\Models\User; use App\Models\UserDetail; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Storage; class ProfileController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $user = Auth::user(); return view('admin.profile.index', compact('user')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = Auth::user(); return view('admin.profile.manage', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'name' => ['required'], 'username' => ['required', 'unique:users,username,' . $id], 'email' => ['required', 'unique:users,email,' . $id, 'email'], ]); $user = User::findorFail($id); $detail = UserDetail::where('user_id', $id)->first(); $image = $request->file('avatar'); $data = $request->except('_token'); if (!empty($data['password'])) { $data['password'] = bcrypt($data['password']); } else { $data['password'] = $user->password; } if (!empty($image)) { $old_path = 'public/user/' . $user->avatar; Storage::delete($old_path); $file_name = time() . "_" . $image->getClientOriginalName(); $image->storeAs('public/user', $file_name); $data['avatar'] = $file_name; } $user->update($data); $detail->update($data); return redirect()->route('profile.index')->with('success', 'Profile updated successfully'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
# Backend System Design Documentation ## Overview This document outlines the design and implementation of a backend system that manages and processes user requests using a queue system. The system ensures that requests are handled in a First-In-First-Out (FIFO) manner, with each client having a dedicated queue. ## System Architecture ### Components - **Client-Server Model**: Users interact with the system through a client interface that sends requests to the server. - **Queue Management**: Manages individual queues for each authenticated user using Redis. - **Worker Processes**: Dedicated processes that pull requests from queues and execute them sequentially. - **Database**: Stores user information, requests, and results. - **Monitoring Tools**: Tools like Prometheus and Grafana are used to collect metrics and provide performance dashboards. ### Detailed Process Flow 1. **User sends a request**: Users interact with the client interface to send requests. 2. **Client Interface forwards the request**: The interface forwards the request to the server. 3. **Server authenticates the user**: The server verifies user credentials using JWT or similar token-based authentication. 4. **Server enqueues the request**: If authenticated, the server adds the request to the user’s dedicated queue. 5. **Worker processes handle the request**: Worker processes poll the queues, process the requests sequentially, and perform necessary operations on the database. 6. **Monitoring**: Tools like Prometheus and Grafana monitor and log the entire process. ## Implementation Details ### User Authentication - Implement user authentication to ensure secure access. - Use JWT or similar token-based authentication. ### Queue Setup for Each Client - Implement a mechanism to create and manage a queue for each authenticated user using Redis. ### Worker Processes - Implement worker processes that pull requests from the queues. - Ensure each request is processed sequentially. ## Testing - Write unit tests to verify the functionality of each component. - Test scenarios include: - User authentication. - Enqueuing and dequeuing requests. - Processing requests. - Handling errors and recovery. ## Monitoring and Logging - Use Prometheus for collecting metrics and Grafana for providing performance dashboards. - Set up logging to track request handling and system performance. ## Conclusion This document provides a framework for the design and implementation of a backend system using a queue structure to manage user requests. The system is designed to be robust, scalable, and capable of handling multiple users concurrently.
if(!require('tidyverse')) install.packages('tidyverse') if(!require('jsonlite')) install.packages('jsonlite') library(tidyverse) config <- function(path, size = 10000) { # str_c() konkateniert strings url <- str_c(path, '?size=', size) url } search <- function(query = '', fields = '', index = 'published_item') { path <- 'https://musikverlage.slub-dresden.de/api/search' url <- config(path) url <- str_c(url, '&index=', index) if (query!= '') { url <- str_c(url, '&query=', query) } if (fields != '') { url <- str_c(url, '&fields=', fields) } doc <- jsonlite::fromJSON(url) if (doc$hits$total$value == 0) { print('No results') NULL } else { as_tibble(doc$hits$hits) %>% unnest(c('_source')) %>% select(!'_index':'uid') } }
import './style.css' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' import * as dat from 'lil-gui' import {FontLoader} from 'three/examples/jsm/loaders/FontLoader' import {TextGeometry} from 'three/examples/jsm/geometries/TextGeometry' /** * Base */ // Debug const gui = new dat.GUI() // Canvas const canvas = document.querySelector('canvas.webgl') // Scene const scene = new THREE.Scene() const axesHelper = new THREE.AxesHelper() scene.add(axesHelper) /** * Textures */ const textureLoader = new THREE.TextureLoader() const matcapTexture = textureLoader.load('/textures/matcaps/1.png') /** * Fonts */ const fontLoader = new FontLoader() const material = new THREE.MeshMatcapMaterial({matcap: matcapTexture}) // does not return anything. fontLoader.load( '/fonts/helvetiker_regular.typeface.json', (font) => { const textGeometry = new TextGeometry( 'Hello Three.js', { font, size: 0.5, height: 0.2, curveSegments: 4, bevelEnabled: true, bevelThickness: 0.01, // stretching of bevel across z-axis bevelSize: 0.02, // x and y bevelOffset: 0, bevelSegments: 5 } ) textGeometry.center() /* textGeometry.computeBoundingBox() textGeometry.translate( - (textGeometry.boundingBox.max.x - 0.02) * 0.5, - (textGeometry.boundingBox.max.y - 0.02) * 0.5, - (textGeometry.boundingBox.max.z - 0.03) * 0.5, ) */ const mesh = new THREE.Mesh(textGeometry, material) scene.add(mesh) } ) /** * Objects */ console.time('load donuts') const geometry = new THREE.TorusGeometry(0.3, 0.2, 20, 45) for (let i = 0; i < 50; ++i) { const mesh = new THREE.Mesh(geometry, material) mesh.position.x = (Math.random() - 0.5) * 10 mesh.position.y = (Math.random() - 0.5) * 10 mesh.position.z = (Math.random() - 0.5) * 10 mesh.rotation.x = Math.random() * Math.PI mesh.rotation.y = Math.random() * Math.PI const scale = Math.random() mesh.scale.set(scale, scale, scale) scene.add(mesh) } console.timeEnd('load donuts') /** * Sizes */ const sizes = { width: window.innerWidth, height: window.innerHeight } window.addEventListener('resize', () => { // Update sizes sizes.width = window.innerWidth sizes.height = window.innerHeight // Update camera camera.aspect = sizes.width / sizes.height camera.updateProjectionMatrix() // Update renderer renderer.setSize(sizes.width, sizes.height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) }) /** * Camera */ // Base camera const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100) camera.position.x = 1 camera.position.y = 1 camera.position.z = 2 scene.add(camera) // Controls const controls = new OrbitControls(camera, canvas) controls.enableDamping = true /** * Renderer */ const renderer = new THREE.WebGLRenderer({ canvas: canvas }) renderer.setSize(sizes.width, sizes.height) renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)) /** * Animate */ const clock = new THREE.Clock() const tick = () => { const elapsedTime = clock.getElapsedTime() // Update controls controls.update() // Render renderer.render(scene, camera) // Call tick again on the next frame window.requestAnimationFrame(tick) } tick()
require File.dirname(__FILE__) + "/../../spec_helper" describe Admin::WelcomeController do scenario :users it "should redirect to page tree on get to /admin/welcome" do get :index response.should be_redirect response.should redirect_to(page_index_url) end it "should render the login screen on get to /admin/login" do get :login response.should be_success response.should render_template("login") end it "should set the current user and redirect when login was successful" do post :login, :user => {:login => "admin", :password => "password"} controller.send(:current_user).should == users(:admin) response.should be_redirect response.should redirect_to(welcome_url) end it "should render the login template when login failed" do post :login, :user => {:login => "admin", :password => "wrong"} response.should render_template("login") flash[:error].should_not be_nil end it "should clear the current user and redirect on logout" do controller.should_receive(:current_user=).with(nil) get :logout response.should be_redirect response.should redirect_to(login_url) end describe "with a logged-in user" do before do login_as :admin end it "should not show /login again" do get :login response.should redirect_to(welcome_url) end describe "and a stored location" do before do session[:return_to] = '/stored/path' post :login, :user => {:login => "admin", :password => "password"} end it "should redirect" do response.should redirect_to('/stored/path') end it "should clear session[:return_to]" do session[:return_to].should be_nil end end end end
import { StyleSheet, Text, View } from "react-native"; import { COLORS, DISTANCE, TIME } from "../../constants"; import { LinearGradient } from "expo-linear-gradient"; import ActivityHeader from "./ActivityHeader"; import ActivityFooter from "./ActivityFooter"; import StatHR from "./StatHR"; import { MyText } from "../Generic"; import StatPace from "./StatPace"; const Activity = ({ activity }) => { const activityTime = () => { let hours = Math.floor(activity.elapsedTime / TIME.secondsPerHour); let minutes = Math.floor( (activity.elapsedTime % TIME.secondsPerHour) / TIME.minutesPerHour ); let seconds = activity.elapsedTime % TIME.minutesPerHour; return ( <MyText style={styles.statsData}> {hours}:{minutes.toString().padStart(2, "0")}: {seconds.toString().padStart(2, "0")} </MyText> ); }; const activityDistance = () => { return ( <MyText style={styles.distanceNumber}> {activity.distance > DISTANCE.metersPerKilometer ? (activity.distance / DISTANCE.metersPerKilometer).toFixed(2) : activity.distance.toFixed(0)} <MyText style={styles.distanceDescriptor}> {activity.distance > DISTANCE.metersPerKilometer ? "km" : "m"} </MyText> </MyText> ); }; const activityWatts = () => { return ( <MyText style={styles.statsData}> {activity.averageWatts !== 0 ? activity.averageWatts.toFixed(0) : "N/A"} </MyText> ); }; return ( <LinearGradient colors={[COLORS.backgroundStart, COLORS.backgroundEnd]} style={styles.background} > <View style={styles.activity}> <ActivityHeader activity={activity}></ActivityHeader> <View style={styles.activityRow2}> <View style={styles.distance}>{activityDistance()}</View> <View style={styles.statsContainer}> <View style={styles.statsRow1}> <MyText style={styles.statsLabel}>Time</MyText> {activityTime()} <MyText style={styles.statsLabel}>HR</MyText> <StatHR style={styles.statsData} averageHeartrate={activity.averageHeartrate} /> </View> <View style={styles.statsRow2}> <MyText style={styles.statsLabel}>Pace</MyText> <StatPace style={styles.statsData} averageSpeed={activity.averageSpeed} /> <MyText style={styles.statsLabel}>Watts</MyText> {activityWatts()} </View> </View> </View> <ActivityFooter activity={activity}></ActivityFooter> </View> </LinearGradient> ); }; const styles = StyleSheet.create({ activity: { flex: 1, borderRadius: 10, }, background: { borderWidth: 1, marginLeft: 20, marginRight: 20, marginTop: 10, borderRadius: 10, }, activityRow2: { flex: 3, flexDirection: "row", }, distance: { flex: 3, flexDirection: "row", alignItems: "center", marginLeft: 15, }, distanceNumber: { flex: 1, fontSize: 35, textAlign: "center", color: COLORS.lightWhite, }, distanceDescriptor: { fontSize: 15, flex: 1, color: COLORS.lightWhite, }, statsContainer: { flex: 5, }, statsRow1: { flex: 1, alignItems: "center", flexDirection: "row", }, statsLabel: { textAlign: "left", flex: 2, margin: 2, fontSize: 14, color: COLORS.gray, }, statsData: { textAlign: "left", flex: 2, margin: 2, fontSize: 13, color: COLORS.lightWhite, }, statsRow2: { flex: 1, alignItems: "center", justifyContent: "center", flexDirection: "row", }, }); export default Activity;
import { useState, useCallback } from "react"; import { ReloadContext } from "context/ReloadContext"; interface ReloadContextProviderProps { children: any; } export const ReloadContextProvider: React.FC<ReloadContextProviderProps> = ({ children, }) => { const [reloadKey, setReloadKey] = useState(0); const reload = useCallback(() => { setReloadKey((reloadKey) => reloadKey + 1); }, []); return ( <ReloadContext.Provider value={{ reload, reloadKey }}> {children} </ReloadContext.Provider> ); };
'use client'; import styles from "./page.module.css"; import Post from "./components/post"; import { Button, Heading, Text } from "@chakra-ui/react"; import { createClient } from "./services/supabase"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import { useAuthContext } from "@/contexts/authContext"; const supabase = createClient(); export default function Home() { const useAuth = useAuthContext(); const router = useRouter(); const [posts, setPosts] = useState<any>([]); const [loading, setLoading] = useState(true); async function fetchPosts () { const { data, error } = await supabase .from('blog') .select('*') if (error) { console.log("Error fetching posts:", error); setLoading(false); return ; } console.log("Fetched posts:", data); setPosts(data); setLoading(false); } useEffect(() => { fetchPosts(); }, []); return ( <main className={styles.main}> <div className={styles.description} style={{ marginBottom: "3rem", display: "flex", justifyContent: "space-between", alignItems: "center" }}> <Heading>Blog personal</Heading> <div style={{ display: "flex", gap: "1rem" }}> {useAuth.isLoggedIn ? ( <> <Button colorScheme='yellow' borderWidth="2px" borderColor="black" onClick={() => router.push('/backoffice/post/create')}>Agregar Post</Button> <Button colorScheme='red' borderWidth="2px" borderColor="black" onClick={() => router.push('/logout')}>Logout</Button> </> ) : ( <> <Button colorScheme='blue' borderWidth="2px" borderColor="black" onClick={() => router.push('/login')}>Login</Button> <Button colorScheme='green' borderWidth="2px" borderColor="black" onClick={() => router.push('/register')}>Register</Button> </> )} </div> </div> {loading ? ( <Text>Cargando posts...</Text> ) : posts.length === 0 ? ( <Text>No hay posts disponibles.</Text> ) : ( posts.map((post: any) => { return <Post key={post.id} post={post} />; }) )} </main> ); }
import { ColumnDef } from "@tanstack/react-table"; import { Link } from "react-router-dom"; import { Button } from "@/components/ui/button"; export type Department = { id: string; name: string; description: string; status: "Active" | "Inactive"; employees: string[]; }; export const columns: ColumnDef<Department>[] = [ { accessorKey: "name", header: "Name", }, { accessorKey: "status", header: "Status", }, { accessorKey: "description", header: "Description", }, { id: "employees", cell: ({ row }) => { return ( <Link className="w-28" to={`/employees?department=${row.original.id}`}> <Button variant="ghost" className="h-8 w-28 p-0"> <span className="w-28">View Employees</span> </Button> </Link> ); }, }, ];
from http import HTTPStatus import allure from pydantic import parse_raw_as from requests import Response from core.api.base_api import ObjectCreatableApi, ObjectQueryableApi, ObjectUpdateableApi from core.api.platform.base import PlatformGettableApi from core.models.platform.base import PlatformListModel from core.models.platform.platform_user import CreatePlatformUser, PlatformUser, UpdatePlatformUser from core.models.platform.role import RoleAssignedToUser from settings import settings from util.assertions.common_assertions import assert_response_status class UsersApi( PlatformGettableApi[PlatformUser], ObjectQueryableApi[PlatformUser], ObjectCreatableApi[CreatePlatformUser, PlatformUser], ObjectUpdateableApi[UpdatePlatformUser, PlatformUser], ): NAME = "Users" PATH_NAME = "users" URL = f"{settings.base_url_platform_api}{PATH_NAME}" MODEL = PlatformUser def get_current_user(self) -> PlatformUser: with allure.step("Get current user info"): return self.get("me") def request_user_roles(self, obj_id: str) -> Response: return self.session.get(f"{self.get_instance_url(obj_id)}/roles") def get_user_roles(self, obj_id: str) -> PlatformListModel[RoleAssignedToUser]: with allure.step("Get user roles"): response = self.request_user_roles(obj_id) assert_response_status(response.status_code, HTTPStatus.OK) return parse_raw_as(PlatformListModel[RoleAssignedToUser], response.text)
import React, { useEffect, useState } from "react"; import { Routes, Route, useParams, useNavigate } from 'react-router-dom'; import All from "./pages/All"; import Replies from "./pages/Replies"; import Likes from "./pages/Likes"; import Follows from "./pages/Follows"; import { getActivitiesApi } from "../../../apis/Api"; const Activity = () => { const navigate = useNavigate(); const { tab = 'all' } = useParams(); const [activities, setActivities] = useState([]); useEffect(() => { // Fetch activities when the component mounts const fetchActivities = async () => { try { const response = await getActivitiesApi(); setActivities(response.data.activities); } catch (error) { console.error("Error fetching activities:", error); } }; fetchActivities(); }, []); const handleTabClick = (tabName) => { const newTabPath = tabName === 'all' ? '/dashboard/activity' : `/dashboard/activity/${tabName}`; navigate(newTabPath); }; return ( <div className="activity-container text-light"> <h3>Activity</h3> <div className="activity-tabs pt-2"> <button className={`btnss me-2 tab ${tab === 'all' ? 'active' : ''}` } onClick={() => handleTabClick('all')} style={{ width: "16%" }} > All </button> <button className={`btnss me-2 tab ${tab === 'follows' ? 'active' : ''}`} onClick={() => handleTabClick('follows')} style={{ width: "16%" }} > Follows </button> <button className={`btnss me-2 tab ${tab === 'replies' ? 'active' : ''}`} onClick={() => handleTabClick('replies')} style={{ width: "16%" }} > Replies </button> <button className={`btnss tab ${tab === 'likes' ? 'active' : ''}`} onClick={() => handleTabClick('likes')} style={{ width: "16%" }} > Likes </button> </div> <div className="activity-content"> <Routes> <Route path="/" element={<All activities={activities} />} /> <Route path="follows" element={<Follows activities={activities} />} /> <Route path="replies" element={<Replies activities={activities} />} /> <Route path="likes" element={<Likes activities={activities} />} /> </Routes> </div> </div> ); }; export default Activity;
// normal array : collection of similar types of variables // but in javascript array can have different types of variables number string boolean etc const arr=['nice',7654, true,null,undefined]; console.log(arr); console.log(typeof arr); console.log(Array.isArray(arr)); const movies=['Salaar', 'Animal','Wonka', 'Arrow','PeaceMaker']; console.log(movies.length); console.log('Nice'.length); //indexing starts from 0 console.log(movies[0]);//also works for string console.log(movies.indexOf('PeaceMaker'));//also works for string //console.log(movie[-4]); does not work console.log(movies.at(-4));//also works for string movies[3]="Batman" //not work for string console.log(movies); // movies.at(-4)="Superman";//not possible, use [] instead of at at is just for access and not for assignment movies[3]="Arrow"; console.log(movies[20]);//galat index me undefined ata hai //undefined works as a conditional in javascript as false //SLICING ---> no modification in original array only display output console.log(movies) console.log(movies.slice(1,4)) console.log(movies.slice(2,40)) //if array se bada end index dene pe bhi pura array hi aa jata hai console.log(movies.slice(20,40)) //if array se bada start index dene pe empty array aa jata hai console.log(movies.slice(-4,3)) //Modifiying STACK Operations PUSH AND POP movies.push("Superman")//add at end console.log(movies); movies.unshift('Flashpoint')//add at start console.log(movies); movies.pop()//remove from end console.log(movies); movies.shift()//remove from start console.log(movies); //SPLICE is a powerful method to insert and replace elements at any position movies.splice(3,2)//remove 2 elements from index 3 console.log(movies); movies.splice(3)//no changes console.log(movies); movies.splice(2,2)//remove 2 elements from index 2 console.log(movies); movies.splice(2,2,"Superman","Batman")//remove 2 elements from index 2 and add 2 elements console.log(movies); movies.splice(2,2,'pitman','Ironman','bulldog')//remove 2 elements from index 2 and add 3 elements console.log(movies); movies.splice(2,0,'pitpit')//add 1 element at index 2 console.log(movies); console.log(movies.splice(2,2))//remove 2 elements from index 2 and display them
package com.guimei.util; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.guimei.dao.Goods_detailDao; import com.guimei.entity.Goods_detail; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; // 上传文件存储目录 private static final String UPLOAD_DIRECTORY = "upload"; // 上传配置 private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); if (!ServletFileUpload.isMultipartContent(request)) { // 如果不是则停止 PrintWriter writer = response.getWriter(); writer.println("Error: 表单必须包含 enctype=multipart/form-data"); writer.flush(); return; } // 配置上传参数 DiskFileItemFactory factory = new DiskFileItemFactory(); // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中 factory.setSizeThreshold(MEMORY_THRESHOLD); // 设置临时存储目录 factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // 设置最大文件上传值 upload.setFileSizeMax(MAX_FILE_SIZE); // 设置最大请求值 (包含文件和表单数据) upload.setSizeMax(MAX_REQUEST_SIZE); // 中文处理 upload.setHeaderEncoding("UTF-8"); // 构造临时路径来存储上传的文件 // 这个路径相对当前应用的目录 String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; String ss=null; // 如果目录不存在则创建 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { // 解析请求的内容提取文件数据 @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // 迭代表单数据 for (FileItem item : formItems) { // 处理不在表单中的字段 if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); System.out.println(fileName); // 在控制台输出文件的上传路径 System.out.println(filePath); // 保存文件到硬盘 item.write(storeFile); /* String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; System.out.println(basePath+fileName);*/ String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; ss=basePath+UPLOAD_DIRECTORY+"/"+fileName; // request.getSession().setAttribute("url", ss); } } } } catch (Exception ex) { request.setAttribute("message", "错误信息: " + ex.getMessage()); } int id=Integer.parseInt(request.getParameter("id")); Goods_detailDao dao = DaoFactory.getGoods_detailDao(); Goods_detail gd=new Goods_detail(); gd.setPic(ss); dao.updateGoods_detail(id, gd); request.getSession().setAttribute("url", ss); /*// 跳转到 message.jsp getServletContext().getRequestDispatcher("/message.jsp").forward( request, response);*/ } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* allocation.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nsainton <nsainton@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/10/12 17:50:55 by nsainton #+# #+# */ /* Updated: 2023/04/12 12:51:05 by nsainton ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void *ft_calloc(size_t nmemb, size_t size) { void *nptr; if (!(nmemb && size)) return (NULL); if (size > SIZE_MAX / nmemb) return (NULL); nptr = malloc(nmemb * size); if (nptr == NULL) return (NULL); ft_bzero(nptr, nmemb * size); return (nptr); } void *ft_reallocf(void *memzone, t_csizet old_size, size_t new_size) { size_t end_of_copy; void *newzone; end_of_copy = ft_minst(old_size, new_size); newzone = malloc(new_size); if (newzone == NULL) { free(memzone); return (NULL); } ft_memmove(newzone, memzone, end_of_copy); free(memzone); return (newzone); } void *ft_realloc(void *memzone, t_csizet old_size, t_csizet new_size) { size_t end_of_copy; void *newzone; end_of_copy = ft_minst(old_size, new_size); newzone = malloc(new_size); if (newzone == NULL) return (NULL); ft_memmove(newzone, memzone, end_of_copy); free(memzone); return (newzone); }
{{!< default}} {{!-- The tag above means: insert everything in this file into the {body} of the default.hbs template --}} <header class="site-header outer"> {{> "site-nav"}} </header> {{!-- Everything inside the #post tags pulls data from the post --}} {{#post}} <main id="site-main" class="site-main outer" role="main"> <div class="inner"> <article class="post-full {{post_class}} {{#unless feature_image}}no-image{{/unless}}"> <div class="article-header"> {{#if feature_image}} <img src="{{feature_image}}" alt=""> {{/if}} <div class="text-block"> <span class="date-time" datetime="{{date format="YYYY-MM-DD"}}">{{date format="MMMM D YYYY"}}</span> <h1 class="f1 lh-title f1-m lh-title-m f-subheadline-l lh-subheadline-l ">{{title}}</h1> </div> </div> <section class="type-block"> {{content}} </section> {{!-- Email subscribe form at the bottom of the page --}} {{#if @labs.subscribers}} {{> "subscribers-box"}} {{/if}} {{!-- If you use Disqus comments, just uncomment this block. The only thing you need to change is "test-apkdzgmqhj" - which should be replaced with your own Disqus site-id. <section class="post-full-comments"> <div id="disqus_thread"></div> <script> var disqus_config = function () { this.page.url = '{{url absolute="true"}}'; this.page.identifier = 'ghost-{{comment_id}}'; }; (function() { var d = document, s = d.createElement('script'); s.src = 'https://test-apkdzgmqhj.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> </section> --}} </article> </div> </main> <div class="type-block clear"><p>&nbsp;</p><p>&nbsp;</p></div> {{!-- Links to Previous/Next posts --}} <aside class="read-next outer"> <div class="inner"> {{!-- If there's a next post, display it using the same markup included from - partials/post-card.hbs --}} {{#next_post}} {{> "post-card"}} {{/next_post}} {{!-- If there's a previous post, display it using the same markup included from - partials/post-card.hbs --}} {{#prev_post}} {{> "post-card"}} {{/prev_post}} </div> </aside> {{/post}} {{!-- The #contentFor helper here will send everything inside it up to the matching #block helper found in default.hbs --}} {{#contentFor "scripts"}} <script> // NOTE: Scroll performance is poor in Safari // - this appears to be due to the events firing much more slowly in Safari. // Dropping the scroll event and using only a raf loop results in smoother // scrolling but continuous processing even when not scrolling $(document).ready(function () { // Start fitVids var $postContent = $(".post-full-content"); $postContent.fitVids(); // End fitVids var progressBar = document.querySelector('progress'); var header = document.querySelector('.floating-header'); var title = document.querySelector('.post-full-title'); var lastScrollY = window.scrollY; var lastWindowHeight = window.innerHeight; var lastDocumentHeight = $(document).height(); var ticking = false; function onScroll() { lastScrollY = window.scrollY; requestTick(); } function onResize() { lastWindowHeight = window.innerHeight; lastDocumentHeight = $(document).height(); requestTick(); } function requestTick() { if (!ticking) { requestAnimationFrame(update); } ticking = true; } function update() { var trigger = title.getBoundingClientRect().top + window.scrollY; var triggerOffset = title.offsetHeight + 35; var progressMax = lastDocumentHeight - lastWindowHeight; // show/hide floating header if (lastScrollY >= trigger + triggerOffset) { header.classList.add('floating-active'); } else { header.classList.remove('floating-active'); } progressBar.setAttribute('max', progressMax); progressBar.setAttribute('value', lastScrollY); ticking = false; } window.addEventListener('scroll', onScroll, {passive: true}); window.addEventListener('resize', onResize, false); update(); }); </script> {{/contentFor}}
const express = require("express"); const { userModel } = require("../models/user.model"); const bcrypt = require("bcrypt") const userRoutes = express.Router(); const jwt = require("jsonwebtoken") userRoutes.post("/register",async(req,res)=>{ const {username,password} = req.body; try{ if(req.body.username && req.body.password){ const preCheck = await userModel.findOne({username}) if(!preCheck) { const hashedPassword = await bcrypt.hash(password,5) const newUser = new userModel({...req.body,password:hashedPassword}) await newUser.save(); res.status(200).send({msg: "User has been Registered!", status: "success"}) }else{ res.status(400).send({msg: "User already registered!"}) } }else{ res.status(400).send({msg : "Invalid data format!"}) } } catch (e){ res.status(400).send({msg:e.message}) } }); userRoutes.post("/login",async (req,res)=>{ const {username,password} = req.body; try{ if(username && password){ const preCheck = await userModel.findOne({username}) if(preCheck){ const hashCheck = await bcrypt.compare(password,preCheck.password); const token = jwt.sign({"userId":preCheck._id},"kryzen",{expiresIn:"7d"}) if(hashCheck){ res.status(200).send({msg:"User logged in Successful!", status:"success",token}) }else{ res.status(400).send({msg:"Invalid password"}) } }else{ res.status(400).send({msg:"User Not Found"}) } }else{ res.status(400).send({msg:"Invalid data format"}) } } catch(e){ res.status(400).send({msg:e.message}) } }) module.exports = {userRoutes}
import React, { useEffect, useState } from 'react' import Table from '../../components/Table' import agent from '../../service/agent' import { SUCCESS } from '../../constants/statusCode' import numberWithVND from '../../utils/numberwithvnd' import { getDate } from '../../utils/date' const customTableHead = [ '', 'Tên khách hàng', 'Số điện thoại', 'Địa chỉ', 'Tổng tiền', 'Ngày đặt hàng', 'Hình thức thanh toán', 'Trạng thái đơn hàng', 'Trạng thái', ] const status = { pending : 'Đang xử lý', shipping : 'Đang giao hàng', success : 'Đã giao hàng', } const renderHead = (item, index) => <th key={index}>{item}</th> const Order = () => { const [orders, setOrders] = useState([]); const [editOrder, setEditOrder] = useState({}) const renderBody = (item, index) => ( <tr key={index} onClick={() => setEditOrder(item)}> <td>{index + 1}</td> <td>{item.name}</td> <td>{item.phone}</td> <td>{item.address}</td> <td>{numberWithVND(item.amount)}</td> <td>{getDate(item.createdAt)}</td> <td>{item.payment_method === 'cash' ? 'Tiền mặt' : 'Thẻ'}</td> <td>{status[item.status_ship]}</td> <td>{item.status_payment === 1 ? <p className='color-green'>Đã thanh toán</p> : <p className='color-red'>Chưa thanh toán</p> }</td> </tr> ) const getOrder = async () => { try { const res = await agent.Order.getOrders() if(res.code === SUCCESS){ setOrders(res.result.items) } } catch (error) { setOrders([]) } } useEffect(() => { getOrder() }, []) return ( <> <div className="list-order"> <Table headData={customTableHead} renderHead={(item, index) => renderHead(item, index)} bodyData={orders} renderBody={(item, index) => renderBody(item, index)} /> </div> </> ) } export default Order
import { IsNotEmpty, Length } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class CreateBookRequest { @ApiProperty({ description: 'Título do livro', example: 'O Senhor dos Anéis', }) @IsNotEmpty({ message: 'Título não pode ser vazio' }) @Length(3, 50, { message: 'Título precisa ter entre 3 e 50 caracteres' }) title: string; @ApiProperty({ description: 'Código de barras do livro', example: '978-85-359-0277-5', }) @IsNotEmpty({ message: 'Código de barras não pode ser vazio' }) barcode: string; @ApiProperty({ description: 'ID do Autor do livro', example: '1', }) @IsNotEmpty({ message: 'Autor não pode ser vazio' }) author_id: number; }
<?xml version='1.0'?> <!--*-nxml-*--> <!DOCTYPE refentry PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"> <!-- This file is part of systemd. Copyright 2010 Lennart Poettering systemd 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. systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>. --> <refentry id="systemd-nspawn" xmlns:xi="http://www.w3.org/2001/XInclude"> <refentryinfo> <title>systemd-nspawn</title> <productname>systemd</productname> <authorgroup> <author> <contrib>Developer</contrib> <firstname>Lennart</firstname> <surname>Poettering</surname> <email>lennart@poettering.net</email> </author> </authorgroup> </refentryinfo> <refmeta> <refentrytitle>systemd-nspawn</refentrytitle> <manvolnum>1</manvolnum> </refmeta> <refnamediv> <refname>systemd-nspawn</refname> <refpurpose>Spawn a namespace container for debugging, testing and building</refpurpose> </refnamediv> <refsynopsisdiv> <cmdsynopsis> <command>systemd-nspawn</command> <arg choice="opt" rep="repeat">OPTIONS</arg> <arg choice="opt"><replaceable>COMMAND</replaceable> <arg choice="opt" rep="repeat">ARGS</arg> </arg> </cmdsynopsis> <cmdsynopsis> <command>systemd-nspawn</command> <arg choice="plain">-b</arg> <arg choice="opt" rep="repeat">OPTIONS</arg> <arg choice="opt" rep="repeat">ARGS</arg> </cmdsynopsis> </refsynopsisdiv> <refsect1> <title>Description</title> <para><command>systemd-nspawn</command> may be used to run a command or OS in a light-weight namespace container. In many ways it is similar to <citerefentry project='man-pages'><refentrytitle>chroot</refentrytitle><manvolnum>1</manvolnum></citerefentry>, but more powerful since it fully virtualizes the file system hierarchy, as well as the process tree, the various IPC subsystems and the host and domain name.</para> <para><command>systemd-nspawn</command> limits access to various kernel interfaces in the container to read-only, such as <filename>/sys</filename>, <filename>/proc/sys</filename> or <filename>/sys/fs/selinux</filename>. Network interfaces and the system clock may not be changed from within the container. Device nodes may not be created. The host system cannot be rebooted and kernel modules may not be loaded from within the container.</para> <para>Note that even though these security precautions are taken <command>systemd-nspawn</command> is not suitable for secure container setups. Many of the security features may be circumvented and are hence primarily useful to avoid accidental changes to the host system from the container. The intended use of this program is debugging and testing as well as building of packages, distributions and software involved with boot and systems management.</para> <para>In contrast to <citerefentry project='man-pages'><refentrytitle>chroot</refentrytitle><manvolnum>1</manvolnum></citerefentry> <command>systemd-nspawn</command> may be used to boot full Linux-based operating systems in a container.</para> <para>Use a tool like <citerefentry project='die-net'><refentrytitle>yum</refentrytitle><manvolnum>8</manvolnum></citerefentry>, <citerefentry project='die-net'><refentrytitle>debootstrap</refentrytitle><manvolnum>8</manvolnum></citerefentry>, or <citerefentry project='archlinux'><refentrytitle>pacman</refentrytitle><manvolnum>8</manvolnum></citerefentry> to set up an OS directory tree suitable as file system hierarchy for <command>systemd-nspawn</command> containers.</para> <para>Note that <command>systemd-nspawn</command> will mount file systems private to the container to <filename>/dev</filename>, <filename>/run</filename> and similar. These will not be visible outside of the container, and their contents will be lost when the container exits.</para> <para>Note that running two <command>systemd-nspawn</command> containers from the same directory tree will not make processes in them see each other. The PID namespace separation of the two containers is complete and the containers will share very few runtime objects except for the underlying file system. Use <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry>'s <command>login</command> command to request an additional login prompt in a running container.</para> <para><command>systemd-nspawn</command> implements the <ulink url="http://www.freedesktop.org/wiki/Software/systemd/ContainerInterface">Container Interface</ulink> specification.</para> <para>As a safety check <command>systemd-nspawn</command> will verify the existence of <filename>/usr/lib/os-release</filename> or <filename>/etc/os-release</filename> in the container tree before starting the container (see <citerefentry><refentrytitle>os-release</refentrytitle><manvolnum>5</manvolnum></citerefentry>). It might be necessary to add this file to the container tree manually if the OS of the container is too old to contain this file out-of-the-box.</para> </refsect1> <refsect1> <title>Options</title> <para>If option <option>-b</option> is specified, the arguments are used as arguments for the init binary. Otherwise, <replaceable>COMMAND</replaceable> specifies the program to launch in the container, and the remaining arguments are used as arguments for this program. If <option>-b</option> is not used and no arguments are specifed, a shell is launched in the container.</para> <para>The following options are understood:</para> <variablelist> <varlistentry> <term><option>-D</option></term> <term><option>--directory=</option></term> <listitem><para>Directory to use as file system root for the container.</para> <para>If neither <option>--directory=</option>, nor <option>--image=</option> is specified the directory is determined as <filename>/var/lib/machines/</filename> suffixed by the machine name as specified with <option>--machine=</option>. If neither <option>--directory=</option>, <option>--image=</option>, nor <option>--machine=</option> are specified, the current directory will be used. May not be specified together with <option>--image=</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>--template=</option></term> <listitem><para>Directory or <literal>btrfs</literal> subvolume to use as template for the container's root directory. If this is specified and the container's root directory (as configured by <option>--directory=</option>) does not yet exist it is created as <literal>btrfs</literal> subvolume and populated from this template tree. Ideally, the specified template path refers to the root of a <literal>btrfs</literal> subvolume, in which case a simple copy-on-write snapshot is taken, and populating the root directory is instant. If the specified template path does not refer to the root of a <literal>btrfs</literal> subvolume (or not even to a <literal>btrfs</literal> file system at all), the tree is copied, which can be substantially more time-consuming. Note that if this option is used the container's root directory (in contrast to the template directory!) must be located on a <literal>btrfs</literal> file system, so that the <literal>btrfs</literal> subvolume may be created. May not be specified together with <option>--image=</option> or <option>--ephemeral</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>-x</option></term> <term><option>--ephemeral</option></term> <listitem><para>If specified, the container is run with a temporary <literal>btrfs</literal> snapshot of its root directory (as configured with <option>--directory=</option>), that is removed immediately when the container terminates. This option is only supported if the root file system is <literal>btrfs</literal>. May not be specified together with <option>--image=</option> or <option>--template=</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>-i</option></term> <term><option>--image=</option></term> <listitem><para>Disk image to mount the root directory for the container from. Takes a path to a regular file or to a block device node. The file or block device must contain either:</para> <itemizedlist> <listitem><para>An MBR partition table with a single partition of type 0x83 that is marked bootable.</para></listitem> <listitem><para>A GUID partition table (GPT) with a single partition of type 0fc63daf-8483-4772-8e79-3d69d8477de4.</para></listitem> <listitem><para>A GUID partition table (GPT) with a marked root partition which is mounted as the root directory of the container. Optionally, GPT images may contain a home and/or a server data partition which are mounted to the appropriate places in the container. All these partitions must be identified by the partition types defined by the <ulink url="http://www.freedesktop.org/wiki/Specifications/DiscoverablePartitionsSpec/">Discoverable Partitions Specification</ulink>.</para></listitem> </itemizedlist> <para>Any other partitions, such as foreign partitions, swap partitions or EFI system partitions are not mounted. May not be specified together with <option>--directory=</option>, <option>--template=</option> or <option>--ephemeral</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>-a</option></term> <term><option>--as-pid2</option></term> <listitem><para>Invoke the shell or specified program as process ID (PID) 2 instead of PID 1 (init). By default, if neither this option nor <option>--boot</option> is used, the selected binary is run as process with PID 1, a mode only suitable for programs that are aware of the special semantics that the process with PID 1 has on UNIX. For example, it needs to reap all processes reparented to it, and should implement <command>sysvinit</command> compatible signal handling (specifically: it needs to reboot on SIGINT, reexecute on SIGTERM, reload configuration on SIGHUP, and so on). With <option>--as-pid2</option> a minimal stub init process is run as PID 1 and the selected binary is executed as PID 2 (and hence does not need to implement any special semantics). The stub init process will reap processes as necessary and react appropriately to signals. It is recommended to use this mode to invoke arbitrary commands in containers, unless they have been modified to run correctly as PID 1. Or in other words: this switch should be used for pretty much all commands, except when the command refers to an init or shell implementation, as these are generally capable of running correctly as PID 1). This option may not be combined with <option>--boot</option> or <option>--share-system</option>.</para> </listitem> </varlistentry> <varlistentry> <term><option>-b</option></term> <term><option>--boot</option></term> <listitem><para>Automatically search for an init binary and invoke it as PID 1, instead of a shell or a user supplied program. If this option is used, arguments specified on the command line are used as arguments for the init binary. This option may not be combined with <option>--as-pid2</option> or <option>--share-system</option>.</para> <para>The following table explains the different modes of invocation and relationship to <option>--as-pid2</option> (see above):</para> <table> <title>Invocation Mode</title> <tgroup cols='2' align='left' colsep='1' rowsep='1'> <colspec colname="switch" /> <colspec colname="explanation" /> <thead> <row> <entry>Switch</entry> <entry>Explanation</entry> </row> </thead> <tbody> <row> <entry>Neither <option>--as-pid2</option> nor <option>--boot</option> specified</entry> <entry>The passed parameters are interpreted as command line, which is executed as PID 1 in the container.</entry> </row> <row> <entry><option>--as-pid2</option> specified</entry> <entry>The passed parameters are interpreted as command line, which are executed as PID 2 in the container. A stub init process is run as PID 1.</entry> </row> <row> <entry><option>--boot</option> specified</entry> <entry>An init binary as automatically searched and run as PID 1 in the container. The passed parameters are used as invocation parameters for this process.</entry> </row> </tbody> </tgroup> </table> </listitem> </varlistentry> <varlistentry> <term><option>-u</option></term> <term><option>--user=</option></term> <listitem><para>After transitioning into the container, change to the specified user-defined in the container's user database. Like all other systemd-nspawn features, this is not a security feature and provides protection against accidental destructive operations only.</para></listitem> </varlistentry> <varlistentry> <term><option>-M</option></term> <term><option>--machine=</option></term> <listitem><para>Sets the machine name for this container. This name may be used to identify this container during its runtime (for example in tools like <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry> and similar), and is used to initialize the container's hostname (which the container can choose to override, however). If not specified, the last component of the root directory path of the container is used, possibly suffixed with a random identifier in case <option>--ephemeral</option> mode is selected. If the root directory selected is the host's root directory the host's hostname is used as default instead.</para></listitem> </varlistentry> <varlistentry> <term><option>--uuid=</option></term> <listitem><para>Set the specified UUID for the container. The init system will initialize <filename>/etc/machine-id</filename> from this if this file is not set yet. </para></listitem> </varlistentry> <varlistentry> <term><option>--slice=</option></term> <listitem><para>Make the container part of the specified slice, instead of the default <filename>machine.slice</filename>.</para> </listitem> </varlistentry> <varlistentry> <term><option>--private-network</option></term> <listitem><para>Disconnect networking of the container from the host. This makes all network interfaces unavailable in the container, with the exception of the loopback device and those specified with <option>--network-interface=</option> and configured with <option>--network-veth</option>. If this option is specified, the CAP_NET_ADMIN capability will be added to the set of capabilities the container retains. The latter may be disabled by using <option>--drop-capability=</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>--network-interface=</option></term> <listitem><para>Assign the specified network interface to the container. This will remove the specified interface from the calling namespace and place it in the container. When the container terminates, it is moved back to the host namespace. Note that <option>--network-interface=</option> implies <option>--private-network</option>. This option may be used more than once to add multiple network interfaces to the container.</para></listitem> </varlistentry> <varlistentry> <term><option>--network-macvlan=</option></term> <listitem><para>Create a <literal>macvlan</literal> interface of the specified Ethernet network interface and add it to the container. A <literal>macvlan</literal> interface is a virtual interface that adds a second MAC address to an existing physical Ethernet link. The interface in the container will be named after the interface on the host, prefixed with <literal>mv-</literal>. Note that <option>--network-macvlan=</option> implies <option>--private-network</option>. This option may be used more than once to add multiple network interfaces to the container.</para></listitem> </varlistentry> <varlistentry> <term><option>--network-ipvlan=</option></term> <listitem><para>Create an <literal>ipvlan</literal> interface of the specified Ethernet network interface and add it to the container. An <literal>ipvlan</literal> interface is a virtual interface, similar to a <literal>macvlan</literal> interface, which uses the same MAC address as the underlying interface. The interface in the container will be named after the interface on the host, prefixed with <literal>iv-</literal>. Note that <option>--network-ipvlan=</option> implies <option>--private-network</option>. This option may be used more than once to add multiple network interfaces to the container.</para></listitem> </varlistentry> <varlistentry> <term><option>-n</option></term> <term><option>--network-veth</option></term> <listitem><para>Create a virtual Ethernet link (<literal>veth</literal>) between host and container. The host side of the Ethernet link will be available as a network interface named after the container's name (as specified with <option>--machine=</option>), prefixed with <literal>ve-</literal>. The container side of the Ethernet link will be named <literal>host0</literal>. Note that <option>--network-veth</option> implies <option>--private-network</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>--network-bridge=</option></term> <listitem><para>Adds the host side of the Ethernet link created with <option>--network-veth</option> to the specified bridge. Note that <option>--network-bridge=</option> implies <option>--network-veth</option>. If this option is used, the host side of the Ethernet link will use the <literal>vb-</literal> prefix instead of <literal>ve-</literal>.</para></listitem> </varlistentry> <varlistentry> <term><option>-p</option></term> <term><option>--port=</option></term> <listitem><para>If private networking is enabled, maps an IP port on the host onto an IP port on the container. Takes a protocol specifier (either <literal>tcp</literal> or <literal>udp</literal>), separated by a colon from a host port number in the range 1 to 65535, separated by a colon from a container port number in the range from 1 to 65535. The protocol specifier and its separating colon may be omitted, in which case <literal>tcp</literal> is assumed. The container port number and its colon may be ommitted, in which case the same port as the host port is implied. This option is only supported if private networking is used, such as <option>--network-veth</option> or <option>--network-bridge=</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>-Z</option></term> <term><option>--selinux-context=</option></term> <listitem><para>Sets the SELinux security context to be used to label processes in the container.</para> </listitem> </varlistentry> <varlistentry> <term><option>-L</option></term> <term><option>--selinux-apifs-context=</option></term> <listitem><para>Sets the SELinux security context to be used to label files in the virtual API file systems in the container.</para> </listitem> </varlistentry> <varlistentry> <term><option>--capability=</option></term> <listitem><para>List one or more additional capabilities to grant the container. Takes a comma-separated list of capability names, see <citerefentry project='man-pages'><refentrytitle>capabilities</refentrytitle><manvolnum>7</manvolnum></citerefentry> for more information. Note that the following capabilities will be granted in any way: CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_DAC_READ_SEARCH, CAP_FOWNER, CAP_FSETID, CAP_IPC_OWNER, CAP_KILL, CAP_LEASE, CAP_LINUX_IMMUTABLE, CAP_NET_BIND_SERVICE, CAP_NET_BROADCAST, CAP_NET_RAW, CAP_SETGID, CAP_SETFCAP, CAP_SETPCAP, CAP_SETUID, CAP_SYS_ADMIN, CAP_SYS_CHROOT, CAP_SYS_NICE, CAP_SYS_PTRACE, CAP_SYS_TTY_CONFIG, CAP_SYS_RESOURCE, CAP_SYS_BOOT, CAP_AUDIT_WRITE, CAP_AUDIT_CONTROL. Also CAP_NET_ADMIN is retained if <option>--private-network</option> is specified. If the special value <literal>all</literal> is passed, all capabilities are retained.</para></listitem> </varlistentry> <varlistentry> <term><option>--drop-capability=</option></term> <listitem><para>Specify one or more additional capabilities to drop for the container. This allows running the container with fewer capabilities than the default (see above).</para></listitem> </varlistentry> <varlistentry> <term><option>--link-journal=</option></term> <listitem><para>Control whether the container's journal shall be made visible to the host system. If enabled, allows viewing the container's journal files from the host (but not vice versa). Takes one of <literal>no</literal>, <literal>host</literal>, <literal>try-host</literal>, <literal>guest</literal>, <literal>try-guest</literal>, <literal>auto</literal>. If <literal>no</literal>, the journal is not linked. If <literal>host</literal>, the journal files are stored on the host file system (beneath <filename>/var/log/journal/<replaceable>machine-id</replaceable></filename>) and the subdirectory is bind-mounted into the container at the same location. If <literal>guest</literal>, the journal files are stored on the guest file system (beneath <filename>/var/log/journal/<replaceable>machine-id</replaceable></filename>) and the subdirectory is symlinked into the host at the same location. <literal>try-host</literal> and <literal>try-guest</literal> do the same but do not fail if the host does not have persistent journalling enabled. If <literal>auto</literal> (the default), and the right subdirectory of <filename>/var/log/journal</filename> exists, it will be bind mounted into the container. If the subdirectory does not exist, no linking is performed. Effectively, booting a container once with <literal>guest</literal> or <literal>host</literal> will link the journal persistently if further on the default of <literal>auto</literal> is used.</para></listitem> </varlistentry> <varlistentry> <term><option>-j</option></term> <listitem><para>Equivalent to <option>--link-journal=try-guest</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>--read-only</option></term> <listitem><para>Mount the root file system read-only for the container.</para></listitem> </varlistentry> <varlistentry> <term><option>--bind=</option></term> <term><option>--bind-ro=</option></term> <listitem><para>Bind mount a file or directory from the host into the container. Either takes a path argument -- in which case the specified path will be mounted from the host to the same path in the container --, or a colon-separated pair of paths -- in which case the first specified path is the source in the host, and the second path is the destination in the container. The <option>--bind-ro=</option> option creates read-only bind mounts.</para></listitem> </varlistentry> <varlistentry> <term><option>--tmpfs=</option></term> <listitem><para>Mount a tmpfs file system into the container. Takes a single absolute path argument that specifies where to mount the tmpfs instance to (in which case the directory access mode will be chosen as 0755, owned by root/root), or optionally a colon-separated pair of path and mount option string, that is used for mounting (in which case the kernel default for access mode and owner will be chosen, unless otherwise specified). This option is particularly useful for mounting directories such as <filename>/var</filename> as tmpfs, to allow state-less systems, in particular when combined with <option>--read-only</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>--setenv=</option></term> <listitem><para>Specifies an environment variable assignment to pass to the init process in the container, in the format <literal>NAME=VALUE</literal>. This may be used to override the default variables or to set additional variables. This parameter may be used more than once.</para></listitem> </varlistentry> <varlistentry> <term><option>--share-system</option></term> <listitem><para>Allows the container to share certain system facilities with the host. More specifically, this turns off PID namespacing, UTS namespacing and IPC namespacing, and thus allows the guest to see and interact more easily with processes outside of the container. Note that using this option makes it impossible to start up a full Operating System in the container, as an init system cannot operate in this mode. It is only useful to run specific programs or applications this way, without involving an init system in the container. This option implies <option>--register=no</option>. This option may not be combined with <option>--boot</option>.</para></listitem> </varlistentry> <varlistentry> <term><option>--register=</option></term> <listitem><para>Controls whether the container is registered with <citerefentry><refentrytitle>systemd-machined</refentrytitle><manvolnum>8</manvolnum></citerefentry>. Takes a boolean argument, defaults to <literal>yes</literal>. This option should be enabled when the container runs a full Operating System (more specifically: an init system), and is useful to ensure that the container is accessible via <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry> and shown by tools such as <citerefentry project='man-pages'><refentrytitle>ps</refentrytitle><manvolnum>1</manvolnum></citerefentry>. If the container does not run an init system, it is recommended to set this option to <literal>no</literal>. Note that <option>--share-system</option> implies <option>--register=no</option>. </para></listitem> </varlistentry> <varlistentry> <term><option>--keep-unit</option></term> <listitem><para>Instead of creating a transient scope unit to run the container in, simply register the service or scope unit <command>systemd-nspawn</command> has been invoked in with <citerefentry><refentrytitle>systemd-machined</refentrytitle><manvolnum>8</manvolnum></citerefentry>. This has no effect if <option>--register=no</option> is used. This switch should be used if <command>systemd-nspawn</command> is invoked from within a service unit, and the service unit's sole purpose is to run a single <command>systemd-nspawn</command> container. This option is not available if run from a user session.</para></listitem> </varlistentry> <varlistentry> <term><option>--personality=</option></term> <listitem><para>Control the architecture ("personality") reported by <citerefentry project='man-pages'><refentrytitle>uname</refentrytitle><manvolnum>2</manvolnum></citerefentry> in the container. Currently, only <literal>x86</literal> and <literal>x86-64</literal> are supported. This is useful when running a 32-bit container on a 64-bit host. If this setting is not used, the personality reported in the container is the same as the one reported on the host.</para></listitem> </varlistentry> <varlistentry> <term><option>-q</option></term> <term><option>--quiet</option></term> <listitem><para>Turns off any status output by the tool itself. When this switch is used, the only output from nspawn will be the console output of the container OS itself.</para></listitem> </varlistentry> <varlistentry> <term><option>--volatile</option><replaceable>=MODE</replaceable></term> <listitem><para>Boots the container in volatile mode. When no mode parameter is passed or when mode is specified as <literal>yes</literal> full volatile mode is enabled. This means the root directory is mounted as mostly unpopulated <literal>tmpfs</literal> instance, and <filename>/usr</filename> from the OS tree is mounted into it, read-only (the system thus starts up with read-only OS resources, but pristine state and configuration, any changes to the either are lost on shutdown). When the mode parameter is specified as <literal>state</literal> the OS tree is mounted read-only, but <filename>/var</filename> is mounted as <literal>tmpfs</literal> instance into it (the system thus starts up with read-only OS resources and configuration, but pristine state, any changes to the latter are lost on shutdown). When the mode parameter is specified as <literal>no</literal> (the default) the whole OS tree is made available writable.</para> <para>Note that setting this to <literal>yes</literal> or <literal>state</literal> will only work correctly with operating systems in the container that can boot up with only <filename>/usr</filename> mounted, and are able to populate <filename>/var</filename> automatically, as needed.</para></listitem> </varlistentry> <xi:include href="standard-options.xml" xpointer="help" /> <xi:include href="standard-options.xml" xpointer="version" /> </variablelist> </refsect1> <refsect1> <title>Examples</title> <example> <title>Download a Fedora image and start a shell in it</title> <programlisting># machinectl pull-raw --verify=no http://ftp.halifax.rwth-aachen.de/fedora/linux/releases/21/Cloud/Images/x86_64/Fedora-Cloud-Base-20141203-21.x86_64.raw.xz # systemd-nspawn -M Fedora-Cloud-Base-20141203-21</programlisting> <para>This downloads an image using <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry> and opens a shell in it.</para> </example> <example> <title>Build and boot a minimal Fedora distribution in a container</title> <programlisting># yum -y --releasever=21 --nogpg --installroot=/srv/mycontainer --disablerepo='*' --enablerepo=fedora install systemd passwd yum fedora-release vim-minimal # systemd-nspawn -bD /srv/mycontainer</programlisting> <para>This installs a minimal Fedora distribution into the directory <filename noindex='true'>/srv/mycontainer/</filename> and then boots an OS in a namespace container in it.</para> </example> <example> <title>Spawn a shell in a container of a minimal Debian unstable distribution</title> <programlisting># debootstrap --arch=amd64 unstable ~/debian-tree/ # systemd-nspawn -D ~/debian-tree/</programlisting> <para>This installs a minimal Debian unstable distribution into the directory <filename>~/debian-tree/</filename> and then spawns a shell in a namespace container in it.</para> </example> <example> <title>Boot a minimal Arch Linux distribution in a container</title> <programlisting># pacstrap -c -d ~/arch-tree/ base # systemd-nspawn -bD ~/arch-tree/</programlisting> <para>This installs a mimimal Arch Linux distribution into the directory <filename>~/arch-tree/</filename> and then boots an OS in a namespace container in it.</para> </example> <example> <title>Boot into an ephemeral <literal>btrfs</literal> snapshot of the host system</title> <programlisting># systemd-nspawn -D / -xb</programlisting> <para>This runs a copy of the host system in a <literal>btrfs</literal> snapshot which is removed immediately when the container exits. All file system changes made during runtime will be lost on shutdown, hence.</para> </example> <example> <title>Run a container with SELinux sandbox security contexts</title> <programlisting># chcon system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 -R /srv/container # systemd-nspawn -L system_u:object_r:svirt_sandbox_file_t:s0:c0,c1 -Z system_u:system_r:svirt_lxc_net_t:s0:c0,c1 -D /srv/container /bin/sh</programlisting> </example> </refsect1> <refsect1> <title>Exit status</title> <para>The exit code of the program executed in the container is returned.</para> </refsect1> <refsect1> <title>See Also</title> <para> <citerefentry><refentrytitle>systemd</refentrytitle><manvolnum>1</manvolnum></citerefentry>, <citerefentry project='man-pages'><refentrytitle>chroot</refentrytitle><manvolnum>1</manvolnum></citerefentry>, <citerefentry project='die-net'><refentrytitle>yum</refentrytitle><manvolnum>8</manvolnum></citerefentry>, <citerefentry project='die-net'><refentrytitle>debootstrap</refentrytitle><manvolnum>8</manvolnum></citerefentry>, <citerefentry project='archlinux'><refentrytitle>pacman</refentrytitle><manvolnum>8</manvolnum></citerefentry>, <citerefentry><refentrytitle>systemd.slice</refentrytitle><manvolnum>5</manvolnum></citerefentry>, <citerefentry><refentrytitle>machinectl</refentrytitle><manvolnum>1</manvolnum></citerefentry>, <citerefentry project='man-pages'><refentrytitle>btrfs</refentrytitle><manvolnum>8</manvolnum></citerefentry> </para> </refsect1> </refentry>
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import { endpoints, endpointsTicket } from '../utils/endpoints'; import { Observable, catchError, take, timeout } from 'rxjs'; import { ErrorHandlerService } from './error-handler.service'; import { iChekTicket, iDefaultResponse, iDocumento, iTicket, iUserparams } from '../interfaces/default.interface'; @Injectable({ providedIn: 'root' }) export class ApiTicketService { request = { user: "gilson", password: "123" } token!: string; constructor( private http: HttpClient, private errorHandler: ErrorHandlerService ) { } getToken() { return this.http.post(environment.api_ticket + endpointsTicket.token, this.request, { responseType: "text"}) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } enviarDados(request: any) { const _headers = new HttpHeaders({ 'x-access-token': this.token }) return this.http.post(environment.api_ticket + endpointsTicket.ticket, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } enviarDocumento(request: any) { const _headers = new HttpHeaders({ 'x-access-token': this.token }) return this.http.post(environment.api_ticket + endpointsTicket.document, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } decryptToken(token: string): Observable<iDefaultResponse> { return this.http.post<iDefaultResponse>(environment.api_ticket + endpointsTicket.decryptToken, { token: token }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } //Setado como "any", pois estava chegando o this.dependentes[elem] como "unknown" e quebrando a aplicação. photoIdentity(user: any) { const _headers = new HttpHeaders({ 'x-access-token': this.token }) let request = { localizador: user.localizador, photo: user.foto } return this.http.post(environment.api_ticket + endpointsTicket.photoIdentify, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } ticketValidation(request: any) { const _headers = new HttpHeaders({ 'x-access-token': this.token }) return this.http.post(environment.api_ticket + endpointsTicket.ticketValidation, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } savePartialTicket(request: iTicket) { const _headers = new HttpHeaders({ 'x-access-token': this.token }) return this.http.post(environment.api_ticket + endpointsTicket.savePartialTicket, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } ticketRevalidation(request: iTicket) { const _headers = new HttpHeaders({ 'x-access-token': this.token }) return this.http.post(environment.api_ticket + endpointsTicket.ticketRevalidation, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } checkPartialTicket(request: iChekTicket): Observable<iDefaultResponse> { const _headers = new HttpHeaders({ 'x-access-token': this.token }) return this.http.post<iDefaultResponse>(environment.api_ticket + endpointsTicket.checkTicket, request, { headers: _headers }) .pipe( take(3), catchError( error => this.errorHandler.handleError(error) ) ) } }
/* Notification of schema changes This procedure reports on table schema changes, any new or deleted tables since the previous run of the stored procedure. It only reports on tables owned by 'dbo' */ create procedure usp_dba_schema_ver_cntrl as BEGIN set nocount on declare @cmd varchar(8000) declare @tbl_name sysname declare @current_ver int declare @stored_ver int declare @current_crdate datetime declare @stored_crdate datetime declare @cnt int declare @msg varchar(600) declare @status smallint declare @subject varchar(255) declare @message varchar(255) declare @query varchar(800) set @status = 0 -- successful status if not exists (select name from sysobjects where name = 'dba_SchemaVerCntrl' and xtype = 'U') create table dba_SchemaVerCntrl (TableName sysname not null, CreateDate datetime not null, SchemaVersion int not null) select @cnt = count(*) from dba_SchemaVerCntrl IF @cnt = 0 BEGIN select @msg = 'Have to initialize dba_SchemaVerCntrl table' print @msg insert into dba_SchemaVerCntrl select name, Crdate, schema_ver from sysobjects where xtype = 'U' and uid = 1 END ELSE BEGIN create table ##dba_schema( tbl_name sysname not null, status char not null, description varchar(50) null) declare tbl_cursor cursor for select name, Crdate, schema_ver from sysobjects where xtype = 'U' and uid = 1 open tbl_cursor fetch next from tbl_cursor into @tbl_name, @current_crdate, @current_ver WHILE @@fetch_status = 0 BEGIN -- compare the current schema version against the stored schema version select @stored_ver = SchemaVersion, @stored_crdate = CreateDate from dba_SchemaVerCntrl where TableName = @tbl_name IF @@ROWCOUNT = 0 -- no record found, a new table BEGIN select @msg = ' created on ' + convert(varchar(20), @current_crdate) --print @msg insert into dba_SchemaVerCntrl values (@tbl_name, @current_crdate, @current_ver) IF @@ERROR <> 0 BEGIN print 'Error inserting into dba_SchemaVerCntrl' set @status = 1 END insert into ##dba_schema values (@tbl_name, 'N', @msg) IF @@ERROR <> 0 BEGIN print 'Error inserting into ##dba_schema' set @status = 1 END END ELSE BEGIN IF @current_crdate <> @stored_crdate or @current_ver <> @stored_ver -- values are different BEGIN -- update stored size value update dba_SchemaVerCntrl set CreateDate = @current_crdate, SchemaVersion = @current_ver where TableName = @tbl_name IF @@ERROR <> 0 BEGIN print 'Error updating dba_SchemaVerCntrl' set @status = 1 END insert into ##dba_schema values(@tbl_name, 'U', null) IF @@ERROR <> 0 BEGIN print 'Error inserting into ##dba_schema' set @status = 1 END END -- table schema has been changed END -- matching record found fetch next from tbl_cursor into @tbl_name, @current_crdate, @current_ver END -- end loop close tbl_cursor deallocate tbl_cursor -- get a list of deleted objects insert into ##dba_schema select tablename, 'D', null from dba_SchemaVerCntrl where not exists (select * from sysobjects where xtype = 'U' and uid = 1 and dba_SchemaVerCntrl.tablename = sysobjects.name) delete dba_SchemaVerCntrl where not exists (select * from sysobjects where xtype = 'U' and uid = 1 and dba_SchemaVerCntrl.tablename = sysobjects.name) select RTRIM(tbl_name) as 'Table Name', case status when 'U' then 'Table schema has been changed' when 'N' then 'New table ' + RTRIM(description) else 'Table has been deleted' end as 'Schema Control Status' from ##dba_schema order by status desc, tbl_name IF @@rowcount <> 0 -- send mail BEGIN SELECT @subject = @@SERVERNAME + ' Database ' + DB_Name() + ': Schema Control Report for ' + convert( varchar(20), GETDATE()) + char(34) SELECT @message = @@SERVERNAME + ' Database ' + DB_Name() + ': Please find attached the Schema Control Report ' select @query = 'select RTRIM(tbl_name) as ''Table Name'', case status when ''U'' then ''Table schema has been changed'' when ''N'' then ''New table '' + RTRIM(description) else ''Table has been deleted'' end as ''Schema Control Status'' from ##dba_schema order by status desc, tbl_name' EXEC @status = master..xp_sendmail @recipients = '<recipients>' ,@message = @message ,@subject = @subject ,@query = @query ,@attach_results = 'false' ,@no_header = 'false' ,@echo_error = 'true' ,@width = 300 END -- end send mail drop table ##dba_schema END -- @cnt <> 0 IF @status <> 0 return 1 return 0 END GO
import 'package:flutter/material.dart'; class ProgressChartPainter extends CustomPainter { final double targetPercentage; final double currentPercentage; final double strokeWidth; final Color progressColor; ProgressChartPainter({ required this.targetPercentage, required this.currentPercentage, required this.strokeWidth, required this.progressColor, }); @override void paint(Canvas canvas, Size size) { final double centerX = size.width / 2; final double centerY = size.height / 2; final double radius = (size.width - strokeWidth) / 2; final progressPaint = Paint() ..color = progressColor ..style = PaintingStyle.stroke ..strokeWidth = strokeWidth; // Draw the target progress arc final targetSweepAngle = 360 * (targetPercentage / 100); canvas.drawArc( Rect.fromCircle(center: Offset(centerX, centerY), radius: radius), -90, targetSweepAngle, false, progressPaint, ); // Draw the current progress arc final currentSweepAngle = 360 * (currentPercentage / 100); progressPaint.color = Colors.green; canvas.drawArc( Rect.fromCircle(center: Offset(centerX, centerY), radius: radius), -90, currentSweepAngle, false, progressPaint, ); } @override bool shouldRepaint(covariant CustomPainter oldDelegate) { return true; } }
## MyToken Smart Contract The MyToken smart contract is an Ethereum-based token contract that extends the functionality of the ERC20 token standard. It provides additional features such as burning tokens, pausing and unpausing token transfers, and allowing users to redeem tokens for specific items. ## Features: ## Token Information: Token Name: MyToken Token Symbol: MTK ## ERC20 Standard: The contract adheres to the ERC20 token standard, allowing for basic token functionality like transferring, approving, and querying balances. 1. Burning Tokens: Users can burn (destroy) their tokens using the ERC20Burnable extension. 2. Pausing and Unpausing: The contract owner can pause and unpause token transfers using the Pausable extension. Pausing prevents any token transfers, while unpausing allows transfers to resume. 3. Redeeming Tokens: Users can redeem tokens for specific items using the redeemtokensForItem function. Redeemable items include a Hoodie, Cap, and Backpack. Each item has a different redemption cost in tokens. A shipping cost is also added to the redemption amount. ## Access Control: The contract uses the Ownable extension to designate the deployer as the contract owner. Only the contract owner can perform certain actions like pausing, unpausing, and minting new tokens. ## Functions: 1. pause(): Pauses token transfers. Only the contract owner can call this function. 2. unpause(): Unpauses token transfers. Only the contract owner can call this function. 3. mint(address to, uint256 amount): Allows the contract owner to mint new tokens and send them to a specified address. 4. redeemtokensForItem(uint256 itemno): Users can redeem tokens for specific items by providing the item number. Tokens are burned, and the item's redemption cost is deducted from the sender's balance. 5. RedeemableItems(): Allows anyone to view the list of redeemable item names. ## Deployment and Compilation: Deploy the contract using a Solidity compiler that supports version 0.8.9.After deployment, the contract owner can mint initial tokens and manage the contract's features. Usage: Users can transfer tokens using standard ERC20 functions. To redeem an item, users call the redeemtokensForItem function with the desired item number. The contract owner can pause/unpause token transfers using the pause and unpause functions. The contract owner can mint new tokens using the mint function.l
Django Mailer ------------- .. image:: https://github.com/pinax/django-mailer/actions/workflows/build.yml/badge.svg :target: https://github.com/pinax/django-mailer/actions/workflows/build.yml .. image:: https://img.shields.io/coveralls/pinax/django-mailer.svg :target: https://coveralls.io/r/pinax/django-mailer .. image:: https://img.shields.io/pypi/dm/django-mailer.svg :target: https://pypi.python.org/pypi/django-mailer/ .. image:: https://img.shields.io/pypi/v/django-mailer.svg :target: https://pypi.python.org/pypi/django-mailer/ .. image:: https://img.shields.io/badge/license-MIT-blue.svg :target: https://pypi.python.org/pypi/django-mailer/ django-mailer ------------- ``django-mailer`` is a reusable Django app for queuing the sending of email. It works by storing email in the database for later sending. This has a number of advantages: - **robustness** - if your email provider goes down or has a temporary error, the email won’t be lost. In addition, since the ``send_mail()`` call always succeeds (unless your database is out of action), then the HTTP request that triggered the email to be sent won’t crash, and any ongoing transaction won’t be rolled back. - **correctness** - when an outgoing email is created as part of a transaction, since it is stored in the database it will participate in transactions. This means it won’t be sent until the transaction is committed, and won’t be sent at all if the transaction is rolled back. In addition, if you want to ensure that mails are sent very quickly, and without heaving polling, django-mailer comes with a PostgreSQL specific ``runmailer_pg`` command. This uses PostgreSQL’s `NOTIFY <https://www.postgresql.org/docs/16/sql-notify.html>`_/`LISTEN <https://www.postgresql.org/docs/16/sql-listen.html>`_ feature to be able to send emails as soon as they are added to the queue. Limitations ----------- File attachments are also temporarily stored in the database, which means if you are sending files larger than several hundred KB in size, you are likely to run into database limitations on how large your query can be. If this happens, you'll either need to fall back to using Django's default mail backend, or increase your database limits (a procedure that depends on which database you are using). With django-mailer, you can’t know in a Django view function whether the email has actually been sent or not - the ``send_mail`` function just stores mail on the queue to be sent later. django-mailer was developed as part of the `Pinax ecosystem <http://pinaxproject.com>`_ but is just a Django app and can be used independently of other Pinax apps. Requirements ------------ * Django >= 2.2 * Databases: django-mailer supports all databases that Django supports, with the following notes: * SQLite: you may experience 'database is locked' errors if the ``send_mail`` command runs when anything else is attempting to put items on the queue. For this reason SQLite is not recommended for use with django-mailer. * MySQL: the developers don’t test against MySQL. Usage ----- See `usage.rst <https://github.com/pinax/django-mailer/blob/master/docs/usage.rst#usage>`_ in the docs. Support ------- The Pinax documentation is available at http://pinaxproject.com/pinax/. This is an Open Source project maintained by volunteers, and outside this documentation the maintainers do not offer other support. For cases where you have found a bug you can file a GitHub issue. In case of any questions we recommend you join the `Pinax Slack team <http://slack.pinaxproject.com>`_ and ping the Pinax team there instead of creating an issue on GitHub. You may also be able to get help on other programming sites like `Stack Overflow <https://stackoverflow.com/>`_. Contribute ---------- See `CONTRIBUTING.rst <https://github.com/pinax/django-mailer/blob/master/CONTRIBUTING.rst>`_ for information about contributing patches to ``django-mailer``. See this `blog post including a video <http://blog.pinaxproject.com/2016/02/26/recap-february-pinax-hangout/>`_, or our `How to Contribute <http://pinaxproject.com/pinax/how_to_contribute/>`_ section for an overview on how contributing to Pinax works. For concrete contribution ideas, please see our `Ways to Contribute/What We Need Help With <http://pinaxproject.com/pinax/ways_to_contribute/>`_ section. We also highly recommend reading our `Open Source and Self-Care blog post <http://blog.pinaxproject.com/2016/01/19/open-source-and-self-care/>`_. Code of Conduct --------------- In order to foster a kind, inclusive, and harassment-free community, the Pinax Project has a `code of conduct <http://pinaxproject.com/pinax/code_of_conduct/>`_. We ask you to treat everyone as a smart human programmer that shares an interest in Python, Django, and Pinax with you. Pinax Project Blog and Twitter ------------------------------ For updates and news regarding the Pinax Project, please follow us on Twitter at @pinaxproject and check out `our blog <http://blog.pinaxproject.com>`_.
import * as React from "react"; import * as ReactDOM from "react-dom"; import { DatePicker } from "@progress/kendo-react-dateinputs"; import { DropDownList } from "@progress/kendo-react-dropdowns"; import { IntlProvider, load, loadMessages, LocalizationProvider } from "@progress/kendo-react-intl"; import likelySubtags from "cldr-core/supplemental/likelySubtags.json"; import currencyData from "cldr-core/supplemental/currencyData.json"; import weekData from "cldr-core/supplemental/weekData.json"; import numbers from "cldr-numbers-full/main/es/numbers.json"; import caGregorian from "cldr-dates-full/main/es/ca-gregorian.json"; import dateFields from "cldr-dates-full/main/es/dateFields.json"; import timeZoneNames from "cldr-dates-full/main/es/timeZoneNames.json"; load(likelySubtags, currencyData, weekData, numbers, caGregorian, dateFields, timeZoneNames); import esMessages from "./es.json"; loadMessages(esMessages, "es-ES"); const App = () => { const locales = [{ language: "en-US", locale: "en" }, { language: "es-ES", locale: "es" }]; const [locale, setLocale] = React.useState(locales[0]); const value = new Date(); return <LocalizationProvider language={locale.language}> <IntlProvider locale={locale.locale}> <div className="example-wrapper row"> <div className="col-xs-12 col-md-12 example-config"> <h6> Locale: <DropDownList value={locale} data={locales} textField={"locale"} onChange={e => { setLocale(e.target.value); }} /> </h6> </div> <div className="col-xs-12 col-md-6 example-col"> <p>Default Show</p> <DatePicker defaultValue={value} defaultShow={true} /> <p>Format and WeekColumn</p> <DatePicker defaultValue={value} format="dd/MMM/yyyy" weekNumber={true} /> <p>Disabled</p> <DatePicker disabled={true} defaultValue={value} format="dd/MMMM/yyyy" /> </div> </div> </IntlProvider> </LocalizationProvider>; }; ReactDOM.render(<App />, document.querySelector("my-app"));
// // ItemCell.swift // EasyMOOC // // Created by 高存折 on 2017/2/22. // Copyright © 2017年 高存折. All rights reserved. // import UIKit import LeanCloud import Alamofire class ItemCell: UICollectionViewCell { var course: Course? { didSet { setupView() } } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let imageView:UIImageView = { let iv = UIImageView() iv.image = #imageLiteral(resourceName: "e-course") iv.contentMode = .scaleAspectFit iv.layer.cornerRadius = 5 iv.layer.masksToBounds = true return iv }() let courseName: UILabel = { let label = UILabel() label.textColor = UIColor(white: 0, alpha: 0.9) label.font = UIFont.systemFont(ofSize: 12) return label }() let universityName: UILabel = { let label = UILabel() label.textColor = UIColor.gray label.font = UIFont.systemFont(ofSize: 12) return label }() func setupView() { backgroundColor = UIColor.clear addSubview(imageView) addSubview(courseName) addSubview(universityName) imageView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height - 20) courseName.frame = CGRect(x: 0, y: frame.height - 20, width: frame.width, height: 10) universityName.frame = CGRect(x: 0, y: frame.height - 5, width: frame.width, height: 10) courseName.text = course?.courseName universityName.text = course?.collegeName let imageUrl = course?.thumnailUrl guard let url = imageUrl else {return} HttpManager.fetchImage(url: url) { image in self.imageView.image = image } } }
package com.example.mdp_group22; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.example.mdp_group22.MainActivity; import com.example.mdp_group22.R; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.UUID; public class BluetoothConnectionService { private static final String TAG = "DebuggingTag"; private static final String appName = "MDP_Group_22"; //A unique identifier for this app public static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private final BluetoothAdapter mBluetoothAdapter; Context mContext; private AcceptThread mInsecureAcceptThread; private ConnectThread mConnectThread; private BluetoothDevice mDevice; private UUID deviceUUID; ProgressDialog mProgressDialog; Intent connectionStatus; public static boolean BluetoothConnectionStatus=false; private static ConnectedThread mConnectedThread; public BluetoothConnectionService(Context context) { this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); this.mContext = context; this.startAcceptThread(); } private class AcceptThread extends Thread{ // Used to listen for incoming connections. private final BluetoothServerSocket ServerSocket; @SuppressLint("MissingPermission") public AcceptThread() { BluetoothServerSocket tmp = null; // starts listening for incoming connections try { tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, myUUID); } catch (IOException e){ e.printStackTrace(); } this.ServerSocket = tmp; } public void run(){ BluetoothSocket socket = null; try { socket = ServerSocket.accept(); } catch (IOException e){ e.printStackTrace(); } // connection accepted if (socket != null){ connected(socket, socket.getRemoteDevice()); } } public void cancel(){ try{ ServerSocket.close(); } catch(IOException e){ e.printStackTrace(); } } } private class ConnectThread extends Thread{ // A BluetoothSocket object that represents the outgoing Bluetooth connection. private BluetoothSocket mSocket; public ConnectThread(BluetoothDevice device, UUID u){ mDevice = device; deviceUUID = u; } @SuppressLint("MissingPermission") public void run(){ BluetoothSocket tmp = null; try { tmp = mDevice.createRfcommSocketToServiceRecord(deviceUUID); } catch (IOException e) { e.printStackTrace(); } mSocket= tmp; mBluetoothAdapter.cancelDiscovery(); try { mSocket.connect(); connected(mSocket,mDevice); } catch (IOException e) { try { mSocket.close(); } catch (IOException e1) { e.printStackTrace(); } try { BluetoothPopUp mBluetoothPopUpActivity = (BluetoothPopUp) mContext; mBluetoothPopUpActivity.runOnUiThread(() -> Toast.makeText(mContext, "Failed to connect to the Device.", Toast.LENGTH_SHORT).show()); } catch (Exception z) { z.printStackTrace(); } } try { mProgressDialog.dismiss(); } catch (NullPointerException e){ e.printStackTrace(); } } public void cancel(){ try{ mSocket.close(); } catch(IOException e){ e.printStackTrace(); } } } public synchronized void startAcceptThread(){ //Cancel any thread attempting to make a connection if (this.mConnectThread != null){ this.mConnectThread.cancel(); this.mConnectThread = null; } // If accept thread is null we want to start a new one if (this.mInsecureAcceptThread == null){ this.mInsecureAcceptThread = new AcceptThread(); this.mInsecureAcceptThread.start(); } } public void startClientThread(BluetoothDevice device, UUID uuid){ try { this.mProgressDialog = ProgressDialog.show(this.mContext, "Connecting Bluetooth", "Please Wait...", true); } catch (Exception e) { e.printStackTrace(); } // starts the ConnectThread this.mConnectThread = new ConnectThread(device, uuid); this.mConnectThread.start(); } private class ConnectedThread extends Thread{ private final BluetoothSocket mSocket; private final InputStream inStream; private final OutputStream outStream; private boolean stopThread = false; @SuppressLint("MissingPermission") public ConnectedThread(BluetoothSocket socket) { Log.d(TAG, "ConnectedThread: Starting."); connectionStatus = new Intent("ConnectionStatus"); connectionStatus.putExtra("Status", "connected"); connectionStatus.putExtra("Device", mDevice); LocalBroadcastManager.getInstance(mContext).sendBroadcast(connectionStatus); BluetoothConnectionStatus = true; TextView status = MainActivity.getBluetoothStatus(); status.setText(R.string.bt_connected); status.setTextColor(Color.GREEN); TextView device = MainActivity.getConnectedDevice(); device.setText(mDevice.getName()); this.mSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try { tmpIn = mSocket.getInputStream(); tmpOut = mSocket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } inStream = tmpIn; outStream = tmpOut; } public void run(){ byte[] buffer = new byte[1024]; int bytes; StringBuilder messageBuffer = new StringBuilder(); while (true){ try { bytes = inStream.read(buffer); String incomingmessage = new String(buffer, 0, bytes); Log.d(TAG, "InputStream: "+ incomingmessage); messageBuffer.append(incomingmessage); int delimiterIndex = messageBuffer.indexOf("\n"); if (delimiterIndex != -1) { String[] messages = messageBuffer.toString().split("\n"); for (String message : messages) { Intent incomingMessageIntent = new Intent("incomingMessage"); incomingMessageIntent.putExtra("receivedMessage", message); LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent); } // Reset the message buffer messageBuffer = new StringBuilder(); } } catch (IOException e) { Log.e(TAG, "Error reading input stream. "+e.getMessage()); connectionStatus = new Intent("ConnectionStatus"); connectionStatus.putExtra("Status", "disconnected"); TextView status = MainActivity.getBluetoothStatus(); status.setText(R.string.bt_disconnect); status.setTextColor(Color.RED); connectionStatus.putExtra("Device", mDevice); LocalBroadcastManager.getInstance(mContext).sendBroadcast(connectionStatus); BluetoothConnectionStatus = false; break; } } } public void write(byte[] bytes){ String text = new String(bytes, Charset.defaultCharset()); Log.d(TAG, "write: Writing to output stream: "+text); try { outStream.write(bytes); } catch (IOException e) { Log.e(TAG, "Error writing to output stream. "+e.getMessage()); } } public void cancel(){ Log.d(TAG, "cancel: Closing Client Socket"); try{ this.stopThread = true; mSocket.close(); } catch(IOException e){ Log.e(TAG, "cancel: Failed to close ConnectThread mSocket " + e.getMessage()); } } } private void connected(BluetoothSocket mSocket, BluetoothDevice device) { mDevice = device; // stops the AcceptThread when received request if (mInsecureAcceptThread != null) { mInsecureAcceptThread.cancel(); mInsecureAcceptThread = null; } mConnectedThread = new ConnectedThread(mSocket); mConnectedThread.start(); } public static void write(byte[] out){ ConnectedThread tmp; Log.d(TAG, "write: Write is called." ); mConnectedThread.write(out); } }
package com.zonief.deeplconnector; import com.zonief.deeplconnector.service.TranslationService; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @AllArgsConstructor @Slf4j public class DeeplConnectorApplication implements CommandLineRunner { private final TranslationService translationService; public static void main(String[] args) { SpringApplication.run(DeeplConnectorApplication.class, args); } @Override public void run(String... args) { if (args.length == 2) { String language = args[1]; //create a new file with the translated language in the name File translationFile = new File( StringUtils.substringBefore(args[0], ".pdf") + "-" + args[1].toUpperCase() + "-" + UUID.randomUUID() + ".pdf"); //translate the file byte[] translation = translationService.translateFile(new File(args[0]), language); //write the file to disk try (FileOutputStream outputStream = new FileOutputStream(translationFile)) { outputStream.write(translation); log.info("File Written Successfully at {}", translationFile.getAbsolutePath()); } catch (IOException e) { log.error("Error writing file", e); } } else { throw new IllegalArgumentException("You must provide a file path as argument"); } System.exit(0); } }
package com.davemorrissey.labs.subscaleview import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint import android.graphics.PointF import android.graphics.Rect import android.graphics.RectF import android.util.AttributeSet import android.util.TypedValue import android.view.GestureDetector import android.view.MotionEvent import android.view.View import androidx.annotation.IntDef import eu.kanade.tachiyomi.ui.reader.setting.ReaderPreferences import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sqrt import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch /** * Displays an image subsampled as necessary to avoid loading too much image data into memory. After zooming in, * a set of image tiles subsampled at higher resolution are loaded and displayed over the base layer. During pan and * zoom, tiles off screen or higher/lower resolution than required are discarded from memory. * * * Tiles are no larger than the max supported bitmap size, so with large images tiling may be used even when zoomed out. * * * v prefixes - coordinates, translations and distances measured in screen (view) pixels * <br></br> * s prefixes - coordinates, translations and distances measured in rotated and cropped source image pixels (scaled) * <br></br> * f prefixes - coordinates, translations and distances measured in original unrotated, uncropped source file pixels * * * [View project on GitHub](https://github.com/davemorrissey/subsampling-scale-image-view) * */ @Suppress("unused") open class SubsamplingScaleImageView @JvmOverloads constructor( context: Context, attr: AttributeSet? = null, ) : View(context, attr) { // Coroutines scope private val coroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) // Current quickscale state private val quickScaleThreshold: Float // Long click handler private var longClickJob: Job? = null // The logical density of the display private val density: Float = resources.displayMetrics.density // Bitmap (preview or full image) private var bitmap: Bitmap? = null // Specifies if a cache handler is also referencing the bitmap. Do not recycle if so. private var bitmapIsCached = false /** * Maximum scale allowed. A value of 1 means 1:1 pixels at maximum scale. You may wish to set this according * to screen density - on a retina screen, 1:1 may still be too small. Consider using [setMinimumDpi], * which is density aware. */ var maxScale = 2F // Pan limiting style @PanLimit private var panLimit = PAN_LIMIT_INSIDE // Minimum scale type @ScaleType private var minimumScaleType = SCALE_TYPE_CENTER_INSIDE // Whether to crop borders. private var cropBorders = false // Gesture detection settings private var panEnabled = true /** * Enable or disable zoom gesture detection. Disabling zoom locks the the current scale. */ var isZoomEnabled = true /** * Enable or disable double tap &amp; swipe to zoom. */ var isQuickScaleEnabled = true // Double tap zoom behaviour private var doubleTapZoomScale = 1F @ZoomStyle private var doubleTapZoomStyle = ZOOM_FOCUS_FIXED private var doubleTapZoomDuration = 500 /** * Returns the current scale value. * * @return the current scale as a source/view pixels ratio. */ var scale = 0F private set private var scaleStart = 0F // Screen coordinate of top-left corner of source image private var vTranslate: PointF? = null private var vTranslateStart: PointF? = null private var vTranslateBefore: PointF? = null // Source coordinate to center on, used when new position is set externally before view is ready private var pendingScale = -1F private var sPendingCenter: PointF? = null private var sRequestedCenter: PointF? = null /** * Get source width. * * @return the source image width in pixels. */ var sWidth = 0 private set /** * Get source height. * * @return the source image height in pixels. */ var sHeight = 0 private set // Min scale allowed (prevent infinite zoom) private var minScale = minScale() private var srcRect = Rect(0, 0, 0, 0) // Is two-finger zooming in progress private var isZooming = false // Is one-finger panning in progress private var isPanning = false // Is quick-scale gesture in progress private var isQuickScaling = false // Max touches used in current gesture private var maxTouchCount = 0 // Fling detector private var detector: GestureDetector? = null private var singleDetector: GestureDetector? = null // Debug values private var vCenterStart: PointF? = null private var vDistStart = 0F private var quickScaleLastDistance = 0F private var quickScaleMoved = false private var quickScaleVLastPoint: PointF? = null private var quickScaleSCenter: PointF? = null private var quickScaleVStart: PointF? = null // Scale and center animation tracking private var anim: Anim? = null /** * Call to find whether the view is initialised, has dimensions, and will display an image on * the next draw. If a preview has been provided, it may be the preview that will be displayed * and the full size image may still be loading. If no preview was provided, this is called once * the base layer tiles of the full size image are loaded. * * @return true if the view is ready to display an image and accept touch gestures. */ var isReady = false private set /** * Call to find whether the main image (base layer tiles where relevant) have been loaded. Before * this event the view is blank unless a preview was provided. * * @return true if the main image (not the preview) has been loaded and is ready to display. */ var isImageLoaded = false private set // Event listener private var onImageEventListener: OnImageEventListener? = null // Scale and center listener private var onStateChangedListener: OnStateChangedListener? = null // Long click listener private var onLongClickListener: OnLongClickListener? = null // Paint objects created once and reused for efficiency private val bitmapPaint by lazy { Paint().apply { isAntiAlias = true isFilterBitmap = true isDither = true } } // Volatile fields used to reduce object creation private var satTemp: ScaleAndTranslate? = null private val mtrx = Matrix() init { setMinimumDpi(160) setDoubleTapZoomDpi(160) setGestureDetector(context) quickScaleThreshold = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20F, context.resources.displayMetrics) } /** * Set the image source from a bitmap, resource, asset, file or other URI. * * @param bitmap Image source. */ fun setImage(bitmap: Bitmap, rect: Rect) { reset(true) srcRect = Rect(rect) onImageLoaded(bitmap) } /** * Reset all state before setting/changing image or setting new rotation. */ private fun reset(newImage: Boolean) { scale = 0F scaleStart = 0F vTranslate = null vTranslateStart = null vTranslateBefore = null pendingScale = -1F sPendingCenter = null sRequestedCenter = null isZooming = false isPanning = false isQuickScaling = false maxTouchCount = 0 vCenterStart = null vDistStart = 0F quickScaleLastDistance = 0F quickScaleMoved = false quickScaleSCenter = null quickScaleVLastPoint = null quickScaleVStart = null anim = null satTemp = null mtrx.reset() if (newImage) { if (!bitmapIsCached) { bitmap?.recycle() } sWidth = 0 sHeight = 0 srcRect.setEmpty() isReady = false isImageLoaded = false bitmap = null bitmapIsCached = false } setGestureDetector(context) } private fun setGestureDetector(context: Context) { detector = GestureDetector( context, object : GestureDetector.SimpleOnGestureListener() { override fun onFling(e1: MotionEvent?, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { if (panEnabled && isReady && vTranslate != null && e1 != null && (abs(e1.x - e2.x) > 50 || abs(e1.y - e2.y) > 50) && (abs(velocityX) > 500 || abs(velocityY) > 500) && !isZooming) { val vTranslateEnd = PointF(vTranslate!!.x + velocityX * 0.25F, vTranslate!!.y + velocityY * 0.25F) val sCenterXEnd = (width / 2 - vTranslateEnd.x) / scale val sCenterYEnd = (height / 2 - vTranslateEnd.y) / scale AnimationBuilder(PointF(sCenterXEnd, sCenterYEnd)) .withEasing(EASE_OUT_QUAD) .withPanLimited(false) .withOrigin(ORIGIN_FLING) .start() return true } return super.onFling(e1, e2, velocityX, velocityY) } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { performClick() return true } override fun onDoubleTap(e: MotionEvent): Boolean { if (!ReaderPreferences.doubleTapToZoom().get()) return false if (isZoomEnabled && isReady && vTranslate != null) { // Hacky solution for #15 - after a double tap the GestureDetector gets in a state // where the next fling is ignored, so here we replace it with a new one. setGestureDetector(context) return if (isQuickScaleEnabled) { // Store quick scale params. This will become either a double tap zoom or a // quick scale depending on whether the user swipes. vCenterStart = PointF(e.x, e.y) vTranslateStart = PointF(vTranslate!!.x, vTranslate!!.y) scaleStart = scale isQuickScaling = true isZooming = true quickScaleLastDistance = -1F quickScaleSCenter = viewToSourceCoord(vCenterStart!!) quickScaleVStart = PointF(e.x, e.y) quickScaleVLastPoint = PointF(quickScaleSCenter!!.x, quickScaleSCenter!!.y) quickScaleMoved = false // We need to get events in onTouchEvent after this. false } else { // Start double tap zoom animation. viewToSourceCoord(PointF(e.x, e.y))?.let { center -> doubleTapZoom(center, PointF(e.x, e.y)) } true } } return super.onDoubleTapEvent(e) } }, ) singleDetector = GestureDetector( context, object : GestureDetector.SimpleOnGestureListener() { override fun onSingleTapConfirmed(e: MotionEvent): Boolean { performClick() return true } }, ) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() coroutineScope.cancel() } /** * On resize, preserve center and scale. Various behaviours are possible, override this method to use another. */ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { if (isReady && center != null) { anim = null pendingScale = scale sPendingCenter = center } } /** * Measures the width and height of the view, preserving the aspect ratio of the image displayed if wrap_content is * used. The image will scale within this box, not resizing the view as it is zoomed. */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthSpecMode = MeasureSpec.getMode(widthMeasureSpec) val heightSpecMode = MeasureSpec.getMode(heightMeasureSpec) val parentWidth = MeasureSpec.getSize(widthMeasureSpec) val parentHeight = MeasureSpec.getSize(heightMeasureSpec) val resizeWidth = widthSpecMode != MeasureSpec.EXACTLY val resizeHeight = heightSpecMode != MeasureSpec.EXACTLY var width = parentWidth var height = parentHeight if (sWidth > 0 && sHeight > 0) { if (resizeWidth && resizeHeight) { width = sWidth height = sHeight } else if (resizeHeight) { height = (sHeight.toDouble() / sWidth.toDouble() * width).toInt() } else if (resizeWidth) { width = (sWidth.toDouble() / sHeight.toDouble() * height).toInt() } } width = width.coerceAtLeast(suggestedMinimumWidth) height = height.coerceAtLeast(suggestedMinimumHeight) setMeasuredDimension(width, height) } /** * Handle touch events. One finger pans, and two finger pinch and zoom plus panning. */ @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { // During non-interruptible anims, ignore all touch events if (anim?.interruptible == false) { requestDisallowInterceptTouchEvent(true) return true } anim = null // Abort if not ready if (vTranslate == null) { singleDetector?.onTouchEvent(event) return true } // Detect flings, taps and double taps // May throw NPE runCatching { if (!isQuickScaling && detector?.onTouchEvent(event) != false) { isZooming = false isPanning = false maxTouchCount = 0 return true } } if (vTranslateStart == null) { vTranslateStart = PointF(0F, 0F) } if (vTranslateBefore == null) { vTranslateBefore = PointF(0F, 0F) } if (vCenterStart == null) { vCenterStart = PointF(0F, 0F) } // Store current values so we can send an event if they change vTranslateBefore!!.set(vTranslate!!) val handled = onTouchEventInternal(event) sendStateChanged(scale, vTranslateBefore!!, ORIGIN_TOUCH) return handled || super.onTouchEvent(event) } private fun onTouchEventInternal(event: MotionEvent): Boolean { val touchCount = event.pointerCount when (event.actionMasked) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { anim = null requestDisallowInterceptTouchEvent(true) maxTouchCount = maxTouchCount.coerceAtLeast(touchCount) if (touchCount >= 2) { if (isZoomEnabled) { // Start pinch to zoom. Calculate distance between touch points and center point of the pinch. scaleStart = scale vDistStart = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)) vTranslateStart!![vTranslate!!.x] = vTranslate!!.y vCenterStart!![(event.getX(0) + event.getX(1)) / 2] = (event.getY(0) + event.getY(1)) / 2 } else { // Abort all gestures on second touch maxTouchCount = 0 } // Cancel long click timer longClickJob?.cancel() } else if (!isQuickScaling) { // Start one-finger pan vTranslateStart!![vTranslate!!.x] = vTranslate!!.y vCenterStart!![event.x] = event.y // Start long click timer longClickJob = coroutineScope.launch { if (onLongClickListener != null) { delay(600) super@SubsamplingScaleImageView.setOnLongClickListener(onLongClickListener) performLongClick() super@SubsamplingScaleImageView.setOnLongClickListener(null) } } } return true } MotionEvent.ACTION_MOVE -> { var consumed = false if (maxTouchCount > 0) { if (touchCount >= 2) { // Calculate new distance between touch points, to scale and pan relative to start values. val vDistEnd = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)) val vCenterEndX = (event.getX(0) + event.getX(1)) / 2 val vCenterEndY = (event.getY(0) + event.getY(1)) / 2 if (isZoomEnabled && (distance(vCenterStart!!.x, vCenterEndX, vCenterStart!!.y, vCenterEndY) > 5 || abs(vDistEnd - vDistStart) > 5 || isPanning)) { isZooming = true isPanning = true consumed = true val previousScale = scale.toDouble() scale = (vDistEnd / vDistStart * scaleStart).coerceAtMost(maxScale) if (scale <= minScale()) { // Minimum scale reached so don't pan. Adjust start settings so any expand will zoom in. vDistStart = vDistEnd scaleStart = minScale() vCenterStart!![vCenterEndX] = vCenterEndY vTranslateStart!!.set(vTranslate!!) } else if (panEnabled) { // Translate to place the source image coordinate that was at the center of the pinch at the start // at the center of the pinch now, to give simultaneous pan + zoom. val vLeftStart = vCenterStart!!.x - vTranslateStart!!.x val vTopStart = vCenterStart!!.y - vTranslateStart!!.y val vLeftNow = vLeftStart * (scale / scaleStart) val vTopNow = vTopStart * (scale / scaleStart) vTranslate!!.x = vCenterEndX - vLeftNow vTranslate!!.y = vCenterEndY - vTopNow if (previousScale * sHeight < height && scale * sHeight >= height || previousScale * sWidth < width && scale * sWidth >= width) { fitToBounds(true) vCenterStart!![vCenterEndX] = vCenterEndY vTranslateStart!!.set(vTranslate!!) scaleStart = scale vDistStart = vDistEnd } } else if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. vTranslate!!.x = width / 2 - scale * sRequestedCenter!!.x vTranslate!!.y = height / 2 - scale * sRequestedCenter!!.y } else { // With no requested center, scale around the image center. vTranslate!!.x = width / 2 - scale * (sWidth / 2) vTranslate!!.y = height / 2 - scale * (sHeight / 2) } fitToBounds(true) } } else if (isQuickScaling) { // One finger zoom // Stole Google's Magical Formula™ to make sure it feels the exact same var dist = abs(quickScaleVStart!!.y - event.y) * 2 + quickScaleThreshold if (quickScaleLastDistance == -1F) { quickScaleLastDistance = dist } val isUpwards = event.y > quickScaleVLastPoint!!.y quickScaleVLastPoint!![0F] = event.y val spanDiff = abs(1 - dist / quickScaleLastDistance) * 0.5F if (spanDiff > 0.03F || quickScaleMoved) { quickScaleMoved = true var multiplier = 1F if (quickScaleLastDistance > 0) { multiplier = if (isUpwards) 1 + spanDiff else 1 - spanDiff } val previousScale = scale.toDouble() scale = (scale * multiplier).coerceIn(minScale(), maxScale) if (panEnabled) { val vLeftStart = vCenterStart!!.x - vTranslateStart!!.x val vTopStart = vCenterStart!!.y - vTranslateStart!!.y val vLeftNow = vLeftStart * (scale / scaleStart) val vTopNow = vTopStart * (scale / scaleStart) vTranslate!!.x = vCenterStart!!.x - vLeftNow vTranslate!!.y = vCenterStart!!.y - vTopNow if (previousScale * sHeight < height && scale * sHeight >= height || previousScale * sWidth < width && scale * sWidth >= width) { fitToBounds(true) vCenterStart!!.set(sourceToViewCoord(quickScaleSCenter)!!) vTranslateStart!!.set(vTranslate!!) scaleStart = scale dist = 0F } } else if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. vTranslate!!.x = width / 2 - scale * sRequestedCenter!!.x vTranslate!!.y = height / 2 - scale * sRequestedCenter!!.y } else { // With no requested center, scale around the image center. vTranslate!!.x = width / 2 - scale * (sWidth / 2) vTranslate!!.y = height / 2 - scale * (sHeight / 2) } } quickScaleLastDistance = dist fitToBounds(true) consumed = true } else if (!isZooming) { // One finger pan - translate the image. We do this calculation even with pan disabled so click // and long click behaviour is preserved. val dx = abs(event.x - vCenterStart!!.x) val dy = abs(event.y - vCenterStart!!.y) // On the Samsung S6 long click event does not work, because the dx > 5 usually true val offset = density * 5 if (dx > offset || dy > offset || isPanning) { consumed = true vTranslate!!.x = vTranslateStart!!.x + (event.x - vCenterStart!!.x) vTranslate!!.y = vTranslateStart!!.y + (event.y - vCenterStart!!.y) val lastX = vTranslate!!.x val lastY = vTranslate!!.y fitToBounds(true) val atXEdge = lastX != vTranslate!!.x val atYEdge = lastY != vTranslate!!.y val edgeXSwipe = atXEdge && dx > dy && !isPanning val edgeYSwipe = atYEdge && dy > dx && !isPanning val yPan = lastY == vTranslate!!.y && dy > offset * 3 if (!edgeXSwipe && !edgeYSwipe && (!atXEdge || !atYEdge || yPan || isPanning)) { isPanning = true } else if (dx > offset || dy > offset) { // Haven't panned the image, and we're at the left or right edge. Switch to page swipe. maxTouchCount = 0 longClickJob?.cancel() requestDisallowInterceptTouchEvent(false) } if (!panEnabled) { vTranslate!!.x = vTranslateStart!!.x vTranslate!!.y = vTranslateStart!!.y requestDisallowInterceptTouchEvent(false) } } } } if (consumed) { longClickJob?.cancel() invalidate() return true } } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { longClickJob?.cancel() if (isQuickScaling) { isQuickScaling = false if (!quickScaleMoved && quickScaleSCenter != null && vCenterStart != null) { doubleTapZoom(quickScaleSCenter!!, vCenterStart!!) } } if (maxTouchCount > 0 && (isZooming || isPanning)) { if (isZooming && touchCount == 2) { // Convert from zoom to pan with remaining touch isPanning = true vTranslateStart!![vTranslate!!.x] = vTranslate!!.y if (event.actionIndex == 1) { vCenterStart!![event.getX(0)] = event.getY(0) } else { vCenterStart!![event.getX(1)] = event.getY(1) } } if (touchCount < 3) { // End zooming when only one touch point isZooming = false } if (touchCount < 2) { // End panning when no touch points isPanning = false maxTouchCount = 0 } // Trigger load of tiles now required return true } if (touchCount == 1) { isZooming = false isPanning = false maxTouchCount = 0 } return true } } return false } private fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) { parent?.requestDisallowInterceptTouchEvent(disallowIntercept) } /** * Double tap zoom handler triggered from gesture detector or on touch, depending on whether * quick scale is enabled. */ private fun doubleTapZoom(sCenter: PointF, vFocus: PointF) { if (!panEnabled) { if (sRequestedCenter != null) { // With a center specified from code, zoom around that point. sCenter.x = sRequestedCenter!!.x sCenter.y = sRequestedCenter!!.y } else { // With no requested center, scale around the image center. sCenter.x = (sWidth / 2).toFloat() sCenter.y = (sHeight / 2).toFloat() } } val doubleTapZoomScale = doubleTapZoomScale.coerceAtMost(maxScale) val zoomIn = scale <= doubleTapZoomScale * 0.9 || scale == minScale val targetScale = if (zoomIn) doubleTapZoomScale else minScale() if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER_IMMEDIATE) { setScaleAndCenter(targetScale, sCenter) } else if (doubleTapZoomStyle == ZOOM_FOCUS_CENTER || !zoomIn || !panEnabled) { AnimationBuilder(targetScale, sCenter) .withInterruptible(false) .withDuration(doubleTapZoomDuration.toLong()) .withOrigin(ORIGIN_DOUBLE_TAP_ZOOM) .start() } else if (doubleTapZoomStyle == ZOOM_FOCUS_FIXED) { AnimationBuilder(targetScale, sCenter, vFocus) .withInterruptible(false) .withDuration(doubleTapZoomDuration.toLong()) .withOrigin(ORIGIN_DOUBLE_TAP_ZOOM) .start() } invalidate() } /** * Draw method should not be called until the view has dimensions so the first calls are used as triggers to calculate * the scaling and tiling required. Once the view is setup, tiles are displayed as they are loaded. */ override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // If image or view dimensions are not known yet, abort. if (sWidth == 0 || sHeight == 0 || width == 0 || height == 0) { return } // If image has been loaded or supplied as a bitmap, onDraw may be the first time the view has // dimensions and therefore the first opportunity to set scale and translate. If this call returns // false there is nothing to be drawn so return immediately. if (!checkReady()) { return } // Set scale and translate before draw. preDraw() // If animating scale, calculate current scale and center with easing equations if (anim != null && anim!!.vFocusStart != null) { // Store current values so we can send an event if they change val scaleBefore = scale if (vTranslateBefore == null) { vTranslateBefore = PointF(0F, 0F) } vTranslateBefore!!.set(vTranslate!!) var scaleElapsed = System.currentTimeMillis() - anim!!.time val finished = scaleElapsed > anim!!.duration scaleElapsed = scaleElapsed.coerceAtMost(anim!!.duration) scale = ease( anim!!.easing, scaleElapsed, anim!!.scaleStart, anim!!.scaleEnd - anim!!.scaleStart, anim!!.duration, ) // Apply required animation to the focal point val vFocusNowX = ease( anim!!.easing, scaleElapsed, anim!!.vFocusStart!!.x, anim!!.vFocusEnd.x - anim!!.vFocusStart!!.x, anim!!.duration, ) val vFocusNowY = ease( anim!!.easing, scaleElapsed, anim!!.vFocusStart!!.y, anim!!.vFocusEnd.y - anim!!.vFocusStart!!.y, anim!!.duration, ) // Find out where the focal point is at this scale and adjust its position to follow the animation path vTranslate!!.x -= sourceToViewX(anim!!.sCenterEnd.x) - vFocusNowX vTranslate!!.y -= sourceToViewY(anim!!.sCenterEnd.y) - vFocusNowY // For translate anims, showing the image non-centered is never allowed, for scaling anims it is during the animation. fitToBounds(finished || anim!!.scaleStart == anim!!.scaleEnd) sendStateChanged(scaleBefore, vTranslateBefore!!, anim!!.origin) if (finished) { anim = null } invalidate() } if (bitmap != null && !bitmap!!.isRecycled) { val xScale = scale val yScale = scale mtrx.reset() mtrx.postTranslate((-srcRect.left).toFloat(), (-srcRect.top).toFloat()) mtrx.postScale(xScale, yScale) mtrx.postTranslate(vTranslate!!.x, vTranslate!!.y) canvas.drawBitmap(bitmap!!, mtrx, bitmapPaint) } } /** * Checks whether the base layer of tiles or full size bitmap is ready. */ private val isBaseLayerReady: Boolean get() = bitmap != null /** * Check whether view and image dimensions are known and either a preview, full size image or * base layer tiles are loaded. First time, send ready event to listener. The next draw will * display an image. */ private fun checkReady(): Boolean { val ready = width > 0 && height > 0 && sWidth > 0 && sHeight > 0 && (bitmap != null || isBaseLayerReady) if (!isReady && ready) { preDraw() isReady = true onImageEventListener?.onReady() } return ready } /** * Check whether either the full size bitmap or base layer tiles are loaded. First time, send image * loaded event to listener. */ private fun checkImageLoaded(): Boolean { val imageLoaded = isBaseLayerReady if (!isImageLoaded && imageLoaded) { preDraw() isImageLoaded = true } return imageLoaded } /** * Sets scale and translate ready for the next draw. */ private fun preDraw() { if (width == 0 || height == 0 || sWidth <= 0 || sHeight <= 0) { return } // If waiting to translate to new center position, set translate now if (sPendingCenter != null && pendingScale >= 0) { scale = pendingScale if (vTranslate == null) { vTranslate = PointF() } vTranslate!!.x = width / 2 - scale * sPendingCenter!!.x vTranslate!!.y = height / 2 - scale * sPendingCenter!!.y sPendingCenter = null pendingScale = -1F fitToBounds(true) } // On first display of base image set up position, and in other cases make sure scale is correct. fitToBounds(false) } /** * Adjusts hypothetical future scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale * is set so one dimension fills the view and the image is centered on the other dimension. Used to calculate what the target of an * animation should be. * * @param _center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. * @param sat The scale we want and the translation we're aiming for. The values are adjusted to be valid. */ private fun fitToBounds(_center: Boolean, sat: ScaleAndTranslate) { var center = _center if (panLimit == PAN_LIMIT_OUTSIDE && isReady) { center = false } val vTranslate = sat.vTranslate val scale = limitedScale(sat.scale) val scaleWidth = scale * sWidth val scaleHeight = scale * sHeight if (panLimit == PAN_LIMIT_CENTER && isReady) { vTranslate.x = vTranslate.x.coerceAtLeast(width / 2 - scaleWidth) vTranslate.y = vTranslate.y.coerceAtLeast(height / 2 - scaleHeight) } else if (center) { vTranslate.x = vTranslate.x.coerceAtLeast(width - scaleWidth) vTranslate.y = vTranslate.y.coerceAtLeast(height - scaleHeight) } else { vTranslate.x = vTranslate.x.coerceAtLeast(-scaleWidth) vTranslate.y = vTranslate.y.coerceAtLeast(-scaleHeight) } // Asymmetric padding adjustments val xPaddingRatio = if (paddingLeft > 0 || paddingRight > 0) paddingLeft / (paddingLeft + paddingRight).toFloat() else 0.5F val yPaddingRatio = if (paddingTop > 0 || paddingBottom > 0) paddingTop / (paddingTop + paddingBottom).toFloat() else 0.5F val maxTx: Float val maxTy: Float if (panLimit == PAN_LIMIT_CENTER && isReady) { maxTx = (width / 2F).coerceAtLeast(0F) maxTy = (height / 2F).coerceAtLeast(0F) } else if (center) { maxTx = ((width - scaleWidth) * xPaddingRatio).coerceAtLeast(0F) maxTy = ((height - scaleHeight) * yPaddingRatio).coerceAtLeast(0F) } else { maxTx = width.toFloat().coerceAtLeast(0F) maxTy = height.toFloat().coerceAtLeast(0F) } vTranslate.x = vTranslate.x.coerceAtMost(maxTx) vTranslate.y = vTranslate.y.coerceAtMost(maxTy) sat.scale = scale } /** * Adjusts current scale and translate values to keep scale within the allowed range and the image on screen. Minimum scale * is set so one dimension fills the view and the image is centered on the other dimension. * * @param center Whether the image should be centered in the dimension it's too small to fill. While animating this can be false to avoid changes in direction as bounds are reached. */ private fun fitToBounds(center: Boolean) { var init = false if (vTranslate == null) { init = true vTranslate = PointF(0F, 0F) } if (satTemp == null) { satTemp = ScaleAndTranslate(0F, PointF(0F, 0F)) } satTemp!!.scale = scale satTemp!!.vTranslate.set(vTranslate!!) fitToBounds(center, satTemp!!) scale = satTemp!!.scale vTranslate!!.set(satTemp!!.vTranslate) if (init) { vTranslate!!.set(vTranslateForSCenter((sWidth / 2).toFloat(), (sHeight / 2).toFloat(), scale)) } } /** * Called by worker task when full size image bitmap is ready (tiling is disabled). */ @Synchronized private fun onImageLoaded(bitmap: Bitmap) { // If actual dimensions don't match the declared size, reset everything. if (sWidth > 0 && sHeight > 0 && (sWidth != srcRect.width() || sHeight != srcRect.height())) { reset(false) } if (!this.bitmapIsCached) { this.bitmap?.recycle() } this.bitmapIsCached = true this.bitmap = bitmap sWidth = srcRect.width() sHeight = srcRect.height() val ready = checkReady() val imageLoaded = checkImageLoaded() if (ready || imageLoaded) { invalidate() requestLayout() } } /** * Set border crop of non-filled (white or black) content. * * @param cropBorders Whether to crop image borders. */ fun setCropBorders(cropBorders: Boolean) { this.cropBorders = cropBorders } /** * Pythagoras distance between two points. */ private fun distance(x0: Float, x1: Float, y0: Float, y1: Float): Float { val x = x0 - x1 val y = y0 - y1 return sqrt((x * x + y * y).toDouble()).toFloat() } /** * Releases all resources the view is using and resets the state, nulling any fields that use significant memory. * After you have called this method, the view can be re-used by setting a new image. Settings are remembered * but state (scale and center) is forgotten. You can restore these yourself if required. */ fun recycle() { reset(true) } /** * Convert screen to source x coordinate. */ private fun viewToSourceX(vx: Float): Float { return if (vTranslate == null) Float.NaN else (vx - vTranslate!!.x) / scale } /** * Convert screen to source y coordinate. */ private fun viewToSourceY(vy: Float): Float { return if (vTranslate == null) Float.NaN else (vy - vTranslate!!.y) / scale } /** * Convert screen coordinate to source coordinate. * * @param vxy view X/Y coordinate. * @return a coordinate representing the corresponding source coordinate. */ fun viewToSourceCoord(vxy: PointF): PointF? { return viewToSourceCoord(vxy.x, vxy.y, PointF()) } /** * Convert screen coordinate to source coordinate. * * @param vx view X coordinate. * @param vy view Y coordinate. * @param sTarget target object for result. The same instance is also returned. * @return a coordinate representing the corresponding source coordinate. This is the same instance passed to the sTarget param. */ fun viewToSourceCoord(vx: Float, vy: Float, sTarget: PointF = PointF()): PointF? { if (vTranslate == null) { return null } sTarget[viewToSourceX(vx)] = viewToSourceY(vy) return sTarget } /** * Convert source to view x coordinate. */ private fun sourceToViewX(sx: Float): Float { return if (vTranslate == null) Float.NaN else sx * scale + vTranslate!!.x } /** * Convert source to view y coordinate. */ private fun sourceToViewY(sy: Float): Float { return if (vTranslate == null) Float.NaN else sy * scale + vTranslate!!.y } /** * Convert source coordinate to view coordinate. * * @param sxy source coordinates to convert. * @return view coordinates. */ fun sourceToViewCoord(sxy: PointF?): PointF? { return sourceToViewCoord(sxy!!.x, sxy.y, PointF()) } /** * Convert source coordinate to view coordinate. * * @param sx source X coordinate. * @param sy source Y coordinate. * @param vTarget target object for result. The same instance is also returned. * @return view coordinates. This is the same instance passed to the vTarget param. */ fun sourceToViewCoord(sx: Float, sy: Float, vTarget: PointF = PointF()): PointF? { if (vTranslate == null) { return null } vTarget[sourceToViewX(sx)] = sourceToViewY(sy) return vTarget } /** * Get the translation required to place a given source coordinate at the center of the screen, with the center * adjusted for asymmetric padding. Accepts the desired scale as an argument, so this is independent of current * translate and scale. The result is fitted to bounds, putting the image point as near to the screen center as permitted. */ private fun vTranslateForSCenter(sCenterX: Float, sCenterY: Float, scale: Float): PointF { val vxCenter = paddingLeft + (width - paddingRight - paddingLeft) / 2 val vyCenter = paddingTop + (height - paddingBottom - paddingTop) / 2 if (satTemp == null) { satTemp = ScaleAndTranslate(0F, PointF(0F, 0F)) } satTemp!!.scale = scale satTemp!!.vTranslate[vxCenter - sCenterX * scale] = vyCenter - sCenterY * scale fitToBounds(true, satTemp!!) return satTemp!!.vTranslate } /** * Given a requested source center and scale, calculate what the actual center will have to be to keep the image in * pan limits, keeping the requested center as near to the middle of the screen as allowed. */ private fun limitedSCenter(sCenterX: Float, sCenterY: Float, scale: Float, sTarget: PointF): PointF { val vTranslate = vTranslateForSCenter(sCenterX, sCenterY, scale) val vxCenter = paddingLeft + (width - paddingRight - paddingLeft) / 2 val vyCenter = paddingTop + (height - paddingBottom - paddingTop) / 2 val sx = (vxCenter - vTranslate.x) / scale val sy = (vyCenter - vTranslate.y) / scale sTarget[sx] = sy return sTarget } /** * Returns the minimum allowed scale. */ private fun minScale(): Float { val vPadding = paddingBottom + paddingTop val hPadding = paddingLeft + paddingRight return when (minimumScaleType) { SCALE_TYPE_CENTER_INSIDE -> min( (width - hPadding) / sWidth.toFloat(), (height - vPadding) / sHeight.toFloat(), ) SCALE_TYPE_CENTER_CROP -> max( (width - hPadding) / sWidth.toFloat(), (height - vPadding) / sHeight.toFloat(), ) SCALE_TYPE_FIT_WIDTH -> (width - hPadding) / sWidth.toFloat() SCALE_TYPE_FIT_HEIGHT -> (height - vPadding) / sHeight.toFloat() SCALE_TYPE_ORIGINAL_SIZE -> 1F SCALE_TYPE_SMART_FIT -> if (sHeight > sWidth) { // Fit to width (width - hPadding) / sWidth.toFloat() } else { // Fit to height (height - vPadding) / sHeight.toFloat() } SCALE_TYPE_CUSTOM -> minScale else -> min((width - hPadding) / sWidth.toFloat(), (height - vPadding) / sHeight.toFloat()) } } /** * Adjust a requested scale to be within the allowed limits. */ private fun limitedScale(targetScale: Float): Float { return targetScale.coerceIn(minScale(), maxScale) } /** * Apply a selected type of easing. * * @param type Easing type, from static fields * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private fun ease(type: Int, time: Long, from: Float, change: Float, duration: Long): Float { return when (type) { EASE_IN_OUT_QUAD -> easeInOutQuad(time, from, change, duration) EASE_OUT_QUAD -> easeOutQuad(time, from, change, duration) else -> throw IllegalStateException("Unexpected easing type: $type") } } /** * Quadratic easing for fling. With thanks to Robert Penner - http://gizma.com/easing/ * * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private fun easeOutQuad(time: Long, from: Float, change: Float, duration: Long): Float { val progress = time.toFloat() / duration.toFloat() return -change * progress * (progress - 2) + from } /** * Quadratic easing for scale and center animations. With thanks to Robert Penner - http://gizma.com/easing/ * * @param time Elapsed time * @param from Start value * @param change Target value * @param duration Anm duration * @return Current value */ private fun easeInOutQuad(time: Long, from: Float, change: Float, duration: Long): Float { var timeF = time / (duration / 2F) return if (timeF < 1) { change / 2f * timeF * timeF + from } else { timeF-- -change / 2f * (timeF * (timeF - 2) - 1) + from } } /** * Calculate how much further the image can be panned in each direction. The results are set on * the supplied [RectF] and expressed as screen pixels. For example, if the image cannot be * panned any further towards the left, the value of [RectF.left] will be set to 0. * * @param vTarget target object for results. Re-use for efficiency. */ fun getPanRemaining(vTarget: RectF) { if (!isReady) { return } val scaleWidth = scale * sWidth val scaleHeight = scale * sHeight when (panLimit) { PAN_LIMIT_CENTER -> { vTarget.top = (-(vTranslate!!.y - height / 2)).coerceAtLeast(0F) vTarget.left = (-(vTranslate!!.x - width / 2)).coerceAtLeast(0F) vTarget.bottom = (vTranslate!!.y - (height / 2 - scaleHeight)).coerceAtLeast(0F) vTarget.right = (vTranslate!!.x - (width / 2 - scaleWidth)).coerceAtLeast(0F) } PAN_LIMIT_OUTSIDE -> { vTarget.top = (-(vTranslate!!.y - height)).coerceAtLeast(0F) vTarget.left = (-(vTranslate!!.x - width)).coerceAtLeast(0F) vTarget.bottom = (vTranslate!!.y + scaleHeight).coerceAtLeast(0F) vTarget.right = (vTranslate!!.x + scaleWidth).coerceAtLeast(0F) } else -> { vTarget.top = (-vTranslate!!.y).coerceAtLeast(0F) vTarget.left = (-vTranslate!!.x).coerceAtLeast(0F) vTarget.bottom = (scaleHeight + vTranslate!!.y - height).coerceAtLeast(0F) vTarget.right = (scaleWidth + vTranslate!!.x - width).coerceAtLeast(0F) } } } /** * Set the pan limiting style. See static fields. Normally [.PAN_LIMIT_INSIDE] is best, for image galleries. * * @param panLimit a pan limit constant. See static fields. */ fun setPanLimit(@PanLimit panLimit: Int) { this.panLimit = panLimit if (isReady) { fitToBounds(true) invalidate() } } /** * Set the minimum scale type. See static fields. Normally [.SCALE_TYPE_CENTER_INSIDE] is best, for image galleries. * * @param scaleType a scale type constant. See static fields. */ fun setMinimumScaleType(@ScaleType scaleType: Int) { minimumScaleType = scaleType if (isReady) { fitToBounds(true) invalidate() } } /** * This is a screen density aware alternative to [.setMaxScale]; it allows you to express the maximum * allowed scale in terms of the minimum pixel density. This avoids the problem of 1:1 scale still being * too small on a high density screen. A sensible starting point is 160 - the default used by this view. * * @param dpi Source image pixel density at maximum zoom. */ fun setMinimumDpi(dpi: Int) { val metrics = resources.displayMetrics val averageDpi = (metrics.xdpi + metrics.ydpi) / 2 maxScale = averageDpi / dpi } /** * This is a screen density aware alternative to [.setMinScale]; it allows you to express the minimum * allowed scale in terms of the maximum pixel density. * * @param dpi Source image pixel density at minimum zoom. */ fun setMaximumDpi(dpi: Int) { val metrics = resources.displayMetrics val averageDpi = (metrics.xdpi + metrics.ydpi) / 2 setMinScale(averageDpi / dpi) } /** * Returns the minimum allowed scale. * * @return the minimum scale as a source/view pixels ratio. */ fun getMinScale(): Float { return minScale() } /** * Set the minimum scale allowed. A value of 1 means 1:1 pixels at minimum scale. You may wish to set this according * to screen density. Consider using [.setMaximumDpi], which is density aware. * * @param minScale minimum scale expressed as a source/view pixels ratio. */ fun setMinScale(minScale: Float) { this.minScale = minScale } /** * Returns the source point at the center of the view. * * @return the source coordinates current at the center of the view. */ val center: PointF? get() { val mX = width / 2F val mY = height / 2F return viewToSourceCoord(mX, mY) } /** * Externally change the scale and translation of the source image. This may be used with getCenter() and getScale() * to restore the scale and zoom after a screen rotate. * * @param scale New scale to set. * @param sCenter New source image coordinate to center on the screen, subject to boundaries. */ fun setScaleAndCenter(scale: Float, sCenter: PointF?) { anim = null pendingScale = scale sPendingCenter = sCenter sRequestedCenter = sCenter invalidate() } /** * Set the scale the image will zoom in to when double tapped. This also the scale point where a double tap is interpreted * as a zoom out gesture - if the scale is greater than 90% of this value, a double tap zooms out. Avoid using values * greater than the max zoom. * * @param doubleTapZoomScale New value for double tap gesture zoom scale. */ fun setDoubleTapZoomScale(doubleTapZoomScale: Float) { this.doubleTapZoomScale = doubleTapZoomScale } /** * A density aware alternative to [.setDoubleTapZoomScale]; this allows you to express the scale the * image will zoom in to when double tapped in terms of the image pixel density. Values lower than the max scale will * be ignored. A sensible starting point is 160 - the default used by this view. * * @param dpi New value for double tap gesture zoom scale. */ fun setDoubleTapZoomDpi(dpi: Int) { val metrics = resources.displayMetrics val averageDpi = (metrics.xdpi + metrics.ydpi) / 2 setDoubleTapZoomScale(averageDpi / dpi) } /** * Set the type of zoom animation to be used for double taps. See static fields. * * @param doubleTapZoomStyle New value for zoom style. */ fun setDoubleTapZoomStyle(@ZoomStyle doubleTapZoomStyle: Int) { this.doubleTapZoomStyle = doubleTapZoomStyle } /** * Set the duration of the double tap zoom animation. * * @param durationMs Duration in milliseconds. */ fun setDoubleTapZoomDuration(durationMs: Int) { doubleTapZoomDuration = durationMs.coerceAtLeast(0) } /** * {@inheritDoc} */ override fun setOnLongClickListener(onLongClickListener: OnLongClickListener?) { this.onLongClickListener = onLongClickListener } /** * Add a listener allowing notification of load and error events. Extend [DefaultOnImageEventListener] * to simplify implementation. * * @param onImageEventListener an [OnImageEventListener] instance. */ fun setOnImageEventListener(onImageEventListener: OnImageEventListener?) { this.onImageEventListener = onImageEventListener } /** * Add a listener for pan and zoom events. * * @param onStateChangedListener an [OnStateChangedListener] instance. */ fun setOnStateChangedListener(onStateChangedListener: OnStateChangedListener?) { this.onStateChangedListener = onStateChangedListener } private fun sendStateChanged(oldScale: Float, oldVTranslate: PointF, origin: Int) { if (scale != oldScale) { onStateChangedListener?.onScaleChanged(scale, origin) } if (vTranslate != oldVTranslate) { onStateChangedListener?.onCenterChanged(center, origin) } } /** * Creates a panning animation builder, that when started will animate the image to place the given coordinates of * the image in the center of the screen. If doing this would move the image beyond the edges of the screen, the * image is instead animated to move the center point as near to the center of the screen as is allowed - it's * guaranteed to be on screen. * * @param sCenter Target center point * @return [AnimationBuilder] instance. Call [SubsamplingScaleImageView.AnimationBuilder.start] to start the anim. */ fun animateCenter(sCenter: PointF): AnimationBuilder? { return if (isReady) AnimationBuilder(sCenter) else null } /** * Creates a scale animation builder, that when started will animate a zoom in or out. If this would move the image * beyond the panning limits, the image is automatically panned during the animation. * * @param scale Target scale. * @param sCenter Target source center. * @return [AnimationBuilder] instance. Call [SubsamplingScaleImageView.AnimationBuilder.start] to start the anim. */ fun animateScaleAndCenter(scale: Float, sCenter: PointF?): AnimationBuilder? { return if (isReady) AnimationBuilder(scale, sCenter) else null } /** * An event listener, allowing subclasses and activities to be notified of significant events. */ interface OnImageEventListener { /** * Called when the dimensions of the image and view are known, and either a preview image, * the full size image, or base layer tiles are loaded. This indicates the scale and translate * are known and the next draw will display an image. This event can be used to hide a loading * graphic, or inform a subclass that it is safe to draw overlays. */ fun onReady() /** * Indicates an error initiliasing the decoder when using a tiling, or when loading the full * size bitmap when tiling is disabled. This method cannot be relied upon; certain encoding * types of supported image formats can result in corrupt or blank images being loaded and * displayed with no detectable error. * * @param e The exception thrown. This error is also logged by the view. */ fun onImageLoadError(e: Exception) } /** * An event listener, allowing activities to be notified of pan and zoom events. Initialisation * and calls made by your code do not trigger events; touch events and animations do. Methods in * this listener will be called on the UI thread and may be called very frequently - your * implementation should return quickly. */ interface OnStateChangedListener { /** * The scale has changed. Use with [.getMaxScale] and [.getMinScale] to determine * whether the image is fully zoomed in or out. * * @param newScale The new scale. * @param origin Where the event originated from - one of [.ORIGIN_ANIM], [.ORIGIN_TOUCH]. */ fun onScaleChanged(newScale: Float, origin: Int) /** * The source center has been changed. This can be a result of panning or zooming. * * @param newCenter The new source center point. * @param origin Where the event originated from - one of [.ORIGIN_ANIM], [.ORIGIN_TOUCH]. */ fun onCenterChanged(newCenter: PointF?, origin: Int) } /** * @param scaleStart Scale at start of anim * @param scaleEnd Scale at end of anim (target) * @param sCenterStart Source center point at start * @param sCenterEnd Source center point at end, adjusted for pan limits * @param sCenterEndRequested Source center point that was requested, without adjustments * @param vFocusStart View point that was double tapped * @param vFocusEnd Where the view focal point should be moved to during the anim * @param duration How long the anim takes * @param interruptible Whether the anim can be interrupted by a touch * @param easing Easing style * @param origin Animation origin (API, double tap or fling) * @param time Start time */ private data class Anim( val scaleStart: Float, val scaleEnd: Float, val sCenterStart: PointF?, val sCenterEnd: PointF, val sCenterEndRequested: PointF, val vFocusStart: PointF?, val vFocusEnd: PointF, val duration: Long, val interruptible: Boolean, val easing: Int, val origin: Int, val time: Long = System.currentTimeMillis(), ) private data class ScaleAndTranslate(var scale: Float, val vTranslate: PointF) /** * Default implementation of [OnImageEventListener] for extension. This does nothing in any method. */ open class DefaultOnImageEventListener : OnImageEventListener { override fun onReady() {} override fun onImageLoadError(e: Exception) {} } /** * Builder class used to set additional options for a scale animation. Create an instance using [.animateScale], * then set your options and call [.start]. */ inner class AnimationBuilder { private val targetScale: Float private val targetSCenter: PointF? private val vFocus: PointF? private var duration: Long = 500 private var easing = EASE_IN_OUT_QUAD private var origin = ORIGIN_ANIM private var interruptible = true private var panLimited = true constructor(sCenter: PointF) { targetScale = scale targetSCenter = sCenter vFocus = null } constructor(scale: Float, sCenter: PointF?) { targetScale = scale targetSCenter = sCenter vFocus = null } constructor(scale: Float, sCenter: PointF?, vFocus: PointF?) { targetScale = scale targetSCenter = sCenter this.vFocus = vFocus } /** * Desired duration of the anim in milliseconds. Default is 500. * * @param duration duration in milliseconds. * @return this builder for method chaining. */ fun withDuration(duration: Long): AnimationBuilder { this.duration = duration return this } /** * Whether the animation can be interrupted with a touch. Default is true. * * @param interruptible interruptible flag. * @return this builder for method chaining. */ fun withInterruptible(interruptible: Boolean): AnimationBuilder { this.interruptible = interruptible return this } /** * Set the easing style. See static fields. [.EASE_IN_OUT_QUAD] is recommended, and the default. * * @param easing easing style. * @return this builder for method chaining. */ fun withEasing(@EasingStyle easing: Int): AnimationBuilder { this.easing = easing return this } /** * Only for internal use. When set to true, the animation proceeds towards the actual end point - the nearest * point to the center allowed by pan limits. When false, animation is in the direction of the requested end * point and is stopped when the limit for each axis is reached. The latter behaviour is used for flings but * nothing else. */ fun withPanLimited(panLimited: Boolean): AnimationBuilder { this.panLimited = panLimited return this } /** * Only for internal use. Indicates what caused the animation. */ fun withOrigin(origin: Int): AnimationBuilder { this.origin = origin return this } /** * Starts the animation. */ fun start() { val vxCenter = paddingLeft + (width - paddingRight - paddingLeft) / 2 val vyCenter = paddingTop + (height - paddingBottom - paddingTop) / 2 val targetScale = limitedScale(targetScale) val targetSCenter = if (panLimited) { limitedSCenter( targetSCenter!!.x, targetSCenter.y, targetScale, PointF(), ) } else { targetSCenter!! } anim = Anim( scaleStart = scale, scaleEnd = targetScale, sCenterEndRequested = targetSCenter, sCenterStart = center, sCenterEnd = targetSCenter, vFocusStart = sourceToViewCoord(targetSCenter), vFocusEnd = PointF( vxCenter.toFloat(), vyCenter.toFloat(), ), duration = duration, interruptible = interruptible, easing = easing, origin = origin, ) if (vFocus != null) { // Calculate where translation will be at the end of the anim val vTranslateXEnd = vFocus.x - targetScale * anim!!.sCenterStart!!.x val vTranslateYEnd = vFocus.y - targetScale * anim!!.sCenterStart!!.y val satEnd = ScaleAndTranslate(targetScale, PointF(vTranslateXEnd, vTranslateYEnd)) // Fit the end translation into bounds fitToBounds(true, satEnd) // Adjust the position of the focus point at end so image will be in bounds anim!!.vFocusEnd.set( vFocus.x + (satEnd.vTranslate.x - vTranslateXEnd), vFocus.y + (satEnd.vTranslate.y - vTranslateYEnd), ) } invalidate() } } companion object { @Retention(AnnotationRetention.SOURCE) @IntDef( ZOOM_FOCUS_FIXED, ZOOM_FOCUS_CENTER, ZOOM_FOCUS_CENTER_IMMEDIATE, ) annotation class ZoomStyle /** * During zoom animation, keep the point of the image that was tapped in the same place, and scale the image around it. */ const val ZOOM_FOCUS_FIXED = 1 /** * During zoom animation, move the point of the image that was tapped to the center of the screen. */ const val ZOOM_FOCUS_CENTER = 2 /** * Zoom in to and center the tapped point immediately without animating. */ const val ZOOM_FOCUS_CENTER_IMMEDIATE = 3 @Retention(AnnotationRetention.SOURCE) @IntDef( EASE_IN_OUT_QUAD, EASE_OUT_QUAD, ) annotation class EasingStyle /** * Quadratic ease out. Not recommended for scale animation, but good for panning. */ const val EASE_OUT_QUAD = 1 /** * Quadratic ease in and out. */ const val EASE_IN_OUT_QUAD = 2 @Retention(AnnotationRetention.SOURCE) @IntDef( PAN_LIMIT_INSIDE, PAN_LIMIT_OUTSIDE, PAN_LIMIT_CENTER, ) annotation class PanLimit /** * Don't allow the image to be panned off screen. As much of the image as possible is always displayed, centered in the view when it is smaller. This is the best option for galleries. */ const val PAN_LIMIT_INSIDE = 1 /** * Allows the image to be panned until it is just off screen, but no further. The edge of the image will stop when it is flush with the screen edge. */ const val PAN_LIMIT_OUTSIDE = 2 /** * Allows the image to be panned until a corner reaches the center of the screen but no further. Useful when you want to pan any spot on the image to the exact center of the screen. */ const val PAN_LIMIT_CENTER = 3 @Retention(AnnotationRetention.SOURCE) @IntDef( SCALE_TYPE_CENTER_INSIDE, SCALE_TYPE_CENTER_CROP, SCALE_TYPE_FIT_WIDTH, SCALE_TYPE_FIT_HEIGHT, SCALE_TYPE_ORIGINAL_SIZE, SCALE_TYPE_SMART_FIT, SCALE_TYPE_CUSTOM, ) annotation class ScaleType /** * Scale the image so that both dimensions of the image will be equal to or less than the corresponding dimension of the view. The image is then centered in the view. This is the default behaviour and best for galleries. */ const val SCALE_TYPE_CENTER_INSIDE = 1 /** * Scale the image uniformly so that both dimensions of the image will be equal to or larger than the corresponding dimension of the view. The image is then centered in the view. */ const val SCALE_TYPE_CENTER_CROP = 2 const val SCALE_TYPE_FIT_WIDTH = 3 const val SCALE_TYPE_FIT_HEIGHT = 4 const val SCALE_TYPE_ORIGINAL_SIZE = 5 const val SCALE_TYPE_SMART_FIT = 6 /** * Scale the image so that both dimensions of the image will be equal to or less than the maxScale and equal to or larger than minScale. The image is then centered in the view. */ const val SCALE_TYPE_CUSTOM = 7 /** * State change originated from animation. */ const val ORIGIN_ANIM = 1 /** * State change originated from touch gesture. */ const val ORIGIN_TOUCH = 2 /** * State change originated from a fling momentum anim. */ const val ORIGIN_FLING = 3 /** * State change originated from a double tap zoom anim. */ const val ORIGIN_DOUBLE_TAP_ZOOM = 4 private val TAG = SubsamplingScaleImageView::class.java.simpleName } }
% Versuch 6 clc;clear; %% Gitter erstellen (nicht mesh nennen, da dies ein Matlab-Befehl ist) #xmesh = 0:1/10:1; #ymesh = 0:1/10:1; #zmesh = 0:1; xmesh = 0:1/40:1; ymesh = 0:1/40:1; zmesh = 0:1; #xmesh = 0:1/90:1; #ymesh = 0:1/90:1; #zmesh = 0:1; msh = cartMesh(xmesh, ymesh, zmesh); % Gitterweiten in x-,y- und z-Richtung (äquidistant vorausgesetzt) delta_x = xmesh(2)-xmesh(1); delta_y = ymesh(2)-ymesh(1); delta_z = zmesh(2)-zmesh(1); nx = msh.nx; ny = msh.ny; nz = msh.nz; Mx = msh.Mx; My = msh.My; Mz = msh.Mz; np = msh.np; %% Erzeugung der topologischen und geometrischen Matrizen [c, s, st] = createTopMats(msh); [ds, dst, da, dat] = createGeoMats(msh); % Erzeugung der Materialmatrizen: Mmui, Mmu, Meps, Mepsi % Achtung bei createMmui und createMeps Randbedingungen übergeben, da % explizites Verfahren und damit Randbedingungen am besten in den % Materialmatrizen gesetzt werden eps0 = 8.854e-12; eps_r = 1; epsilon = eps_r*eps0; mu0 = 4e-7*pi; mu_r = 1; mu = mu0*mu_r; mui = 1/mu; bcs = [ 0, 0, 0, 0, 1, 1 ]; Mmui = createMmui(msh, ds, dst, da, mui, bcs); Mmu = nullInv(Mmui); Meps = createMeps(msh, ds, da, dat, epsilon, bcs); Mepsi = nullInv(Meps); %% CFL-Bedingungdelta_s % Minimale Gitterweite bestimmen delta_s = delta_x; % Berechnung und Ausgabe des minimalen Zeitschritts mittels CFL-Bedingung #deltaTmaxCFL = sqrt(mu*epsilon)*delta_s*(1/3)^0.5; deltaTmaxCFL = sqrt( epsilon*mu ) * sqrt( 1/( 1/delta_x^2 + 1/delta_y^2 + 1/delta_z^2 ) ); fprintf('Nach CFL-Bedingung: deltaTmax = %e\n',deltaTmaxCFL); %% Stabilitätsuntersuchung mithilfe der Systemmatrix % Methode 1 if msh.np<4000 A12 = -Mmui*c; A21 = Mepsi*c'; zero = sparse(3*np, 3*np); A = [zero, A12; A21, zero]; [~, lambdaMaxA] = eigs(A,1); % Gibt EW zurück der den größten Betrag hat % Workaround, da Octave bei [V,D] = eigs(A,1) eine Matrix zurückgibt if ~isscalar(lambdaMaxA) lambdaMaxA = lambdaMaxA(1,1); end % delta T bestimmen deltaTmaxEigA = 2/norm(lambdaMaxA); fprintf('Nach Eigenwert-Berechnung von A: deltaTmax = %e\n', deltaTmaxEigA); end %% Experimentelle Bestimmung mithilfe der Energie des Systems % Parameter der Zeitsimulation sigma = 6e-10; dt = 1.*deltaTmaxCFL; tend = 10*sigma; steps = length( [0:dt:tend] ) - 1; sourcetype= 1; % 1: Gauss Anregung, 2: Harmonisch, 3: Konstante Anregung % Anregung jsbow als anonyme Funktion, die einen 3*np Vektor zurückgibt % Anregung wird später in Schleife für t>2*sigma_gauss abgeschnitten, also null gesetzt jsbow_space = zeros(3*np, 1); % jsbow_space(...) = ... for i=1:msh.nx for j=1:msh.ny for k=1:msh.nz n = 1 + ( i-1 )*Mx + ( j-1 )*My + ( k-1 )*Mz; #% kanonischer Index if ( n==ceil( (msh.nx*msh.ny)/2 ) + Mz*(k-1) ) && k<msh.nz #% wenn betrachteter Punkt Mittelpunkt ist => weise Strom zu! jsbow_space(n+2*np) = 1; end end end end % Gauss Anregung jsbow_gauss = @(t)(jsbow_space * exp(-4*((t-sigma)/sigma)^2)); % Harmonische Anregung (optional) % jsbow_harm = @(t)(jsbow_space * ...); % Konstante Anregung (optional, für t>0) % jsbow_const = @(t)(jsbow_space * ...); % Initialisierungen ebow_new = sparse(3*np,1); hbow_new = sparse(3*np,1); energy = zeros(1,steps); leistungQuelle = zeros(1,steps); % Plot parameter für "movie" figure(1) zlimit = 30/(delta_x(1)); draw_only_every = 4; % Zeitintegration for ii = 1:steps % Zeitpunkt berechnen t = ii*dt; if ii > 1 ebow_old_old = ebow_old; else ebow_old_old = sparse(3*np,1); end % alte Werte speichern ebow_old = ebow_new; hbow_old = hbow_new; if sourcetype == 1 % Stromanregung js aus jsbow(t) für diesen Zeitschritt berechnen if t <= 20*sigma js = jsbow_gauss(t); else js = 0; end elseif sourcetype == 2 % Harmonische Anregung js = jsbow_harm(t); elseif sourcetype == 3 % konstante Anregung js = jsbow_const(t); end % Leapfrogschritt durchführen [hbow_new,ebow_new] = leapfrog(hbow_old, ebow_old, js, Mmui, Mepsi, c, dt); % Feld anzeigen if mod(ii, draw_only_every) z_plane = 1; idx2plot = (2*np+1+(z_plane-1)*Mz):(2*np+z_plane*Mz); ebow_mat = reshape(ebow_new(idx2plot),nx,ny); figure(1) mesh(ebow_mat) xlabel('i') ylabel('j') zlabel(['z-Komponente des E-Feldes fuer z=',num2str(z_plane)]) axis([1 nx 1 ny -zlimit zlimit]) caxis([-zlimit zlimit]) drawnow end ebow_m = 0.5*(ebow_old_old + ebow_old); hbow_m_half=0.5*(hbow_new+hbow_old); % Gesamtenergie und Quellenenergie für diesen Zeitschritt berechnen energy_t = (ebow_m'*Meps*ebow_old + hbow_old'*Mmu*hbow_m_half) % Gleichung (6.36) leistungQuelle_t = ebow_new'*js; % Energiewerte speichern energy(ii) = energy_t; leistungQuelle(ii) = leistungQuelle_t; end #print -depsc V6D5.eps % Anregungsstrom über der Zeit plotten figure(2) jsbow_plot = zeros(1,steps); for step = 1:steps if sourcetype == 1 jsbow_spatial = jsbow_gauss(step*dt); elseif sourcetype == 2 jsbow_spatial = jsbow_harm(step*dt); elseif sourcetype == 3 jsbow_spatial = jsbow_const(step*dt); end nonzero_idx = find(jsbow_spatial~=0); jsbow_plot(step) = jsbow_spatial(nonzero_idx); end plot(dt:dt:dt*steps, jsbow_plot); xlabel('t in s'); ylabel('Anregungsstrom J in A'); #print -depsc V6D6_1.eps % Energie über der Zeit plotten figure(3); clf; plot (dt:dt:dt*steps, energy) legend(['Zeitschritt: ', num2str(dt)]) xlabel('t in s') ylabel('Energie des EM-Feldes W in J') #print -depsc V6D6.eps % Zeitliche Änderung der Energie (Leistung) t=0:dt:tend; for i=2:length(t)-3 leistungSystem(i) = (energy(i+1)-energy(i-1))/(2*(t(i+1)-t(i-1))); end figure(4); clf; hold on plot(2*dt:dt:dt*(steps-1), leistungSystem) plot(dt:dt:dt*steps, leistungQuelle, 'r') hold off legend('Leistung System', 'Leistung Quelle') xlabel('t in s') ylabel('Leistung P in W') #print -depsc V6D7.eps