text
stringlengths
184
4.48M
--- title: Lidarr Windows Installation description: Windows-Installationsanleitung für Lidarr published: true date: 2023-07-03T20:30:47.519Z tags: editor: markdown dateCreated: 2023-07-03T20:11:02.991Z --- # Windows Lidarr wird nativ unter Windows unterstützt. Lidarr kann auf Windows als Windows-Dienst oder als Anwendung in der Systemleiste installiert werden. > Die Unterstützung für Windows-Versionen ist auf diejenigen beschränkt, die derzeit von Microsoft unterstützt werden. Andere Versionen können funktionieren, aber dies ist eine nicht unterstützte Konfiguration. {.is-warning} Ein Windows-Dienst läuft auch dann, wenn der Benutzer nicht angemeldet ist. Es müssen jedoch besondere Vorkehrungen getroffen werden, da Windows-Dienste [nicht auf Netzlaufwerke](https://learn.microsoft.com/en-us/windows/win32/services/services-and-redirected-drives) (X:\-Laufwerke oder \\\server\share UNC-Pfade) zugreifen können, ohne spezielle Konfigurationsschritte durchzuführen. Zusätzlich läuft der Windows-Dienst unter dem Konto "Lokaler Dienst". Standardmäßig **hat dieses Konto keine Berechtigungen, um auf das Benutzerverzeichnis zuzugreifen, es sei denn, die Berechtigungen wurden manuell zugewiesen**. Dies ist besonders relevant, wenn Download-Clients konfiguriert sind, um in Ihr Benutzerverzeichnis herunterzuladen. Daher empfiehlt es sich, Lidarr als Anwendung in der Systemleiste zu installieren, wenn der Benutzer angemeldet bleiben kann. Diese Option wird während der Installation angeboten. > Möglicherweise müssen Sie nach der Installation im Systemleistenmodus einmalig "Als Administrator" ausführen, wenn Sie einen Zugriffsfehler erhalten - wie z.B. "Der Zugriff auf den Pfad `C:\ProgramData\Lidarr\config.xml` wurde verweigert" - oder wenn Sie Netzlaufwerke verwenden. Dadurch erhält Lidarr die erforderlichen Berechtigungen. Sie sollten nicht jedes Mal als Administrator ausführen müssen. {.is-warning} 1. Laden Sie die neueste Version von Lidarr für Ihre Architektur über den unten stehenden Link herunter. 1. Führen Sie das Installationsprogramm aus. 1. Öffnen Sie <http://localhost:8686>, um Lidarr zu verwenden. - [Windows x64 Installer](https://lidarr.servarr.com/v1/update/master/updatefile?os=windows&runtime=netcore&arch=x64&installer=true) - [Windows x32 Installer](https://lidarr.servarr.com/v1/update/master/updatefile?os=windows&runtime=netcore&arch=x86&installer=true) {.links-list} > Es ist möglich, Lidarr manuell mit dem [x64 .zip-Download](https://lidarr.servarr.com/v1/update/master/updatefile?os=windows&runtime=netcore&arch=x64) zu installieren. In diesem Fall müssen Sie jedoch manuell Abhängigkeiten, Installation und Berechtigungen behandeln. {.is-info}
// // ColorSchemeExtension.swift // // Created by Antoine Bollengier on 04.02.23. // import SwiftUI extension ColorScheme { /// The color that must be used depending on the color style of the device. /// /// /// When you implement a `Text`, you must be sure that is will stay visible whether choice your user do. /// The `textColor` attribute provides the right color your `Text` has to be. /// /// struct MyView: View { /// @Environment(\.colorScheme) var colorScheme /// var body: some View { /// Text("Hello, World!") /// .foregroundColor(colorScheme.textColor) /// } /// } var textColor: Color { self == .dark ? .white : .black } /// The color that must be used depending on the color style of the device. /// /// /// When you implement a `View`, you must be sure that its background will stay in the background whether choice your user do. /// The `backgroundColor` attribute provides the right color your `View` has to be. /// /// struct MyView: View { /// @Environment(\.colorScheme) var colorScheme /// var body: some View { /// Rectangle() /// .foregroundColor(colorScheme.backgroundColor) /// } /// } var backgroundColor: Color { self == .dark ? .black : .white } #if !os(macOS) var blurStyle: UIBlurEffect.Style { self == .dark ? .systemUltraThinMaterial : .systemThickMaterial } #endif }
import React, { Component, Fragment, PureComponent } from 'react' const Context = React.createContext() const { Provider, Consumer } = Context export default class Demo extends Component { state = { name: 'vujson' } render() { return ( <Provider value={this.state.name} > <h2>A组件的名字是:{this.state.name}</h2> <button onClick={this.changeName}>changeName</button> <B /> </Provider> ) } changeName = () => { const data = Math.random() + '11' this.setState({ name: data }) } } class B extends PureComponent { render() { console.log('b---render') return ( <Fragment> <h2>b组件的名字是</h2> <C render={carName => <D carName={carName} />} /> </Fragment> ) } } class C extends PureComponent { static contextType = Context state = { carName: '迈巴克' } render() { const { carName } = this.state console.log('c---render') return ( <Fragment> <h2>C组件的名字是{this.context}</h2> {this.props.render(carName)} </Fragment> ) } } class D extends Component { render() { console.log('d---render', this.props) return ( < h2 > D组件的名字是:{this.props.carName} </h2 > ) } }
import { Link } from "react-router-dom"; const navigation = [ { name: 'Open Trades', href: '/' }, { name: 'Closed Trades', href: '/closed-trades' }, { name: 'Trade Stats', href: '/trade-stats' }, ] function MainNavigation() { return ( <header className="bg-gray-800"> <nav className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8" aria-label="Top"> <div className="w-full py-6 flex items-center justify-between border-b border-green-600 lg:border-none"> <div className="flex items-center"> <a href="#"> <span className="sr-only">Workflow</span> <img className="h-10 w-auto" src="https://tailwindui.com/img/logos/workflow-mark.svg?color=white" alt="" /> </a> <div className="hidden ml-10 space-x-8 lg:block"> {navigation.map((link) => ( <Link key={link.name} to={link.href} className="text-base font-medium text-white hover:text-green-50" > {link.name} </Link> ))} </div> </div> <div className="ml-10 space-x-4"> <a href="#" className="inline-block bg-green-600 py-2 px-4 border border-transparent rounded-md text-base font-medium text-white hover:bg-opacity-75" > Log Out </a> <a href="#" className="inline-block bg-white py-2 px-4 border border-transparent rounded-md text-base font-medium text-green-900 hover:bg-green-50" > Sign up </a> </div> </div> <div className="py-4 flex flex-wrap justify-center space-x-6 lg:hidden"> {navigation.map((link) => ( <a key={link.name} href={link.href} className="text-base font-medium text-white hover:text-indigo-50" > {link.name} </a> ))} </div> </nav> </header> ); } export default MainNavigation;
package metrics import ( "encoding/json" "strings" ) var metrics = `{"files":[{"code":1282,"comment":0,"blank":336,"name":"spm-go/output.html","language":"HTML"},{"code":458,"comment":0,"blank":9,"name":".arch-go/report.css","language":"CSS"},{"code":228,"comment":0,"blank":44,"name":".arch-go/report.html","language":"HTML"},{"code":98,"comment":1,"blank":19,"name":"pkg/architecture/main.go","language":"Go"},{"code":84,"comment":1,"blank":13,"name":"pkg/ginReturnSerializer/main.go","language":"Go"},{"code":83,"comment":1,"blank":8,"name":"pkg/forceNotNil/main.go","language":"Go"},{"code":69,"comment":15,"blank":21,"name":"pkg/traceavility/main.go","language":"Go"},{"code":54,"comment":41,"blank":9,"name":".golangci.yml","language":"YAML"},{"code":46,"comment":2,"blank":7,"name":"pkg/swaggo/main.go","language":"Go"},{"code":37,"comment":0,"blank":5,"name":".air.toml","language":"TOML"},{"code":37,"comment":5,"blank":6,"name":"pkg/modularization/main.go","language":"Go"},{"code":30,"comment":13,"blank":10,"name":"modules/comments/interfaces/gin.go","language":"Go"},{"code":30,"comment":0,"blank":10,"name":"pkg/modularization/README.md","language":"Markdown"},{"code":28,"comment":0,"blank":10,"name":"cmd/main.go","language":"Go"},{"code":27,"comment":0,"blank":6,"name":"pkg/swaggo/README.md","language":"Markdown"},{"code":24,"comment":12,"blank":8,"name":"modules/posts/interfaces/gin.go","language":"Go"},{"code":21,"comment":0,"blank":3,"name":"arch-go.yml","language":"YAML"},{"code":20,"comment":2,"blank":5,"name":"modules/comments/main.go","language":"Go"},{"code":20,"comment":0,"blank":3,"name":"modules/comments/serializers/comment_serializer.go","language":"Go"},{"code":20,"comment":0,"blank":6,"name":"modules/comments/services/comment_service.go","language":"Go"},{"code":20,"comment":0,"blank":6,"name":"modules/posts/services/posts_service.go","language":"Go"},{"code":20,"comment":4,"blank":6,"name":"plugins/arch.go","language":"Go"},{"code":19,"comment":2,"blank":6,"name":"modules/posts/main.go","language":"Go"},{"code":19,"comment":0,"blank":10,"name":"pkg/forceNotNil/README.md","language":"Markdown"},{"code":17,"comment":0,"blank":7,"name":"pkg/ginReturnSerializer/README.md","language":"Markdown"},{"code":16,"comment":0,"blank":1,"name":".vscode/settings.json","language":"JSON"},{"code":16,"comment":0,"blank":8,"name":"pkg/traceavility/README.md","language":"Markdown"},{"code":15,"comment":0,"blank":5,"name":"modules/comments/repositories/comments_mysql.go","language":"Go"},{"code":14,"comment":0,"blank":5,"name":"modules/posts/repositories/post_mysql.go","language":"Go"},{"code":13,"comment":0,"blank":6,"name":"makefile","language":"Makefile"},{"code":12,"comment":0,"blank":3,"name":"pkg/gorm_sqlite.go","language":"Go"},{"code":9,"comment":42,"blank":0,"name":".reviewdog.yml","language":"YAML"},{"code":9,"comment":0,"blank":1,"name":"docker-compose.yml","language":"YAML"},{"code":8,"comment":0,"blank":3,"name":"README.md","language":"Markdown"},{"code":8,"comment":0,"blank":3,"name":"cmd/linter/main.go","language":"Go"},{"code":5,"comment":0,"blank":2,"name":"modules/comments/repositories/comments.go","language":"Go"},{"code":5,"comment":0,"blank":2,"name":"modules/posts/repositories/post.go","language":"Go"}],"total":{"files":37,"code":2921,"comment":141,"blank":612}}` type Metrics struct { Files []File } type File struct { Code int Name string Language string } type Module struct { Name string Files int Code int } func Code() map[string]*Module { var result Metrics json.Unmarshal([]byte(metrics), &result) numFiles := 0 numLines := 0 var modules = make(map[string]*Module) for _, file := range result.Files { if file.Language != "Go" { continue } if strings.Contains(file.Name, "modules/") { modulesName := strings.Split(file.Name, "/")[1] if _, ok := modules[modulesName]; !ok { modules[modulesName] = &Module{ Files: 0, Code: 0, } } modules[modulesName] = &Module{ Files: modules[modulesName].Files + 1, Code: modules[modulesName].Code + file.Code, } numFiles += 1 numLines += file.Code } } return modules }
# Exercise 3 def my_abs_3(number): """ Print the absolute value of a number number: an integer or a floating point number """ if number >= 0: print(number) else: print(-number) # my_abs_3(-10) # Exercise 4 def my_abs_4(number): """ Return the absolute value of a number number: an integer or a floating point number """ if number >= 0: return number else: return -number # print(my_abs_4(-10)) # Exercise 5 def my_abs_5(number): """ Return the absolute value of a number number: an integer or a floating point number pseudo-code: 1. check the type of number 1. if it is int or float: if the number is negative: return the opposite 2. otherwise, raise an Error """ if isinstance(number, (int, float)): if number >= 0: return number else: return -number else: print('I don\'t know how to solve this') # return 'Wrong type of arguments' raise TypeError("We do not accept this type as argument!") # a good way to handle unexpected situation print(my_abs_5(-10)) print(my_abs_5('abc')) print('Hi')
using System.Collections.Generic; using UnityEngine; using Random = UnityEngine.Random; public class MazeGenerator : MonoBehaviour { /* * Per generare un labirinto ho bisogno di: * - dimensione X x Y (che sar� x,z) * - Stanza del tesoro e uscita * - La stanza del tesoro viene generata dopo N passi di generazione */ [Header("Generation parameters")] public int length; public int width; public int startLengthIndex = 0; public int startWidthIndex = 0; private MazeCellObj[,] maze; private MazeCellObj currentCell; List<Direction> availableDirection = new List<Direction> { Direction.FORWARD, Direction.BACKWARD, Direction.LEFT, Direction.RIGHT }; private void Awake() { //Init maze matrix maze = new MazeCellObj[length, width]; for (int i = 0; i < length; i++) { for (int j = 0; j < width; j++) { maze[i, j] = new MazeCellObj(i, j); } } currentCell = maze[startLengthIndex, startWidthIndex]; } public MazeCellObj[,] GetMaze() { RecursiveMazeGeneration(startLengthIndex, startWidthIndex); return maze; } private void RecursiveMazeGeneration(int currentLength, int currentWidth) { //Base case if (currentLength < 0 || currentLength >= length || currentWidth < 0 || currentWidth >= width) return; //If node is outside the maze dimension, return if (maze[currentLength, currentWidth].visited) return; //If node is visited, return MazeCellObj currentLoopCell = maze[currentLength, currentWidth]; maze[currentLength, currentWidth].visited = true; BreakWall(currentCell, currentLoopCell); List<Direction> direction = new List<Direction>(availableDirection); //Randomize direction of the lab Node for (int i = 0; i < 4; i++) { currentCell = currentLoopCell; Direction randomDirection = direction[Random.Range(0, direction.Count)]; direction.Remove(randomDirection); switch (randomDirection) { case Direction.FORWARD: RecursiveMazeGeneration(currentLength + 1, currentWidth); // Forward break; case Direction.BACKWARD: RecursiveMazeGeneration(currentLength - 1, currentWidth); // Backward break; case Direction.LEFT: RecursiveMazeGeneration(currentLength, currentWidth - 1); // Left break; case Direction.RIGHT: RecursiveMazeGeneration(currentLength, currentWidth + 1); // Right break; } } } void BreakWall(MazeCellObj currentCell, MazeCellObj nextCell) { if (currentCell.position == nextCell.position) return; if (currentCell.position.x > nextCell.position.x) { maze[currentCell.position.x, currentCell.position.y].isLeftWall = false; } else if (currentCell.position.x < nextCell.position.x) { maze[nextCell.position.x, nextCell.position.y].isLeftWall = false; } else if (currentCell.position.y < nextCell.position.y) { maze[currentCell.position.x, currentCell.position.y].isForwardWall = false; } else if (currentCell.position.y > nextCell.position.y) { maze[nextCell.position.x, nextCell.position.y].isForwardWall = false; } } } public enum Direction { FORWARD = 0, BACKWARD = 1, LEFT = 2, RIGHT = 3 } public class MazeCellObj { public bool visited; public Vector2Int position; public bool isForwardWall, isLeftWall; public MazeCellObj(int x, int y) { this.position = new Vector2Int(x, y); visited = false; isForwardWall = true; isLeftWall = true; } }
<?php declare(strict_types=1); //declare(strict_types=1); //mb do not use it here, as it generates conflict on line 280: base64_encode(): Argument #1 ($string) must be of type string, bool given namespace XoopsModules\Tag; /* You may not change or alter any portion of this comment or credits of supporting developers from this source code or any supporting source code which is considered copyrighted (c) material of the original comment or credit authors. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /** * Module: Tag * * @author ZySpec <zyspec@yahoo.com> * @copyright Copyright (c) 2001-2019 {@link https://xoops.org XOOPS Project}} * @license https://www.gnu.org/licenses/gpl-2.0.html GNU Public License * @since 2.00 */ /** * Issues class to collect information from GitHub */ class Issues { /** * @var array */ protected $hdrs; /** * @var string module directory name */ protected $dirname; /** * @var string response from involking curl */ protected $curl_response; /** * @var int Curl response header size */ protected $hdrSize; /** * @var string Service URL for curl */ protected $serviceUrl; /** * @var string prefix for all SESSION vars */ protected $sessPrefix; /** * @var string class error text */ protected $err; /** * Constructor * * return void */ public function __construct() { $this->hdrs = []; $this->curl_response = ''; $this->hdrSize = 0; $this->dirname = \basename(\dirname(__DIR__)); //$this->serviceUrl = 'https://api.github.com/repos/xoops/xoopscore25/issues?state=open'; //$this->serviceUrl = 'https://github.com/zyspec/' . $this->dirname . '/issues?state=open'; $this->serviceUrl = 'https://api.github.com/repos/XoopsModules25x/' . $this->dirname . '/issues?state=open'; $this->setSessPrefix($this->dirname); $this->err = ''; } /** * Function to put HTTP headers in an array * * @param resource $curl * * @return int length of header line put into array */ public function handleHeaderLine($curl, string $hdrLine): int { $this->hdrs[] = \trim($hdrLine); return mb_strlen($hdrLine); } /** * Function to get a header from the header array * * * @return array|string array($hdr => value) or false if not found */ public function getHeaderFromArray(string $hdr, bool $asArray = false) { $val = ''; foreach ($this->hdrs as $thisHdr) { if (\preg_match("/^{$hdr}/i", $thisHdr)) { $val = mb_substr($thisHdr, mb_strlen($hdr)); break; } } return $asArray ? [$hdr => \trim($val)] : \trim($val); } /** * Returns response from involking Curl * * @param bool $serialized (default = false) */ public function getCurlResponse(bool $serialized = false): string { return $serialized ? \serialize(\base64_encode($this->curl_response)) : $this->curl_response; } /** * Get the size of curl response headers * * @return int size of header in bytes */ public function getHdrSize(): int { return $this->hdrSize; } /** * Get the URL for curl */ public function getServiceUrl(): string { return $this->serviceUrl; } /** * Get the Prefix for SESSION variable */ public function getSessPrefix(): string { return $this->sessPrefix; } /** * Set the Prefix for SESSION variable * * @param string $prefix string to prepend to session variable * * @return string prefix */ public function setSessPrefix(string $prefix): string { $this->sessPrefix = \htmlspecialchars($prefix, \ENT_QUOTES | \ENT_HTML5) . '_'; return $this->sessPrefix; } /** * Get the SESSION variable name for Etag key */ public function getsKeyEtag(): string { return $this->sessPrefix . 'github_etag'; } /** * Get the SESSION variable name for Header Size key */ public function getsKeyHdrSize(): string { return $this->sessPrefix . 'github_hdr_size'; } /** * Get the SESSION variable name for Response key */ public function getsKeyResponse(): string { return $this->sessPrefix . 'github_curl_response'; } /** * Get the SESSION variable name for Array key */ public function getsKeyArray(): array { return [$this->getsKeyEtag(), $this->getsKeyHdrSize(), $this->getsKeyResponse()]; } /** * Get the SESSION cached Etag key contents * * @return string|bool Etag key or false if tag not set */ public function getCachedEtag() { return isset($_SESSION[$this->getsKeyEtag()]) ? \base64_decode(\unserialize($_SESSION[$this->getsKeyEtag()]), true) : false; } /** * Set the error message associated with the latest Curl operation * * @param string $msg the error message to save */ public function setError(string $msg): void { $this->err = $msg; } /** * Get the error message associated with the latest Curl operation * * @return string the current error message */ public function getError(): string { return $this->err; } /** * Execute a curl operation to retrieve data from GitHub server * * Also sets the SESSION vars for the curl operation * * @return int the current header size from curl */ public function execCurl(): int { $curl = \curl_init($this->getServiceUrl()); \curl_setopt_array( $curl, [ \CURLOPT_RETURNTRANSFER => true, \CURLOPT_HEADER => true, \CURLOPT_VERBOSE => true, \CURLOPT_TIMEOUT => 5, \CURLOPT_HTTPGET => true, \CURLOPT_USERAGENT => 'XOOPS-' . \mb_strtoupper($this->dirname), \CURLOPT_HTTPHEADER => [ 'Content-type:application/json', 'If-None-Match: ' . $this->getCachedEtag(), ], \CURLINFO_HEADER_OUT => true, \CURLOPT_HEADERFUNCTION => [$this, 'handleHeaderLine'], ] ); // execute the session $this->curl_response = \curl_exec($curl); // get the header size and finish off the session $this->hdrSize = \curl_getinfo($curl, \CURLINFO_HEADER_SIZE); $this->hdrSize = (int)$this->hdrSize; \curl_close($curl); $hdrEtag = $this->getHeaderFromArray('Etag: '); $_SESSION[$this->getsKeyEtag()] = \serialize(\base64_encode($hdrEtag)); $_SESSION[$this->getsKeyHdrSize()] = \serialize($this->hdrSize); $_SESSION[$this->getsKeyResponse()] = \serialize(\base64_encode($this->curl_response)); return $this->hdrSize; } }
local function regex(pattern, replacement) return function(link) return vim.fn.substitute(link, pattern, replacement, "") end end local github_regex = vim.regex("\\v^[a-zA-Z0-9_-]+/[.a-zA-Z0-9_-]+$") ---@param link string ---@return string|nil local function github(link) if github_regex:match_str(link) then return "https://github.com/" .. link end end ---@param base_url string ---@param prefixes string[] ---@return LinkExpander local function jira(base_url, prefixes) local re_str = "\\v\\c^(" .. table.concat(prefixes, "|") .. ")-\\d+$" local re = vim.regex(re_str) return function(link) if re:match_str(link) then return base_url .. link end end end ---@param keyword string ---@param github_project string ---@return LinkExpander local function github_issue_or_pr(keyword, github_project) return function(link) return vim.fn.substitute( link, "\\v\\c^" .. keyword .. "#(\\d+)", "https://github.com/" .. github_project .. "/pull/\\1", "" ) end end -- Expand ~/path/to/file to file://{HOME}/path/to/file local function homedir() return function(link) if vim.startswith(link, "~") then return "file://" .. os.getenv("HOME") .. link:sub(2) end end end return { regex = regex, github = github, jira = jira, github_issue_or_pr = github_issue_or_pr, homedir = homedir, }
#include <memory> #include <string> #include <iostream> #include "Image.h" #define MAX_BUFFER_SIZE 256 //! A structure. /*! A structure that stores check, encode, decode and get information functions, unique pointer and file name, message storing variables. */ struct ImageHelper { ImageHelper() {} ImageHelper(const std::string& _filename) : ImageHelper(_filename, {}) {} ImageHelper(const std::string& _filename, const std::string& _message) : filename(_filename), message(_message) {} //! A function variable. /*! A function that checks if it is possible to encode a message into the image. */ void check(); //! A function variable. /*! A function that encodes the message into the image. */ void encode(); //! A function variable. /*! A function that decodes the message into the image. */ void decode(); //! A function variable. /*! A function that displays the information about chosen file type and image size. */ void getInfo(); std::unique_ptr<Image> image; //!< A unique pointer that manages image object. const std::string filename; //!< A constant variable that stores the file name. const std::string message; //!< A constant variable that stores the message. };
'use client'; import { ColumnDef, ColumnFiltersState, SortingState, flexRender, getCoreRowModel, getFilteredRowModel, getPaginationRowModel, getSortedRowModel, useReactTable, Table as ReactTable, } from '@tanstack/react-table'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from '../table'; import { Input } from '../input'; import { DataTablePagination } from './data-table-pagination'; import { UrlUpdateType } from 'use-query-params'; import { DataTableType } from '../../types'; import { useInView } from 'react-intersection-observer'; import { useEffect } from 'react'; import clsx from 'clsx'; import { useQuery, keepPreviousData, UseQueryResult, useInfiniteQuery, UseInfiniteQueryResult, } from '@tanstack/react-query'; import { DataTableFilter } from './data-table-filters'; import { ArrowDownIcon, ArrowRightIcon, ArrowUpIcon, CheckCircledIcon, CircleIcon, CrossCircledIcon, QuestionMarkCircledIcon, StopwatchIcon, Cross2Icon, } from '@radix-ui/react-icons'; import { Button } from '../button'; declare type NewValueType<D> = D | ((latestValue: D) => D); interface DataTableProps<TData, TValue> { table: ReactTable<TData>; columns: ColumnDef<TData, TValue>[]; search: string; setSearch: ( newValue: NewValueType<string | null | undefined>, updateType?: UrlUpdateType ) => void; type: DataTableType; fetchNextPage?: () => void; isFetching?: boolean; searchText?: string; filterOptions?: any; //queryResult: UseInfiniteQueryResult | UseQueryResult; } export function DataTable<TData, TValue>({ table, columns, search, setSearch, type, fetchNextPage, isFetching, searchText = 'Search...', filterOptions, }: DataTableProps<TData, TValue>) { const { rows } = table.getRowModel(); const { ref, inView } = useInView({ threshold: 0, skip: type !== DataTableType.INFINITE_SCROLL, }); useEffect(() => { if (!isFetching && type === DataTableType.INFINITE_SCROLL && inView) { fetchNextPage!(); } }, [inView]); const isFiltered = table.getState().columnFilters.length > 0; const statuses = [ { value: 'backlog', label: 'Backlog', icon: QuestionMarkCircledIcon, }, { value: 'todo', label: 'Todo', icon: CircleIcon, }, { value: 'in progress', label: 'In Progress', icon: StopwatchIcon, }, { value: 'done', label: 'Done', icon: CheckCircledIcon, }, { value: 'canceled', label: 'Canceled', icon: CrossCircledIcon, }, ]; const priorities = [ { label: 'Low', value: 'low', icon: ArrowDownIcon, }, { label: 'Medium', value: 'medium', icon: ArrowRightIcon, }, { label: 'High', value: 'high', icon: ArrowUpIcon, }, ]; return ( <div className='grid gap-y-4'> <div className='flex items-center'> <Input placeholder={searchText} value={search} onChange={(event) => setSearch(event.target.value)} className='max-w-sm' /> </div> <div className='flex'> {table.getColumn('status') && ( <DataTableFilter column={table.getColumn('status')} title='Status' options={statuses} /> )} {table.getColumn('priority') && ( <DataTableFilter column={table.getColumn('priority')} title='Priority' options={priorities} /> )} {isFiltered && ( <Button variant='ghost' onClick={() => table.resetColumnFilters()} className='h-8 px-2 lg:px-3' > Reset <Cross2Icon className='ml-2 h-4 w-4' /> </Button> )} </div> <div className={clsx('w-full rounded-md border', { 'relative h-[600px] w-full overflow-auto': type === DataTableType.INFINITE_SCROLL, })} > <Table> <TableHeader> {table.getHeaderGroups().map((headerGroup) => ( <TableRow key={headerGroup.id}> {headerGroup.headers.map((header) => { return ( <TableHead key={header.id}> {header.isPlaceholder ? null : flexRender( header.column.columnDef.header, header.getContext() )} </TableHead> ); })} </TableRow> ))} </TableHeader> <TableBody> {rows?.length ? ( rows.map((row, rowIndex) => { return ( <TableRow key={row.id} ref={ type === DataTableType.INFINITE_SCROLL && rowIndex === rows?.length - 4 ? ref : null } data-state={row.getIsSelected() && 'selected'} > {row.getVisibleCells().map((cell) => ( <TableCell key={cell.id}> {flexRender( cell.column.columnDef.cell, cell.getContext() )} </TableCell> ))} </TableRow> ); }) ) : ( <TableRow> <TableCell colSpan={columns.length} className='h-24 text-center' > No results. </TableCell> </TableRow> )} </TableBody> </Table> </div>{' '} {type === DataTableType.PAGINATION ? ( <div className='mt-4'> <DataTablePagination table={table} /> </div> ) : ( <></> )} </div> ); }
/* * Copyright (c) 2023 Lunabee Studio * * 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. * * Created by Lunabee Studio / Date - 5/17/2023 - for the oneSafe6 SDK. * Last modified 5/17/23, 4:25 PM */ package studio.lunabee.onesafe.domain.usecase.item import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emitAll import kotlinx.coroutines.flow.transformLatest import studio.lunabee.onesafe.domain.model.safeitem.SafeItemField import studio.lunabee.onesafe.domain.repository.SafeItemFieldRepository import studio.lunabee.onesafe.domain.usecase.authentication.IsCryptoDataReadyInMemoryUseCase import java.util.UUID import javax.inject.Inject /** * Use case to retrieve item fields only if the master key is loaded */ class SecureGetItemFieldUseCase @Inject constructor( private val safeItemFieldRepository: SafeItemFieldRepository, private val isCryptoDataReadyInMemoryUseCase: IsCryptoDataReadyInMemoryUseCase, ) { /** * @param id the item id * * @return a flow of [SafeItemField] list or an empty flow master key is not loaded */ @OptIn(ExperimentalCoroutinesApi::class) operator fun invoke(id: UUID): Flow<List<SafeItemField>> = isCryptoDataReadyInMemoryUseCase.flow().transformLatest { isCryptoLoaded -> if (isCryptoLoaded) { emitAll(safeItemFieldRepository.getSafeItemFieldsFlow(id)) } } }
import { Card, Container, Grid, Step, StepLabel, Stepper } from '@material-ui/core' import React from 'react' interface StepWrapperProps { activeStep: number, } const steps = ['Track Info', 'Upload cover', 'Upload Track'] const StepWrapper: React.FC<StepWrapperProps> = ({ activeStep, children }) => { return ( <Container> <Stepper activeStep={activeStep}> {steps.map((step, index) => <Step key={index} completed={activeStep > index}> <StepLabel>{step}</StepLabel> </Step> )} </Stepper> <Grid container justifyContent="center" style={{ margin: '70px 0 ', height: 270 }}> <Card style={{ width: 600 }}> {children} </Card> </Grid> </Container> ) } export default StepWrapper
<section class="mt-5 mx-5 text-light"> <h1>PelisUP!</h1> <h6>Plataforma para ver películas y Series 😉</h6> </section> <section class="my-5 mx-5"> <div class="mb-3 input-group"> <span class="input-group-text" id="inputGroupPrepend"><i class="bi bi-search"></i></span> <input type="search" class="form-control" id="exampleFormControlInput1" placeholder="Buscar películas y series"> </div> </section> <section class="my-5 mx-5"> <div class="btn-group"> <button class="btn btn-outline-info" [ngClass]="filter === 'Todos' ? 'btn-selected' :''" role="button" (click)="changeFilter('Todos')">Todos</button> <button class="btn btn-outline-info" [ngClass]="filter === 'Peliculas' ? 'btn-selected' :''" role="button" (click)="changeFilter('Peliculas')">Peliculas</button> <button class="btn btn-outline-info" [ngClass]="filter === 'Series' ? 'btn-selected' :''" role="button" (click)="changeFilter('Series')">Series</button> </div> </section> <section class="my-5 mx-5"> <div class="my-3 d-flex text-light"> <h2>Todos</h2> <h6>({{movies_series.length}})</h6> </div> <div class="container"> <div class="row" *ngIf="filter === 'Todos'"> <div class="col-3 my-3" *ngFor="let item of movies_series"> <app-movie-card [title]="item.title || item.name" [img]="'https://www.themoviedb.org/t/p/w220_and_h330_face' + item.poster_path"></app-movie-card> </div> </div> <div class="row" *ngIf="filter === 'Peliculas'"> <div class="col-3 my-3" *ngFor="let item of movies"> <app-movie-card [title]="item.title || item.name" [img]="'https://www.themoviedb.org/t/p/w220_and_h330_face' + item.poster_path"></app-movie-card> </div> </div> <div class="row" *ngIf="filter === 'Series'"> <div class="col-3 my-3" *ngFor="let item of series"> <app-movie-card [title]="item.title || item.name" [img]="'https://www.themoviedb.org/t/p/w220_and_h330_face' + item.poster_path"></app-movie-card> </div> </div> </div> </section>
// 发布反馈组件,用于发布反馈 <template> <div class="wallformal" > <div class="headimage"> <div class="tablewhole"> <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" > <el-form-item label="反馈标题" prop="title"> <el-input v-model="ruleForm.title"></el-input> </el-form-item> <el-form-item label="反馈正文" prop="ttext"> <el-input type="textarea" v-model="ruleForm.ttext" rows="6"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm('ruleForm')">反馈</el-button> <el-button @click="inbroser">取消</el-button> </el-form-item> </el-form> </div> </div> </div> </template> <style> .headimage{ /* margin: 50px; */ left: 50px; width: 100px; height: 100px; z-index: 200; background-image: url(../assets/css/headimage.png); background-size: cover; position: relative; top: -50px; } .wallformal{ width: 950px; height: 550px; background-color: #f3f3f3; margin: 5px auto; box-shadow: 1px 1px 6px #000000; z-index: 100; position: relative; top: -370px; } .tablewhole{ padding: 5px; width: 750px; height: 450px; background-color: #f3f3f3; margin: 5px auto; box-shadow: 1px 1px 6px #000000; z-index: 200; position: relative; top: 120px; left: 50px; } </style> <script> import {insertFeedback} from '@/api/user' import { mapGetters } from 'vuex' import Selector from './Selector.vue' export default{ components: { Selector }, name: "Feededit", data() { return { feedBack:{ feedbackId:1, feedbackTitle:'', feedbackContent:'', feedbackUserid:'', feedbackState:'未处理', }, ruleForm: { title:'', ttext:'', }, rules: { title: [ { required: true, message: '请输入反馈标题', trigger: 'blur' }, { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' } ], ttext: [ { required: true, message: '请填写反馈内容', trigger: 'blur' }, { min: 3, max: 140, message: '长度在 3 到 140 个字符', trigger: 'blur' } ] } }; }, computed: { ...mapGetters(['token', 'user']) }, methods: { submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { this.feedBack.feedbackUserid=this.user.userId this.feedBack.feedbackTitle=this.ruleForm.title this.feedBack.feedbackContent=this.ruleForm.ttext insertFeedback(this.feedBack) alert('反馈成功!'); this.inbroser() } else { alert('反馈失败!'); return false; } }); }, inbroser(){ this.$router.push({path:'/Browser'}) }, } } </script>
// define styles :D interface typeObjects { [key: string]: string | typeObjects; } type Styles = typeObjects | Record<string, typeObjects>; // all styles export const styles: Styles = { html: "scroll-smooth", body: "family-[--font-body] bg-$neutral-100 tc-$neutral-900", p: "family-[--font-body] tc-$neutral-800 lh-1.75rem", code: "family-[--font-mono]", a: "tc-$neutral-800", "p code, .code": "family-[--font-mono] tc-$neutral-900 bg-$neutral-200-opa ph-6px br-4px fw-500 fs-80%", "code.primary": "tc-$accent-500", "code span.primary": "tc-$accent-500", "p.text, .paragraph, .para": "fs-1rem lh-1.5rem ta-justify", nav: { "": "bg-$neutral-100 w-100% w-mx-1440px mh-auto p-2rem pv-1rem d-flex flex-parent-center jc-[--sb] position-fixed t-0 l-0 r-0 z-998", ul: "d-flex flex-parent-center", "ul li": "d-flex flex-parent-center tc-$neutral-800 cursor-pointer", a: "tc-inherit", }, // heading h1: "fs-2.25rem fw-800 ls--0.025em", h2: "fs-1.875rem", h3: "fs-1.5rem", h4: "fs-1.25rem", "h2,h3,h4": "fw-600 ls--0.025em", ".flex": "d-flex", ".w-full": "w-100%", ".flex-center": "d-flex flex-parent-center", ".flex-wrap": "d-flex flex-wrap-wrap", ".space-between": "jc-[space-between]", ".items-center": "ai-center", "a.breadcrumb-link": "tc-$neutral-700 td-li-none", "a.breadcrumb-link.last.active": "tc-$neutral-900 td-li-underline td-c-[--accent-500]", ".btn": "bg-none bdr-none tc-$neutral-900 cursor-pointer fw-500", ".flex-1": "flex-grow-1 flex-shrink-1 flex-basis-0%", ".center": "flex-parent-center", ".space > * + *": "ml-1rem", // sidebar ".sidebar-links": { "": "", a: "tc-inherit", }, ".sidebar-group": { ".sidebar-link": "tc-$neutral-900", ".sidebar-link.active": "tc-$accent-500", ".sidebar-route-link": "tc-$neutral-600 bw-0 bc-transparent p-0", ".sidebar-route-link.active": "bs-solid bw-0 bw-left-1px pl-8px bc-[--accent-500] tc-$neutral-900", }, ".nav-link": "bs-solid bw-0 bw-bottom-1px bc-transparent tc-$neutral-600", ".nav-link.active": "bc-[--accent-500] tc-$neutral-900", // footer ".footer-link": { "": "mt-0.75rem tc-$neutral-800", a: "tc-inherit", }, // important selector must be last ".text-xs": "fs-0.75rem lh-1rem", ".text-sm": "fs-0.875rem lh-1.25rem", ".text-base": "fs-1rem lh-1.5rem", ".text-lg": "fs-1.125rem lh-1.75rem", ".text-xl": "fs-1.25rem lh-1.75rem", ".text-2xl": "fs-1.5rem lh-2rem", ".text-3xl": "fs-1.875rem lh-2.25rem", ".text-4xl": "fs-2.25rem lh-2.5rem", ".text-5xl": "fs-3rem lh-1", ".text-6xl": "fs-3.75rem lh-1", ".text-7xl": "fs-4.5rem lh-1", ".text-8xl": "fs-6rem lh-1", ".text-9xl": "fs-8rem lh-1", // line height ".leading-3": "lh-0.75rem", ".leading-4": "lh-1rem", ".leading-5": "lh-1.25rem", ".leading-6": "lh-1.5rem", ".leading-7": "lh-1.75rem", ".leading-8": "lh-2rem", ".leading-9": "lh-2.25rem", ".leading-10": "lh-2.5rem", ".leading-none": "lh-1", ".leading-tight": "lh-1.25", ".leading-snug": "lh-1.375", ".leading-normal": "lh-1.5", ".leading-relaxed": "lh-1.625", ".leading-loose": "lh-2", // line height ".font-thin": "fw-100", ".font-extralight": "fw-200", ".font-light": "fw-300", ".font-normal": "fw-400", ".font-medium": "fw-500", ".font-semibold": "fw-600", ".font-bold": "fw-700", ".font-extrabold": "fw-800", ".font-black": "fw-900", // line spacing ".tracking-tighter": "ls--0.05em", ".tracking-tight": "ls--0.025em", ".tracking-normal": "ls-0em", ".tracking-wide": "ls-0.025em", ".tracking-wider": "ls-0.05em", ".tracking-widest": "ls-0.1em", // position ".static": "position-static", ".fixed": "position-fixed", ".absolute": "position-absolute", ".relative": "position-relative", ".sticky": "position-sticky", // box shadow ".shadow": "shadow-[--tx__shadow]", ".shadow-md": "shadow-[--tx__shadow-md]", ".shadow-lg": "shadow-[--tx__shadow-lg]", ".shadow-xl": "shadow-[--tx__shadow-xl]", ".shadow-2xl": "shadow-[--tx__shadow-2xl]", ".shadow-inner": "shadow-[--tx__shadow-inner]", ".shadow-none": "shadow-[--tx__shadow-none]", // border radius ".rounded-none": "br-0px", ".rounded-sm": "br-0.125rem", ".rounded": "br-0.25rem", ".rounded-md": "br-0.375rem", ".rounded-lg": "br-0.5rem", ".rounded-xl": "br-0.75rem", ".rounded-2xl": "br-1rem", ".rounded-3xl": "br-1.5rem", ".rounded-full": "br-9999px", // others ".italic": "font-s-italic", // Text decoration ".underline": "td-li-underline td-c-inherit", ".overline": "td-li-overline td-c-inherit", ".line-through": "td-li-line-through td-c-inherit", ".no-underline": "td-li-none", ".max-md-none": "d-[--max-md\\:none]", ".max-lg-none": "d-[--max-lg\\:none]", ".min-lg-none": "d-[--min-lg\\:none]", ".min-md-none": "d-[--min-md\\:none]", ".none": "d-none", ".text-nowrap": "white-space-nowrap", ".isolate": "isolation-isolate", ".border": "bs-solid bw-0", ".text-primary, .text-primary-500": "tc-$accent-500", ".space-x-4 > * + *": "ml-1rem", ".space-y-4 > * + *": "mt-1rem", // list style position ".list-inside": "li-s-loc-inside", ".list-outside": "li-s-loc-outside", // list style type ".list-none": "li-s-type-none", ".list-disc": "li-s-type-disc", ".list-decimal": "li-s-type-decimal", // docs list item styles ".docs-list": { "": "li-s-loc-inside", li: { "": "fs-1rem lh-1.5rem mt-8px", "code, span.code": "tc-$neutral-900 bg-$neutral-200 ph-6px br-4px fw-500 fs-80%", "code.primary, span.code.primary": "tc-$accent-500", }, }, };
import { Component, EventEmitter, Output } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { ContactFormService } from '../../services/contact-form.service'; import { FormSubmissionResult } from './contact-form.types'; // regex pattern (99) 9-9999-9999 const PATTERN = /^\(\d{2}\)\s\d-\d{4}-\d{4}$/; export type ContactFormValue = { name: string; phone: string; email: string; message: string; }; @Component({ selector: 'app-contact-form', templateUrl: './contact-form.component.html', styles: [], }) export class ContactFormComponent { @Output() onFormSubmit = new EventEmitter<FormSubmissionResult>(); constructor(private formService: ContactFormService) {} form = new FormGroup({ name: new FormControl('', [Validators.required, Validators.minLength(1)]), phone: new FormControl('', [ Validators.required, Validators.pattern(PATTERN), Validators.minLength(11), ]), email: new FormControl('', [ Validators.required, Validators.email, Validators.minLength(5), ]), message: new FormControl('', []), }); onPhoneChange(value: { maskedValue: string; value: string }) { this.form.controls.phone.patchValue(value.maskedValue); } onSubmit() { const form = this.form; if (form.valid) { const formData = form.value; this.formService.postContactForm(formData as ContactFormValue).subscribe({ next: (response) => { this.onFormSubmit.emit({ type: 'success', response }); }, error: (error) => { this.onFormSubmit.emit({ type: 'error', error }); }, }); } } }
/// <reference types="@types/googlemaps" /> import { Component, NgZone, Input, OnInit, ViewChild} from '@angular/core'; import {TodoListData} from '../dataTypes/TodoListData'; import {TodoItemData} from '../dataTypes/TodoItemData'; import { TodoService } from '../todo.service'; import { AgmMap, MapsAPILoader} from '@agm/core'; import { GoogleMapsAPIWrapper } from '@agm/core'; import { SpeechRecognitionLang, SpeechRecognitionMaxAlternatives, SpeechRecognitionService, } from '@kamiazya/ngx-speech-recognition'; type FonctionFiltreItem = (item: TodoItemData) => boolean; declare var google: any; // fait la liaison avec le javascript google @Component({ selector: 'app-todo-list', templateUrl: './todo-list.component.html', styleUrls: ['./todo-list.component.css'], providers: [ { provide: SpeechRecognitionLang, useValue: 'fr-FR', }, { provide: SpeechRecognitionMaxAlternatives, useValue: 1, }, SpeechRecognitionService, ], }) export class TodoListComponent implements OnInit { @ViewChild('gSearch', {static: false}) formSearch; @ViewChild('searchKey', {static: false}) hiddenSearchHandler; @ViewChild('gMap', {static: false}) gmapElement: any; @ViewChild(AgmMap, {static: false}) map: AgmMap; @Input() // déclaration de tout les attributs ou objets dont on aura besoin private data: TodoListData; private dataitem: TodoItemData; itemLabel: any; private infoWindow: string; private geocoder: any; private filtre: string; public message = ''; constructor(private todoService: TodoService, public mapsApiLoader: MapsAPILoader, private service: SpeechRecognitionService, private zone: NgZone, private wrapper: GoogleMapsAPIWrapper) { this.mapsApiLoader = mapsApiLoader; this.zone = zone; this.wrapper = wrapper; this.mapsApiLoader.load().then(() => { this.geocoder = new google.maps.Geocoder(); }); console.log('SubComponent', this.service); // verifie si il y a bien la liaison entre le service et le component. this.service.onstart = (e) => { console.log('onstart'); }; // le service se met en route this.service.onresult = (e) => { this.message = e.results[0].item(0).transcript; // on affecte la retranscription de la voix dans l'attribut message this.addTodo(this.message); // on ajoute une Todo avec omme label la retranscription de ce qu'on a dit console.log('SubComponent:onresult', this.message, e); }; // le this.message est le message qu on a dit a haute voix. On l'ajoute a la todolist et on verifie via la console } // en fonction de si la Todo est cocheé ou non elle apparaitra dans le filtre correspondant filterCheck: FonctionFiltreItem = item => item.check; filterUnCheck: FonctionFiltreItem = item => !item.check; filterAll: FonctionFiltreItem = () => true; // tslint:disable-next-line: member-ordering filtreCourant: FonctionFiltreItem = this.filterAll; ngOnInit() { this.filtre = 'toutes'; } // si le label existe on retourne le label sinon il est vide getlabel(): string { return this.data ? this.data.label : ''; } getitems(): TodoItemData[] { return this.data ? this.data.items : []; } // Ajouter la todo avec la methode situe dans Service permettant de faire le MVC addTodo(todoLabel: string) { if (todoLabel) { this.todoService.addTodos({ label: todoLabel, check: false, location : { lat: 50.1, lng: 5.7, viewport: Object, zoom: 5, marker : { lat: 50.1, lng: 5.7, draggable: true } }, map : new google.maps.Geocoder(), }); } } // retourne le label gettodoLabel() { return this.dataitem.label; } // on met tout les attributs check des items à true tousCheck(): boolean { return this.getitems().reduce( (acc, item) => acc && item.check, true); } // si il n'existe aucune todo vide() { return this.getitems().length === 0; } // on supprime les todo coché SuppTodoCoche() { let AnnulerRetablir = false; for ( let i = 0; i < this.getitems().filter(item => item.check).length; i++ ) { if (i === this.getitems().filter(item => item.check).length - 1) { AnnulerRetablir = true; } this.supprimerTodo(this.getitems().filter(item => item.check)[i], AnnulerRetablir); } } // on supprime le todo via la bouton supprimerTodo(item: TodoItemData, AnnulerRetablir: boolean) { this.todoService.supprimerTodos(AnnulerRetablir, item); } Annuler(): void { this.todoService.Actionannuler(); } Retablir(): void { this.todoService.Actionretablir(); } getitemfiltre(): TodoItemData[] { return this.getitems().filter(this.filtreCourant); } nbitemcoche(): number { return this.data.items.reduce( (acc, item) => acc + (item.check ? 1 : 0), 0 ); } // nombre de taches restantes suivant le nombre de todo cocheé ou non tachesRestantes(): number { return this.getitems().filter(todo => !todo.check).length; } // juste pour gerer les "s" si il y a une tâche ou plusieurs tâches affichagetache() { if (this.tachesRestantes() > 1 ) { return 'Tâches restantes'; } else { return 'Tâche restante'; } } setTodoCheck(item: TodoItemData, check: boolean, edite: boolean) { this.todoService.setTodosCheck(check, true, item); } // changeCheck() { const check = !this.tousCheck(); let AnnulerRetablir = false; for (let i = 0; i < this.data.items.length; i++ ) { if (i === this.data.items.length - 1) { AnnulerRetablir = true; } this.todoService.setTodosCheck(check, AnnulerRetablir, this.data.items[i] ); } } // commencer a parler dans le micro et fait appel a une methode dans le service du package start() { this.service.start(); } stop() { this.service.stop(); } }
package com.ark.center.iam.application.user.executor; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.lang.tree.TreeUtil; import com.ark.center.iam.client.permission.vo.PermissionDTO; import com.ark.center.iam.client.user.dto.UserRouteDTO; import com.ark.center.iam.domain.permission.Permission; import com.ark.center.iam.domain.menu.gateway.RouteGateway; import com.ark.center.iam.domain.user.service.UserPermissionService; import com.ark.center.iam.infra.permission.assembler.PermissionAssembler; import com.ark.component.cache.core.CacheHelper; import com.ark.component.context.core.ServiceContext; import com.ark.component.security.base.user.LoginUser; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static com.ark.center.iam.domain.permission.enums.PermissionType.FRONT_ROUTE; import static com.ark.center.iam.domain.permission.enums.PermissionType.PAGE_ELEMENT; import static com.ark.center.iam.infra.user.common.UserCacheKey.CACHE_KEY_USER_ELEMS; import static com.ark.center.iam.infra.user.common.UserCacheKey.CACHE_KEY_USER_ROUTES; @Component @RequiredArgsConstructor public class UserSelfQryExe { private final UserPermissionService userPermissionService; private final RouteGateway routeGateway; private final PermissionAssembler permissionAssembler; public List<PermissionDTO> queryUserSelfElements() { LoginUser user = ServiceContext.getCurrentUser(); Long userId = user.getUserId(); String cacheKey = String.format(CACHE_KEY_USER_ELEMS, userId); return CacheHelper.execute(cacheKey, key -> { List<Permission> permissions = userPermissionService.queryUserPermissions(user.getUserId(), PAGE_ELEMENT); return permissions.stream() .filter(Objects::nonNull) .map(permissionAssembler::toPermissionDTO) .toList(); }); } public List<UserRouteDTO> queryUserSelfRoutes() { LoginUser user = ServiceContext.getCurrentUser(); Long userId = user.getUserId(); String cacheKey = String.format(CACHE_KEY_USER_ROUTES, userId); return CacheHelper.execute(cacheKey, key -> { List<Permission> permissions = userPermissionService.queryUserPermissions(userId, FRONT_ROUTE); List<Long> routeIds = permissions.stream() .filter(Objects::nonNull) .map(Permission::getResourceId) .toList(); return routeGateway.selectByRouteIds(routeIds); }); } public List<Tree<Long>> queryUserSelfRoutesV2() { LoginUser user = ServiceContext.getCurrentUser(); Long userId = user.getUserId(); // String cacheKey = String.format(CACHE_KEY_USER_ROUTES, userId); // return CacheHelper.execute(cacheKey, key -> { List<Permission> permissions = userPermissionService.queryUserPermissions(userId, FRONT_ROUTE); List<Long> menuIds = permissions.stream() .filter(Objects::nonNull) .map(Permission::getResourceId) .collect(Collectors.toList()); List<UserRouteDTO> userMenuDTOS = routeGateway.selectByRouteIds(menuIds); List<Tree<Long>> build = TreeUtil.build(userMenuDTOS, 0L, (object, treeNode) -> { treeNode.setId(object.getId()); treeNode.setParentId(object.getParentId()); // treeNode.setWeight(object.getWeight()); treeNode.setName(object.getName()); treeNode.putAll(BeanUtil.beanToMap(object)); }); return build; // }); } }
//FUNCION FLECHA ESPERAR const esperar = condicion =>{ return new Promise((resolve, reject) =>{ setTimeout(() => { if(condicion){ resolve("Hola mundo"); }else{ reject("Hubo un error") } }, 2000) }) } //FUNCION NORMAL COMUN ESPERAR function esperar(condicion) { return new Promise((resolve, reject) =>{ setTimeout(() => { if(condicion){ resolve("Hola mundo"); }else{ reject("Hubo un error") } }, 2000) }) } //FUNCION FLECHA DE MANEJO ERROR const manejoError = async codicion =>{ try{ const resultado = await esperar(condicion); console.log(resultado); }catch(error){ //aca capturo el error y lo controlo yo console.log(error); } } //FUNCION NORMAL COMUN MANEJO ERROR async function manejoError(condicion){ try{ const resultado = await esperar(condicion); console.log(resultado); }catch(error){ //aca capturo el error y lo controlo yo console.log(error); } }
package com.sorrowblue.comicviewer.feature.library.dropbox import androidx.paging.PagingSource import androidx.paging.PagingState import com.dropbox.core.v2.files.FileMetadata import com.dropbox.core.v2.files.FolderMetadata import com.sorrowblue.comicviewer.domain.model.bookshelf.BookshelfId import com.sorrowblue.comicviewer.domain.model.file.BookFile import com.sorrowblue.comicviewer.domain.model.file.File import com.sorrowblue.comicviewer.domain.model.file.Folder import com.sorrowblue.comicviewer.feature.library.dropbox.data.DropBoxApiRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext internal class DropBoxPagingSource( private val parent: String, private val repository: DropBoxApiRepository, private val dispatcher: CoroutineDispatcher = Dispatchers.IO, ) : PagingSource<String, File>() { override fun getRefreshKey(state: PagingState<String, File>): String? { return state.anchorPosition?.let { state.closestPageToPosition(it) }?.nextKey } override suspend fun load(params: LoadParams<String>): LoadResult<String, File> { val result = withContext(dispatcher) { repository.list(parent, params.loadSize.toLong(), params.key) } val list = result?.entries?.mapNotNull { when (it) { is FolderMetadata -> { Folder( BookshelfId(0), it.name, parent, it.pathLower.orEmpty(), 0, 0, false, mapOf("preview_url" to it.previewUrl) ) } is FileMetadata -> { BookFile( BookshelfId(0), it.name, parent, it.pathLower.orEmpty(), it.size, it.serverModified.time, false, "", 0, 0, 0, mapOf("preview_url" to it.previewUrl) ) } else -> null } }.orEmpty() return LoadResult.Page( data = list, prevKey = null, nextKey = if (result?.hasMore == true) result.cursor else null ) } }
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { var ct1 = TextEditingController(); String celsicus = ""; String farh = ""; void toCelcius() { try { setState(() { celsicus = "Celsicus = ${(int.parse(ct1.text) - 32) * 5 / 9}"; farh = ''; }); } catch (e) { print("Error computing $e"); } } void toFarhn() { try { setState(() { farh = "Fahrenheit = ${(int.parse(ct1.text) * (9 / 5)) + 32}"; celsicus = ''; }); } catch (e) { print("Error computing $e"); } } Widget myText(String text) { return Text( text, style: TextStyle( fontSize: 21, ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("App"), ), body: Padding( padding: const EdgeInsets.all(8.0), child: SizedBox( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ TextField( controller: ct1, decoration: const InputDecoration( labelText: "Enter Number", border: OutlineInputBorder(), ), ), myText(celsicus), myText(farh), ElevatedButton( onPressed: toCelcius, child: Text( "Computer to Celcius", style: TextStyle( fontSize: 21, ), ), ), SizedBox( height: 10, ), ElevatedButton( onPressed: toFarhn, child: Text( "Computer to Fahrenheit", style: TextStyle( fontSize: 21, ), ), ), ], ), ), ), ); } }
import os.path as osp import torch import torch.nn as nn from torch.nn import functional as F from torch.cuda.amp import GradScaler, autocast from dassl.engine import TRAINER_REGISTRY, TrainerX from dassl.metrics import compute_accuracy from dassl.utils import load_pretrained_weights, load_checkpoint from dassl.optim import build_optimizer, build_lr_scheduler from dassl.data.transforms.transforms import build_transform from datasets.cifar100 import CIFAR100, CLASSNAME_CFIAR100 from datasets.cub200 import CUB200, CLASSNAME_CUB200 from datasets.miniImageNet import MiniImageNet, CLASSNAME_miniImageNet from datasets.sun397 import SUN397, CLASSNAME_SUN397 from datasets.cub200_wo_base import CUB200_wo_Base from models.model import load_clip_to_cpu, CustomCLIP from tqdm import tqdm @TRAINER_REGISTRY.register() class LP_DiF(TrainerX): def check_cfg(self, cfg): assert cfg.TRAINER.COOP.PREC in ["fp16", "fp32", "amp"] def build_data_loader(self): self.tfm_train = build_transform(self.cfg, is_train=True) self.tfm_test = build_transform(self.cfg, is_train=False) self.batch_size_train = self.cfg.DATALOADER.TRAIN_X.BATCH_SIZE self.batch_size_test = self.cfg.DATALOADER.TEST.BATCH_SIZE self.num_workers = self.cfg.DATALOADER.NUM_WORKERS self.task_id = self.cfg.TRAINER.TASK_ID self.dataset_name = self.cfg.DATASET.NAME self.data_root = self.cfg.DATASET.ROOT self.num_classes = self.cfg.DATASET.NUM_CLASSES self.num_classes_base = self.cfg.DATASET.NUM_CLASSES_BASE self.class_per_task = self.cfg.DATASET.CLASS_PER_TASK self.shot = self.cfg.DATASET.NUM_SHOTS self.B = self.cfg.DATASET.B self.GD_path = self.cfg.DATASET.GD_PATH self.task_num = int((self.num_classes-self.num_classes_base)/self.class_per_task) if self.num_classes_base>0: self.encounter_class_id = self.num_classes_base + self.class_per_task * self.task_id else: self.encounter_class_id = self.class_per_task * (self.task_id + 1) if self.dataset_name=='CIFAR100': train_set_task0 = CIFAR100(shot=self.shot, tfm=self.tfm_train, task_id = self.task_id, mode='train', class_per_task=self.class_per_task, B=self.B, GD_path = self.GD_path) test_set_task0 = CIFAR100( tfm=self.tfm_test, task_id = self.task_id, mode='test', class_per_task=self.class_per_task, ) self.classnames = CLASSNAME_CFIAR100 elif self.dataset_name=='CUB200': train_set_task0 = CUB200(data_root=self.data_root, shot=self.shot, tfm=self.tfm_train, task_id = self.task_id, mode='train', class_per_task=self.class_per_task, B=self.B, GD_path = self.GD_path) test_set_task0 = CUB200(data_root=self.data_root, tfm=self.tfm_test, task_id = self.task_id, mode='test', class_per_task=self.class_per_task) self.classnames = CLASSNAME_CUB200 elif self.dataset_name=='miniImageNet': train_set_task0 = MiniImageNet(data_root=self.data_root, tfm=self.tfm_train, task_id = self.task_id, mode='train', class_per_task=self.class_per_task, B=self.B, GD_path = self.GD_path) test_set_task0 = MiniImageNet(data_root=self.data_root, tfm=self.tfm_test, task_id = self.task_id, mode='test', class_per_task=self.class_per_task ) self.classnames = CLASSNAME_miniImageNet elif self.dataset_name=='SUN397': train_set_task0 = SUN397(data_root=self.data_root, shot=self.shot, tfm=self.tfm_train, task_id = self.task_id, mode='train', class_per_task=self.class_per_task, B=self.B, GD_path = self.GD_path) test_set_task0 = SUN397(data_root=self.data_root, tfm=self.tfm_test, task_id = self.task_id, mode='test', class_per_task=self.class_per_task, ) self.classnames = CLASSNAME_SUN397 elif self.dataset_name=='CUB200_wo_Base': train_set_task0 = CUB200_wo_Base(data_root=self.data_root, shot=self.shot, tfm=self.tfm_train, task_id = self.task_id, mode='train', class_per_task=self.class_per_task, B=self.B, GD_path = self.GD_path) test_set_task0 = CUB200_wo_Base(data_root=self.data_root, tfm=self.tfm_test, task_id = self.task_id, mode='test', class_per_task=self.class_per_task, ) self.classnames = CLASSNAME_CUB200 self.classnames_encountered = self.classnames[:self.encounter_class_id] train_loader = torch.utils.data.DataLoader(train_set_task0,batch_size=self.batch_size_train, num_workers=self.num_workers, drop_last=False, shuffle=True) test_loader = torch.utils.data.DataLoader(test_set_task0,batch_size=self.batch_size_test, num_workers=self.num_workers, drop_last=False) self.train_loader_x = train_loader self.val_loader = test_loader self.test_loader = test_loader self.lab2cname = {x:self.classnames_encountered[x] for x in range(len(self.classnames_encountered))} def build_model(self): cfg = self.cfg print(f"Loading CLIP (backbone: {cfg.MODEL.BACKBONE.NAME})") clip_model = load_clip_to_cpu(cfg) if cfg.TRAINER.COOP.PREC == "fp32" or cfg.TRAINER.COOP.PREC == "amp": clip_model.float() self.clip_model = clip_model print("Building custom CLIP") self.model = CustomCLIP(cfg, self.classnames_encountered, clip_model) print("Turning off gradients in both the image and the text encoder") for name, param in self.model.named_parameters(): if "prompt_learner" not in name: param.requires_grad_(False) if cfg.MODEL.INIT_WEIGHTS: load_pretrained_weights(self.model.prompt_learner, cfg.MODEL.INIT_WEIGHTS) self.model.to(self.device) self.optim = build_optimizer(self.model.prompt_learner, cfg.OPTIM) self.sched = build_lr_scheduler(self.optim, cfg.OPTIM) self.register_model("prompt_learner", self.model.prompt_learner, self.optim, self.sched) self.scaler = GradScaler() if cfg.TRAINER.COOP.PREC == "amp" else None device_count = torch.cuda.device_count() if device_count > 1: print(f"Multiple GPUs detected (n_gpus={device_count}), use all of them!") self.model = nn.DataParallel(self.model,device_ids=[0, 1, 2,3,4,5,6]) self.lambda_o = self.cfg.TRAINER.LAMBDA_O def forward_backward(self, batch): if self.task_id==0: image, label = batch image = image.to(self.device) label = label.to(self.device) prec = self.cfg.TRAINER.COOP.PREC if prec == "amp": with autocast(): output = self.model(image) loss = F.cross_entropy(output, label) self.optim.zero_grad() self.scaler.scale(loss).backward() self.scaler.step(self.optim) self.scaler.update() else: output = self.model(image) loss = F.cross_entropy(output, label) self.model_backward_and_update(loss) else: image, label,pseudo_feat,pseudo_label = batch pseudo_feat = pseudo_feat.view(-1,512) pseudo_label = pseudo_label.view(-1) image = image.to(self.device) label = label.to(self.device) pseudo_label = pseudo_label.to(self.device) pseudo_feat = pseudo_feat.to(self.device) prec = self.cfg.TRAINER.COOP.PREC if prec == "amp": with autocast(): output = self.model(image) loss = F.cross_entropy(output, label) self.optim.zero_grad() self.scaler.scale(loss).backward() self.scaler.step(self.optim) self.scaler.update() else: output,output_pseudo = self.model(image,pseudo_feat) loss = F.cross_entropy(torch.cat((output,output_pseudo)), torch.cat((label,pseudo_label)),reduction='none') weight_n = torch.ones((image.shape[0])) weight_o = torch.ones((pseudo_feat.shape[0])) * self.lambda_o weight = torch.cat((weight_n,weight_o)).half() loss = loss * (weight.to(loss.device).detach()) loss = loss.mean() self.model_backward_and_update(loss) loss_summary = { "loss": loss.item(), "acc": compute_accuracy(output, label)[0].item(), } if (self.batch_idx + 1) == self.num_batches: self.update_lr() return loss_summary def parse_batch_train(self, batch): input = batch["img"] label = batch["label"] input = input.to(self.device) label = label.to(self.device) return input, label @torch.no_grad() def test(self, split=None): """A generic testing pipeline.""" self.set_model_mode("eval") self.evaluator.reset() if split is None: split = self.cfg.TEST.SPLIT if split == "val" and self.val_loader is not None: data_loader = self.val_loader else: split = "test" data_loader = self.test_loader print(f"Evaluate on the *{split}* set") for batch_idx, batch in enumerate(tqdm(data_loader)): image, label = batch image = image.to(self.device) label = label.to(self.device) output = self.model_inference(image) self.evaluator.process(output, label) results = self.evaluator.evaluate() for k, v in results.items(): tag = f"{split}/{k}" self.write_scalar(tag, v, self.epoch) return list(results.values())[0] def load_model(self, directory, epoch=None): if not directory: print("Note that load_model() is skipped as no pretrained model is given") return names = self.get_model_names() # By default, the best model is loaded model_file = "model-best.pth.tar" if epoch is not None: model_file = "model.pth.tar-" + str(epoch) for name in names: model_path = osp.join(directory, name, model_file) if not osp.exists(model_path): raise FileNotFoundError('Model not found at "{}"'.format(model_path)) checkpoint = load_checkpoint(model_path) state_dict = checkpoint["state_dict"] epoch = checkpoint["epoch"] # Ignore fixed token vectors if "token_prefix" in state_dict: del state_dict["token_prefix"] if "token_suffix" in state_dict: del state_dict["token_suffix"] print("Loading weights to {} " 'from "{}" (epoch = {})'.format(name, model_path, epoch)) # set strict=False self._models[name].load_state_dict(state_dict, strict=False)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- import CSS --> <link rel="stylesheet" href="https://unpkg.com/element-ui@2.15.6/lib/theme-chalk/index.css"> </head> <body> <div id="app"> <template> <el-table ref="multipleTable" :data="tableData" :row-style="rowStyle" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange" @row-click="handleRowClick"> <el-table-column type="index" width="55"> </el-table-column> <el-table-column type="selection" width="55"> </el-table-column> <el-table-column prop="date" label="日期" sortable width="120"> <!-- <template v-slot="scope">{{ scope.row.date }}</template>--> </el-table-column> <el-table-column prop="name" label="姓名" sortable width="120"> </el-table-column> <el-table-column prop="address" label="地址" sortable show-overflow-tooltip> </el-table-column> </el-table> <div style="margin-top: 20px"> <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button> <el-button @click="toggleSelection()">取消选择</el-button> </div> </template> </div> </body> <!-- import Vue before Element --> <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script> <!-- import JavaScript --> <script src="https://unpkg.com/element-ui@2.15.6/lib/index.js"></script> <script> var vm = new Vue({ el: '#app', data: function () { return { tableData: [], rowStyle: function ({row, rowIndex}) { }, multipleSelection: [] }; }, // mounted: function () { // this.$nextTick(function () { // // 仅在整个视图都被渲染之后才会运行的代码 // this.setTableData(); // }) // }, created: function () { this.setTableData(); }, methods: { setTableData() { this.tableData = [ { date: '2016-05-03', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-02', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-04', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-01', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-08', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-06', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }, { date: '2016-05-07', name: '王小虎', address: '上海市普陀区金沙江路 1518 弄' }]; }, toggleSelection(rows) { if (rows) { rows.forEach(row => { this.$refs.multipleTable.toggleRowSelection(row); }); } else { this.$refs.multipleTable.clearSelection(); } }, handleRowClick(row, column, event) { this.$refs.multipleTable.toggleRowSelection(row, true); }, handleSelectionChange(selection) { this.multipleSelection = selection; } } }); </script> </html>
package ac.ke.usiu.example.midsemproject; import androidx.annotation.NonNull; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.FirebaseFirestore; import java.util.HashMap; import java.util.Map; public class termPaperUpdate extends AppCompatActivity { public static String data; String key1 = "Term Paper 1"; String key2 = "Term Paper 2"; String key3 = "Term Paper 3"; int paper1Score; int paper2Score; int paper3Score; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_term_paper_update); //Hiding the action bar ActionBar actionBar = getSupportActionBar(); actionBar.hide(); FirebaseFirestore store = FirebaseFirestore.getInstance(); EditText firstTermPaper = findViewById(R.id.termPaper1); EditText secondTermPaper = findViewById(R.id.termPaper2); EditText thirdTermPaper = findViewById(R.id.termPaper3); Button updateTermPapers = findViewById(R.id.updateStudentTermPapers); Button goBack = findViewById(R.id.backToUpdatePage); Bundle save = getIntent().getExtras(); updateTermPapers.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String documentName = save.getString(data); String paperOne = firstTermPaper.getText().toString().trim(); String paperTwo = secondTermPaper.getText().toString().trim(); String paperThree = thirdTermPaper.getText().toString().trim(); int paper1Change; if(paperOne.isEmpty()) { paper1Change = 0; paper1Score = paper1Change + 102; } else { paper1Change = Integer.parseInt(paperOne); paper1Score = paper1Change; } if(paper1Change > 100) { Toast.makeText(getApplicationContext(),"The inserted score for Term Paper 1 is incorrect", Toast.LENGTH_LONG).show(); firstTermPaper.setError("The score must be in percentage format(from 0 to 100 only)"); return; } int paper2Change; if(paperTwo.isEmpty()) { paper2Change = 0; paper2Score = paper2Change + 102; } else { paper2Change = Integer.parseInt(paperTwo); paper2Score = paper2Change; } if(paper2Change > 100) { Toast.makeText(getApplicationContext(),"The inserted score for Term Paper 2 is incorrect", Toast.LENGTH_LONG).show(); secondTermPaper.setError("The score must be in percentage format(from 0 to 100 only)"); return; } int paper3Change; if(paperThree.isEmpty()) { paper3Change = 0; paper3Score = paper3Change + 102; } else { paper3Change = Integer.parseInt(paperThree); paper3Score = paper3Change; } if(paper3Change > 100) { Toast.makeText(getApplicationContext(),"The inserted score for Term Paper 3 is incorrect", Toast.LENGTH_LONG).show(); thirdTermPaper.setError("The score must be in percentage format(from 0 to 100 only)"); return; } Map<String,Object>updatePaperScore = new HashMap<>(); updatePaperScore.put(key1,paper1Score); updatePaperScore.put(key2,paper2Score); updatePaperScore.put(key3,paper3Score); store.collection("CourseData") .document(documentName) .update(updatePaperScore) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { Toast.makeText(getApplicationContext(),"Term Paper scores have been updated", Toast.LENGTH_LONG).show(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(getApplicationContext(),"Error: The term paper scores have not been updated", Toast.LENGTH_LONG).show(); } }); } }); goBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } }
/* Creates Grid with CardItems(individual Offers) and gives the required Information for an Offer, * usage of MUI library */ import React, {useEffect, useState} from 'react'; import './Cards.css'; import {getFollowingsByUser} from "../../fetchoperations/FollowingsOperations"; import CardItem from "./CardItem"; import Grid from "@mui/material/Grid"; import {isLoggedIn} from "../utils/StorageInterface"; import Box from "@mui/material/Box"; export default function Cards({offers}) { const [followings, setFollowings] = useState([]); const [needsNewFetch, setNeedsNewFetch] = useState(0); useEffect(() => { if (isLoggedIn()) { getFollowingsByUser().then(r => setFollowings(r)) } }, [needsNewFetch]); return ( <Box className='cards' sx={{maxWidth: "100%"}}> <Grid container spacing={4} > {offers.map((offer, index) => ( <Grid item xs={12} sm={4} md={3} lg={2} xl={2} key={index} margin={"10px"} className='cards__items'> <CardItem key={offer.id} src={offer.primary_image} text={offer.title} alt={offer.title} label={offer.price + offer.currency} path={`/offer/${offer.id}`} id='offer_section' offer_id={offer.id} followings={followings} setFollowings={setFollowings} setNewFetch={setNeedsNewFetch}/> </Grid> ) )} </Grid> </Box> ); };
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('inventarios', function (Blueprint $table) { $table->id(); $table->string('modelo'); $table->string('descripcion'); $table->string('serial'); //$table->string('marca_id'); //$table->string('hw_id'); $table->foreignId('marca_id') ->nullable() ->references('id')->on('marcahws') ->cascadeOnUpdate() ->nullOnDelete(); $table->foreignId('hw_id') ->nullable() ->references('id')->on('hardware') ->cascadeOnUpdate() ->nullOnDelete(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('inventarios'); } };
MAME32 Screen Shot Organizer Copyright (C) Moose O'Malley, ---------------------------- July 2003. | T A B L E O F C O N T E N T S | | * Introduction (LONG) | * Why I wrote this Program / Why use this Program | * Using this Program | * Limitations / Restrictions of the program | * The Future | * Special Greetings / Thanks to | * Warranty | * Amendment History | * Contacting the Program's Author Introduction : -------------- MAME32 Screen Shot Organizer for Windows 95, 98, NT, ME, 2000, XP, and similar operating systems. MAME32 Screen Shot Organizer is a companion utility / tool for the MAME 32 Arcade Machine Emulator : http://www.mame.net MAME32 Screen Shot Organizer simply enables you to view and drag & drop (with the mouse) screen shots so that you can arrange your screen shots for each parent game and its clones with ease. This could be useful for anyone who wants to arrange their screen shots in a certain way. e.g. show the title screen for each parent game of each set, and then show various screen shots of each game in action for the clones. To enable this functionality, you need to : 1. Specify the snap shots directory. i.e. the directory where your MAME Screen Shots reside as PNG files. These screen shots cannot be inside a ZIP file(s). i.e. they need to exist as separate PNG files in the above directory. 2. Specify the directory path and name of the DOS or Windows Command Line version of MAME. 3. Press the "Refresh Originals / Clones List" button. Once you do these three things, then you are ready to view and drag & drop the screen shots so you can reorganise the screen shots for each parent game and its clones as desired. Without this program, you would need to manually rename files using Windows Explorer or by typing commands at the DOS Command prompt. Both very slow and tedious ways to rename bunches of files. This program makes it exceptionally easy to reorganise the screen shots for each game. I hope you find this program useful. MAME32 Screen Shot Organizer is NOT an official part of the MAME project. Developed using 32-bit Delphi. Why I wrote this Program / Why use this Program : ------------------------------------------------- I wrote this program so that I could reorganise all of my MAME screen shots. I decided that I wanted to have the title screen for each game as the screen shot for each parent game, and then various screen shots in the order I liked best for each clone. After renaming some files manually using Windows Explorer, I soon grew very tired of that approach, so - as I usually do - I sat down and wrote this program. And, soon I had all of my screen shots organised as required. Using this Program : -------------------- To use this program, simply unzip it to a directory (using PKUNIP, WinZIP, or similar), run it, and click on the buttons to view / perform the activities you require. You can Drag & Drop a file or a directory onto this program using Windows Explorer. Before you can use this program, you need to : 1. Specify the snap shots directory. i.e. the directory where your MAME Screen Shots reside as PNG files. These screen shots cannot be inside a ZIP file(s). i.e. they need to exist as separate PNG files in the above directory. 2. Specify the directory path and name of the DOS or Windows Command Line version of MAME. 3. Press the "Refresh Originals / Clones List" button. Once you do these three things, then you are ready to view and drag & drop the screen shots so you can reorganise the screen shots for each parent game and its clones as desired. Simply, click on the parent game, and any screen shots for it and its clones will be displayed. Reorganising the screen shots is as simple as dragging and dropping them with your mouse. Limitations / Restrictions of the program : ------------------------------------------- None. There is no trial period and there is no "cutdown" or "restricted" functionality that requires users to register. This program is FREE software - any person and any company is welcome to copy it, use it, and distribute it as they see fit, as long as the EXEcutable and this text file remain intact. If you paid money for this program, then you were ripped off, and you should complain to the person who sold it to you !! (Don't complain to me, it's nothing to do with me !!). The Future : ------------ In the future, many improvements could be made to this program, such as : - Add a right-mouse click Popup Menu to enable you to : * Delete a screen shot, or, * Execute MAME so that you can redo a screen shot. - A version with US spelling, such as "organizer" instead of the standard English "organiser" !! ;) - Anything else ? If you would like any of these improvements, or would like to suggest more, or would like to give me some feedback on the program, please email me and let me know. Special Greetings / Thanks to : ------------------------------- Special thanks to all arcade emulator authors, people who maintain arcade emulator sites, those who dump the roms, and those who work hard to try and preserve the actual physical arcade machines, with special mention to : - Dave Spicer for developing Sparcade - the very first Arcade Emulator for PCs, which introduced me to Arcade Emulation way back in 1995. I was and still am compltely blown away by arcade emulation !! - Nicola Salmoria (for MAME and other emulators) and the fabulous MAME and various MAME 32 Development Teams. - Neil Bradley (Emu, Retrocade and others). - Antiriad and the Raine Development Team. - Dave (Final Burn). - Anders Nilsson & Janne Korpela (Neo Rage and Tutankham). - Thierry Lescot (System 16 Emulator). - Neill Corlett (MGE). - Michael Cuddy (KEM & Gyruss). - and all other arcade emulator developers - you guys rule !!! - Virtu Al, Brian Peek, MAME DK, and others - you guys rule too !!! Even though some of these emulators are no longer under development, your amazing work is NOT forgotten !! Warranty : ---------- This software and the accompanying files are provided "as is" and without warranties as to performance or merchantability or any other warranties whether expressed or implied. The user assumes the entire risk of using this software. If you do find any faults with this program, email me and let me know, and I will do my best to fix it ASAP. Amendment History : -------------------- Vers Date Description 1.0 9-July-2003 First Public Release. (61,305 lines of code / comments.) 21-July-2003 - Email Retrogames (Prophet and Griking) to announce this program. If this program was not downloaded from my Home Page, then it might be an old version. The latest version of this program is available from my WEB page - see below. For more great software, please visit my WEB page ! Mike "Moose" O'Malley ____________________________________________________ Moose's Software Valley - Established July, 1996. WEB: http://move.to/moose ____________________________________________________
# Создайте функцию generate_csv_file(file_name, rows), которая будет генерировать по три случайны числа # в каждой строке, от 100-1000 строк, и записывать их в CSV-файл. Функция принимает два аргумента: # # file_name (строка) - имя файла, в который будут записаны данные. # rows(целое число) - количество строк (записей) данных, которые нужно сгенерировать. # # Создайте функцию find_roots(a, b, c), которая будет находить корни квадратного уравнения вида ax^2 + bx + c = 0. # Функция принимает три аргумента: # # a, b, c (целые числа) - коэффициенты квадратного уравнения. # # Функция возвращает: # None, если уравнение не имеет корней (дискриминант отрицателен). # Одно число, если уравнение имеет один корень (дискриминант равен нулю). # Два числа (корни), если уравнение имеет два корня (дискриминант положителен). # # Создайте декоратор save_to_json(func), который будет оборачивать функцию find_roots. Декоратор выполняет # следующие действия: # # Читает данные из CSV-файла, переданного в аргументе функции, исходя из аргумента args[0]. # Для каждой строки данных вычисляет корни квадратного уравнения с помощью функции find_roots. # Сохраняет результаты в формате JSON в файл results.json. Каждая запись JSON содержит параметры a, b, c # и результаты вычислений. # Таким образом, после выполнения функций generate_csv_file и find_roots в файле results.json будет сохранена информация # о параметрах и результатах вычислений для каждой строки данных из CSV-файла. # # Пример # # На входе: # # generate_csv_file("input_data.csv", 101) # find_roots("input_data.csv") # # with open("results.json", 'r') as f: # data = json.load(f) # # if 100<=len(data)<=1000: # print(True) # else: # print(f"Количество строк в файле не находится в диапазоне от 100 до 1000.") # # print(len(data)==101) # # На выходе: # # True # True # # Формат JSON файла определён следующим образом: # # [ # {"parameters": [a, b, c], "result": result}, # {"parameters": [a, b, c], "result": result}, # ... # ] # Тест 1 # # generate_csv_file("input_data.csv", 101) # find_roots("input_data.csv") # # with open("results.json", 'r') as f: # data = json.load(f) # # if 100<=len(data)<=1000: # print(True) # else: # print(f"Количество строк в файле не находится в диапазоне от 100 до 1000.") # # print(len(data)==101) # Тест 2 # generate_csv_file("input_data.csv", 999) # find_roots("input_data.csv") # # with open("results.json", 'r') as f: # data = json.load(f) # # if 100<=len(data)<=1000: # print(True) # else: # print(f"Количество строк в файле не находится в диапазоне от 100 до 1000.") # # print(len(data)==999) # Тест 3 # generate_csv_file("input_data.csv", 1500) # find_roots("input_data.csv") # # with open("results.json", 'r') as f: # data = json.load(f) # # if 100<=len(data)<=1000: # print(True) # else: # print(f"Количество строк в файле не находится в диапазоне от 100 до 1000.") # # print(len(data)==1500) from typing import Callable import csv import json from random import randint INPUT_DATA_CSV = 'input_data.csv' RESULTS_JSON = 'results.json' DATA_ROWS = 101 MIN_DATA_ROWS = 100 MAX_DATA_ROWS = 1000 MIN_NUM = 1 MAX_NUM = 10 def save_to_json(func: Callable) -> Callable[[], None]: def wrapper(a: str) -> None: with open(a, 'r', newline='') as f: reader = csv.reader(f) results = [] for parameters in reader: parameters = [int(num) for num in parameters] results.append({'parameters': parameters, 'result': func(*parameters)}) with open(RESULTS_JSON, 'w') as f: json.dump(results, f, indent=2) return wrapper def generate_csv_file(file_name: str, rows: int) -> None: with open(file_name, 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) for _ in range(rows): line =\ [ randint(MIN_NUM, MAX_NUM), randint(MIN_NUM, MAX_NUM), randint(MIN_NUM, MAX_NUM), ] writer.writerow(line) @save_to_json def find_roots(a: [int, str], *args: int): if not isinstance(a, int): return b, c = args d = b ** 2 - 4 * a * c if d > 0: return ((-b + d ** 0.5) / (2 * a), (-b - d ** 0.5) / (2 * a)) elif d == 0: return (-b) / (2 * a) else: return None if __name__ == '__main__': generate_csv_file(INPUT_DATA_CSV, DATA_ROWS) find_roots(INPUT_DATA_CSV) with open(RESULTS_JSON, 'r') as f: data = json.load(f) if MIN_DATA_ROWS <= len(data) <= MAX_DATA_ROWS: print(True) else: print(f"Количество строк в файле не находится в диапазоне от 100 до 1000.") print(len(data) == DATA_ROWS)
# This function is part of renpass published under the GNU GPL 3 license. # See also: code_R_start_renpass.R and http://opensource.org/licenses/GPL-3.0 #----- # Name: # convertRegionMatrixToDpr # Description: # converts a matrix(timesteps x number_of_regions) # into a matrix(timesteps x number_of_dprs) # Arguments: # region_matrix matrix,numeric(timesteps * number_of_regions) # Region_dpr_assignment data.frame: region_vector(numeric), # dpr_number(numeric) # standard value: region_dpr_assignement # Details: # The region_matrix has the original regions with their region_id and the # dpr_matrix has the dispatch regions that are the region unit for the specific # calculation/scenario # Value: # dpr_matrix, numeric(timesteps * number_of_dpr) # Examples: # dpr_matrix <- convertRegionMatrixToDpr(wind_onshore_reg) #------------------------------------------ convertRegionMatrixToDpr <- function(region_matrix, Region_dpr_assignment = region_dpr_assignment){ idx <- match(Region_dpr_assignment$region_id, as.numeric(colnames(region_matrix))) region_dpr_assignment_list <- split(Region_dpr_assignment, Region_dpr_assignment$dpr_number) dpr_matrix <- sapply(region_dpr_assignment_list, function(x){ idx <- which(as.numeric(colnames(region_matrix)) %in% x$region_id) #rowSums needs two columns if(length(idx) == 1){ as.numeric(region_matrix[,idx]) }else{ rowSums(region_matrix[,idx]) } }) return(dpr_matrix) }
// // HomeViewController.swift // Factilicious // // Created by Arnav Arora on 02/05/20. // Copyright © 2020 Jayant Arora. All rights reserved. // import UIKit import Firebase class SavedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cleanFacts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "savedCell") as! SavedTableViewCell cell.factLabel.text = cleanFacts[indexPath.row] cell.selectionStyle = .none cell.delegate = self return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 280 } @IBOutlet weak var noneView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var saveSpinner: UIActivityIndicatorView! var defaults = UserDefaults.standard var ref: DatabaseReference? var handle: DatabaseHandle? var uid: String! var facts = [String] () var cleanFacts = [String] () override func viewDidLoad() { super.viewDidLoad() noneView.isHidden = false tableView.isHidden = true saveSpinner.startAnimating() // Assign delegate and DataSource tableView.delegate = self tableView.dataSource = self // Init UID and REF uid = defaults.string(forKey: "uid") ref = Database.database().reference() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) noneView.backgroundColor = UIColor(patternImage: UIImage(named: FactsViewController.backgroundImage!)!) // Bg self.tableView.backgroundView = UIImageView(image: UIImage(named: FactsViewController.backgroundImage!)) handle = ref?.child("Users").child(uid).child("Saved").observe(.childAdded, with: { (snapshot) in let fact = snapshot.value as! String self.facts.append(fact) self.cleanFacts = self.facts.removingDuplicates().reversed() self.tableView.reloadData() self.noneView.isHidden = true self.tableView.isHidden = false self.saveSpinner.stopAnimating() self.saveSpinner.isHidden = true }) } @IBAction func deleteAllPressed(_ sender: Any) { let alert = UIAlertController(title: "Notice", message: "Are you sure you want to delete all of your favourites? This action cannot be undone.", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "Delete", style: .destructive, handler: { (action) in self.ref?.child("Users").child(self.uid).child("Saved").setValue(nil) alert.dismiss(animated: true, completion: nil) self.performSegue(withIdentifier: "deleteSegue", sender: nil) })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: { (action) in alert.dismiss(animated: true, completion: nil) })) present(alert, animated: true, completion: nil) } } extension Array where Element: Hashable { func removingDuplicates() -> [Element] { var addedDict = [Element: Bool]() return filter { addedDict.updateValue(true, forKey: $0) == nil } } mutating func removeDuplicates() { self = self.removingDuplicates() } } extension SavedViewController: SaveCellDelegate { func didPressShare(fact: String) { // Instantiate Share View Controller let shareString = "I want to share this awesome fact with you!\n\n" + fact as Any let shareVC = UIActivityViewController (activityItems: [shareString], applicationActivities: nil) shareVC.popoverPresentationController?.sourceView = self.view // Present it self.present(shareVC, animated: true, completion: nil) } }
import { useEffect, useRef } from "react"; import { CSSTransition } from "react-transition-group"; import { useReactRedux, useLockedBody } from "../../hooks"; import { modalClear, modalClose } from "../../redux/modal/modal.slice"; import { selectModalIsOpen, selectModalWithCloseButton, selectModalMain, selectModalMainProps, selectModalSizeType, } from "../../redux/modal/modal.selectors"; import { Close } from "../../svg"; import "./modal.css"; function Modal() { const { dispatch, useSelector } = useReactRedux(); const isOpened = useSelector(selectModalIsOpen); const withCloseButton = useSelector(selectModalWithCloseButton); const size = useSelector(selectModalSizeType); const Main = useSelector(selectModalMain); const mainProps = useSelector(selectModalMainProps); const ref = useRef<HTMLDivElement>(null); const { setLocked } = useLockedBody(); useEffect(() => { setLocked(isOpened); }, [isOpened, setLocked]); const close = () => { dispatch(modalClose()); }; const onEntered = () => { if (ref.current) { ref.current.focus(); } }; const onExited = () => { dispatch(modalClear()); }; return ( <CSSTransition in={isOpened} timeout={{ enter: 600, exit: 1050 }} nodeRef={ref} classNames="modal" onEntered={onEntered} onExited={onExited} unmountOnExit > <div ref={ref} tabIndex={0} role="button" className="modal"> <div className="modal__body" data-modal-size={size}> {withCloseButton && ( <button type="button" className="modal__close" onClick={close}> <Close className="modal__icon" /> </button> )} {Main && <Main {...mainProps} />} </div> </div> </CSSTransition> ); } export default Modal;
import { uuidv4 } from '@firebase/util'; import { doc, serverTimestamp, setDoc } from 'firebase/firestore'; import { getDownloadURL, ref, uploadBytes } from 'firebase/storage'; import React, { useRef, useState } from 'react'; import { styled } from 'styled-components'; import { auth, db, storage } from '../shared/firebase'; import { useDispatch, useSelector } from 'react-redux'; import { done, load } from '../redux/modules/loadingReducer'; import Loading from '../components/ui/Loading'; import { useNavigate } from 'react-router-dom'; const PostAdd = () => { const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const [imageFile, setImageFile] = useState(null); const [imageUrl, setImageUrl] = useState(null); const [inputImg, setInputImg] = useState(''); const dispatch = useDispatch(); const isLoading = useSelector((state) => state.loadingReducer.isLoading); const fileInput = useRef(); const user = auth.currentUser; const displayName = user.displayName; const photoURL = user.photoURL; const navigate = useNavigate(); const postToAdd = { id: uuidv4(), title, content, user: user.uid, timestamp: serverTimestamp(), image: imageFile, nickname: displayName, likeBox: [], photoURL }; const onSubmit = (e) => { e.preventDefault(); }; const titleChangeHandler = (event) => { setTitle(event.target.value); }; const contentChangeHandler = (event) => { setContent(event.target.value); }; // 이미지 미리보기 const imageChangeHandler = (event) => { const file = event.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(file); return new Promise((resolve) => { reader.onload = () => { setImageFile(reader.result || null); resolve(); }; setImageUrl(file); }); }; const cancelBtn = () => { navigate('/mypage'); }; // 업로드 버튼 const uploadHandler = async () => { const uploadCheck = window.confirm('등록하시겠습니까?'); if (uploadCheck) { if (title === '') { alert('제목을 입력해주세요'); return; } if (!inputImg && !imageUrl) { alert('이미지를 업로드해주세요'); return; } if (content === '') { alert('설명을 입력해주세요'); return; } try { dispatch(load()); await setDoc(doc(db, 'Post', postToAdd.id), postToAdd); const imageRef = ref(storage, `${displayName}/Post-image`); await uploadBytes(imageRef, imageUrl); await getDownloadURL(imageRef); dispatch(done()); navigate(`/detailpage/${postToAdd.id}`); } catch (error) { console.error(error); } } else { return; } }; // 등록하기 전에 이미지 업로드했다가 삭제 const imageDeleteBtn = () => { const deleteCheck = window.confirm('삭제하시겠습니까?'); if (deleteCheck) { setImageFile(null); setInputImg(null); fileInput.current.value = ''; } else { return; } }; return ( <div> {isLoading ? ( <Loading /> ) : ( <Container> <FormWrap onSubmit={onSubmit}> <InputTitle value={title} type='text' onChange={titleChangeHandler} placeholder='제목을 입력해주세요(최대 15자)' maxLength={15} /> <div style={{ width: '100vw', borderTop: '1px solid black', marginBottom: '50px' }} ></div> <ButtonWrap> <ImageInput id='inputFile' type='file' ref={fileInput} accept='image/*' value={inputImg} style={{ display: 'none' }} onChange={(e) => imageChangeHandler(e)} /> <ImgUploadButton htmlFor='inputFile'>O</ImgUploadButton> <ImgDeleteButton onClick={imageDeleteBtn}>X</ImgDeleteButton> </ButtonWrap> <ImageWrap> <Img src={imageFile} /> {!imageFile && <Span>이미지를 업로드해주세요</Span>} </ImageWrap> <InputContent value={content} type='text' onChange={contentChangeHandler} placeholder='설명을 입력해주세요(최대 300자)' maxLength={300} /> <ButtonWrap> <Button onClick={uploadHandler}>등록하기</Button> <Button onClick={cancelBtn}>취소하기</Button> </ButtonWrap> </FormWrap> </Container> )} </div> ); }; const Container = styled.div` display: flex; justify-content: center; /* background-color: green; */ width: 100vw; height: 200vh; `; const FormWrap = styled.form` display: flex; justify-content: center; align-items: center; flex-direction: column; width: 80vw; height: 180vh; `; const InputTitle = styled.input` display: flex; justify-content: center; width: 760px; height: 120px; font-size: 50px; font-family: GmarketSansMedium; margin: 150px auto 30px auto; padding: 20px; border: none; outline: none; `; const ImageWrap = styled.div` display: flex; justify-content: center; flex-direction: column; width: 800px; height: 800px; background-color: white; margin: 0 auto; border: 2px solid black; overflow: hidden; `; const Span = styled.span` padding-bottom: 400px; text-align: center; font-size: 20px; color: gray; font-family: GmarketSansMedium; `; const ImageInput = styled.input` width: 150px; height: 30px; /* display: none; */ `; const ImgUploadButton = styled.label` display: flex; justify-content: center; align-items: center; width: 40px; height: 40px; background-color: white; border: 2px solid black; cursor: pointer; &:hover { transform: scale(1.1); transition: all 0.2s; } `; const ImgDeleteButton = styled.button` width: 40px; height: 40px; background-color: white; border: 2px solid black; margin-left: 10px; cursor: pointer; &:hover { transform: scale(1.1); transition: all 0.3s; } `; const Img = styled.img` width: 100%; height: 100%; object-fit: cover; `; const InputContent = styled.textarea` display: flex; justify-content: center; width: 760px; height: 300px; padding: 20px; margin: 50px auto 0 auto; font-size: 22px; font-family: GmarketSansMedium; line-height: 35px; resize: none; background: none; border-width: 0 0 2px; border-color: black; outline: none; `; const ButtonWrap = styled.div` width: 800px; display: flex; justify-content: flex-end; margin: 10px; `; const Button = styled.button` width: 150px; height: 50px; font-size: 20px; font-family: GmarketSansLight; background-color: ${(props) => props.theme.mainColor}; color: white; border: none; border-radius: 100px; margin: 30px 0 0 30px; cursor: pointer; &:hover { transform: scale(1.1); transition: all 0.3s; } `; export default PostAdd;
import { ArticleLayout } from '@/components/ArticleLayout' import Image from 'next/image' export const meta = { author: 'Nathan Galindo', date: '2023-01-09', title: 'Rust Generics, Traits, and Lifetimes', tag: "programming", description: 'The Rust programming language is a tool which allows programmers to write incredibly performant code via the use of novel features, namely: generics, traits, and lifetimes.', } export default (props) => <ArticleLayout meta={meta} {...props} /> ## Objectives > * Understand generic types, traits and lifetimes > * Understand modules ## Generics Generics are simply stand-ins for other concrete types or properties. This way, we can express the behavior of generics without knowing what will be in their place at compile time. An example of a generic would be the `T` type in `Vec<T>` or `Option<T>`: - For `Vec<T>`, we are declaring a vector of some unknown data type, `T`. - For `Option<T>`, we are specifying that the `Option` enum will return a `Some` value of `T`. **Function Definitions** We use generics to create definitions for functions or structs, and then apply those definitions to concrete data types. The example below shows a function that finds the largest number in a vector in integers: ```rust fn largest(list: &[u32]) -> u32 { let mut largest = list[0]; for &num in list.iter() { if num > largest { largest = num; } } largest } ``` The example below shows a function that finds the largest item n a vector, using generic types in its function definition: ```rust use std::cmp::PartialOrd; fn generic_largest<T: PartialOrd>(list: &[T]) -> T { let mut largest = list[0]; for &num in list.iter() { if num > largest { largest = num; } } largest } ``` Although the `generic_largest` function definition looks nearly identical to that of `largest`, `generic_largest`'s use of the `T` generic type allows this function to be applicable to a variety of concrete data types, rather than just a vector of `u32` types. Take note of the `std::cmp::PartialOrd`. This is an example of a *trait*, and it allows us to define a generic type `T` that has the ability to be ordered. More on this later… **Struct Definitions** You can use generic types in structs for a given parameter or multiple parameters using the `<>` syntax. Below is an example of a `Coordinates` struct that uses the `T` generic type: ```rust fn main() { struct Coordinates<T> { x: T, y: T } } ``` Above, we define a struct called `Coordinates` that has two parameters, `x` and `y`. Both parameters are generic over some type `T`, and both `x` and `y` have the same type. - *Why does the following example result in an error?* It results in an error because the function definition states that `x` and `y` both have the same data type `T`. However, we are instantiating a `Coordinates` struct using two different data types: a `u32` and `f32`. ```rust fn main() { struct Coordinates<T> { x: T, y: T } return Coordinates { x: 1, y: 2.0 }; } ``` Below is an example of a struct that uses generic types in its function definition, but allows the assignment of different data types to its parameters: ```rust fn main() { struct Coordinates<T, U> { x: T, y: U } return Coordinates { x: 5, y: 3.4 }; } ``` To define a struct or function where its parameters use multiple data types, use multiple generic parameters. You can use as many generic parameters as you want, but the more you have the harder you code is to read. **Enum Definitions** We can define enum definitions to hold generic types in their variants. A good example of an enum that uses generic types is the `Option<T>` enum. The `Option<T>` enum is generic over type `T` and holds two values: - `Some<T>`: holds an unspecified value of type `T`. - `None`: indicates the absence of a value. The `Option<T>` enum is excellent for when you want to call a method that might or might not return some kind of value. Enum definitions are also able to use multiple generic types as well. <aside> 🤔 **Fun Fact** > Rust does not run any slower when we use generic types. This is accomplished through *monomorphization*, where the generic code is turned into specific code by filling in the concrete types at compile time. </aside> ## Traits Traits specify the behaviors of any given type. The behaviors of a type include the methods and functions that we can call on that type. For example: the `.floor()` method applies only to floating-point values, and cannot be used on a char. The char and a floating-point data types have different behaviors that determine that the `.floor()` method does not work for char. Traits are a way of grouping types together according to their functionalities. Traits are especially useful when we want to use a generic type `T`, but still impose some restrictions on what kind of values can inhabit `T`. **Trait Implementations** We declare a trait using the `trait` keyword. Below, we define a trait called `Summary` for two different structs (`Tweet` and `Article`) that both use `String` data: ```rust fn main() { // defining default behavior for a trait pub trait Summary { fn summarize_content(&self) -> String; // default implementations can call other methods fn summarize(&self) -> String { format!("Content: {}", self.summarize_content()) } } pub struct Article { pub headline: String, pub author: String, pub content: String } // syntax for implementing a trait on a struct impl Summary for Article { fn summarize_author(&self) -> String { format!("{}", self.author) } } pub struct Tweet { pub author: String, pub content: String } // syntax for implementing a trait on a struct impl Summary for Tweet { fn summarize_author(&self) -> String { format!("{}", self.author) } } let tweet = Tweet { author: String::from("nathanzebedee"), content: String::from("this is a tweet") }; tweet.summarize(); } ``` Above, we are declaring a trait with default behaviors: `summarize` and `summarize_author`. It is important to note that default implementations (`summarize`) can call other methods in the same trait (`summarize_author`), even if those methods do not have default implementations. In our example, the `summarize` method has a default implementation that calls the `summarize_author` method. In this example, we only need to define `summarize_author` when we implement the trait on a type. Implementing a trait on a type differs from implementing regular methods in the way that you must declare the trait name (`Summary`), use the `for` keyword, and then specify the name of the type we want to to implement the trait for (`Tweet`, or `Article`). **Trait Bounds** Trait bounds are constraints on our generic types that insists they adhere to certain traits or behaviors defined by the programmer. In an earlier example, you saw the use of the `std::cmp::PartialOrd` trait bound which restricted our generic type `T` from being any type that does not implement the `PartialOrd` trait. We place trait bounds with a declaration of the generic type, after a colon and inside angle brackets: ```rust fn example_fn<T: Clone>(number: T) -> i32 { // ... } ``` There is also an alternative syntax for declaring trait bounds in which we use the `where` clause after a function signature: ```rust fn example_fn<T>(number: T) -> i32 where T: Clone { // ... } ``` Whether you use the `where` clause to define your trait bounds or not is entirely up to your own preference. There is no performance difference. ## Lifetimes In an earlier lesson, we discussed references (which are pointers to owned values in memory). An important detail to understand regarding references is that every reference has a *lifetime*. The lifetime of a reference simple refers to how long (and in which scope(s)) the reference is valid for. The primary goal of lifetimes is to prevent dangling references (or pointers). Most of the time, lifetimes are implicit and do not need to be typed out. However, when the lifetimes of multiple references could be related, we must be explicit. Lifetime annotations describe the relationships of the lifetimes of multiple references to each other without affecting the lifetimes. **Syntax rules for declaring lifetime parameters** - We place lifetime parameter annotations after the `&` of a reference - All lifetime parameters must start with a single quote `'`. - The names of lifetime parameters are usually kept short. ```rust fn main() { &i32 // immutable reference &'a i32 // immutable reference with an explicit lifetime &'a mut i32 // mutable reference with an explicit lifetime } ``` - *The code example below does not yet compile. Why is this?* Because string slices `&str` are both references, they have lifetimes associated with them. The `longest` function receives two references, and returns one. At compile time, the compiler is unable to determine which reference will be returned. In order to fix this issue, we must annotate the lifetimes of the two references in our function definition. ```rust // notice that we use `&str` in our function signature instead of `&String`. // `&str` is preferable because then we can use the same function on both `String` and `&str` values fn longest(x: &str, y: &str) -> &str { if x.len() > y.len() { x } else { y } } ``` Below, we rewrite the function definition of `longest` using generic lifetime parameters: ```rust fn longest<'a>( x: &'a str, y: &'a str ) -> &'a str { if x.len() > y.len() { x } else { y } } ``` In the example above, we’re not changing the lifetimes of any reference. We are simply telling the borrow checker to reject any values that do not adhere to these constraints. The `longest` function definition states the following: *for some lifetime `'a`, the function takes two references `&str`, both of which live at least as long as lifetime `'a`.* When returning a reference from a function, the lifetime parameter for a return type needs to match the lifetime parameter for one of the parameters. Lifetime syntax is about connecting the lifetimes of various parameters and return values of functions. Lifetimes on function or method parameters are called *input lifetimes*. Lifetimes on return types are called *output lifetimes*. **Lifetime Annotations in Struct Definitions** Structs can hold references as well as owned values, but we must add a lifetime to the struct definition for every reference: ```rust pub struct Example<'a, 'b> { content: &'a str, author: &'b str } fn main() { use super::*; let example = Example { content: "This is an example", author: "nathanzebedee" }; } ``` The lifetime annotations `'a` and `'b` mean that an instance of `Example` cannot outlive the reference it holds in its `content` or `author` fields. **The Static Lifetime** The `'static` lifetime is a special lifetime in Rust which applies to all string literals, and denotes the entire duration of the program. This is because string literals are stored directly into the binary of our program, which is always available. ```rust fn main() { let string_literal: 'static str = "I am a string literal"; } ``` **Elision Rules** The Rust compiler uses a set of rules called the *Elision Rules* to determine what lifetimes references have when there aren’t explicit annotations: 1. Each parameter that is a reference gets its own lifetime. 2. If there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters. 3. If there are multiple input lifetime parameters, but one of them is a `&self` or `&mut self`, then the lifetime of `self` is assigned to all output lifetime parameters. <aside> 🤔 **Fun Fact** > The core Rust team is constantly observing Rust community code to determine if there are any deterministic patters where the compiler can automatically infer the lifetime of our references. That being said, as the Rust programming language matures, it is entirely possible that we will need to explicitly annotate our lifetimes less and less. </aside> **All Together Now** Now, let’s view an example using generic types, traits, and lifetimes: ```rust use std::fmt::Display; fn longest<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str where T: Display { println!("Accouncement: {}", ann); if x.len() > y.len() { x } else { y } } ``` ## Modules Modules are meant to organize your code into reusable components. In the same way you extract lines of code into functions, you can extract functions into modules. A *module* is a namespace that contains definitions of functions or types, and you can choose whether those definitions are visible outside their module (`pub`) or private. **Overview Module Rules an Syntax** - To define a module, use the `mod` keyword and follow it with a name. The name should be lowercase and snake case (i.e., `module_example`). - Functions, types, constants, and modules are *private by default*. use the `pub` keyword to make them visible outside their namespace. - The `use` keyword brings modules (or the definitions inside them) into scope so it’s easier to refer to them. Below is an example of accessing a function inside a module: ```rust pub mod module_ex { pub fn example() -> String { String::from("ex") } } fn main() { // syntax for accessing functions inside a module let string_ex = module_ex::example(); println!("{}", string_ex); } ``` - *Why does the following code fail to compile?* Because `mod_one` exists outside the namespace of `mod_two`, we need to give `mod_two` the `use super::*` statement in order to access items in the parent scope. ```rust mod mod_one { pub fn ex() -> String { String::from("ex") } } mod mod_two { pub fn call_ex() -> String { mod_one::ex() } } fn main() { let string_ex = mod_two::call_ex(); println!("{}", string_ex); } ``` Typically, we separate modules into their own files named after themselves. In practice, it is best to create an entire folder dedicated to some specific function or type definitions and include a `[mod.rs](http://mod.rs)` file that will modularize the code and make it public for the rest of your code to access.
package com.zero.ddd.akka.cluster.core.initializer; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Semaphore; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.event.EventListener; import com.typesafe.config.Config; import com.zero.ddd.akka.cluster.core.helper.ClientAskRemoteExecutorConfig; import com.zero.ddd.akka.cluster.core.initializer.actor.IAsSpawnActor; import com.zero.ddd.akka.cluster.core.initializer.config.AkkaClusterProperties; import com.zero.ddd.akka.cluster.core.initializer.config.AkkaOverrideConfig; import com.zero.ddd.akka.cluster.core.initializer.config.IOverriderAkkaClusterConfig; import com.zero.ddd.akka.cluster.core.initializer.event.AkkaClusterCommand; import com.zero.ddd.akka.cluster.core.initializer.event.AkkaClusterLifecycleEvent; import com.zero.helper.GU; import akka.actor.typed.ActorSystem; import akka.actor.typed.Behavior; import akka.actor.typed.DispatcherSelector; import akka.actor.typed.javadsl.Behaviors; import lombok.extern.slf4j.Slf4j; import scala.concurrent.ExecutionContextExecutor; /** * * @say little Boy, don't be sad. * @name Rezar * @time 2022-06-29 04:17:44 * @Desc 些年若许,不负芳华. * * akka cluster 启动入口 * */ @Slf4j public class AkkaClusterServerInitialization { @Autowired private AkkaClusterProperties clusterConfig; @Autowired private ApplicationContext context; private Semaphore startSemaphore = new Semaphore(1); private Semaphore stopSemaphore = new Semaphore(1); private ActorSystem<Void> system; @EventListener(AkkaClusterCommand.class) public void onLifecycleEvent( AkkaClusterCommand event) { if (event == AkkaClusterCommand.DO_START) { this.doStartAkkaCluster(); } else if (event == AkkaClusterCommand.DO_STOP) { this.doStopAkkaCluster(); } } private void doStopAkkaCluster() { if (!stopSemaphore.tryAcquire()) { return; } this.notifyClusterBeforeStop(); this.system.terminate(); try { this.system.getWhenTerminated() .toCompletableFuture() .whenComplete((done, error) -> { this.notifyClusterStoped(); log.info( "Cluster [{}] Terminated, bye bye ~~~", clusterConfig.getClusterName()); }) .join(); } catch (Exception e) { log.error("error stop akka cluster:{}", e); } } private void doStartAkkaCluster() { if (!startSemaphore.tryAcquire()) { return; } // 存在dns配置,进行映射 clusterConfig.initDnsMapper(); AkkaOverrideConfig overrideConfig = new AkkaOverrideConfig(); // 覆盖默认配置 this.overrideConfig(overrideConfig); Config config = overrideConfig.parseAllConfig( this.clusterConfig.getAkkaConfigLoad()); this.notifyClusterBeforeStart(); this.system = ActorSystem.create( RootBehavior.create( this.initActores()), this.clusterConfig.getClusterName(), config); final ExecutionContextExecutor blockEx = system.dispatchers() .lookup( DispatcherSelector.fromConfig("blocking-io-dispatcher")); ClientAskRemoteExecutorConfig.configAskRemoteExecutor(blockEx); this.notifyClusterStarted(); log.info("Cluster [{}] start successful - ^_^", clusterConfig.getClusterName()); } private List<IAsSpawnActor> initActores() { Map<String, IAsSpawnActor> beansOfType = this.context.getBeansOfType( IAsSpawnActor.class); return beansOfType .entrySet() .stream() .map(entry -> entry.getValue()) .collect(Collectors.toList()); } private void notifyClusterBeforeStart() { context.publishEvent( AkkaClusterLifecycleEvent.BEFORE_START); } private void notifyClusterBeforeStop() { context.publishEvent( AkkaClusterLifecycleEvent.BEFORE_STOP); } private void notifyClusterStarted() { context.publishEvent( AkkaClusterLifecycleEvent.STARTED); } private void notifyClusterStoped() { context.publishEvent( AkkaClusterLifecycleEvent.STOPED); } private static class RootBehavior { static Behavior<Void> create( List<IAsSpawnActor> initActores) { return Behaviors.setup(context -> { if (GU.notNullAndEmpty(initActores)) { initActores.stream() .forEach(as -> { as.spawn(context); }); } return Behaviors.empty(); }); } } private Map<String, Object> overrideConfig( AkkaOverrideConfig overrideConfig) { Map<String, Object> sourceOverrideMap = new HashMap<>(); this.iOverriderAkkaClusterConfiges() .stream() .sorted( Comparator.comparing( IOverriderAkkaClusterConfig::order)) .forEach(override -> { override.doOverride( clusterConfig, overrideConfig); }); return sourceOverrideMap; } private Collection<IOverriderAkkaClusterConfig> iOverriderAkkaClusterConfiges() { return this.context.getBeansOfType( IOverriderAkkaClusterConfig.class) .entrySet() .stream() .map(entry -> entry.getValue()) .collect(Collectors.toList()); } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ import expect from '@kbn/expect'; import { TopNodesRequestRT, TopNodesResponseRT, } from '@kbn/infra-plugin/common/http_api/overview_api'; import { decodeOrThrow } from '@kbn/infra-plugin/common/runtime_types'; import { FtrProviderContext } from '../../ftr_provider_context'; import { DATES } from './constants'; export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const supertest = getService('supertest'); describe('API /metrics/overview/top', () => { before(() => esArchiver.load('x-pack/test/functional/es_archives/infra/7.0.0/hosts')); after(() => esArchiver.unload('x-pack/test/functional/es_archives/infra/7.0.0/hosts')); it('works', async () => { const { min, max } = DATES['7.0.0'].hosts; const response = await supertest .post('/api/metrics/overview/top') .set({ 'kbn-xsrf': 'some-xsrf-token', }) .send( TopNodesRequestRT.encode({ sourceId: 'default', bucketSize: '300s', size: 5, timerange: { from: min, to: max, }, }) ) .expect(200); const { series } = decodeOrThrow(TopNodesResponseRT)(response.body); expect(series.length).to.be(1); expect(series[0].id).to.be('demo-stack-mysql-01'); expect(series[0].timeseries[1].timestamp - series[0].timeseries[0].timestamp).to.be(300_000); }); describe('Runtime fields calculation', () => { before(() => esArchiver.load('x-pack/test/functional/es_archives/infra/8.0.0/hosts_and_network') ); after(() => esArchiver.unload('x-pack/test/functional/es_archives/infra/8.0.0/hosts_and_network') ); it('should return correct sorted calculations', async () => { const { min, max } = DATES['8.0.0'].hosts_and_netowrk; const response = await supertest .post('/api/metrics/overview/top') .set({ 'kbn-xsrf': 'some-xsrf-token', }) .send( TopNodesRequestRT.encode({ sourceId: 'default', bucketSize: '300s', size: 5, timerange: { from: min, to: max, }, sort: 'rx', sortDirection: 'asc', }) ) .expect(200); const { series } = decodeOrThrow(TopNodesResponseRT)(response.body); const hosts = series.map((s) => ({ name: s.name, rx: s.rx, tx: s.tx, })); expect(hosts.length).to.be(3); expect(hosts[0]).to.eql({ name: 'metricbeat-2', rx: 8000, tx: 16860 }); expect(hosts[1]).to.eql({ name: 'metricbeat-1', rx: 11250, tx: 25290.5 }); expect(hosts[2]).to.eql({ name: 'metricbeat-3', rx: null, tx: null }); }); }); }); }
// Custom Joint Grab Attach|GrabAttachMechanics|50060 namespace VRTK.GrabAttachMechanics { using UnityEngine; /// <summary> /// The Custom Joint Grab Attach script allows a custom joint to be provided for the grab attach mechanic. /// </summary> /// <remarks> /// The custom joint is placed on the interactable object and at runtime the joint is copied into a `JointHolder` game object that becomes a child of the interactable object. /// /// The custom joint is then copied from this `JointHolder` to the interactable object when a grab happens and is removed when a grab ends. /// </remarks> /// <example> /// `VRTK/Examples/021_Controller_GrabbingObjectsWithJoints` demonstrates this grab attach mechanic on the Lamp object in the scene. /// </example> [AddComponentMenu("VRTK/Scripts/Interactions/Grab Attach Mechanics/VRTK_CustomJointGrabAttach")] public class VRTK_CustomJointGrabAttach : VRTK_BaseJointGrabAttach { [Tooltip("The joint to use for the grab attach joint.")] public Joint customJoint; protected GameObject jointHolder; protected override void Initialise() { base.Initialise(); CopyCustomJoint(); } protected override void CreateJoint(GameObject obj) { if (!jointHolder) { VRTK_Logger.Error(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.REQUIRED_COMPONENT_MISSING_NOT_INJECTED, "VRTK_CustomJointGrabAttach", "Joint", "customJoint", "the same")); return; } var storedJoint = jointHolder.GetComponent<Joint>(); var storeName = gameObject.name; VRTK_SharedMethods.CloneComponent(storedJoint, obj, true); gameObject.name = storeName; givenJoint = obj.GetComponent(storedJoint.GetType()) as Joint; base.CreateJoint(obj); } protected override void DestroyJoint(bool withDestroyImmediate, bool applyGrabbingObjectVelocity) { base.DestroyJoint(true, true); } protected virtual void CopyCustomJoint() { if (customJoint) { jointHolder = new GameObject(); jointHolder.transform.SetParent(transform); jointHolder.AddComponent<Rigidbody>().isKinematic = true; VRTK_SharedMethods.CloneComponent(customJoint, jointHolder, true); jointHolder.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, "JointHolder"); jointHolder.SetActive(false); Destroy(customJoint); customJoint = jointHolder.GetComponent<Joint>(); } } } }
from ad.models import MiniAd, Studio from django.db import models from django.utils import timezone class StudioStatistic(models.Model): class Meta: verbose_name = 'Статистика студий' verbose_name_plural = 'Статистика студий' db_table = "StudioStatistic" studio = models.ForeignKey(Studio, on_delete=models.CASCADE) date = models.DateField('Дата', default=timezone.now) views = models.IntegerField('Просмотры', default=0) telegram_clicks = models.IntegerField('Нажатий на Telegram', default=0) website_clicks = models.IntegerField('Нажатий на вебсайт', default=0) phone_clicks = models.IntegerField('Нажатий на телефон', default=0) def __str__(self): return self.studio.name class MiniAdStatistic(models.Model): class Meta: verbose_name = 'Статистика мини рекламы' verbose_name_plural = 'Статистика мини рекламы' db_table = "MiniAdStatistic" mini_ad = models.ForeignKey(MiniAd, on_delete=models.CASCADE) date = models.DateField('Дата', default=timezone.now) views = models.IntegerField('Просмотры', default=0) clicks = models.IntegerField('Нажатий на рекламу', default=0) def __str__(self): return self.mini_ad.name
from fastapi import FastAPI, HTTPException from pydantic import BaseModel, constr from databases import Database app = FastAPI() # URL для PostgreSQL (измените его под свою БД) DATABASE_URL = "postgresql://postgres:vasea01@localhost/postgres" database = Database(DATABASE_URL) @app.on_event("startup") async def startup_database(): await database.connect() @app.on_event("shutdown") async def shutdown_database(): await database.disconnect() class User(BaseModel): username: str password: constr(min_length=6, max_length=16) fake_db = [{'username': 'olajda', 'password': '12345767'}] # создание роута для создания юзеров @app.post("/users", response_model=User) async def create_user(user: User): query = "INSERT INTO users (username, password) VALUES (:username, :password)" values = {"username": user.username, "password": user.password} try: await database.execute(query=query, values=values) return user except Exception as e: print(f"Error creating user: {e}") raise HTTPException(status_code=500, detail="Failed to create user") @app.get("/users/{username}", response_model=User) async def get_user(username: str): query = "SELECT * FROM users WHERE username = :username" values = {"username": username} try: result = await database.fetch_one(query=query, values=values) except Exception as e: raise HTTPException(status_code=500, detail="Failed to fetch user from database") if result is None: raise HTTPException(status_code=404, detail="User not found") # Создаем экземпляр UserReturn на основе данных из базы данных user_data = dict(result) return User(**user_data) @app.put("/users/{username}", response_model=User) async def update_user(username: str, new_user: User): query = "UPDATE users SET username = :new_username, password = :password WHERE username = :old_username" values = {"new_username": new_user.username, "password": new_user.password, "old_username": username} try: await database.execute(query=query, values=values) return {**new_user.dict(), "username": new_user.username} except Exception as e: raise HTTPException(status_code=500, detail="Failed to update user in database")
#pragma once # include<string> class Employee { public: Employee(std::string, int, std::string); //constructor with parameters void setName(std::string); //setter for name std::string getName(void) const; //getter for name void setEmployeeID(int); //setter for employee D int getEmployeeID(void) const; //getter for employee ID void setPosition(std::string);//setter for position std::string getPosition(void) const; //getter for position void display(void) const; //display info for employee ~Employee();//destructor private: std::string name; int employeeID; std::string position; };
package dynamicprogramming_decisionmaking; /** * Say you have an array for which the ith element is the price of a given stock * on day i. * * If you were only permitted to complete at most one transaction (i.e., buy one * and sell one share of the stock), design an algorithm to find the maximum * profit. * * Note that you cannot sell a stock before you buy one. * * Input: [7,1,5,3,6,4] Output: 5 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. * Not 7-1 = 6, as selling price needs to be larger than buying price. * * Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is * done, i.e. max profit = 0. * * */ public class BestTimeToBuyAndSellStock { public static void main(String[] args) { int[] prices = {1, 3, 2, 8, 4, 9}; System.out.println(maxProfit(prices)); System.out.println(maxProfit1(prices)); } public static int maxProfit(int prices[]) { int buy = Integer.MIN_VALUE; int sell = 0; for (int price :prices){ buy = Math.max(buy,-price); sell = Math.max(sell,price+buy); } return sell; } public static int maxProfit1(int prices[]) { int buy = Integer.MAX_VALUE; int sell = 0; for (int price :prices){ buy = Math.min(buy,price); sell = Math.max(sell,price-buy); } return sell; } }
// // GHTimePickerView.swift // GuahaoWithChat // // Created by Jeff Wong on 15/11/8. // Copyright © 2015年 Jeff. All rights reserved. // import UIKit protocol GHTimePickerViewDelegate: NSObjectProtocol { func pickerDidCancel() func pickerDidConfirm(date: NSDate) } class GHTimePickerView: UIView { weak var delegate: GHTimePickerViewDelegate? private var timeStamp: Double let datePickerView = UIDatePicker() init(frame: CGRect, timeStamp: Float) { self.timeStamp = Double(timeStamp) super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupSubviews() { backgroundColor = UIColor(white: 0, alpha: 0.5) let centerView = UIView() let titleLabel = UILabel() let negativeBtn = UIButton() let positiveBtn = UIButton() let seperateLine1 = UIView() let seperateLine2 = UIView() centerView.backgroundColor = UIColor.whiteColor() centerView.layer.cornerRadius = 5 centerView.layer.borderWidth = 0.5 centerView.layer.borderColor = UIColor.grayColor().CGColor centerView.layer.shadowColor = UIColor.grayColor().CGColor centerView.layer.shadowOffset = CGSizeMake(0, 0) centerView.clipsToBounds = true titleLabel.text = "选择时间" titleLabel.textAlignment = .Center titleLabel.textColor = UIColor.blackColor() datePickerView.datePickerMode = .Time datePickerView.minimumDate = NSDate(timeIntervalSince1970: timeStamp) datePickerView.maximumDate = NSDate(timeIntervalSince1970: timeStamp + 86400) negativeBtn.setTitle("取消", forState: .Normal) negativeBtn.setTitleColor(UIColor.blueColor(), forState: .Normal) negativeBtn.addTarget(self, action: Selector("cancel"), forControlEvents: .TouchUpInside) positiveBtn.setTitle("确定", forState: .Normal) positiveBtn.setTitleColor(UIColor.blueColor(), forState: .Normal) positiveBtn.addTarget(self, action: Selector("confirm"), forControlEvents: .TouchUpInside) seperateLine1.backgroundColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1) seperateLine2.backgroundColor = seperateLine1.backgroundColor centerView.addSubview(titleLabel) centerView.addSubview(datePickerView) centerView.addSubview(negativeBtn) centerView.addSubview(positiveBtn) centerView.addSubview(seperateLine1) centerView.addSubview(seperateLine2) addSubview(centerView) let centerHeight = datePickerView.frame.height + 60 let centerWidth = datePickerView.frame.width - 60 centerView.snp_makeConstraints { (make) -> Void in make.height.equalTo(centerHeight) make.width.equalTo(centerWidth) make.center.equalTo(self) } titleLabel.snp_makeConstraints { (make) -> Void in make.top.left.right.equalTo(centerView) make.height.equalTo(30) } datePickerView.snp_makeConstraints { (make) -> Void in make.left.right.equalTo(centerView) make.top.equalTo(titleLabel.snp_bottom) make.bottom.equalTo(seperateLine1.snp_top) } seperateLine1.snp_makeConstraints { (make) -> Void in make.top.equalTo(datePickerView.snp_bottom) make.left.right.equalTo(centerView) make.bottom.equalTo(negativeBtn.snp_top) make.width.equalTo(centerView) make.height.equalTo(0.5) } negativeBtn.snp_makeConstraints { (make) -> Void in make.left.equalTo(centerView) make.top.equalTo(seperateLine1.snp_bottom) make.right.equalTo(seperateLine2.snp_left) make.bottom.equalTo(centerView) make.width.equalTo(positiveBtn) } seperateLine2.snp_makeConstraints { (make) -> Void in make.top.equalTo(seperateLine1.snp_bottom) make.left.equalTo(negativeBtn.snp_right) make.right.equalTo(positiveBtn.snp_left) make.bottom.equalTo(centerView) make.width.equalTo(0.5) } positiveBtn.snp_makeConstraints { (make) -> Void in make.left.equalTo(seperateLine2.snp_right) make.top.equalTo(negativeBtn.snp_top) make.right.bottom.equalTo(centerView) make.width.equalTo(negativeBtn) } } // MARK: 以动画显示到指定view func show(view: UIView) { runAsyncOnMainThread { self.alpha = 0 view.addSubview(self) UIView.animateWithDuration(0.2) { self.alpha = 1 } } } // MARK: 隐藏 func hide() { runAsyncOnMainThread { UIView.animateWithDuration( 0.2, animations: { () -> Void in self.alpha = 0 }, completion: { (_) -> Void in self.removeFromSuperview() }) } } // MARK: 取消按钮 func cancel() { hide() delegate?.pickerDidCancel() } // MARK: 确认按钮 func confirm() { hide() delegate?.pickerDidConfirm(datePickerView.date) } }
import tkinter as tk from tkinter import StringVar, ttk, filedialog, simpledialog from typing import Optional from preset_options.PresetProcessor import PresetProcessor from preset_options.Preset import Preset from Model import Model class PresetOptions: """PresetOptions Class.""" tab: ttk.Frame model: Model processor: PresetProcessor loadedPreset: Optional[Preset] = None def __init__(self, root: ttk.Notebook, model: Model): """Main Frame and driver for the Preset Options tab.""" self.tab = ttk.Frame(root) self.model = model self.processor = PresetProcessor(self.model) self.set_Var = tk.IntVar() # set up and place title and content frames self.title_frame = ttk.Frame(self.tab, padding=25) self.content_frame = ttk.Frame(self.tab, padding=25) self.title_frame.grid(row=0, column=0) self.content_frame.grid(row=1, column=0) # add title ttk.Label(self.title_frame, text="Preset Options", style="Heading.TLabel").grid() # set up and place preview and control frames self.control_frame = ttk.Frame(self.content_frame) self.preview_frame = ttk.Frame(self.content_frame) self.set_frame = ttk.Frame(self.content_frame) self.control_frame.grid(row=0, column=0, padx=(20, 50)) self.preview_frame.grid(row=0, column=1) self.set_frame.grid(row=1,column=0,padx=(20,40)) # create and place buttons inside control frame, disable apply button self.select_button = ttk.Button( self.control_frame, text="Select Preset", width=15, command=self.browse) self.apply_button = ttk.Button( self.control_frame, text='Apply This Preset', width=15, command=lambda: self.apply_preset()) self.create_button = ttk.Button( self.control_frame, text="Create New Preset", width=15, command=self.create_preset) self.select_button.grid(column=0, row=0) ttk.Label(self.control_frame, text=' ').grid(column=0, row=1) self.apply_button.grid(column=0, row=2) ttk.Label(self.control_frame, text=' ').grid(column=0, row=3) self.create_button.grid(column=0, row=4) self.enable_apply_preset() #create set choice self.set_select_label = ttk.Label(self.set_frame, text = 'Select which set you would like this preset to apply to: ') self.set_select_label.grid(column=0,row=0) # create and place widgets for param preview frame display self.param_input_vars = {param: StringVar() for param in self.model.ALL_PARAMS} self.param_input_labels = [ttk.Label(self.preview_frame, text=param, width=10) for param in self.model.ALL_PARAMS] self.param_inputs = [ttk.Label(self.preview_frame, textvariable=self.param_input_vars[param], width=7) for param in self.model.ALL_PARAMS] for i in range(3): for j in range(6): self.param_input_labels[i * 6 + j].grid(column=i * 2, row=j + 1, padx=15, pady=15) self.param_inputs[i * 6 + j].grid(column=i * 2 + 1, row=j + 1, padx=15, pady=15) root.add(self.tab, text='Preset Options') def onSelect(self): """This method is called when the notebook switched the view to this tab.""" self.enable_apply_preset() for index, motor_dict in enumerate(self.model.live_motors_sets): self.radbutton = ttk.Radiobutton(self.set_frame, text = f"Set {index +1}: Motors {list(motor_dict.keys())}\n", variable=self.set_Var, value=index, command=self.selectedSet()) self.radbutton.grid(column=0,row=index+1) def selectedSet(self): pass def browse(self): """Function to browse for desired preset file. Need to change to correct starting directory""" filename = filedialog.askopenfilename( initialdir='Presets', title="Select a Preset CSV File") try: self.loadedPreset = self.processor.processPreset(filename) for key in self.loadedPreset .all_row: self.param_input_vars[key].set(self.loadedPreset .all_row[key]) self.enable_apply_preset() except: self.model.LOGGER.debug( "Internal Error: Could not open the specified file name.") def apply_preset(self): if (self.loadedPreset is not None) and (self.set_Var is not None): selected_Set = self.model.live_motors_sets[self.set_Var.get()] for mot_num, motor in selected_Set.items(): for key, value in self.loadedPreset.rows[mot_num].items(): motor.write_params[key] = value def create_preset(self): filename = simpledialog.askstring( 'Create New Preset', 'Enter name of new preset:') if type(filename) is str: self.processor.create_preset(filename) def enable_apply_preset(self): if (self.loadedPreset == None): self.apply_button['state'] = 'disabled' else: self.apply_button['state'] = 'normal'
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js" import axios from "axios" import React, { useState } from 'react' const CARD_OPTIONS = { iconStyle: "solid", style: { base: { iconColor: "#c4f0ff", fontWeight: 500, fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif", fontSize: "16px", fontSmoothing: "antialiased", ":-webkit-autofill": { color: "#fce883" }, "::placeholder": { color: "#87bbfd" } }, invalid: { iconColor: "#ffc7ee", color: "#ffc7ee" } } } export default function PaymentForm(amount) { const [success, setSuccess] = useState(false) const stripe = useStripe() const elements = useElements() const handleSubmit = async (e) => { e.preventDefault() // const response = await axios.post("http://35.74.25.58/api/generate_payment_intent", { // amount: amount.amount, // paymentMethod: 'card', // }) // console.log(response.data) try { const response = await axios.post("http://35.74.25.58/api/generate_payment_intent", { amount: amount.amount, paymentMethod: 'card', }) console.log("first-->",response.data) const cardElement = elements.getElement(CardElement); const confirmPayment = await stripe.confirmCardPayment( response.data.seceret , { payment_method: { card: cardElement } } ); console.log("sec->",confirmPayment); const { paymentIntent } = confirmPayment; if (paymentIntent.status === "succeeded") alert(`Payment successful!`); else alert(`Payment failed!`); } catch (err) { console.error(err); } // const { error, paymentMethod } = await stripe.confirmCardPayment({ // type: "card", // card: elements.getElement(CardElement), // }) // console.log("stripe-->", paymentMethod) // if (!error) { // try { // const response = await axios.post("http://35.74.25.58/api/generate_payment_intent", { // amount: amount.amount, // paymentMethod: 'card', // name:"xyz", // email:'xddhcjnyrz@example.com', // }) // console.log("2nd", response) // if (response.data) { // const res = await axios.post("http://35.74.25.58/api/payment", { // pi: response.data.payment_intent, // pm: paymentMethod.id, // customer: response.data.customer, // }) // console.log("3rd-->", res) // if (res.data) { // if (res.data.status == "requires_action") { // const resp = await axios.post("http://35.74.25.58/api/td_secure_payment", { // pi: response.data.payment_intent, // return_url: res.data.next_action.use_stripe_sdk.stripe_js, // pm: paymentMethod.id, // }) // // console.log("res-4", resp) // console.log("-->4rd", resp) // console.log("url", resp.data.next_action.redirect_to_url.url) // // window.location = res.data.next_action.use_stripe_sdk.stripe_js // window.location = resp.data.next_action.redirect_to_url.url; // // console.log("res-4", resp) // console.log("Successful payment") // setSuccess(true) // } // } // } // } catch (error) { // console.log("Error", error) // } // if (pi && pm) { // try { // console.log(pi, pm) // const response = await axios.post("http://35.74.25.58/api/payment", { // pi, // pm // }) // console.log("3rd-->", response) // if (response.data) { // if (response.data.status == "requires_action") { // const resp = await axios.post(response.data.next_action.use_stripe_sdk.stripe_js) // console.log("res-4", resp) // console.log("Successful payment") // console.log(pi, pm) // setSuccess(true) // } // } // } catch (error) { // console.log("Error", error) // } // }else{ // console.log("id not found") // } // } else { // console.log(error.message) // } } return ( <> <form > <fieldset className="FormGroup"> <div className="FormRow"> <CardElement options={CARD_OPTIONS} /> </div> </fieldset> <button onClick={handleSubmit}>Pay</button> </form> </> ) }
-- Creating tables for PH-EmployeeDB CREATE TABLE departments( dept_no VARCHAR (4) NOT NULL, dept_name VARCHAR (40) NOT NULL, PRIMARY KEY (dept_no), UNIQUE (dept_name) ); CREATE TABLE employees( emp_no INT NOT NULL, birth_date DATE NOT NULL, first_name VARCHAR NOT NULL, last_name VARCHAR NOT NULL, gender VARCHAR NOT NULL, hire_date DATE NOT NULL, PRIMARY KEY (emp_no) ); CREATE TABLE dept_manager( dept_no VARCHAR NOT NULL, emp_no INT NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (emp_no) REFERENCES employees (emp_no), FOREIGN KEY (dept_no) REFERENCES departments (dept_no), PRIMARY KEY (emp_no, dept_no) ); CREATE TABLE salaries ( emp_no INT NOT NULL, salary INT NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (emp_no) REFERENCES employees (emp_no), PRIMARY KEY (emp_no) ); CREATE TABLE employee_dept( emp_no INT NOT NULL, dept_no VARCHAR NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (dept_no) REFERENCES departments (dept_no), FOREIGN KEY (emp_no) REFERENCES employees (emp_no), PRIMARY KEY (emp_no, dept_no) ); CREATE TABLE titles( emp_no INT NOT NULL, title VARCHAR NOT NULL, from_date DATE NOT NULL, to_date DATE NOT NULL, FOREIGN KEY (emp_no) REFERENCES employees (emp_no), PRIMARY KEY (emp_no, title, from_date) ); SELECT * FROM departments; -- Retirement Eligibility SELECT first_name, last_name FROM employees WHERE birth_date BETWEEN '1952-01-01' AND '1955-12-31'; -- Find employees with birth dates in 1952 SELECT first_name, last_name FROM employees WHERE birth_date BETWEEN '1952-01-01' AND '1952-12-31' -- Find employees with birth dates in 1953 SELECT first_name, last_name FROM employees WHERE birth_date BETWEEN '1953-01-01' AND '1953-12-31'; -- Find employees with birth dates in 1954 SELECT first_name, last_name FROM employees WHERE birth_date BETWEEN '1954-01-01' AND '1954-12-31'; -- Find employees with birth dates in 1955 SELECT first_name, last_name FROM employees WHERE birth_date BETWEEN '1955-01-01' AND '1955-12-31'; -- Retirement Eligibility SELECT first_name, last_name FROM employees WHERE (birth_date BETWEEN '1952-01-01' AND '1955-12-31') AND (hire_date BETWEEN '1985-01-01' AND '1988-12-31'); -- Number of employees retiring SELECT COUNT(first_name) FROM employees WHERE (birth_date BETWEEN '1952-01-01' AND '1955-12-31') AND (hire_date BETWEEN '1985-01-01' AND '1988-12-31'); -- Create a Retirement Info table to then export to CSV SELECT first_name, last_name INTO retirement_info FROM employees WHERE (birth_date BETWEEN '1952-01-01' AND '1955-12-31') AND (hire_date BETWEEN '1985-01-01' AND '1988-12-31'); SELECT * FROM retirement_info; DROP TABLE retirement_info; -- Create a Retirement Info table to include emp_no SELECT emp_no, first_name, last_name INTO retirement_info FROM employees WHERE (birth_date BETWEEN '1952-01-01' AND '1955-12-31') AND (hire_date BETWEEN '1985-01-01' AND '1988-12-31'); SELECT * FROM retirement_info; -- Joining departments and dept_manager tables SELECT departments.dept_name, dept_manager.emp_no, dept_manager.from_date, dept_manager.to_date FROM departments INNER JOIN dept_manager ON departments.dept_no = dept_manager.dept_no; -- Joining retirement_info and dept_emp tables SELECT retirement_info.emp_no, retirement_info.first_name, retirement_info.last_name, employee_dept.to_date FROM retirement_info LEFT JOIN employee_dept ON retirement_info.emp_no = employee_dept.emp_no; -- Joining retirement_info and dept_emp tables using Aliases SELECT ri.emp_no, ri.first_name, ri.last_name, ed.to_date FROM retirement_info as ri LEFT JOIN employee_dept as ed ON ri.emp_no = ed.emp_no; -- Join retirement_info and employee_dept tables to create a table current_emp SELECT ri.emp_no, ri.first_name, ri.last_name, ed.to_date INTO current_emp FROM retirement_info as ri LEFT JOIN employee_dept as ed ON ri.emp_no = ed.emp_no WHERE ed.to_date = ('9999-01-01'); -- Employee count by department number SELECT COUNT(ce.emp_no), ed.dept_no INTO dept_emp_count FROM current_emp as ce LEFT JOIN employee_dept as ed ON ce.emp_no = ed.emp_no GROUP BY ed.dept_no ORDER BY ed.dept_no; SELECT * FROM salaries ORDER BY to_date DESC; SELECT emp_no, first_name, last_name, gender INTO emp_info FROM employees WHERE (birth_date BETWEEN '1952-01-01' AND '1955-12-31') AND (hire_date BETWEEN '1985-01-01' AND '1988-12-31'); -- List of employee information SELECT e.emp_no, e.first_name, e.last_name, e.gender, s.salary, ed.to_date -- INTO emp_info From employees as e INNER JOIN salaries as s ON (e.emp_no = s.emp_no) INNER JOIN employee_dept as ed ON (e.emp_no = ed.emp_no) WHERE (birth_date BETWEEN '1952-01-01' AND '1955-12-31') AND (hire_date BETWEEN '1985-01-01' AND '1988-12-31') AND (ed.to_date = '9999-01-01'); -- List of managers per department SELECT dm.dept_no, d.dept_name, dm.emp_no, ce.last_name, ce.first_name, dm.from_date, dm.to_date INTO manager_info FROM dept_manager AS dm INNER JOIN departments AS d ON (dm.dept_no = d.dept_no) INNER JOIN current_emp AS ce ON (dm.emp_no = ce.emp_no); SELECT * FROM manager_info; -- List of Department Retirees SELECT ce.emp_no, ce.first_name, ce.last_name, d.dept_name INTO dept_info FROM current_emp as ce INNER JOIN employee_dept as ed ON (ce.emp_no = ed.emp_no) INNER JOIN departments as d ON (ed.dept_no = d.dept_no); SELECT * FROM dept_info; DROP TABLE sales_info; -- Sales Retirement List SELECT ri.emp_no, ri.first_name, ri.last_name, d.dept_name INTO sales_info FROM retirement_info as ri INNER JOIN employee_dept as ed ON (ri.emp_no = ed.emp_no) INNER JOIN departments as d ON (ed.dept_no = d.dept_no) WHERE d.dept_name = ('Sales'); SELECT * FROM sales_info; DROP TABLE sales_develop_info; -- Sales Retirement List SELECT ri.emp_no, ri.first_name, ri.last_name, d.dept_name INTO sales_develop_info FROM retirement_info as ri INNER JOIN employee_dept as ed ON (ri.emp_no = ed.emp_no) INNER JOIN departments as d ON (ed.dept_no = d.dept_no) WHERE d.dept_name IN ('Sales', 'Development'); SELECT * FROM sales_develop_info; ---CHALLENGE CODE---- -- Create a table showing the number of retiring employees by title SELECT e.emp_no, e.first_name, e.last_name, t.title, t.from_date,t.to_date INTO ee_retiring_title FROM employees AS e INNER JOIN titles as t ON e.emp_no = t.emp_no WHERE e.birth_date BETWEEN '1952-01-01' AND '1955-12-31' ORDER BY e.emp_no; SELECT * FROM ee_retiring_title -- Use Dictinct with Orderby to remove duplicate rows SELECT DISTINCT ON (rt.emp_no) rt.emp_no, first_name, last_name, title INTO unique_titles FROM ee_retiring_title as rt ORDER BY rt.emp_no, rt.to_date DESC; SELECT * FROM unique_titles -- Retrieve the number of employees by their most recent job title who are about to retire SELECT COUNT(emp_no), title INTO retiring_titles FROM unique_titles GROUP BY title ORDER BY COUNT (emp_no) DESC; SELECT * FROM retiring_titles -- Create Mentorship Eligibility table SELECT DISTINCT ON (e.emp_no) e.emp_no, e.first_name, e.last_name, e.birth_date, ed.from_date, ed.to_date, t.title INTO mentorship_eligibility FROM employees AS e INNER JOIN employee_dept AS ed ON e.emp_no = ed.emp_no INNER JOIN titles AS t ON e.emp_no = t.emp_no WHERE ed.to_date = ('9999-01-01') AND e.birth_date BETWEEN '1965-01-01' AND '1965-12-31' ORDER BY e.emp_no; SELECT * FROM mentorship_eligibility
<mat-accordion> <mat-expansion-panel hideToggle [expanded]="true" > <mat-expansion-panel-header [@.disabled]="true" expandedHeight="150px" collapsedHeight="60px"> <mat-panel-title> Bet1 </mat-panel-title> </mat-expansion-panel-header> <form [formGroup]="form" (submit)="onSend()" id="editForm"> <h2 matDialogTitle>New Config</h2> <mat-label>Config name</mat-label> <input matInput type="text" name="title" formControlName="ConfigName" [ngClass]="{ 'is-invalid': f.ConfigName.errors}"/> <div *ngIf="f.ConfigName.touched && f.ConfigName.invalid" class="text-danger"> <p *ngIf="f.ConfigName.errors?.required" style="color: red">ConfigName is required.</p> </div> <div> <input type="checkbox" class="example-margin" formControlName="Home">Home <input type="checkbox" class="example-margin" formControlName="Favourite">Favourite <input type="checkbox" class="example-margin" formControlName="PreGame">Pre Game </div> <div class="wrapper"> <div id="SportsBook"> <label for="sportsbookInput">SportsBook:</label> <input matInput type="text" name="SportsBook" id="sportsbookInput" formControlName="SportsBook"> <div *ngIf="f.SportsBook.touched && f.SportsBook.invalid" class="text-danger"> <p *ngIf="f.SportsBook.errors?.required" style="color: red">SportsBook is required.</p> </div> </div> <div id="LineMax"> <label for="linemaxInput">LineMax:</label> <input matInput type="text" name="LineMax" id="linemaxInput" formControlName="LineMax"/> <div *ngIf="f.LineMax.touched && f.LineMax.invalid" class="text-danger"> <p *ngIf="f.LineMax.errors?.required" style="color: red">LineMax is required.</p> </div> </div> </div> <div class="wrapper"> <div id="GameTime"> <label for="gametimeInput" >GameTime:</label> <input matInput type="text" name="GameTime" id="gametimeInput" formControlName="GameTime"/> <div *ngIf="f.GameTime.touched && f.GameTime.invalid" class="text-danger"> <p *ngIf="f.GameTime.errors?.required" style="color: red">GameTime is required.</p> </div> </div> <div> <label for="linemin" >LineMin:</label> <input matInput type="text" name="LineMin" id="linemin" formControlName="LineMin"/> <div *ngIf="f.LineMin.touched && f.LineMin.invalid" class="text-danger"> <p *ngIf="f.LineMin.errors?.required" style="color: red">LineMin is required.</p> </div> </div> </div> <div> <mat-label>Bet on movement:</mat-label> <input matInput type="text" name="BetOnMovement" id="betOnMovementInput" formControlName="BetOnMovement"/> <div *ngIf="f.BetOnMovement.touched && f.BetOnMovement.invalid" class="text-danger"> <p *ngIf="f.BetOnMovement.errors?.required" style="color: red">BetOnMovement is required.</p> </div> </div> <mat-dialog-actions align="end"> <button mat-button matDialogClose="no">Cancel</button> <button type="submit" mat-button [disabled]="!form.valid">Submit</button> </mat-dialog-actions> </form> </mat-expansion-panel> <mat-expansion-panel [expanded]="false"> <mat-expansion-panel-header [@.disabled]="true" expandedHeight="100px" collapsedHeight="60px"> <mat-panel-title> Bet2 </mat-panel-title> </mat-expansion-panel-header> <form [formGroup]="bet2" (submit)="onSend()"> <div> <input type="checkbox" class="example-margin" formControlName="Home">Home <input type="checkbox" class="example-margin" formControlName="PreGame">PreGame </div> <div class="wrapper"> <div id="SportsBookBet2"> <label for="SportsBookBet2Input">SportsBook:</label> <input matInput type="text" name="SportsBook" id="SportsBookBet2Input" formControlName="SportsBook"> <div *ngIf="f.SportsBook.touched && f.SportsBook.invalid" class="text-danger"> <p *ngIf="f.SportsBook.errors?.required" style="color: red">SportsBook is required.</p> </div> </div> <div id="LineMaxBet2"> <label for="LineMaxBet2Input">LineMax:</label> <input matInput type="text" name="LineMax" id="LineMaxBet2Input" formControlName="LineMax"/> <div *ngIf="f.LineMax.touched && f.LineMax.invalid" class="text-danger"> <p *ngIf="f.LineMax.errors?.required" style="color: red">LineMax is required.</p> </div> </div> </div> <div class="wrapper"> <div id="GameTimeBet2"> <label for="GameTimeBet2Input" >GameTime:</label> <input matInput type="text" name="GameTime" id="GameTimeBet2Input" formControlName="GameTime"/> <div *ngIf="f.GameTime.touched && f.GameTime.invalid" class="text-danger"> <p *ngIf="f.GameTime.errors?.required" style="color: red">GameTime is required.</p> </div> </div> <div> <label for="lineminBet2" >LineMin:</label> <input matInput type="text" name="LineMin" id="lineminBet2" formControlName="LineMin"/> <div *ngIf="f.LineMin.touched && f.LineMin.invalid" class="text-danger"> <p *ngIf="f.LineMin.errors?.required" style="color: red">LineMin is required.</p> </div> </div> </div> <input type="checkbox" class="example-margin" ([ngModel])="Qualification">Qualification <div *ngIf ="Qualification">lala</div> <div> <mat-label>referenceLine:</mat-label> <input matInput type="text" name="BetOnMovement" id="referenceLine" formControlName="referenceLine"/> <div *ngIf="f.BetOnMovement.touched && f.BetOnMovement.invalid" class="text-danger"> <p *ngIf="f.BetOnMovement.errors?.required" style="color: red">BetOnMovement is required.</p> </div> </div> <div> <mat-label>range:</mat-label> <input matInput type="text" name="BetOnMovement" id="range" formControlName="range"/> <div *ngIf="f.BetOnMovement.touched && f.BetOnMovement.invalid" class="text-danger"> <p *ngIf="f.BetOnMovement.errors?.required" style="color: red">BetOnMovement is required.</p> </div> </div> <div> <mat-label>period:</mat-label> <input matInput type="text" name="BetOnMovement" id="period" formControlName="period"/> <div *ngIf="f.BetOnMovement.touched && f.BetOnMovement.invalid" class="text-danger"> <p *ngIf="f.BetOnMovement.errors?.required" style="color: red">BetOnMovement is required.</p> </div> </div> <div> <mat-label>BetOfRecovery:</mat-label> <input matInput type="text" name="BetOnMovement" id="BetOfRecovery" formControlName="BetOfRecovery"/> <div *ngIf="f.BetOnMovement.touched && f.BetOnMovement.invalid" class="text-danger"> <p *ngIf="f.BetOnMovement.errors?.required" style="color: red">BetOnMovement is required.</p> </div> </div> <mat-dialog-actions align="end"> <button mat-button matDialogClose="no">Cancel</button> <button type="submit" mat-button [disabled]="!form.valid">Submit</button> </mat-dialog-actions> </form> </mat-expansion-panel> </mat-accordion>
echo "# SampleTokenizeTSLAstock" >> README.md git init git add README.md git commit -m "first commit" git branch -M main git remote add origin https://github.com/iantstaley/SampleTokenizeTSLAstock.git git push -u origin main pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; contract TeslaStockToken is ERC20 { AggregatorV3Interface internal priceFeed; constructor() ERC20("Tesla Stock Token", "TSLA") { priceFeed = AggregatorV3Interface(0x8A791620dd6260079BF849Dc5567aDC3F2FdC318); _mint(msg.sender, 1000000 * 10 ** decimals()); } function updateTokenPrice() public { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); uint decimals = priceFeed.decimals(); uint priceInWei = uint(price) * 10 ** (18 - decimals); uint tokenPrice = priceInWei / 100; _setPrice(tokenPrice); } function _setPrice(uint price) internal { // Set the token price to the latest price fetched from the Chainlink Oracle } }
package com.project.DuAnTotNghiep.service.serviceImpl; import com.project.DuAnTotNghiep.controller.QRCodeService; import com.project.DuAnTotNghiep.dto.Product.ProductDetailDto; import com.project.DuAnTotNghiep.dto.Product.ProductDto; import com.project.DuAnTotNghiep.dto.ProductSearchDto; import com.project.DuAnTotNghiep.dto.Product.SearchProductDto; import com.project.DuAnTotNghiep.entity.Product; import com.project.DuAnTotNghiep.entity.ProductDetail; import com.project.DuAnTotNghiep.exception.NotFoundException; import com.project.DuAnTotNghiep.exception.ShopApiException; import com.project.DuAnTotNghiep.repository.ProductDetailRepository; import com.project.DuAnTotNghiep.repository.ProductRepository; import com.project.DuAnTotNghiep.repository.Specification.ProductSpecification; import com.project.DuAnTotNghiep.service.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import java.io.IOException; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class ProductServiceImpl implements ProductService { @Autowired private ProductRepository productRepository; @Autowired private ProductDetailRepository productDetailRepository; @Override public Page<Product> getAllProduct(Pageable pageable0) { return productRepository.findAll(pageable0); } @Override public Page<ProductSearchDto> getAll(Pageable pageable) { return productRepository.getAll(pageable); } @Override public Product save(Product product) throws IOException { if(product.getCode().trim() == "" || product.getCode() == null) { Product productCurrent = productRepository.findTopByOrderByIdDesc(); Long nextCode = (productCurrent == null) ? 1 : productCurrent.getId() + 1; String productCode = "SP" + String.format("%04d", nextCode); product.setCode(productCode); } Double minPrice = Double.valueOf(1000000000); for (ProductDetail productDetail: product.getProductDetails()) { if(productDetail.getPrice() < minPrice) { minPrice = productDetail.getPrice(); } QRCodeService.generateQRCode(productDetail.getBarcode(), productDetail.getBarcode()); } product.setPrice(minPrice); product.setDeleteFlag(false); product.setCreateDate(LocalDateTime.now()); product.setUpdatedDate(LocalDateTime.now()); return productRepository.save(product); } @Override public void delete(Long id) throws NotFoundException { Product product = productRepository.findById(id).orElseThrow( () -> new NotFoundException("Product not found")); product.setDeleteFlag(true); productRepository.save(product); } @Override public Product getProductByCode(String code) { Product product = productRepository.findByCode(code); if(product != null) { return product; } return null; } @Override public boolean existsByCode(String code) { return productRepository.existsByCode(code); } public Page<Product> search(String productName, Pageable pageable) { Page<Product> page = productRepository.searchProductName(productName, pageable); return page; } @Override public Page<ProductSearchDto> listSearchProduct(String maSanPham, String tenSanPham, Long nhanHang, Long chatLieu, Long theLoai,Integer trangThai, Pageable pageable) { Page<ProductSearchDto> productSearchDtos = productRepository.listSearchProduct(maSanPham,tenSanPham,nhanHang,chatLieu,theLoai,trangThai,pageable); return productSearchDtos; } @Override public Page<Product> getAllByStatus(int status, Pageable pageable) { return productRepository.findAllByStatusAndDeleteFlag(status, false, pageable); } @Override public Optional<Product> getProductById(Long id) { return productRepository.findById(id); } @Override public Page<ProductDto> searchProduct(SearchProductDto searchDto, Pageable pageable) { Specification<Product> spec = new ProductSpecification(searchDto); Page<Product> products = productRepository.findAll(spec, pageable); return products.map(this::convertToDto); } @Override public Page<ProductDto> getAllProductApi(Pageable pageable) { Page<Product> productPage = productRepository.findAllByDeleteFlagFalse(pageable); return productPage.map(this::convertToDto); } @Override public ProductDto getProductByBarcode(String barcode) { ProductDetail productDetail = productDetailRepository.findByBarcodeContainingIgnoreCase(barcode); if(productDetail == null) { throw new ShopApiException(HttpStatus.NOT_FOUND, "Không tìm thấy sản phẩm có mã vạch: " + barcode); } Product product = productDetail.getProduct(); ProductDto productDto = new ProductDto(); productDto.setId(product.getId()); productDto.setCode(product.getCode()); productDto.setName(product.getName()); productDto.setCategoryName(product.getCategory().getName()); productDto.setImageUrl(product.getImage().get(0).getLink()); productDto.setDescription(product.getDescribe()); productDto.setPriceMin(product.getProductDetails().get(0).getPrice()); productDto.setCreateDate(product.getCreateDate()); productDto.setUpdatedDate(product.getUpdatedDate()); List<ProductDetailDto> productDetailDtoList = new ArrayList<>(); ProductDetailDto productDetailDto = new ProductDetailDto(); productDetailDto.setId(productDetail.getId()); productDetailDto.setProductId(product.getId()); productDetailDto.setColor(productDetail.getColor()); productDetailDto.setSize(productDetail.getSize()); productDetailDto.setPrice(productDetail.getPrice()); productDetailDto.setQuantity(productDetail.getQuantity()); productDetailDto.setBarcode(productDetail.getBarcode()); productDetailDtoList.add(productDetailDto); productDto.setProductDetailDtos(productDetailDtoList); return productDto; } private ProductDto convertToDto(Product product) { ProductDto productDto = new ProductDto(); productDto.setId(product.getId()); productDto.setCode(product.getCode()); productDto.setName(product.getName()); productDto.setCategoryName(product.getCategory().getName()); productDto.setImageUrl(product.getImage().get(0).getLink()); productDto.setDescription(product.getDescribe()); productDto.setCreateDate(product.getCreateDate()); productDto.setUpdatedDate(product.getUpdatedDate()); List<ProductDetailDto> productDetailDtoList = new ArrayList<>(); Double priceMin = Double.valueOf(100000000); for (ProductDetail productDetail: product.getProductDetails()) { if(productDetail.getPrice() < priceMin) { priceMin = productDetail.getPrice(); } ProductDetailDto productDetailDto = new ProductDetailDto(); productDetailDto.setId(productDetail.getId()); productDetailDto.setProductId(product.getId()); productDetailDto.setColor(productDetail.getColor()); productDetailDto.setSize(productDetail.getSize()); productDetailDto.setPrice(productDetail.getPrice()); productDetailDto.setQuantity(productDetail.getQuantity()); productDetailDto.setBarcode(productDetail.getBarcode()); productDetailDtoList.add(productDetailDto); } productDto.setPriceMin(priceMin); productDto.setProductDetailDtos(productDetailDtoList); return productDto; } }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class Deck extends Component { render() { const { cardName, cardDescription, cardAttr1, cardAttr2, cardAttr3, cardImage, cardRare, cardTrunfo, onDeleteButtonClick, } = this.props; return ( <section> <div> <span data-testid="name-card" > { cardName } </span> </div> <div> <img data-testid="image-card" src={ cardImage } alt={ cardName } /> </div> <div> <span data-testid="description-card" > {cardDescription} </span> </div> <div> <span data-testid="attr1-card" > {cardAttr1} </span> </div> <div> <span data-testid="attr2-card" > {cardAttr2} </span> </div> <div> <span data-testid="attr3-card" > {cardAttr3} </span> </div> <div> <span data-testid="rare-card" > {cardRare} </span> { cardTrunfo ? <span data-testid="trunfo-card">Super Trunfo</span> : '' } </div> <button data-testid="delete-button" value={ cardName } type="button" onClick={ onDeleteButtonClick } > Excluir </button> </section> ); } } Deck.propTypes = { cardName: PropTypes.string.isRequired, cardDescription: PropTypes.string.isRequired, cardAttr1: PropTypes.string.isRequired, cardAttr2: PropTypes.string.isRequired, cardAttr3: PropTypes.string.isRequired, cardImage: PropTypes.string.isRequired, cardRare: PropTypes.string.isRequired, cardTrunfo: PropTypes.bool.isRequired, onDeleteButtonClick: PropTypes.func.isRequired, }; export default Deck;
import type { Request } from 'express'; import type { IWebhookFunctions } from 'n8n-workflow'; import { mock } from 'jest-mock-extended'; import { Webhook } from '../Webhook.node'; import { testWorkflows, getWorkflowFilenames } from '@test/nodes/Helpers'; const workflows = getWorkflowFilenames(__dirname); describe('Test Webhook Node', () => { testWorkflows(workflows); describe('handleFormData', () => { const node = new Webhook(); const context = mock<IWebhookFunctions>({ nodeHelpers: mock(), }); context.getNodeParameter.calledWith('options').mockReturnValue({}); context.getNode.calledWith().mockReturnValue({ type: 'n8n-nodes-base.webhook', typeVersion: 1.1, } as any); const req = mock<Request>(); req.contentType = 'multipart/form-data'; context.getRequestObject.mockReturnValue(req); it('should handle when no files are present', async () => { req.body = { files: {}, }; const returnData = await node.webhook(context); expect(returnData.workflowData?.[0][0].binary).toBeUndefined(); expect(context.nodeHelpers.copyBinaryFile).not.toHaveBeenCalled(); }); it('should handle when files are present', async () => { req.body = { files: { file1: {} }, }; const returnData = await node.webhook(context); expect(returnData.workflowData?.[0][0].binary).not.toBeUndefined(); expect(context.nodeHelpers.copyBinaryFile).toHaveBeenCalled(); }); }); });
/* * Copyright 2024 tison <wander4096@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tisonkun.git.core.plumbing.format.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.tisonkun.git.core.test.TestUtils; import java.io.File; import java.util.List; import org.junit.jupiter.api.Test; class ConfigTest { @Test public void testSample() throws Exception { // git configuration example from: https://git-scm.com/docs/git-config#_example final File file = new File(TestUtils.testResourceDir(), "gitconfig/sample-config.ini"); final Config config = Config.create(file); assertThat(config.hasSection("core")).isTrue(); final ConfigSection core = config.section("core"); assertThat(core.options()).hasSize(3); assertThat(core.option("filemode")).map(ConfigOption::value).hasValue("false"); assertThat(core.optionAll("gitproxy")) .map(ConfigOption::value) .containsExactlyInAnyOrder("ssh for kernel.org", "default-proxy"); assertThat(config.hasSection("diff")).isTrue(); final ConfigSection diff = config.section("diff"); assertThat(diff.options()).hasSize(2); assertThat(diff.option("external")).map(ConfigOption::value).hasValue("/usr/local/bin/diff-wrapper"); assertThat(diff.option("renames")).map(ConfigOption::value).hasValue("true"); assertThat(config.hasSection("branch")).isTrue(); final ConfigSection branch = config.section("branch"); assertThat(branch.subsections()).hasSize(1); final ConfigSubsection devel = branch.subsection("devel"); assertThat(devel.options()).hasSize(2); assertThat(devel.option("remote")).map(ConfigOption::value).hasValue("origin"); assertThat(devel.option("merge")).map(ConfigOption::value).hasValue("refs/heads/devel"); assertThat(config.hasSection("remote")).isTrue(); final ConfigSection remote = config.section("remote"); assertThat(remote.subsections()).hasSize(1); final ConfigSubsection origin = remote.subsection("origin"); assertThat(origin.options()).hasSize(1); assertThat(origin.option("url")).map(ConfigOption::value).hasValue("https://example.com/git"); final List<ConfigInclude> includes = config.includes(); assertThat(includes).hasSize(9); assertThat(includes) .containsExactlyInAnyOrder( new ConfigInclude(null, "/path/to/foo.inc"), new ConfigInclude(null, "foo.inc"), new ConfigInclude(null, "~/foo.inc"), new ConfigInclude("gitdir:/path/to/foo/.git", "/path/to/foo.inc"), new ConfigInclude("gitdir:~/to/group/", "/path/to/foo.inc"), new ConfigInclude("gitdir:/path/to/group/", "/path/to/foo.inc"), new ConfigInclude("gitdir:/path/to/group/", "foo.inc"), new ConfigInclude("onbranch:foo-branch", "foo.inc"), new ConfigInclude("hasconfig:remote.*.url:https://example.com/**", "foo.inc")); } @Test public void testCornerCase() throws Exception { final File file = new File(TestUtils.testResourceDir(), "gitconfig/corner-config.ini"); final Config config = Config.create(file); assertThat(config.sections()).hasSize(3); assertThat(config.hasSection("core")).isTrue(); final ConfigSection core = config.section("core"); assertThat(core.options()).hasSize(3); assertThat(core.option("filemode")).map(ConfigOption::value).hasValue("false"); assertThat(core.option("buttonoption")).map(ConfigOption::value).hasValue(""); assertThat(core.option("buttonoptionagain")).map(ConfigOption::value).hasValue(""); assertThat(config.hasSection("bar.baz")).isTrue(); final ConfigSection barBaz = config.section("bar.baz"); assertThat(barBaz.options()).hasSize(2); assertThat(barBaz.option("foo")).map(ConfigOption::value).hasValue("bar"); assertThat(barBaz.option("url")).map(ConfigOption::value).hasValue("https://example.com/git"); assertThat(config.hasSection("url")).isTrue(); final ConfigSubsection subsection = config.section("url").subsection("git@example.com:"); assertThat(subsection.options()).hasSize(1); final ConfigOption option = subsection.options().getFirst(); assertThat(option.key()).isEqualTo("insteadof"); assertThat(option.value()).isEqualTo("https://example.com/"); } @Test public void testMalformed() { final String[] messages = new String[] {"malformed section name", "malformed variable names", "malformed section name"}; for (int i = 0; i < messages.length; i++) { final String filename = "gitconfig/malformed-config-%s.ini".formatted(i + 1); final File file = new File(TestUtils.testResourceDir(), filename); assertThatThrownBy(() -> Config.create(file)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining(messages[i]); } } }
"use client" import Link from "next/link" import { useSelectedLayoutSegment } from "next/navigation" import { CellReport, CellReportAssistant, CellReportAttendees, Disciple, Lesson, } from "@prisma/client" import { format } from "date-fns" import { useSession } from "next-auth/react" import { cn } from "@/lib/utils" interface Props { report: CellReport & { attendees: CellReportAttendees[] lesson: Lesson | null leader: Disciple assistant: CellReportAssistant | null } } function CellReportListItem({ report }: Props) { const session = useSession() const segment = useSelectedLayoutSegment() const isCurrent = report.id === segment const isAdmin = session.data?.user?.role === "ADMIN" return ( <Link href={`/cell-reports/${report.id}`}> <div className={cn( "flex items-center justify-between rounded-lg border p-4 ring-2 ring-transparent hover:border-primary", { "ring-primary border-primary pointer-events-none": isCurrent } )} > <div> <h3 className="text-lg font-semibold tracking-tight"> {report.lesson_name ? report.lesson_name : report.lesson?.title} </h3> <p className="text-sm text-muted-foreground"> {format(report.date, "MMMM dd, yyyy")} &mdash; {report.time} </p> </div> {isAdmin && ( <span className="inline-block text-sm text-muted-foreground"> {report.leader.name} </span> )} </div> </Link> ) } export default CellReportListItem
package ru.yandex.practicum.filmorate.controller; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import ru.yandex.practicum.filmorate.model.Mpa; import ru.yandex.practicum.filmorate.repository.MpaRepository; import java.util.List; @Slf4j @RestController @RequestMapping("/mpa") @RequiredArgsConstructor public class MpaController { private final MpaRepository mpaRepository; @GetMapping(produces = "application/json") public List<Mpa> getMpaList() { log.info("Fetching all Mpa"); return mpaRepository.getMpaList(); } @GetMapping(path = "/{id}", produces = "application/json") public Mpa getMpa(@PathVariable long id) { log.info("Fetching Mpa with id: {}", id); return mpaRepository.getMpaById(id); } }
# 달팽이 숫자 # 달팽이는 1부터 N*N까지의 숫자가 시계방향으로 이루어져 있다. # 다음과 같이 정수 N을 입력 받아 N크기의 달팽이를 출력하시오. # [예제] # N이 3일 경우, # N이 4일 경우, # [제약사항] # 달팽이의 크기 N은 1 이상 10 이하의 정수이다. (1 ≤ N ≤ 10) # [입력] # 가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다. # 각 테스트 케이스에는 N이 주어진다. # [출력] # 각 줄은 '#t'로 시작하고, 다음 줄부터 빈칸을 사이에 두고 달팽이 숫자를 출력한다. # (t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.) # 입력 # 2 # 3 # 4 # 출력 # #1 # 1 2 3 # 8 9 4 # 7 6 5 # #2 # 1 2 3 4 # 12 13 14 5 # 11 16 15 6 # 10 9 8 7 T = int(input()) for tc in range(1, T+1): num = int(input()) num_list = [[0] * num for _ in range(num)] # 현재 위치 i, j = 0, 0 # 다음 위치 di, dj = 0, 1 for k in range(1, num*num + 1): num_list[i][j] = k if num_list[(i+di)%num][(j+dj)%num] != 0: di, dj = dj, -di i, j = i+di, j+dj print(f"#{tc}") for i in num_list: print(' '.join(map(str, i)))
/* * Copyright 2021 The Flink Remote Shuffle Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.flink.shuffle.e2e; import com.alibaba.flink.shuffle.e2e.util.WordCountData; import org.apache.flink.api.common.ExecutionMode; import org.apache.flink.api.common.InputDependencyConstraint; import org.apache.flink.api.common.RuntimeExecutionMode; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.MultipleParameterTool; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.ExecutionOptions; import org.apache.flink.runtime.jobgraph.JobType; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.graph.GlobalStreamExchangeMode; import org.apache.flink.streaming.api.graph.StreamGraph; import org.apache.flink.util.Collector; import org.apache.flink.util.Preconditions; /** * Implements the "WordCount" program that computes a simple word occurrence histogram over text * files in a streaming fashion. * * <p>The input is a plain text file with lines separated by newline characters. * * <p>Usage: <code>WordCount --input &lt;path&gt; --output &lt;path&gt;</code><br> * If no parameters are provided, the program is run with default data from {@link WordCountData}. * * <p>This example shows how to: * * <ul> * <li>write a simple Flink Streaming program, * <li>use tuple data types, * <li>write and use user-defined functions. * </ul> */ public class WordCount { // ************************************************************************* // PROGRAM // ************************************************************************* public static void main(String[] args) throws Exception { // Checking input parameters final MultipleParameterTool params = MultipleParameterTool.fromArgs(args); // set up the execution environment Configuration configuration = new Configuration(); configuration.set(ExecutionOptions.RUNTIME_MODE, RuntimeExecutionMode.BATCH); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration); // make parameters available in the web interface env.getConfig().setGlobalJobParameters(params); env.getConfig().setExecutionMode(ExecutionMode.BATCH); env.getConfig().setParallelism(1); env.getConfig().setDefaultInputDependencyConstraint(InputDependencyConstraint.ALL); // get input data DataStream<String> text = null; if (params.has("input")) { // union all the inputs from text files for (String input : params.getMultiParameterRequired("input")) { if (text == null) { text = env.readTextFile(input); } else { text = text.union(env.readTextFile(input)); } } Preconditions.checkNotNull(text, "Input DataStream should not be null."); } else { System.out.println("Executing WordCount example with default input data set."); System.out.println("Use --input to specify file input."); // get default test text data text = env.fromElements(WordCountData.WORDS); } DataStream<Tuple2<String, Integer>> counts = text.flatMap(new Tokenizer()).keyBy(value -> value.f0).sum(1); // emit result if (params.has("output")) { counts.writeAsText(params.get("output")); } else { System.out.println("Printing result to stdout. Use --output to specify output path."); counts.print(); } StreamGraph streamGraph = env.getStreamGraph(); streamGraph.setGlobalStreamExchangeMode(GlobalStreamExchangeMode.ALL_EDGES_BLOCKING); streamGraph.setJobType(JobType.BATCH); // execute program env.execute(streamGraph); } // ************************************************************************* // USER FUNCTIONS // ************************************************************************* /** * Implements the string tokenizer that splits sentences into words as a user-defined * FlatMapFunction. The function takes a line (String) and splits it into multiple pairs in the * form of "(word,1)" ({@code Tuple2<String, Integer>}). */ public static final class Tokenizer implements FlatMapFunction<String, Tuple2<String, Integer>> { @Override public void flatMap(String value, Collector<Tuple2<String, Integer>> out) { // normalize and split the line String[] tokens = value.toLowerCase().split("\\W+"); // emit the pairs for (String token : tokens) { if (token.length() > 0) { out.collect(new Tuple2<>(token, 1)); } } } } }
/* * iSGL3D: http://isgl3d.com * * Copyright (c) 2010-2011 Stuart Caunt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #import "AccelerometerDemoView.h" #include "Isgl3dPhysicsWorld.h" #include "Isgl3dPhysicsObject3D.h" #include "Isgl3dMotionState.h" #include "btBulletDynamicsCommon.h" #include <BulletCollision/CollisionShapes/btBox2dShape.h> @interface AccelerometerDemoView () - (void) translateCamera:(float)phi; - (Isgl3dPhysicsObject3D *) createPhysicsObject:(Isgl3dMeshNode *)node shape:(btCollisionShape *)shape mass:(float)mass restitution:(float)restitution; @end @implementation AccelerometerDemoView - (id) init { if ((self = [super init])) { _pauseActive = NO; _theta = M_PI / 2; _orbitalDistance = 20; // Initialise camera position [self translateCamera:M_PI / 4.0]; [Isgl3dDirector sharedInstance].shadowRenderingMethod = Isgl3dShadowPlanar; [Isgl3dDirector sharedInstance].shadowAlpha = 0.4; // Create physics world with discrete dynamics _collisionConfig = new btDefaultCollisionConfiguration(); _broadphase = new btDbvtBroadphase(); _collisionDispatcher = new btCollisionDispatcher(_collisionConfig); _constraintSolver = new btSequentialImpulseConstraintSolver; _discreteDynamicsWorld = new btDiscreteDynamicsWorld(_collisionDispatcher, _broadphase, _constraintSolver, _collisionConfig); _discreteDynamicsWorld->setGravity(btVector3(0,-10,0)); _physicsWorld = [[Isgl3dPhysicsWorld alloc] init]; [_physicsWorld setDiscreteDynamicsWorld:_discreteDynamicsWorld]; [self.scene addChild:_physicsWorld]; // Create the sphere Isgl3dTextureMaterial * beachBallMaterial = [Isgl3dTextureMaterial materialWithTextureFile:@"BeachBall.png" shininess:0.9 precision:Isgl3dTexturePrecisionMedium repeatX:NO repeatY:NO]; Isgl3dSphere * sphereMesh = [Isgl3dSphere meshWithGeometry:1 longs:16 lats:16]; Isgl3dMeshNode * sphereNode = [self.scene createNodeWithMesh:sphereMesh andMaterial:beachBallMaterial]; sphereNode.position = iv3(0, 3, 0); sphereNode.enableShadowCasting = YES; btCollisionShape * sphereShape = new btSphereShape(sphereMesh.radius); [self createPhysicsObject:sphereNode shape:sphereShape mass:1.0 restitution:0.9]; // Create the ground surface Isgl3dTextureMaterial * woodMaterial = [Isgl3dTextureMaterial materialWithTextureFile:@"wood.png" shininess:0.9 precision:Isgl3dTexturePrecisionMedium repeatX:NO repeatY:NO]; Isgl3dPlane * plane = [Isgl3dPlane meshWithGeometry:100.0 height:100.0 nx:10 ny:10]; Isgl3dMeshNode * groundNode = [_physicsWorld createNodeWithMesh:plane andMaterial:woodMaterial]; groundNode.rotationX = -90; groundNode.position = iv3(0, -2, 0); btCollisionShape* groundShape = new btBox2dShape(btVector3(50, 50, 0)); [self createPhysicsObject:groundNode shape:groundShape mass:0 restitution:0.6]; // Add shadow casting light Isgl3dShadowCastingLight * light = [Isgl3dShadowCastingLight lightWithHexColor:@"FFFFFF" diffuseColor:@"FFFFFF" specularColor:@"FFFFFF" attenuation:0.001]; light.position = iv3(10, 20, 10); light.planarShadowsNode = groundNode; [self.scene addChild:light]; // Initialise accelerometer [[Isgl3dAccelerometer sharedInstance] setup:30]; [[Isgl3dAccelerometer sharedInstance] startTiltCalibration]; // Schedule updates [self schedule:@selector(tick:)]; } return self; } - (void) dealloc { delete _discreteDynamicsWorld; delete _collisionConfig; delete _broadphase; delete _collisionDispatcher; delete _constraintSolver; [_physicsWorld release]; [super dealloc]; } - (void) tick:(float)dt { if (_pauseActive) { // Move the camera if it is active if (_cameraActive && ![Isgl3dAccelerometer sharedInstance].isCalibrating) { _theta += 0.05 * [[Isgl3dAccelerometer sharedInstance] rotationAngle]; [self translateCamera:[[Isgl3dAccelerometer sharedInstance] tiltAngle]]; } } else { // Update gravity if calibration not in progress float G = 10.0; float * gravityVector = [Isgl3dAccelerometer sharedInstance].gravity; // Rotate gravity vector x-z components relative to camera horizontal angle // (Accelerometer returns gravity relative to the device itself: needs to be converted to coordinates of camera) float horizontalAngle = atan2(self.camera.viewMatrix.szx, self.camera.viewMatrix.szz); float transformedGravity[3]; transformedGravity[0] = cos(horizontalAngle) * gravityVector[0] + sin(horizontalAngle) * gravityVector[2]; transformedGravity[1] = gravityVector[1]; transformedGravity[2] = -sin(horizontalAngle) * gravityVector[0] + cos(horizontalAngle) * gravityVector[2]; [_physicsWorld setGravity:transformedGravity[0] * G y:transformedGravity[1]* G z:transformedGravity[2] * G]; } } - (void) calibrateAccelerometer:(Isgl3dEvent3D *)event { // Calibrates the accelerometer tilt [[Isgl3dAccelerometer sharedInstance] startTiltCalibration]; } - (void) togglePause:(Isgl3dEvent3D *)event { // Toggles the scene transformation calculations _pauseActive = !_pauseActive; if (_pauseActive) { self.cameraUpdateOnly = YES; } else { self.cameraUpdateOnly = NO; _cameraActive = NO; } } - (void) toggleCamera:(Isgl3dEvent3D *)event { // Toggles the camera mode _cameraActive = !_cameraActive; _pauseActive = _cameraActive; if (!_cameraActive) { [[Isgl3dAccelerometer sharedInstance] startTiltCalibration]; } } - (void) translateCamera:(float)phi { // Calculate the position of the camera from given angles float y = _orbitalDistance * cos(phi); float radius = _orbitalDistance * sin(phi); float x = radius * sin(_theta); float z = radius * cos(_theta); self.camera.position = iv3(x, y, z); } - (Isgl3dPhysicsObject3D *) createPhysicsObject:(Isgl3dMeshNode *)node shape:(btCollisionShape *)shape mass:(float)mass restitution:(float)restitution { // Create a motion state for the object Isgl3dMotionState * motionState = new Isgl3dMotionState(node); // Create a rigid body btVector3 localInertia(0, 0, 0); shape->calculateLocalInertia(mass, localInertia); btRigidBody * rigidBody = new btRigidBody(mass, motionState, shape, localInertia); rigidBody->setRestitution(restitution); rigidBody->setActivationState(DISABLE_DEACTIVATION); // Create a physics object and add it to the physics world Isgl3dPhysicsObject3D * physicsObject = [Isgl3dPhysicsObject3D physicsObjectWithNode:node andRigidBody:rigidBody]; [_physicsWorld addPhysicsObject:physicsObject]; return physicsObject; } @end #pragma mark SimpleUIView @implementation SimpleUIView @synthesize calibrateButton = _calibrateButton; @synthesize pauseButton = _pauseButton; @synthesize cameraButton = _cameraButton; - (id) init { if ((self = [super init])) { // Create a button to calibrate the accelerometer Isgl3dTextureMaterial * calibrateButtonMaterial = [Isgl3dTextureMaterial materialWithTextureFile:@"angle.png" shininess:0.9 precision:Isgl3dTexturePrecisionMedium repeatX:NO repeatY:NO]; _calibrateButton = [Isgl3dGLUIButton buttonWithMaterial:calibrateButtonMaterial]; [self.scene addChild:_calibrateButton]; [_calibrateButton setX:8 andY:264]; _calibrateButton.alpha = 0.7; // Create a button to pause the scene Isgl3dTextureMaterial * pauseButtonMaterial = [Isgl3dTextureMaterial materialWithTextureFile:@"pause.png" shininess:0.9 precision:Isgl3dTexturePrecisionMedium repeatX:NO repeatY:NO]; _pauseButton = [Isgl3dGLUIButton buttonWithMaterial:pauseButtonMaterial]; [self.scene addChild:_pauseButton]; [_pauseButton setX:424 andY:264]; _pauseButton.alpha = 0.7; // Create a button to allow movement of the camera Isgl3dTextureMaterial * cameraButtonMaterial = [Isgl3dTextureMaterial materialWithTextureFile:@"camera.png" shininess:0.9 precision:Isgl3dTexturePrecisionMedium repeatX:NO repeatY:NO]; _cameraButton = [Isgl3dGLUIButton buttonWithMaterial:cameraButtonMaterial]; [self.scene addChild:_cameraButton]; [_cameraButton setX:8 andY:8]; _cameraButton.alpha = 0.7; } return self; } - (void) dealloc { [super dealloc]; } @end #pragma mark AppDelegate /* * Implement principal class: creates the view(s) and adds them to the director */ @implementation AppDelegate - (void) createViews { // Set the device orientation [Isgl3dDirector sharedInstance].deviceOrientation = Isgl3dOrientation90CounterClockwise; // Create views AccelerometerDemoView * mainView = [AccelerometerDemoView view]; [[Isgl3dDirector sharedInstance] addView:mainView]; SimpleUIView * uiView = [SimpleUIView view]; [[Isgl3dDirector sharedInstance] addView:uiView]; [uiView.calibrateButton addEvent3DListener:mainView method:@selector(calibrateAccelerometer:) forEventType:TOUCH_EVENT]; [uiView.pauseButton addEvent3DListener:mainView method:@selector(togglePause:) forEventType:TOUCH_EVENT]; [uiView.cameraButton addEvent3DListener:mainView method:@selector(toggleCamera:) forEventType:TOUCH_EVENT]; } @end
''' The Device Array API is not implemented in the simulator. This module provides stubs to allow tests to import correctly. ''' from contextlib import contextmanager import numpy as np DeviceRecord = None from_record_like = None errmsg_contiguous_buffer = ("Array contains non-contiguous buffer and cannot " "be transferred as a single memory region. Please " "ensure contiguous buffer with numpy " ".ascontiguousarray()") class FakeShape(tuple): ''' The FakeShape class is used to provide a shape which does not allow negative indexing, similar to the shape in CUDA Python. (Numpy shape arrays allow negative indexing) ''' def __getitem__(self, k): if isinstance(k, int) and k < 0: raise IndexError('tuple index out of range') return super(FakeShape, self).__getitem__(k) class FakeWithinKernelCUDAArray(object): ''' Created to emulate the behavior of arrays within kernels, where either array.item or array['item'] is valid (that is, give all structured arrays `numpy.recarray`-like semantics). This behaviour does not follow the semantics of Python and NumPy with non-jitted code, and will be deprecated and removed. ''' def __init__(self, item): assert isinstance(item, FakeCUDAArray) self.__dict__['_item'] = item def __wrap_if_fake(self, item): if isinstance(item, FakeCUDAArray): return FakeWithinKernelCUDAArray(item) else: return item def __getattr__(self, attrname): if attrname in dir(self._item._ary): # For e.g. array size. return self.__wrap_if_fake(getattr(self._item._ary, attrname)) else: return self.__wrap_if_fake(self._item.__getitem__(attrname)) def __setattr__(self, nm, val): self._item.__setitem__(nm, val) def __getitem__(self, idx): return self.__wrap_if_fake(self._item.__getitem__(idx)) def __setitem__(self, idx, val): self._item.__setitem__(idx, val) def __len__(self): return len(self._item) class FakeCUDAArray(object): ''' Implements the interface of a DeviceArray/DeviceRecord, but mostly just wraps a NumPy array. ''' __cuda_ndarray__ = True # There must be gpu_data attribute def __init__(self, ary, stream=0): self._ary = ary self.stream = stream @property def alloc_size(self): return self._ary.nbytes @property def nbytes(self): # return nbytes -- FakeCUDAArray is a wrapper around NumPy return self._ary.nbytes def __getattr__(self, attrname): try: attr = getattr(self._ary, attrname) return attr except AttributeError as e: msg = "Wrapped array has no attribute '%s'" % attrname raise AttributeError(msg) from e def bind(self, stream=0): return FakeCUDAArray(self._ary, stream) @property def T(self): return self.transpose() def transpose(self, axes=None): return FakeCUDAArray(np.transpose(self._ary, axes=axes)) def __getitem__(self, idx): ret = self._ary.__getitem__(idx) if type(ret) not in [np.ndarray, np.void]: return ret else: return FakeCUDAArray(ret, stream=self.stream) def __setitem__(self, idx, val): return self._ary.__setitem__(idx, val) def copy_to_host(self, ary=None, stream=0): if ary is None: ary = np.empty_like(self._ary) else: check_array_compatibility(self, ary) np.copyto(ary, self._ary) return ary def copy_to_device(self, ary, stream=0): ''' Copy from the provided array into this array. This may be less forgiving than the CUDA Python implementation, which will copy data up to the length of the smallest of the two arrays, whereas this expects the size of the arrays to be equal. ''' sentry_contiguous(self) self_core, ary_core = array_core(self), array_core(ary) if isinstance(ary, FakeCUDAArray): sentry_contiguous(ary) check_array_compatibility(self_core, ary_core) else: ary_core = np.array( ary_core, order='C' if self_core.flags['C_CONTIGUOUS'] else 'F', subok=True, copy=False) check_array_compatibility(self_core, ary_core) np.copyto(self_core._ary, ary_core) @property def shape(self): return FakeShape(self._ary.shape) def ravel(self, *args, **kwargs): return FakeCUDAArray(self._ary.ravel(*args, **kwargs)) def reshape(self, *args, **kwargs): return FakeCUDAArray(self._ary.reshape(*args, **kwargs)) def view(self, *args, **kwargs): return FakeCUDAArray(self._ary.view(*args, **kwargs)) def is_c_contiguous(self): return self._ary.flags.c_contiguous def is_f_contiguous(self): return self._ary.flags.f_contiguous def __str__(self): return str(self._ary) def __repr__(self): return repr(self._ary) def __len__(self): return len(self._ary) # TODO: Add inplace, bitwise, unary magic methods # (or maybe inherit this class from numpy)? def __eq__(self, other): return FakeCUDAArray(self._ary == other) def __ne__(self, other): return FakeCUDAArray(self._ary != other) def __lt__(self, other): return FakeCUDAArray(self._ary < other) def __le__(self, other): return FakeCUDAArray(self._ary <= other) def __gt__(self, other): return FakeCUDAArray(self._ary > other) def __ge__(self, other): return FakeCUDAArray(self._ary >= other) def __add__(self, other): return FakeCUDAArray(self._ary + other) def __sub__(self, other): return FakeCUDAArray(self._ary - other) def __mul__(self, other): return FakeCUDAArray(self._ary * other) def __floordiv__(self, other): return FakeCUDAArray(self._ary // other) def __truediv__(self, other): return FakeCUDAArray(self._ary / other) def __mod__(self, other): return FakeCUDAArray(self._ary % other) def __pow__(self, other): return FakeCUDAArray(self._ary ** other) def split(self, section, stream=0): return [ FakeCUDAArray(a) for a in np.split(self._ary, range(section, len(self), section)) ] def array_core(ary): """ Extract the repeated core of a broadcast array. Broadcast arrays are by definition non-contiguous due to repeated dimensions, i.e., dimensions with stride 0. In order to ascertain memory contiguity and copy the underlying data from such arrays, we must create a view without the repeated dimensions. """ if not ary.strides: return ary core_index = [] for stride in ary.strides: core_index.append(0 if stride == 0 else slice(None)) return ary[tuple(core_index)] def is_contiguous(ary): """ Returns True iff `ary` is C-style contiguous while ignoring broadcasted and 1-sized dimensions. As opposed to array_core(), it does not call require_context(), which can be quite expensive. """ size = ary.dtype.itemsize for shape, stride in zip(reversed(ary.shape), reversed(ary.strides)): if shape > 1 and stride != 0: if size != stride: return False size *= shape return True def sentry_contiguous(ary): core = array_core(ary) if not core.flags['C_CONTIGUOUS'] and not core.flags['F_CONTIGUOUS']: raise ValueError(errmsg_contiguous_buffer) def check_array_compatibility(ary1, ary2): ary1sq, ary2sq = ary1.squeeze(), ary2.squeeze() if ary1.dtype != ary2.dtype: raise TypeError('incompatible dtype: %s vs. %s' % (ary1.dtype, ary2.dtype)) if ary1sq.shape != ary2sq.shape: raise ValueError('incompatible shape: %s vs. %s' % (ary1.shape, ary2.shape)) if ary1sq.strides != ary2sq.strides: raise ValueError('incompatible strides: %s vs. %s' % (ary1.strides, ary2.strides)) def to_device(ary, stream=0, copy=True, to=None): ary = np.array(ary, copy=False, subok=True) sentry_contiguous(ary) if to is None: buffer_dtype = np.int64 if ary.dtype.char in 'Mm' else ary.dtype return FakeCUDAArray( np.ndarray( buffer=np.copy(array_core(ary)).view(buffer_dtype), dtype=ary.dtype, shape=ary.shape, strides=ary.strides, ).view(type=type(ary)), ) else: to.copy_to_device(ary, stream=stream) @contextmanager def pinned(arg): yield def mapped_array(*args, **kwargs): for unused_arg in ('portable', 'wc'): if unused_arg in kwargs: kwargs.pop(unused_arg) return device_array(*args, **kwargs) def pinned_array(shape, dtype=np.float_, strides=None, order='C'): return np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order) def managed_array(shape, dtype=np.float_, strides=None, order='C'): return np.ndarray(shape=shape, strides=strides, dtype=dtype, order=order) def device_array(*args, **kwargs): stream = kwargs.pop('stream') if 'stream' in kwargs else 0 return FakeCUDAArray(np.ndarray(*args, **kwargs), stream=stream) def _contiguous_strides_like_array(ary): """ Given an array, compute strides for a new contiguous array of the same shape. """ # Don't recompute strides if the default strides will be sufficient to # create a contiguous array. if ary.flags['C_CONTIGUOUS'] or ary.flags['F_CONTIGUOUS'] or ary.ndim <= 1: return None # Otherwise, we need to compute new strides using an algorithm adapted from # NumPy v1.17.4's PyArray_NewLikeArrayWithShape in # core/src/multiarray/ctors.c. We permute the strides in ascending order # then compute the stride for the dimensions with the same permutation. # Stride permutation. E.g. a stride array (4, -2, 12) becomes # [(1, -2), (0, 4), (2, 12)] strideperm = [ x for x in enumerate(ary.strides) ] strideperm.sort(key=lambda x: x[1]) # Compute new strides using permutation strides = [0] * len(ary.strides) stride = ary.dtype.itemsize for i_perm, _ in strideperm: strides[i_perm] = stride stride *= ary.shape[i_perm] return tuple(strides) def _order_like_array(ary): if ary.flags['F_CONTIGUOUS'] and not ary.flags['C_CONTIGUOUS']: return 'F' else: return 'C' def device_array_like(ary, stream=0): strides = _contiguous_strides_like_array(ary) order = _order_like_array(ary) return device_array(shape=ary.shape, dtype=ary.dtype, strides=strides, order=order) def pinned_array_like(ary): strides = _contiguous_strides_like_array(ary) order = _order_like_array(ary) return pinned_array(shape=ary.shape, dtype=ary.dtype, strides=strides, order=order) def auto_device(ary, stream=0, copy=True): if isinstance(ary, FakeCUDAArray): return ary, False if not isinstance(ary, np.void): ary = np.array( ary, copy=False, subok=True) return to_device(ary, stream, copy), True def is_cuda_ndarray(obj): "Check if an object is a CUDA ndarray" return getattr(obj, '__cuda_ndarray__', False) def verify_cuda_ndarray_interface(obj): "Verify the CUDA ndarray interface for an obj" require_cuda_ndarray(obj) def requires_attr(attr, typ): if not hasattr(obj, attr): raise AttributeError(attr) if not isinstance(getattr(obj, attr), typ): raise AttributeError('%s must be of type %s' % (attr, typ)) requires_attr('shape', tuple) requires_attr('strides', tuple) requires_attr('dtype', np.dtype) requires_attr('size', int) def require_cuda_ndarray(obj): "Raises ValueError is is_cuda_ndarray(obj) evaluates False" if not is_cuda_ndarray(obj): raise ValueError('require an cuda ndarray object')
// // Cambiar_Recolector_View.swift // AdminCaritas // // Created by Jimena Gallegos on 24/11/23. // import SwiftUI struct Cambiar_Recolector_View: View { let donador: Int var administrador: Administrador @State var listaRecolectores: Array<Repartidores> = [] @State var cambiar = false @State var cambiado = false @State var nombre = "Jimena" @State var id_rec = 0 @State var estatus_entrega = "" var body: some View { NavigationStack{ VStack{ Header() .padding(.top) Text("Recolectores Disponibles") .font(.largeTitle) .fontWeight(.bold) .frame(width: 350, alignment: .center) VStack{ List{ ForEach(listaRecolectores.filter{$0.EstadoEntrega == "No Entregado"}) { recolectores in Button(action: { cambiar = true nombre = recolectores.Nombre id_rec = recolectores.id estatus_entrega = "Entregado" }){ SwiftUIView(recolector: recolectores) } .alert(isPresented: $cambiar) { Alert( title: Text("¿Seguro que desea reasignar el recibo al recolector \(nombre)?"), primaryButton: .default( Text("Continuar"), action: { ReasignarRecolector(reasignar: Reasignar(id_recolector: id_rec, id_bitacora: donador), token: administrador.access_token ) cambiar = false cambiado = true } ), secondaryButton: .destructive( Text("Cancelar"), action: { cambiar = false } ) ) } } } .listStyle(InsetListStyle()) NavigationLink(isActive: $cambiado, destination: { ContentView(administrador: administrador) }, label: { EmptyView()}) Spacer() } .frame(width: 350) .onAppear(){ listaRecolectores = getRepartidores(token: administrador.access_token) } } } } } struct Cambiar_Recolector_View_Previews: PreviewProvider { static var previews: some View { Cambiar_Recolector_View(donador: 1, administrador: Administrador(access_token: "", token_type: "", idRecolector: 1)) } }
--- title: Real-Time Latent Consistency Model Image-to-Image ControlNet emoji: 🖼️🖼️ colorFrom: gray colorTo: indigo sdk: docker pinned: false suggested_hardware: a10g-small disable_embedding: true --- # Real-Time Latent Consistency Model This demo showcases [Latent Consistency Model (LCM)](https://latent-consistency-models.github.io/) using [Diffusers](https://huggingface.co/docs/diffusers/using-diffusers/lcm) with a MJPEG stream server. You can read more about LCM + LoRAs with diffusers [here](https://huggingface.co/blog/lcm_lora). You need a webcam to run this demo. 🤗 See a collecting with live demos [here](https://huggingface.co/collections/latent-consistency/latent-consistency-model-demos-654e90c52adb0688a0acbe6f) ## Running Locally You need CUDA and Python 3.10, Node > 19, Mac with an M1/M2/M3 chip or Intel Arc GPU ## Install ```bash python -m venv venv source venv/bin/activate pip3 install -r server/requirements.txt cd frontend && npm install && npm run build && cd .. python server/main.py --reload --pipeline img2imgSDTurbo ``` Don't forget to fuild the frontend!!! ```bash cd frontend && npm install && npm run build && cd .. ``` # Pipelines You can build your own pipeline following examples here [here](pipelines), # LCM ### Image to Image ```bash python server/main.py --reload --pipeline img2img ``` # LCM ### Text to Image ```bash python server/main.py --reload --pipeline txt2img ``` ### Image to Image ControlNet Canny ```bash python server/main.py --reload --pipeline controlnet ``` # LCM + LoRa Using LCM-LoRA, giving it the super power of doing inference in as little as 4 steps. [Learn more here](https://huggingface.co/blog/lcm_lora) or [technical report](https://huggingface.co/papers/2311.05556) ### Image to Image ControlNet Canny LoRa ```bash python server/main.py --reload --pipeline controlnetLoraSD15 ``` or SDXL, note that SDXL is slower than SD15 since the inference runs on 1024x1024 images ```bash python server/main.py --reload --pipeline controlnetLoraSDXL ``` ### Text to Image ```bash python server/main.py --reload --pipeline txt2imgLora ``` ```bash python server/main.py --reload --pipeline txt2imgLoraSDXL ``` # Available Pipelines #### [LCM](https://huggingface.co/SimianLuo/LCM_Dreamshaper_v7) `img2img` `txt2img` `controlnet` `txt2imgLora` `controlnetLoraSD15` #### [SD15](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0) `controlnetLoraSDXL` `txt2imgLoraSDXL` #### [SDXL Turbo](https://huggingface.co/stabilityai/sd-xl-turbo) `img2imgSDXLTurbo` `controlnetSDXLTurbo` #### [SDTurbo](https://huggingface.co/stabilityai/sd-turbo) `img2imgSDTurbo` `controlnetSDTurbo` #### [Segmind-Vega](https://huggingface.co/segmind/Segmind-Vega) `controlnetSegmindVegaRT` `img2imgSegmindVegaRT` ### Setting environment variables * `--host`: Host address (default: 0.0.0.0) * `--port`: Port number (default: 7860) * `--reload`: Reload code on change * `--max-queue-size`: Maximum queue size (optional) * `--timeout`: Timeout period (optional) * `--safety-checker`: Enable Safety Checker (optional) * `--torch-compile`: Use Torch Compile * `--use-taesd` / `--no-taesd`: Use Tiny Autoencoder * `--pipeline`: Pipeline to use (default: "txt2img") * `--ssl-certfile`: SSL Certificate File (optional) * `--ssl-keyfile`: SSL Key File (optional) * `--debug`: Print Inference time * `--compel`: Compel option * `--sfast`: Enable Stable Fast * `--onediff`: Enable OneDiff If you run using `bash build-run.sh` you can set `PIPELINE` variables to choose the pipeline you want to run ```bash PIPELINE=txt2imgLoraSDXL bash build-run.sh ``` and setting environment variables ```bash TIMEOUT=120 SAFETY_CHECKER=True MAX_QUEUE_SIZE=4 python server/main.py --reload --pipeline txt2imgLoraSDXL ``` If you're running locally and want to test it on Mobile Safari, the webserver needs to be served over HTTPS, or follow this instruction on my [comment](https://github.com/radames/Real-Time-Latent-Consistency-Model/issues/17#issuecomment-1811957196) ```bash openssl req -newkey rsa:4096 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem python server/main.py --reload --ssl-certfile=certificate.pem --ssl-keyfile=key.pem ``` ## Docker You need NVIDIA Container Toolkit for Docker, defaults to `controlnet`` ```bash docker build -t lcm-live . docker run -ti -p 7860:7860 --gpus all lcm-live ``` reuse models data from host to avoid downloading them again, you can change `~/.cache/huggingface` to any other directory, but if you use hugingface-cli locally, you can share the same cache ```bash docker run -ti -p 7860:7860 -e HF_HOME=/data -v ~/.cache/huggingface:/data --gpus all lcm-live ``` or with environment variables ```bash docker run -ti -e PIPELINE=txt2imgLoraSDXL -p 7860:7860 --gpus all lcm-live ``` # Demo on Hugging Face * [radames/Real-Time-Latent-Consistency-Model](https://huggingface.co/spaces/radames/Real-Time-Latent-Consistency-Model) * [radames/Real-Time-SD-Turbo](https://huggingface.co/spaces/radames/Real-Time-SD-Turbo) * [latent-consistency/Real-Time-LCM-ControlNet-Lora-SD1.5](https://huggingface.co/spaces/latent-consistency/Real-Time-LCM-ControlNet-Lora-SD1.5) * [latent-consistency/Real-Time-LCM-Text-to-Image-Lora-SD1.5](https://huggingface.co/spaces/latent-consistency/Real-Time-LCM-Text-to-Image-Lora-SD1.5) * [radames/Real-Time-Latent-Consistency-Model-Text-To-Image](https://huggingface.co/spaces/radames/Real-Time-Latent-Consistency-Model-Text-To-Image) https://github.com/radames/Real-Time-Latent-Consistency-Model/assets/102277/c4003ac5-e7ff-44c0-97d3-464bb659de70
/** * two pass array using loops, * intiate prefix and postfix variables with 1. * Compute result array with prefix products and push it into the array, * Compute postfix product and update the result array. * the result array will have the products except self values * @param {number[]} nums * @returns {number[]} */ const productExceptSelf = function (nums) { let prefix = 1, postfix = 1; const result = []; /** * in the prefix computation we are storing the prefix values * in the resultant arr before computing */ for (let index = 0; index < nums.length; index++) { const num = nums[index]; result[index] = prefix; prefix *= nums[index]; } /** * in the postfix computation we are computing and storing the resultant values first * and then we are computing the postfix product */ for (let index = nums.length - 1; index > -1; index--) { const num = nums[index]; result[index] *= postfix; postfix *= nums[index]; } return result; }; console.log(productExceptSelf([1, 2, 3, 4]));
(function(tagger) { if (typeof define === 'function' && define.amd) { define(['riot'], function(riot) { tagger(riot); }); } else if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { tagger(require('riot')); } else { tagger(window.riot); } })(function(riot) { riot.tag2('help', '<help-modal onclick="{stopPropagation}"> <help-modal-title> Help <button type="button" name="close" onclick="{close}"> &times; </button> </help-modal-title> <help-modal-content> <collapsible title="Global Command Utterances"> <p>Define the utterances that trigger the available global commands such as &quot;<em>go back</em>&quot;, or &quot;<em>repeat options</em>&quot;. Each command supports multiple utterances and each utterance must be separated by a new line.</p> </collapsible> <collapsible title="Global Responses"> <p>Here are links to configure Alexa’s responses to <strong>global commands</strong> such as:</p> <ul> <li> <p><strong>Ask to Resore State</strong>: This is Alexa’s response upon invoking the skill if a previous state is has been found within the Dynamo DB Table (defined in the AWS Settins section below.)</p> </li> <li> <p><strong>Unrecognized</strong>: This is Alexa’s response when a command has not been matched to the options available.</p> </li> <li> <p><strong>Help</strong>: This is Alexa’s response when the user asks for help.</p> </li> <li> <p><strong>Exit</strong>: This is Alexa’s response when the user asks to exit or cancel the skill.</p> </li> </ul> </collapsible> <collapsible title="AWS Settings"> <p>These options help configure various the AWS technologies leveraged by the skill. The only required parameter is the <strong>AWS Lambda Function Name</strong>, otherwise you will not be able to upload your changes to the AWS Lambda platform.</p> <ul> <li> <p><strong>AWS Lambda Function Name</strong>: This must match the name you provided when creating your lambda function through the AWS administration interface.</p> </li> <li> <p><strong>Dynamo DB Table Name</strong>: <em>(This field is optional)</em> This value is used to identify the Dynamo DB table to which the current session state should be persisted to. If a Dynamo DB Table Name is not provided, user state will not be persisted and previous states can not be resumed upon future invocation. The Table identified must be accessible by the same AWS account identified below.</p> </li> <li> <p><strong>AWS Profile</strong>: <em>(This field is optional)</em> In order to upload your code to the AWS Lambda function hosted in the cloud you must use the credentials associated with your AWS account with the required IAM role permissions. AWS credentials should be stored @ ~/.aws/credentials. See <a href="http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html#Setting_AWS_Credentials">Setting AWS Credentials</a> for more details.</p> </li> </ul> </collapsible> <collapsible title="Keyboard Shortcuts"> <dl> <div> <dt>Save</dt> <dd> <kbd>⌘</kbd> + <kbd>S</kbd> </dd> </div> <div> <dt>Upload</dt> <dd> <kbd>⌘</kbd> + <kbd>U</kbd> </dd> </div> <div> <dt>Help</dt> <dd> <kbd>⌘</kbd> + <kbd>H</kbd> </dd> </div> </dl> </collapsible> </help-modal-content> </help-modal>', '', 'if="{isVisible}" onclick="{close}"', function(opts) { var _this = this; this.isVisible = false; var subRoute = riot.route.create(); subRoute('/help', function (x) { _this.isVisible = true; _this.update(); }); subRoute('/..', function (x) { _this.isVisible = false; _this.update(); }); this.stopPropagation = function (e) { e.stopPropagation(); }; this.close = function (e) { e.stopPropagation(); history.back(); }; }); });
import React from 'react' import { useDispatch, useSelector } from 'react-redux' import webApi from '../../web/webApi'; import WebService from '../../web/webService'; import {toast,ToastContainer} from 'react-toastify' import { deletePlacement } from '../../web/placementSlice'; export default function EditPlacements() { const dispatch = useDispatch(); const {placementList} = useSelector(state=>state.placement.value); const deletePlacements = async(id,index)=>{ try { let res = await WebService.getApi(webApi.DELETE_PLACEMENT+"/"+id); if(res.data.status){ toast.success("Record deleted successfully"); dispatch(deletePlacement(index)); } else toast.error("Oops!.. something went wrong"); } catch (error) { toast.error("Oops!.. something went wrong"); } } return ( <div className='container table-responsive'> <ToastContainer/> <table className='table text-center'> <thead> <tr> <th>S.No.</th> <th>Image</th> <th>Name</th> <th>Company</th> <th>Delete</th> </tr> </thead> <tbody> {placementList.map((student,index)=><tr key={index}> <td>{index+1}</td> <td><img src={"/placement/"+student.image} className="img-fluid" style={{width:'150px',height:'100px'}}></img></td> <td>{student.name}</td> <td>{student.company}</td> <td><button className='btn btn-outline-danger' onClick={()=>deletePlacements(student._id,index)}>Delete</button></td> </tr>)} </tbody> </table> </div> ) }
public static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { // 一趟中通过两两比较,将最大的数放在最右 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } /* 下面函数是为了打印出每一趟过后,序列的状态,方便理解各个排序算法 */ System.out.print(i + 1 + ":" + " "); for (int y = 0; y < arr.length; y++) { System.out.print(arr[y]+" "); } System.out.println(); } }
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ if not digits: return [] phone = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} def backtrack(index, path): # If the path is the same length as digits, we have a complete combination if len(path) == len(digits): combinations.append("".join(path)) return # Backtrack # Add a letter for each possible next digit for letter in phone[digits[index]]: path.append(letter) # Add the letter to our current path backtrack(index + 1, path) # Move on to the next digit path.pop() # Remove the letter from the path before backtracking combinations = [] backtrack(0, []) return combinations
import assert from "node:assert/strict"; import compile from "../src/compiler.js"; // Note: compiler's lines 14-16 cannot be tested as the analyzer fails first // and the optimize/generate lines are unreacheable const sampleProgram = "serve(0);"; describe("The compiler", () => { it("throws when the output type is missing", (done) => { assert.throws(() => compile(sampleProgram), /Unknown output type/); done(); }); it("throws when the output type is unknown", (done) => { assert.throws( () => compile(sampleProgram, "no such type"), /Unknown output type/ ); done(); }); it("accepts the parsed option", (done) => { const compiled = compile(sampleProgram, "parsed"); assert(compiled.startsWith("Syntax is ok")); done(); }); it("throws an error with the 'analyzed' option", () => { // Assuming `sampleProgram` is defined elsewhere and valid let errorCaught = false; try { const analyzed = compile(sampleProgram, "analyzed"); } catch (error) { // Check if the error is of the expected type, for example, a TypeError // This is a generic check; adjust the condition based on your error handling errorCaught = true; assert.equal(error instanceof Error, true); // Or any specific error type expected } assert.equal(errorCaught, false); }); it("accepts the optimized option", (done) => { const compiled = compile(sampleProgram, "optimized"); assert(compiled.kind === "Program"); done(); }); it("generates js code when given the js option", (done) => { const compiled = compile(sampleProgram, "js"); assert(compiled.startsWith("console.log(0)")); done(); }); });
import './globals.css'; import React from 'react'; import tv from '@/public/travel.jpg'; interface Link { color: string; text: string; link: string; } const Home: React.FC = () => { const links: Link[] = [ { color: "bg-red-300", text: "Buy me coffee ☕️", link: "https://github.com", }, { color: "bg-sky-300", text: "Join My Newslatter 🗞", link: "https://github.com", }, { color: "bg-pink-400", text: "Learn Code 💻", link: "https://github.com", }, ]; return ( <main className="w-full h-screen bg-yellow-300 flex justify-center items-center"> <section className="max-w-2xl mx-auto flex flex-col gap-5"> <article className="h-48 w-48 mx-auto"> <div className=" aspect-w-1 aspect-h-1"> <img src={tv.src} className=" rounded-full object-cover object-center" alt="Rose" /> </div> </article> <div className="text-center p-3"> <h1 className="text-4xl font-bold">Spread Hope Travels</h1> <p className="text-lg mt-3"> Lorem Ipsum has been the industry's since the 500s. </p> </div> <article className="flex flex-col gap-10"> {links.map(({ text, color, link }, index) => { return ( <a href={link} key={index} target="_blank" rel="noopener noreferrer"> <div className={`w-80 sm:w-96 mx-auto ${color} text-center text-xl font-bold py-3 border-2 border-black shadow-custom hover:shadow-none transition-all hover:translate-x-1 hover:translate-y-1`} > {text} </div> </a> ); })} </article> </section> </main> ); } export default Home;
/* * Nolan Blevins * NBlevins@email.sc.edu * October 25 2021 * CSCE 145 * PB&J */ public class Jelly { // instance variables private String name; private int calories; private String FruitType; public Jelly () { this.name = "none"; this.calories = 100; this.FruitType = "none"; } public Jelly (String aN, String aFT, int aC) { this.setName(aN); this.setFruitType(aFT); this.setCalories(aC); } public String getName() //getter method { return this.name; } public int getCalories() //getter method { return this.calories; } public String getFruitType() //getter method { return this.FruitType; } public void setName(String aN) //setter method { if(aN != null) { this.name = aN; } else { this.name = "none"; } } public void setCalories(int aC) //setter method { if(aC >= 50 && aC <= 200) { this.calories = aC; } else { this.calories = 100; } } public void setFruitType(String aFT) { //setter method if (aFT == "Apple") { this.FruitType = aFT; } else if (aFT == "Blackberry") { this.FruitType = aFT; } else if (aFT == "Grape") { this.FruitType = aFT; } else if (aFT == "Mango") { this.FruitType = aFT; } else if (aFT == "Tomato") { this.FruitType = aFT; } } public boolean equals(Jelly aJ) // equals expression { return aJ != null && this.FruitType.equals(aJ.getFruitType()) && this.name.equals(aJ.getName()) && this.calories == aJ.getCalories(); } public String toString() { return this.name+" "+this.FruitType+" "+this.calories; } }
package gormbuilder import ( "github.com/stretchr/testify/assert" "gorm.io/gorm/clause" "testing" ) func TestAnd(t *testing.T) { e := []clause.Expression{ clause.And(clause.Eq{Column: "username", Value: "test"}), } testStr := "test" c := Filter().And(Eq[string]("username", &testStr)).Build() assert.Equal(t, e, c) } func TestAndNil(t *testing.T) { e := make([]clause.Expression, 0) filter := struct { UserName *string }{nil} c := Filter().And(Eq[string]("username", filter.UserName)).Build() assert.Equal(t, e, c) } func TestAndNoGeneric(t *testing.T) { e := []clause.Expression{ clause.And(clause.Eq{Column: "username", Value: "test"}), } testStr := "test" c := Filter().And(Eq("username", &testStr)).Build() assert.Equal(t, e, c) } func TestAndIn(t *testing.T) { e := []clause.Expression{ clause.And(clause.IN{Column: "username", Values: []interface{}{"a", "b"}}), } c := Filter().And(In("username", []string{"a", "b"})).Build() assert.Equal(t, e, c) } func TestOr(t *testing.T) { e := []clause.Expression{ clause.Or( clause.Eq{Column: "username", Value: "a"}, clause.Eq{Column: "password", Value: "b"}, ), } testStr := "a" testStr2 := "b" c := Filter().Or( Eq("username", &testStr), Eq("password", &testStr2), ).Build() assert.Equal(t, e, c) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"> </script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet"> <script src="registration.js"></script> <link rel="stylesheet" href="registration.css"> <title>Registration page for Students</title> </head> <body> <header class="header" ng-app="SimpleApplicationApp"> <div class="main"> <div class="container"> <div class="row"> <div class="col-sm-12 col-md-10 col-lg-8 offset-lg-2 offset-md-1"> <div class="content"> <form ng-controller="RegistrationController as registration" name="registrationForm" novalidate action="/login/login.html"> <h2 class="form__heading text-center">Registration</h2> <div class="form-group"> <label for="name" class="form__label">Your name</label> <input type="text" class="form-control" id="form__name" name="name" ng-model="registration.name" required spellcheck="false" ng-blur="registration.nameValidation()"> <!-- ng-pattern="/^[a-zA-Z\ ]+$/" --> <span class="form__span__errors" name="registration.formspanerrorname" id="form__span__error__name"></span> </div> <div class="form-group"> <label for="libid" class="form__label">Library Id</label> <input type="text" spellcheck="false" class="form-control" id="form__libid" name="libid" ng-model="registration.libid" required ng-blur="registration.libidValidation()"> <!-- ng-pattern="/^[1][6-9][1-2][0-3][C-M][A-Z][1][\d]{3}$/" --> <!-- ng-if="(registrationForm.libid.$error.required || registrationForm.libid.$invalid || registrationForm.libid.$error.minlength || registrationForm.libid.$error.maxlength) && registrationForm.libid.$touched" --> <span class="form__span__errors" id="form__span__error__libid"></span> </div> <div class="form-group"> <label for="email" class="form__label">Email address</label> <input type="email" class="form-control" id="form__email" name="email" ng-model="registration.email" required> <span ng-if="(registrationForm.email.$error.required || registrationForm.email.$invalid || registrationForm.email.$error.minlength || registrationForm.email.$error.maxlength) && registrationForm.email.$touched" class="form__span__errors" id="form__span__error__email" ng-if="registrationForm.email.$valid">Enter a valid Email</span> </div> <div class="form-group"> <label for="password" class="form__label">Password</label> <input type="password" class="form-control" name="password" required ng-model="registration.password" ng-minlength="8" ng-maxlength="16"> <span ng-if="(registrationForm.password.$error.required || registrationForm.password.$error.minlength || registrationForm.password.$error.maxlength) && registrationForm.password.$touched" class="form__span__errors" id="form__span__error__password" ng-if="(registrationForm.libid.$error.required || registrationForm.libid.$invalid || registrationForm.libid.$error.minlength || registrationForm.libid.$error.maxlength) && registrationForm.libid.$touched">enter a password of minlength of 8</span> </div> <div class="form-group"> <label for="confirm-password" class="form__label">Confirm Password</label> <input type="password" class="form-control" id="confirm-password" name="confirmPassword" ng-model="registration.confirmPassword" ng-keyup="registration.confirmpasswordValidation()" required> <span class="form__span__errors" id="form__span__error__confirmpassword"></span> </div> <div class="d-flex justify-content-center"> <button type="submit" class="btn form__btn" id="button" disabled="disabled" ng-disabled="registrationForm.$invalid">Submit</button> </div> </form> </div> </div> </div> </div> </div> </header> </body> </html>
import {Utils} from "./utils/utils.js"; import collisionPortalProps = Portals.CollisionPortalProps; import {Controls} from "./controls.js"; import {collisionChecker} from "./global.js"; import CollisionPortalProps = Portals.CollisionPortalProps; import {Bee} from "./bee.js"; export module Portals { export type CollisionPortalProps = { collisionElement: HTMLElement, onCollision?: () => void, target?: URL, noposition?: boolean }; } export class Portals { private appearAnimation = { step: 4, speed: 10, duration: 450 } private bee; constructor(bee: HTMLElement) { this.bee = bee; } public setSidePortalsDisplay(visible: boolean) { for (let portalDiv of document.getElementsByClassName("side-portal")) (portalDiv as HTMLElement).style.display = visible ? "" : "none"; } public generateRandomPortal(timeout: number, canvas: HTMLCanvasElement, bee: Bee) { const ctx = canvas.getContext('2d') as CanvasRenderingContext2D; const locationOffset = 100; const maxX = document.body.clientWidth - locationOffset; const maxY = document.body.clientHeight - locationOffset; const minX = locationOffset; const minY = locationOffset; const y = Utils.randomIntFromInterval(minY, maxY); const x = Utils.randomIntFromInterval(minX, maxX); const portY = Utils.randomIntFromInterval(minY, maxY); const portX = Utils.randomIntFromInterval(minX, maxX); const portal = this.createPortal(); this.placePortal(portal, x, y); Portals.drawPoint(portX, portY, canvas); const timeoutId = window.setTimeout(() => { this.removePortal(portal); ctx.clearRect(0, 0, canvas.width, canvas.height); }, timeout); const props: CollisionPortalProps = { collisionElement: portal, onCollision: () => { clearTimeout(timeoutId); this.handlePortalTouched(portal, portX, portY, canvas, bee); } }; this.registerPortal(props); } private static drawPoint(x: number, y:number, canvas: HTMLCanvasElement) { const ctx = canvas.getContext("2d") as CanvasRenderingContext2D; ctx.clearRect(0, 0, canvas.width, canvas.height); const radius = 15; ctx.beginPath(); ctx.arc(x, y, radius, 0, 2 * Math.PI, false); ctx.fillStyle = 'rgba(91, 80, 155, 0.35)'; ctx.fill(); ctx.lineWidth = 5; ctx.strokeStyle = 'rgba(63,55,105,0.35)'; ctx.stroke(); } private handlePortalTouched(portal: HTMLElement, portX: number, portY: number, canvas: HTMLCanvasElement, bee: Bee) { const ctx = canvas.getContext('2d') as CanvasRenderingContext2D; this.removePortal(portal); ctx.clearRect(0, 0, canvas.width, canvas.height); bee.currPos = {x: portX, y: portY}; const endPortal = this.createPortal(); this.placePortal(endPortal, portX, portY); window.setTimeout(() => this.removePortal(endPortal), this.appearAnimation.duration); } public removePortal(portal: HTMLElement) { let width = portal.clientWidth; let height = portal.clientHeight; const id = window.setInterval(() => { if (width > this.appearAnimation.step) { portal.style.width = (width -= this.appearAnimation.step) + "px"; portal.style.left = (portal.getBoundingClientRect().left + this.appearAnimation.step / 2) + "px"; } if (height > this.appearAnimation.step) { portal.style.height = (height -= this.appearAnimation.step) + "px"; portal.style.top = (portal.getBoundingClientRect().top + this.appearAnimation.step / 2) + "px"; } if (width <= this.appearAnimation.step && height <= this.appearAnimation.step) { portal.remove(); clearInterval(id); return; } }, this.appearAnimation.speed); } public placePortal(portal: HTMLElement, x: number, y: number) { Object.assign(portal.style, { left: x + "px", top: y + "px", }); document.body.appendChild(portal); this.animateAppearance(portal); } private animateAppearance(portal: HTMLElement) { const targetWidth = portal.clientWidth; const targetHeight = portal.clientHeight; portal.style.width = "0px"; portal.style.height = "0px"; let width = 0; let height = 0; const id = window.setInterval(() => { if (width < targetWidth - this.appearAnimation.step) { portal.style.width = (width += this.appearAnimation.step) + "px"; portal.style.left = (portal.getBoundingClientRect().left - this.appearAnimation.step / 2) + "px"; } if (height < targetHeight - this.appearAnimation.step) { portal.style.height = (height += this.appearAnimation.step) + "px"; portal.style.top = (portal.getBoundingClientRect().top - this.appearAnimation.step / 2) + "px"; } if (width >= targetWidth - (this.appearAnimation.step - 1) && height >= targetHeight - (this.appearAnimation.step - 1)) { clearInterval(id); return; } }, this.appearAnimation.speed); } public createPortal(): HTMLElement { const portal = document.createElement("div"); //portal.src = "../resources/portal.png"; portal.classList.add("portal", "unselectable"); portal.onselectstart = () => false; return portal; } /** Registers all side portals in document for collision. */ public registerSidePortals(): void { for (let portalDiv of document.getElementsByClassName("side-portal")) { const collisionElement = (portalDiv.getElementsByTagName('img')[0] as HTMLElement); let target = portalDiv.getAttribute("target"); if (!target) continue; const noPosition = portalDiv.getAttribute("noposition") === "" || portalDiv.getAttribute("noposition") === "true"; const url = new URL(target, window.location.href); if (!noPosition && portalDiv.classList.contains("portal-right")) url.searchParams.append("from", "right"); else if (!noPosition && portalDiv.classList.contains("portal-left")) url.searchParams.append("from", "left"); this.registerPortal({collisionElement: collisionElement, target: url, noposition: noPosition}); } } public registerPortal(props: collisionPortalProps): void { const onCollision = () => { if (props.onCollision) props.onCollision(); if (!props.target) return; if (!props.noposition) { props.target.searchParams.append("left", Controls.keys.left.pressed + ""); props.target.searchParams.append("right", Controls.keys.right.pressed + ""); props.target.searchParams.append("floss", Controls.keys.floss.pressed + ""); } window.location.replace(props.target); } collisionChecker.add({element: props.collisionElement, onCollisionEnter: onCollision.bind(this)}); } }
package com.manerajona.java.designpatterns.creationals.singleton.example1; import java.io.Serial; import java.io.Serializable; class BasicSingleton implements Serializable { private static final BasicSingleton INSTANCE = new BasicSingleton(); private int value = 0; // cannot new this class, however // * instance can be created deliberately (reflection) // * instance can be created accidentally (serialization) private BasicSingleton() { System.out.println("Singleton is initializing"); } // generated getter public static BasicSingleton getInstance() { return INSTANCE; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } // required for correct serialization // readResolve is used for _replacing_ the object read from the stream @Serial protected Object readResolve() { return INSTANCE; } }
import format from '../../util/lib/format'; import dateParse from '../../util/lib/dateParse'; import getMonthLength from '../../util/lib/getMonthLength'; import getMonthFirstDay from '../../util/lib/getMonthFirstDay'; import divideArr from '../../util/lib/divideArr'; import './css/datePicker.less'; const WEEK_LABLE = ['一','二','三','四','五','六','日']; const TODAY_BTN_TEXT = ['','今年','本月','今天','本周']; /** * 日期组件 */ export default class DatePicker { /** * 构造方法 * @param input 模板input * @param type one of ['year','month','day','week'] 默认day * @param currentDate 当前时间 * @param startDate 开始时间 * @param endDate 结束时间 * @param defaultFormat 日期格式 * @param onDateChange 日期改变回调函数 * @param canClose 是否显示清空按钮 默认显示 * @param dropUp 向上弹出 */ constructor({ input, type='day', currentDate, startDate, endDate, defaultFormat, onDateChange=()=>{},canClose=true,dropUp }) { if(!(input instanceof $) || (input instanceof $ && input.length !== 1)) throw new Error('DatePicker param input must be an one length jqueryDom'); this.input = input; this.type = {'year':1,'month':2,'day':3,'week':4}[type] || 3; this.startDate = new Date(startDate); this.endDate = new Date(endDate); if(!this.startDate.getTime()) this.startDate = new Date('1970/1/1'); if(!this.endDate.getTime()) this.endDate = null; if(this.startDate && this.endDate && this.startDate.getTime()>this.endDate.getTime()){ this.startDate = new Date('1970/1/1'); } this.todayDisabled = (this.startDate && this.startDate.getTime()>Date.now()) || (this.endDate && this.endDate.getTime()<Date.now()); if(defaultFormat){ this.defaultFormat = defaultFormat; }else { this.defaultFormat = ['','yyyy','yyyy-MM','yyyy-MM-dd','yyyy-MM'][this.type]; } this.onDateChange = onDateChange; this.canClose = canClose; if(this.input[0].tagName !== 'INPUT') throw new Error('DatePicker param input must be input tag'); this.id = 'datePicker'+Math.round(Math.random()*100000); if(currentDate){ if(new Date(currentDate).getTime()){ this.input.val(format(currentDate,this.defaultFormat)); this.currentDate = new Date(currentDate); }else { this.input.val(currentDate); this.currentDate = dateParse(currentDate,this.defaultFormat); } }else { this.currentDate = new Date(currentDate || this.input.val()).getTime()?new Date(currentDate || this.input.val()):new Date(); } if(this.endDate && this.endDate.getTime()<this.currentDate.getTime()){ this.currentDate = new Date(this.endDate); } else if(this.startDate && this.startDate.getTime()>this.currentDate.getTime()) { this.currentDate = new Date(this.startDate); } this.currentYear = this.currentDate.getFullYear(); this.currentMonth = this.currentDate.getMonth()+1; this.currentDay = this.currentDate.getDate(); this.dropUp = dropUp; this.outer = null; this._init(); } _getDays(year,month){ const firstDay = getMonthFirstDay(year,month) || 7; const thisMonthLength = getMonthLength(year,month); const PreMonthLength = getMonthLength(year,month-1); const defaultDay = this.defaultDate.getDate(); let startF,endF; if(this.startDate && format(this.startDate,'yyyy/MM') === format(year+'/'+month,'yyyy/MM')){ startF = true; } if(this.endDate && format(this.endDate,'yyyy/MM') === format(year+'/'+month,'yyyy/MM')){ endF = true; } let dayArr = []; for(let i=0;i<firstDay-1;i++){ dayArr.unshift({ day:PreMonthLength - i, type:'prev', disabled:startF }); } for(let i=0;i<thisMonthLength;i++){ let disabled; if(!startF && !endF){ disabled = false; }else if(startF && !endF){ disabled = i+1 < this.startDate.getDate(); }else if(!startF && endF){ disabled = i+1 > this.endDate.getDate(); }else { disabled = i+1 < this.startDate.getDate() || i+1 > this.endDate.getDate(); } dayArr.push({ day:i+1, type:'now', disabled }); } for(let i = 0;i<42-firstDay-thisMonthLength+1;i++){ dayArr.push({ day:i+1, type:'next', disabled:endF }); } const divDays = divideArr(dayArr,7); const ci = divDays.findIndex(v=>{ return v[0].type === 'now' && v[0].day <= defaultDay && v[0].day+7>defaultDay }); if(ci>-1 && this.defaultDate.getFullYear() === this.currentYear && this.defaultDate.getMonth()+1 === this.currentMonth){ divDays[ci][0].currentWeek = true; } return { days:divDays, startF, endF }; } _init() { this._renderHtml(); } /** * 设置日期 * @param date */ setData(date){ const p_date = new Date(dateParse(date,this.defaultFormat)); if(p_date.getTime()){ this.currentDate = new Date(dateParse(date,this.defaultFormat)); this.currentYear = this.currentDate.getFullYear(); this.currentMonth = this.currentDate.getMonth()+1; this.currentDay = this.currentDate.getDate(); } this.input.val(date); this.onDateChange(date); } _getYearTable({yearArr,sy,ey}){ return `<table class="data-picker-table"> <thead> <tr> <th class="go-btn go-prev-10year${(this.startDate && this.startDate.getFullYear()>sy+1)?' disabled':''}"><i class="fa fa-arrow-left"></i></th> <th colSpan="5" style="cursor: default" class="switch">${(sy+1)+'-'+(ey-1)}</th> <th class="go-btn go-next-10year${(this.endDate && this.endDate.getFullYear()<ey-1)?' disabled':''}"><i class="fa fa-arrow-right"></i></th> </tr> </thead> <tbody> <tr><td colspan="7">${yearArr.map((v)=>{ return `<span class="year${v.active?' active':''}${v.disabled?' disabled':''}">${v.year}</span>`; }).join('')}</td></tr> </tbody> <tfoot> <tr><th colSpan="7" class="today-btn${this.todayDisabled?' disabled':''}">${TODAY_BTN_TEXT[this.type]}</th></tr> </tfoot> </table>`; } /** * 日期置空 */ reset(){ this.input.val(''); this.onDateChange(''); } _renderYearTable(year){ const sy = (Math.ceil(year/10)-1)*10-1,ey = sy+11; let yearArr = new Array(12).join(',').split(',').map((v,i)=> { return { year:sy+i, active:sy+i === this.currentYear, disabled:(this.startDate && sy+i<this.startDate.getFullYear()) || (this.endDate && sy+i>this.endDate.getFullYear()) } }); this.picker.find('.year-table-c').html(this._getYearTable({yearArr,sy,ey})); } _getMonthTable(){ return `<table class="data-picker-table"> <thead> <tr> <th class="go-btn go-prev-year"><i class="fa fa-arrow-left"></i></th> <th colSpan="5" class="switch">${this.currentYear+'年'}</th> <th class="go-btn go-next-year"><i class="fa fa-arrow-right"></i></th> </tr> </thead> <tbody> <tr><td colspan="7"> ${new Array(12).join(',').split(',').map((v,i)=>{ return `<span class="month${this.currentMonth === i+1?' active':''}">${i+1}月</span>`; }).join('')} </td></tr> </tbody> <tfoot> <tr><th colSpan="7" class="today-btn${this.todayDisabled?' disabled':''}">${TODAY_BTN_TEXT[this.type]}</th></tr> </tfoot> </table>`; } _getDayTable(){ const { days, startF, endF } = this._getDays(this.currentYear,this.currentMonth); return `<table class="data-picker-table${this.type === 4?' week':''}"> <thead> <tr> <th class="go-btn go-prev-month${startF?' disabled':''}"><i class="fa fa-arrow-left"></i></th> <th colSpan="5" class="switch">${this.currentYear+'年'+this.currentMonth+'月'}</th> <th class="go-btn go-next-month${endF?' disabled':''}"><i class="fa fa-arrow-right"></i></th> </tr> <tr> ${WEEK_LABLE.map((v)=>{return `<th>${v}</th>`}).join('')} </tr> </thead> <tbody> ${days.map((v)=>{ const weekCan = v.some(v2=>!v2.disabled); return `<tr class="${weekCan?'':'disabled'}${v[0].currentWeek?'current-week':''}">${v.map((v2)=>{ return `<td class="day${' '+v2.type}${v2.day === this.currentDay?' today':''}${v2.disabled?' disabled':''}">${v2.day}</td>`; }).join('')}</tr>`; }).join('')} </tbody> <tfoot> <tr><th colSpan="7" class="today-btn${this.todayDisabled?' disabled':''}">${TODAY_BTN_TEXT[this.type]}</th></tr> </tfoot> </table>`; } _renderDayTable(type){ const date = this.currentDate; switch (type){ case 'prev':{ date.setMonth(this.currentMonth-2); break; } case 'next':{ date.setMonth(this.currentMonth); break; } } this.currentDate = date; this.currentYear = this.currentDate.getFullYear(); this.currentMonth = this.currentDate.getMonth()+1; this.currentDay = this.currentDate.getDate(); this.picker.find('.day-table-c').html(this._getDayTable()); } _getHtml(){ return `<div id="${this.id}" class="data-picker-container${this.dropUp?' drop-up':''}"> <div class="data-picker-days year-table-c ${this.type === 1?'table-show':''}"></div> <div class="data-picker-days month-table-c ${this.type === 2?'table-show':''}">${this._getMonthTable()}</div> <div class="data-picker-days day-table-c ${this.type > 2?'table-show':''}"></div> </div>`; } _renderHtml() { if($('#'+this.id).length === 0){ $('body').append(this._getHtml()); if(!this.input.closest('.datepicker-input-c').length){ this.input.wrap(`<div id="${this.id+'Input'}" class="datepicker-input-c"></div>`).after(`<i class="fa fa-calendar"></i><i class="fa fa-times"></i>`); } this.picker = $('#'+this.id); this.outer = $('#'+this.id+'Input'); this._bindEvent(); } } /** * 打开日期 */ pickerShow(){ this.defaultDate = new Date(this.currentDate); this._switchTable(this.type-1); if(this.dropUp){ const {left,top:offt} = this.input.offset(),top = offt-this.picker.height()-20; this.picker.css({left,top}).fadeIn(200); }else { const {left,top:offt} = this.input.offset(),top = offt+this.input[0].clientHeight; this.picker.css({left,top}).fadeIn(200); } this.outer.find('.fa-calendar').hide(); this.outer.find('.fa-times').toggle(this.canClose); } /** * 关闭日期 */ pickerHide(){ this.picker.fadeOut(200); this.outer.find('.fa-calendar').show(); this.outer.find('.fa-times').hide(); } _setFinDate(year,month,day,type){ let date = new Date(year+'/'+month+'/'+day); switch (type){ case 'prev':{ date.setMonth(month-2); break; } case 'next':{ date.setMonth(month); break; } } this.currentDate = date; this.currentYear = this.currentDate.getFullYear(); this.currentMonth = this.currentDate.getMonth()+1; this.currentDay = this.currentDate.getDate(); const f_date = format(date,this.defaultFormat); if(this.type === 4){ const md1 = getMonthFirstDay(this.currentYear,this.currentMonth) || 7; const mw1d = 7-md1+2; const wn = Math.floor((this.currentDay - mw1d)/7)+1; this.input.val(f_date+` 第${wn}周`); this.onDateChange({ start:this.currentDate, end:new Date(this.currentDate).setDate(this.currentDay+6), weekNumber:wn }) }else { this.input.val(f_date); this.onDateChange(f_date); } this.pickerHide(); } _switchTable(n){ switch (n){ case 0:{ this._renderYearTable(this.currentYear); break; } case 1:{ const startF = this.startDate?this.startDate.getFullYear() == this.currentYear:false, endF = this.endDate?this.endDate.getFullYear() == this.currentYear:false, that = this; this.picker.find('.month').each(function () { $(this).toggleClass('disabled',(startF && $(this).index()<that.startDate.getMonth()) ||(endF && $(this).index()>that.endDate.getMonth())); }).eq(this.currentMonth-1).addClass('active').siblings().removeClass('active'); this.picker.find('.month-table-c .switch').text(this.currentYear+'年'); this.picker.find('.go-prev-year').toggleClass('disabled',startF); this.picker.find('.go-next-year').toggleClass('disabled',endF); break; } case 2: case 3:{ this._renderDayTable(); break; } } this.picker.find('.data-picker-days').eq(n).addClass('table-show').siblings().removeClass('table-show'); } _formatADate(val){ let date = new Date(val); date = date.getTime()?date:new Date(); let currentDate; if((!this.startDate || this.startDate.getTime()<date.getTime()) && (!this.endDate || this.endDate.getTime()>date.getTime())){ currentDate = new Date(date); }else if(!(!this.startDate || this.startDate.getTime()<date.getTime())){ currentDate = new Date(this.startDate); }else { currentDate = new Date(this.endDate); } return currentDate; } /** * 设置开始时间 * @param date */ setStartDate(date){ this.startDate = date?new Date(date):null; this.todayDisabled = (this.startDate && this.startDate.getTime()>Date.now()) || (this.endDate && this.endDate.getTime()+86400000<Date.now()); if(this.startDate && this.currentDate<this.startDate){ this.currentDate = new Date(this.startDate); } return this; } /** * 设置结束时间 * @param date */ setEndDate(date){ this.endDate = date?new Date(date):null; this.todayDisabled = (this.startDate && this.startDate.getTime()>Date.now()) || (this.endDate && this.endDate.getTime()+86400000<Date.now()); if(this.endDate && this.currentDate > this.endDate){ this.currentDate = new Date(this.endDate); } } _bindEvent() { const that = this; this.outer.on('click',() => { if(this.input[0].disabled) return; this.pickerShow(); }).on('keyup',()=>{ this.currentDate = this._formatADate(this.input.val()); this._switchTable(this.type-1); }).on('keydown',()=>{ this.keyPress = true; }).on('click','.fa-calendar',()=> { if(this.input[0].disabled) return; this.input.focus(); }).on('click','.fa-times',function (e) { e.stopPropagation(); that.reset(); that.pickerHide(); }); this.picker.on('click','.data-picker-table:not(.week) .day:not(.disabled)',function () { const $this = $(this),day = $this.text(); if($this.hasClass('prev')){ that._setFinDate(that.currentYear,that.currentMonth,day,'prev'); }else if($this.hasClass('next')){ that._setFinDate(that.currentYear,that.currentMonth,day,'next'); }else { that._setFinDate(that.currentYear,that.currentMonth,day,'now'); } }).on('click','.go-prev-month:not(.disabled)',function () { that._renderDayTable('prev'); }).on('click','.go-next-month:not(.disabled)',function () { that._renderDayTable('next'); }).on('click','.today-btn:not(.disabled)',function () { const date = new Date(); if(that.type === 4){ const tw = date.getDay() || 7; date.setDate(date.getDate()-tw+1); } that._setFinDate(date.getFullYear(),date.getMonth()+1,date.getDate(),'now'); }).on('click','.day-table-c .switch',function () { that._switchTable(1); }).on('click','.month:not(.disabled)',function () { that.currentDate.setMonth($(this).index()); if(that.type === 2){ that.currentMonth = that.currentDate.getMonth()+1; return that._setFinDate(that.currentYear,that.currentMonth,1,'now'); } that._switchTable(2); }).on('click','.go-prev-year:not(.disabled)',function () { that.currentYear--; that.currentDate = new Date(that.currentYear+'/'+that.currentMonth+'/'+that.currentDay); that._switchTable(1); }).on('click','.go-next-year:not(.disabled)',function () { that.currentYear++; that.currentDate = new Date(that.currentYear+'/'+that.currentMonth+'/'+that.currentDay); that._switchTable(1); }).on('click','.month-table-c .switch',function () { that._switchTable(0); }).on('click','.go-prev-10year:not(.disabled)',function () { const year = $(this).next().text().split('-')[0]; that._renderYearTable(year); }).on('click','.go-next-10year:not(.disabled)',function () { const year = $(this).prev().text().split('-')[1] -0 + 10; that._renderYearTable(year); }).on('click','.year:not(.disabled)',function () { const year = $(this).text(); that.currentDate.setFullYear(year); that.currentYear = year; if(that.type === 1){ return that._setFinDate(that.currentYear,1,1,'now'); } that._switchTable(1); }).on('click','.week tbody tr:not(.disabled)',function () { let weekType = 'now'; const monday = $(this).find('td').eq(0); if(monday.hasClass('now')){ weekType = 'now'; }else if(monday.hasClass('prev')){ weekType = 'prev'; }else { weekType = 'next'; } that._setFinDate(that.currentYear,that.currentMonth,monday.text(),weekType); }); $(document).on('mousedown',function (e) { if($(e.target).closest('#'+that.id).length !== 1 && $(e.target).closest('#'+that.id+'Input').length !== 1){ if(that.keyPress && that.input.val()){ const f_date = format(that.currentDate,that.defaultFormat); that.input.val(f_date); that.onDateChange(f_date); } that.pickerHide(); that.keyPress = false; } }); } }
<?php namespace Database\Seeders; use App\Models\Author; use App\Models\Book; use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class AuthorBookTableSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { $books = Book::all(); $authors = Author::all(); foreach ($books as $book) { $authorIds = $authors ->random(2) ->pluck('id') ->all(); $book->authors()->attach($authorIds); } } }
using Core.Model.OrderModel; using Core.Model.PromoCodeModel; using Core.Model.RestaurantModel; using Core.ValueObject.PromoCode; using Core.ValueObject.Staff.User; namespace Core.Services.Abstraction; public interface IPromoCodeService { /// <summary> /// Change promo code value /// </summary> /// <param name="promoCode">Promo code <see cref="PromoCode"/></param> /// <param name="value">New value <see cref="PromoCodeValue"/></param> /// <param name="userRole">Requesting user role <see cref="UserRole"/></param> /// <param name="restaurantOrders"><see cref="Restaurant"/> orders.</param> void ChangePromoCodeValue(PromoCode promoCode, PromoCodeValue value,UserRole userRole,IReadOnlyList<Order> restaurantOrders); /// <summary> /// Change promo code state /// </summary> /// <param name="promoCode">Promo code <see cref="PromoCode"/></param> /// <param name="state">New state <see cref="PromoCodeState"/></param> /// <param name="userRole">Requesting user role <see cref="UserRole"/></param> void ChangePromoCodeState(PromoCode promoCode, PromoCodeState state, UserRole userRole); /// <summary> /// Change dates of <see cref="RangeDatePromoCode"/> /// </summary> /// <param name="promoCode">Instance of <see cref="RangeDatePromoCode"/></param> /// <param name="from">Date from</param> /// <param name="to">Date to</param> /// <param name="currentDate">Current date</param> /// <param name="userRole">Requesting user roles <see cref="UserRole"/></param> /// <param name="restaurantOrders"><see cref="Restaurant"/> orders</param> void ChangeRangeDatePromoCodeDates(RangeDatePromoCode promoCode, DateOnly from, DateOnly to, DateOnly currentDate, UserRole userRole, IReadOnlyList<Order> restaurantOrders); /// <summary> /// Change specific date promo code date. /// </summary> /// <param name="promoCode">Instance of <see cref="SpecificDatePromoCode"/></param> /// <param name="date">New date</param> /// <param name="currentDate">Current date</param> /// <param name="userRole">Requesting user role <see cref="UserRole"/></param> /// <param name="restaurantOrders"><see cref="Restaurant"/> orders</param> void ChangeSpecificDatePromoCodeDate(SpecificDatePromoCode promoCode, DateOnly date, DateOnly currentDate, UserRole userRole, IReadOnlyList<Order> restaurantOrders); }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.userServices = void 0; const bcrypt_1 = __importDefault(require("bcrypt")); /* eslint-disable no-unused-expressions */ const user_model_1 = __importDefault(require("./user.model")); const config_1 = __importDefault(require("../config")); const createUser = (userData) => __awaiter(void 0, void 0, void 0, function* () { const result = yield user_model_1.default.create(userData); return result; }); const getAllUser = () => __awaiter(void 0, void 0, void 0, function* () { const result = yield user_model_1.default.find(); return result; }); const getSingleUser = (userId) => __awaiter(void 0, void 0, void 0, function* () { if (yield user_model_1.default.isUserExists(userId)) { const result = yield user_model_1.default.findOne({ userId }); return result; } }); const updateUser = (userId, userData) => __awaiter(void 0, void 0, void 0, function* () { try { if (yield user_model_1.default.isUserExists(userId)) { if (userData.password) { userData.password = yield bcrypt_1.default.hash(userData.password, Number(config_1.default.bcrypt_salt)); } const result = user_model_1.default.findOneAndUpdate({ userId }, userData, { new: true }); return result; } } catch (error) { throw new Error('user is missing'); } }); const deleteUser = (userId) => __awaiter(void 0, void 0, void 0, function* () { try { if (yield user_model_1.default.isUserExists(userId)) { const result = yield user_model_1.default.deleteOne({ userId }); return result; } } catch (error) { throw new Error('missing is absent'); } }); const AddNewProduct = (id, userData) => __awaiter(void 0, void 0, void 0, function* () { try { if (yield user_model_1.default.isUserExists(id)) { const addproduct = yield user_model_1.default.updateOne({ userId: id }, { $push: { orders: userData }, }, { new: true }); return addproduct; } } catch (error) { throw new Error('invalid user'); } }); const getOrder = (userId) => __awaiter(void 0, void 0, void 0, function* () { try { if (yield user_model_1.default.isUserExists(userId)) { const result = yield user_model_1.default.findOne({ userId }); return result; } } catch (error) { throw new Error('invalid user'); } }); const totalPrice = (userId) => __awaiter(void 0, void 0, void 0, function* () { try { if (yield user_model_1.default.isUserExists(userId)) { const userData = yield user_model_1.default.findOne({ userId }).select('orders'); const orders = userData === null || userData === void 0 ? void 0 : userData.orders; let sum = 0; // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-unused-vars const totalPrice = orders === null || orders === void 0 ? void 0 : orders.map((order) => { const total = order.price * order.quantity; sum = sum + total; }); return sum; } } catch (error) { throw new Error('no total price'); } }); exports.userServices = { createUser, getAllUser, getSingleUser, deleteUser, updateUser, AddNewProduct, getOrder, totalPrice, };
import { createSlice } from '@reduxjs/toolkit'; export const formSlice = createSlice({ name: 'form', initialState: { personalDetails: { name: '', age: '', sex: '', mobile: '', govIdType: '', govId: '', }, }, reducers: { updatePersonalDetails: (state, action) => { state.personalDetails = { ...state.personalDetails, ...action.payload }; }, }, }); export const { updatePersonalDetails } = formSlice.actions; export const selectPersonalDetails = (state) => state.form.personalDetails; export default formSlice.reducer;
const router = require("express").Router(); const Movie = require("../models/Movie"); // CREATE router.post("/", async (req, res) => { const newMovie = new Movie(req.body); try { const savedMovie = await newMovie.save(); res.status(201).json(savedMovie); } catch (err) { res.status(500).json(err); } }); // Update router.put("/:id", async (req, res) => { try { const updatedMovie = await Movie.findByIdAndUpdate( req.params.id, { $set: req.body, }, { new: true } ); res.status(200).json(updatedMovie); } catch (err) { res.status(500).json(err); } }); // DELETE router.delete("/:id", async (req, res) => { try { await Movie.findByIdAndDelete(req.params.id); res.status(200).json("The Movie has been deleted..."); } catch (err) { res.status(500).json(err); } }); // GET router.get("/find/:id", async (req, res) => { try { const movie = await Movie.findById(req.params.id); res.status(200).json(movie); } catch (err) { res.status(500).json(err); } }); // GET RANDOM router.get("/random", async (req, res) => { const type = req.query.type; let movie; try { if (type === "series") { movie = await Movie.aggregate([ { $match: { isSeries: true } }, { $sample: { size: 1 } }, ]); } else { movie = await Movie.aggregate([ { $match: { isSeries: false } }, { $sample: { size: 1 } }, ]); } res.status(200).json(movie); } catch (err) { res.status(500).json(err); } }); // GET ALL router.get("/", async (req, res) => { try { const movies = await Movie.find(); res.status(200).json(movies.reverse()); } catch (err) { res.status(500).json(err); } }); module.exports = router;
#!/usr/bin/env python """ * Project : HistFitter - A ROOT-based package for statistical data analysis * * Package : HistFitter * * Script : HistFitter.py * * Created : November 2012 * * * * Description: * * Top-level control script for all commands/run-conditions * * * * Authors: * * HistFitter group * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted according to the terms listed in the file * * LICENSE. * """ #python imports import os import cProfile from code import InteractiveConsole import argparse import sys import subprocess import json from pathlib import Path #ROOT imports import ROOT ROOT.PyConfig.IgnoreCommandLineOptions = True ROOT.SetMemoryPolicy( ROOT.kMemoryStrict ) from ROOT import gROOT, gSystem, gDirectory, RooAbsData, RooRandom, RooWorkspace #HistFitter c++ imports ROOT.gSystem.Load(f"libHistFitter.so") from ROOT import hf ConfigMgr = hf.ConfigMgr Util = hf.Util #Histfitter imports from logger import Logger from configManager import configMgr import usepyhf #Create logger log = Logger('HistFitter') def GenerateFitAndPlotCPP(fc, anaName, drawBeforeFit, drawAfterFit, drawStackPlots, storeSingleFiles, storeMergedFile, drawCorrelationMatrix, drawSeparateComponents, drawLogLikelihood, minos, minosPars, doFixParameters, fixedPars, ReduceCorrMatrix, noFit, plotInterpolation): """ function call to top-level C++ side function Util.GenerateFitAndPlot() @param fc FitConfig name connected to fit and plot details @param anaName Analysis name defined in config file, mainly used for output file/dir naming @param drawBeforeFit Boolean deciding whether before-fit plots are produced @param drawAfterFit Boolean deciding whether after-fit plots are produced @param drawStackPlots Boolean deciding whether stacked before/after plots are produced, or just the individual histograms are stored @param storeSingleFiles Boolean deciding whether single files will be created for each before/after plot @param storeMergedFile Boolean deciding whether a central file will be created for all before/after plots @param drawCorrelationMatrix Boolean deciding whether correlation matrix plot is produced @param drawSeparateComponents Boolean deciding whether separate component (=sample) plots are produced @param drawLogLikelihood Boolean deciding whether log-likelihood plots are produced @param minos Boolean deciding whether asymmetric errors are calculated, eg whether MINOS is run @param minosPars When minos is called, defining what parameters need asymmetric error calculation @param doFixParameters Boolean deciding if some parameters are fixed to a value given or not @param fixedPars String of parameter1:value1,parameter2:value2 giving information on which parameter to fix to which value if dofixParameter == True @param ReduceCorrMatrix Boolean deciding whether reduced correlation matrix plot is produced @param noFit Don't re-run fit but use after-fit workspace @param plotInterpolation plot the interpolation scheme """ log.debug('GenerateFitAndPlotCPP: anaName %s ' % anaName) log.debug("GenerateFitAndPlotCPP: drawBeforeFit %s " % drawBeforeFit) log.debug("GenerateFitAndPlotCPP: drawAfterFit %s " % drawAfterFit) log.debug("GenerateFitAndPlotCPP: drawStackPlots %s " % drawStackPlots) log.debug("GenerateFitAndPlotCPP: storeSingleFiles %s " % storeSingleFiles) log.debug("GenerateFitAndPlotCPP: storeMergedFile %s " % storeMergedFile) log.debug("GenerateFitAndPlotCPP: drawCorrelationMatrix %s " % drawCorrelationMatrix) log.debug("GenerateFitAndPlotCPP: drawSeparateComponents %s " % drawSeparateComponents) log.debug("GenerateFitAndPlotCPP: drawLogLikelihood %s " % drawLogLikelihood) log.debug("GenerateFitAndPlotCPP: minos %s " % minos) log.debug("GenerateFitAndPlotCPP: minosPars %s " % minosPars) log.debug("GenerateFitAndPlotCPP: doFixParameters %s " % doFixParameters) log.debug("GenerateFitAndPlotCPP: fixedPars %s " % fixedPars) log.debug("GenerateFitAndPlotCPP: ReduceCorrMatrix %s " % ReduceCorrMatrix) log.debug(f"GenerateFitAndPlotCPP: noFit {noFit}") log.debug(f"GenerateFitAndPlotCPP: plotInterpolation {plotInterpolation}") Util.GenerateFitAndPlot(fc.name, anaName, drawBeforeFit, drawAfterFit, drawStackPlots, storeSingleFiles, storeMergedFile, drawCorrelationMatrix, drawSeparateComponents, drawLogLikelihood, minos, minosPars, doFixParameters, fixedPars, ReduceCorrMatrix, noFit, plotInterpolation) if __name__ == "__main__": """ Main function call starts here .... """ """ set some default options """ configMgr.readFromTree = False configMgr.executeHistFactory = False runInterpreter = False runFit = False createJSON = False printLimits = False doHypoTests = False doDiscoveryHypoTests = False drawBeforeFit = False drawAfterFit = False drawCorrelationMatrix = False drawSeparateComponents = False drawLogLikelihood = False drawSystematics = False drawInterpolation = False pickedSRs = [] runToys = False runMinos = False minosPars = "" doCodeProfiling = False doFixParameters = False fixedPars = "" usePyhf = False FitType = configMgr.FitType #enum('FitType','Discovery , Exclusion , Background') myFitType=FitType.Background doValidation = False print("\n * * * Welcome to HistFitter * * *\n") """ Definition of all options and defaults given as arguments """ mode_helper = { "bkg": "Run background-only fit", "excl": "Run exclusion fit (model-dependent fit)", "model-dep": "Run exclusion fit (model-dependent fit) (alias of excl)", "disc": "Run discovery fit (model-independent fit)", "model-indep": "Run discovery fit (model-indepndent fit) (alias of disc)"} parser = argparse.ArgumentParser(description="HistFitter options:") parser.add_argument("configFile", nargs="+", help="configuration file to execute") parser.add_argument("-L", "--log-level", help="set log level", choices=["VERBOSE", "DEBUG", "INFO", "WARNING", "ERROR", "FATAL", "ALWAYS"]) parser.add_argument("-v", "--verbose", action="store_true", default=False, help="an alias of -L VERBOSE") parser.add_argument("-F", "--fit-type", help="type of fit to run: bkg (background-only fit), excl (exclusion fit / model-dependent fit), disc (discovery fit / model-independent fit), model-dep (alias of excl), model-indep (alias of disc)", choices=["bkg", "excl", "disc", "model-dep", "model-indep"]) parser.add_argument("-t", "--create-histograms", help="re-create histograms from TTrees", action="store_true", default=configMgr.readFromTree) parser.add_argument("-w", "--create-workspace", help="re-create workspace from histograms", action="store_true", default=configMgr.executeHistFactory) parser.add_argument("-x", "--use-XML", help="write XML files by hand and call hist2workspace on them, instead of directly writing workspaces", action="store_true", default=configMgr.writeXML) parser.add_argument("-j", "--create-JSON", help="write JSON file from XML output.", action="store_true", default=createJSON) parser.add_argument("-f", "--fit", help="fit the workspace", action="store_true", default=configMgr.executeHistFactory) parser.add_argument("--fitname", dest="fitname", help="workspace name for fit (not specified takes 1st available fitConfig)", default="") parser.add_argument("-m", "--minos", help="run minos for asymmetric error calculation, optionally give parameter names for which minos should be run, space separated. For all params, use ALL", metavar="PARAM") parser.add_argument("-n", "--num_toys", type=int, help="set the number of toys, <=0 means to use real data", default=configMgr.nTOYs) parser.add_argument("-s", "--seed", type=int, help="set the random seed for toy generation", default=configMgr.toySeed) parser.add_argument("-a", "--use-asimov", help="use Asimov dataset for fitting and plotting", action="store_true", default=configMgr.useAsimovSet) parser.add_argument("-i", "--interactive", help="remain in interactive mode after running", action="store_true", default=runInterpreter) parser.add_argument("-l", "--limit-plot", help="make limit plot of workspace", action="store_true", default=printLimits) parser.add_argument("-p", "--hypotest", help="run exclusion hypothesis test", action="store_true", default=doHypoTests) parser.add_argument("-z", "--discovery-hypotest", help="run discovery hypothesis test", action="store_true", default=doDiscoveryHypoTests) parser.add_argument("-g", "--grid_points", help="grid points to process (comma-separated)") parser.add_argument("-r", "--regions", help="signal regions to process (comma-separated)", default="all") parser.add_argument("-R", "--rebin", help="rebin all histograms to proxy x-axis bins [0, 1, 2, ... N] and unfold them post-fit", action="store_true", default=False) """ note that we cannot make -d and -D the same due to http://bugs.python.org/issue9338 if we do so, specifying -d without argument would, if -d is the last option, eat the configFile as draw option i.e. 'HistFitter -f -d configFile.py' would fail, 'HistFitter -d -f configFile.py' would work (a workaround using '-f -d -- configFile.py' exists but it would confuse users) --GJ 14/11/2012 """ parser.add_argument("-d", action="store_true", help="draw before/after plots") parser.add_argument("-D", "--draw", help="specify plots to draw, comma separated; choose from "+str(["allPlots", "before","after", "corrMatrix", "correlationMatrix", "sepComponents", "separateComponents", "likelihood", "systematics", "plotInterpolation"])) parser.add_argument("-syst", "--systematics", help="specify the systematics to be considered with '-D systematics' option, comma separated;") parser.add_argument("-b", "--background", help="when doing hypotest, set background levels to values, form of bkgParName,value") parser.add_argument("-0", "--no-empty", help="do not draw empty bins when drawing", action="store_true") parser.add_argument("-T", "--run-toys", help="run toys (default with mu)", action="store_true") parser.add_argument("-V", "--validation", help="include validation regions", action="store_true") parser.add_argument("-c", "--cmd", help="python commands to process (semi-colon-separated)") parser.add_argument("-u", "--userArg", help="arbitrary user argument(s)", default="") parser.add_argument("-A", "--use-archive-histfile", help="use backup histogram cache file", action="store_true") parser.add_argument("-P", "--run-profiling", help="Run a python profiler during main HistFitter execution", action="store_true") parser.add_argument("-C", "--constant", help="Set parameters to constant in the fit, Give list of parameters and their values as parameter1:value1,parameter2:value2:...", metavar="PARAM") parser.add_argument("--pyhf", help="Use pyhf as backend where possible.", action="store_true") parser.add_argument("--pyhf-backend", help="Use specific pyhf backend. Options: ['numpy', 'tensorflow', 'pytorch', 'jax'].", choices=['numpy', 'tensorflow', 'pytorch', 'jax'], default="numpy") HistFitterArgs = parser.parse_args() """ process all the arguments/options """ if not os.path.exists(HistFitterArgs.configFile[0]) and not os.path.isfile(HistFitterArgs.configFile[0]): log.fatal(f"Specified input file '{HistFitterArgs.configFile[0]}' does not exist or is not a file") sys.exit(-1) if HistFitterArgs.fit_type == "bkg": myFitType = FitType.Background log.info("Will run in background-only fit mode") elif HistFitterArgs.fit_type == "excl" or HistFitterArgs.fit_type == "model-dep": myFitType = FitType.Exclusion log.info("Will run in exclusion (model-dependent) fit mode") elif HistFitterArgs.fit_type == "disc" or HistFitterArgs.fit_type == "model-indep": myFitType = FitType.Discovery log.info("Will run in discovery (model-independent) fit mode") # Combining -p and -z can give funny results. It's not recommend. We stop the user from doing this and # force them to execute in two steps. if HistFitterArgs.hypotest and HistFitterArgs.discovery_hypotest: log.error("You specified both -p and -z in the options. This can currently lead to unexpected results for the obtained CLs values for the -p option.") log.error("Please run these two steps separately - there is no need to regenerate the workspace, so there is no overhead to do so.") sys.exit() if HistFitterArgs.pyhf: usePyhf = True log.info("Will use pyhf as backend where possible. Checking that pyhf is installed.") #Check that pyhf python module is installed try: import pyhf log.info("import pyhf successful.") except ImportError: log.error("import pyhf failed. Install the python pyhf module by running 'pip install pyhf'.") sys.exit() #Check that pyhf is installed on the command line process = subprocess.run(["pyhf", "-h"]) if process.returncode == 0: log.info("pyhf command line tool installed.") else: log.error("Install the pyhf command line tool by running 'pip install pyhf'.") sys.exit() #Import modules import usepyhf #Set up backend pyhf.set_backend(HistFitterArgs.pyhf_backend, custom_optimizer=pyhf.optimize.minuit_optimizer(tolerance=1e-3)) configMgr.myFitType = myFitType if HistFitterArgs.validation: doValidation = True if HistFitterArgs.use_archive_histfile: configMgr.useHistBackupCacheFile = True if HistFitterArgs.run_profiling: doCodeProfiling = True if HistFitterArgs.create_histograms: configMgr.readFromTree = True if HistFitterArgs.create_workspace: configMgr.executeHistFactory = True if HistFitterArgs.use_XML: configMgr.writeXML = True if HistFitterArgs.create_JSON: createJSON = True configMgr.writeXML = True if HistFitterArgs.fit: runFit = True configMgr.userArg = HistFitterArgs.userArg configMgr.nTOYs = HistFitterArgs.num_toys if HistFitterArgs.interactive: runInterpreter = True if HistFitterArgs.verbose: log.setLevel("VERBOSE", True) elif HistFitterArgs.log_level: log.setLevel(HistFitterArgs.log_level, True) #do not add a default to HistFitterArgs.log_level or we will always lock it if HistFitterArgs.limit_plot: printLimits = True if HistFitterArgs.hypotest: if not usePyhf: configMgr.doHypoTest = True doHypoTests = True if HistFitterArgs.discovery_hypotest: configMgr.doDiscoveryHypoTest = True doDiscoveryHypoTests = True if HistFitterArgs.d: drawBeforeFit = True drawAfterFit = True if HistFitterArgs.draw: drawArgs = HistFitterArgs.draw.split(",") if len(drawArgs) == 1 and (drawArgs[0] == "allPlots" or drawArgs[0] == "all"): drawBeforeFit = True drawAfterFit = True drawCorrelationMatrix = True drawSeparateComponents = True drawLogLikelihood = True drawSystematics = True drawInterpolation = True elif len(drawArgs)>0: for drawArg in drawArgs: if drawArg == "before": drawBeforeFit = True elif drawArg == "after": drawAfterFit = True elif drawArg == "corrMatrix" or drawArg == "correlationMatrix": drawCorrelationMatrix = True elif drawArg == "sepComponents" or drawArg == "separateComponents": drawSeparateComponents = True elif drawArg == "likelihood": drawLogLikelihood = True elif drawArg == "systematics": drawSystematics = True elif drawArg == "plotInterpolation": drawInterpolation = True else: log.fatal("Wrong draw argument: '%s'. Possible draw arguments are 'allPlots' or comma separated 'before after corrMatrix correlationMatrix sepComponents separateComponents likelihood'" % drawArg) if drawInterpolation and not os.path.isdir("./interpolation"): os.mkdir("./interpolation") if HistFitterArgs.no_empty: configMgr.removeEmptyBins = True if HistFitterArgs.seed != 0: #0 is default because type is int configMgr.toySeedSet = True configMgr.toySeed = HistFitterArgs.seed if HistFitterArgs.use_asimov: configMgr.useAsimovSet = True if HistFitterArgs.rebin: configMgr.rebin = True if HistFitterArgs.grid_points and HistFitterArgs.grid_points != "": sigSamples = HistFitterArgs.grid_points.split(",") log.info("Grid points specified: %s" % sigSamples) if HistFitterArgs.regions and HistFitterArgs.regions != "" and HistFitterArgs.regions != "all": pickedSRs = HistFitterArgs.regions.split(",") else: pickedSRs = [] #MB: used by 0-lepton fit if len(pickedSRs) > 0: log.info("Selected signal regions: %s" % pickedSRs) if HistFitterArgs.run_toys: runToys = True if HistFitterArgs.background: bkgArgs = HistFitterArgs.background.split(',') if len(bkgArgs) == 2: configMgr.SetBkgParName(bkgArgs[0]) configMgr.SetBkgCorrVal(float(bkgArgs[1])) configMgr.SetBkgChlName("") elif len(bkgArgs) >= 3 and len(bkgArgs) % 3 == 0: for iChan in range(len(bkgArgs) / 3): iCx = iChan * 3 configMgr.AddBkgChlName(bkgArgs[iCx]) configMgr.AddBkgParName(bkgArgs[iCx+1]) configMgr.AddBkgCorrVal(float(bkgArgs[iCx+2])) continue if HistFitterArgs.minos: runMinos = True minosArgs = HistFitterArgs.minos.split(",") for idx, arg in enumerate(minosArgs): if arg.lower() == "all": minosArgs[idx] = "all" minosPars = ",".join(minosArgs) if HistFitterArgs.constant: doFixParameters = True fixedPars = HistFitterArgs.constant if HistFitterArgs.cmd: log.info("Python commands executed: %s" % HistFitterArgs.cmd) exec(HistFitterArgs.cmd) ## python execute gROOT.SetBatch(not runInterpreter) """ mandatory user-defined configuration file """ exec(compile(open(HistFitterArgs.configFile[0], "rb").read(), HistFitterArgs.configFile[0], 'exec')) #[0] since any extra arguments (sys.argv[-1], etc.) are caught here """ standard execution from now on """ configMgr.initialize() RooRandom.randomGenerator().SetSeed(configMgr.toySeed) ReduceCorrMatrix = configMgr.ReduceCorrMatrix """ runs Trees->histos and/or histos->workspace according to specifications """ if configMgr.readFromTree or configMgr.executeHistFactory: if doCodeProfiling: cProfile.run('configMgr.executeAll()') else: configMgr.executeAll() """ shows systematics """ if drawSystematics: if not os.path.isdir("./plots"): log.info("no directory './plots' found - attempting to create one") os.mkdir("./plots") for fC in configMgr.fitConfigs: for chan in fC.channels: for sam in chan.sampleList: if not sam.isData: if HistFitterArgs.systematics: Systs = HistFitterArgs.systematics else: log.info("no systematic has been specified.... all the systematics will be considered") print(sam.systDict) Systs = "" for i in list(sam.systDict.keys()): Systs+=i if 'Norm' in sam.systDict[i].method or 'norm' in sam.systDict[i].method: Systs+="Norm" Systs+="," if Systs!="": Systs=Systs[:-1] if Systs != "": Util.plotUpDown(configMgr.histCacheFile,sam.name,Systs,chan.regionString,chan.variableName) """ create JSONs """ if createJSON: from usepyhf import util if not Path("./json").exists(): log.info("no directory './json' found - attempting to create one") Path("./json").mkdir(parents=True, exist_ok=True) log.info("json directory created") for fc in configMgr.fitConfigs: util.create_json(configMgr.analysisName, fc.name) """ runs fitting and plotting, by calling C++ side functions """ if runFit or HistFitterArgs.draw: idx = 0 if len(configMgr.fitConfigs) == 0: log.fatal("No fit configurations found!") runAll = True if HistFitterArgs.fitname != "": # user specified a fit name fitFound = False for (i, config) in enumerate(configMgr.fitConfigs): if configMgr.fitConfigs[i].name == HistFitterArgs.fitname: idx = i fitFound = True runAll = False log.info("Found fitConfig with name %s at index %d" % (HistFitterArgs.fitname, idx)) break if not fitFound: log.fatal("Unable to find fitConfig with name %s, bailing out" % HistFitterArgs.fitname) noFit = False if not runFit: noFit = True for i in range(len(configMgr.fitConfigs)): if not runAll and i != idx: log.debug(f"Skipping fit config {configMgr.fitConfigs[i].name}") continue log.info("Running on fitConfig %s" % configMgr.fitConfigs[i].name) log.info(f"Setting noFit = {noFit}") r = GenerateFitAndPlotCPP(configMgr.fitConfigs[i], configMgr.analysisName, drawBeforeFit, drawAfterFit, configMgr.plotStacked, configMgr.storeSinglePlotFiles, configMgr.storeMergedPlotFile, drawCorrelationMatrix, drawSeparateComponents, drawLogLikelihood, runMinos, minosPars, doFixParameters, fixedPars, ReduceCorrMatrix, noFit, drawInterpolation) log.debug(" GenerateFitAndPlotCPP(configMgr.fitConfigs[%d], configMgr.analysisName, drawBeforeFit, drawAfterFit, configMgr.plotStacked, configMgr.storeSinglePlotFiles, configMgr.storeMergedPlotFile, drawCorrelationMatrix, drawSeparateComponents, drawLogLikelihood, runMinos, minosPars, doFixParameters, fixedPars, ReduceCorrMatrix, noFit, drawInterpolation)" % idx) log.debug(" where drawBeforeFit, drawAfterFit, drawCorrelationMatrix, drawSeparateComponents, drawLogLikelihood, ReduceCorrMatrix, noFit, drawInterpolation are booleans") pass """ calculating and printing upper limits for model-(in)dependent signal fit configurations (aka Exclusion/Discovery fit setup) """ if printLimits: for fc in configMgr.fitConfigs: if len(fc.validationChannels) > 0: raise Exception pass if usePyhf: from usepyhf import plot, confidence, inference for fc in configMgr.fitConfigs: json_file_path = f"./json/{configMgr.analysisName}/{configMgr.analysisName}_{fc.name}.json" if not Path(json_file_path).exists(): log.error("Please use the -j flag at least once to create JSON files for the pyhf analysis.") sys.exit() else: with open(json_file_path) as serialized: json_file = json.load(serialized) workspace = pyhf.Workspace(json_file) best_fit = inference.mle_fit(workspace) log.info(f"Making plot and saving it as ./results/{configMgr.analysisName}/upperlimit_{fc.name}.png") fig, ax = plot.brazil_plot(workspace, n_points=configMgr.nPoints, bounds=configMgr.scanRange) fig.savefig(f"./results/{configMgr.analysisName}/upperlimit_{fc.name}.png") confidence.upper_limit(workspace, configMgr.nPoints, bounds=configMgr.scanRange) else: configMgr.cppMgr.doUpperLimitAll() pass """ run exclusion or discovery hypotest """ if doHypoTests or doDiscoveryHypoTests: for fc in configMgr.fitConfigs: if len(fc.validationChannels) > 0 and not (fc.signalSample is None or 'Bkg' in fc.signalSample): raise Exception pass if doDiscoveryHypoTests: if usePyhf: from usepyhf import inference for fc in configMgr.fitConfigs: json_file_path = f"./json/{configMgr.analysisName}/{configMgr.analysisName}_{fc.name}.json" if not Path(json_file_path).exists(): log.error("Please use the -j flag at least once to create JSON files for the pyhf analysis.") sys.exit() else: with open(json_file_path) as serialized: json_file = json.load(serialized) workspace = pyhf.Workspace(json_file) best_fit = inference.mle_fit(workspace) inference.p_values_disc(workspace) else: configMgr.cppMgr.doHypoTestAll('results/', False) if doHypoTests: if usePyhf: from usepyhf import inference for fc in configMgr.fitConfigs: json_file_path = f"./json/{configMgr.analysisName}/{configMgr.analysisName}_{fc.name}.json" if not Path(json_file_path).exists(): log.error("Please use the -j flag at least once to create JSON files for the pyhf analysis.") sys.exit() else: with open(json_file_path) as serialized: json_file = json.load(serialized) workspace = pyhf.Workspace(json_file) best_fit = inference.mle_fit(workspace) inference.p_values_excl(workspace) else: configMgr.cppMgr.doHypoTestAll('results/', True) pass if runToys and configMgr.nTOYs > 0 and doHypoTests == False and printLimits == False and runFit == False: configMgr.cppMgr.runToysAll() pass if runInterpreter: cons = InteractiveConsole(locals()) cons.interact("Continuing interactive session... press Ctrl+d to exit") pass log.info("Leaving HistFitter... Bye!")
import { createLocalVue, mount } from "@vue/test-utils"; import { ValidationObserver, ValidationProvider, extend } from 'vee-validate' import App from "@/pages/input_password.vue"; const localVue = createLocalVue() localVue.component('ValidationObserver', ValidationObserver) localVue.component('ValidationProvider', ValidationProvider) const { required, min } = require('vee-validate/dist/rules.umd') extend('required', required) extend('min', min) describe("input_password.vue test", () => { it("Password check", async () => { const wrapper = mount(App, { localVue }) window.alert = jest.fn() await wrapper.get('[data-test="password"]').setValue("testtest") await wrapper.get('[data-test="confirmPassword"]').setValue("test") await wrapper.get('[data-test="send"]').trigger("click") expect(window.alert).toHaveBeenCalledWith("パスワードが一致しません") }); it("Registration success", async () => { const wrapper = mount(App, { localVue, mocks: { $axios: { post: jest.fn(() => Promise.resolve({ data: { statusText: "Success" } })) }, $config: { baseURL: 'http://localhost:8000' }, $route: { query: { id: "foobar" } }, $router: { push:jest.fn() }, } }) Object.defineProperty(window, "location", { value: {} }); await wrapper.get('[data-test="password"]').setValue("testtest") await wrapper.get('[data-test="confirmPassword"]').setValue("testtest") await wrapper.get('[data-test="send"]').trigger("click") expect(wrapper.vm.$router.push).toBeCalledWith("/successchange") }); it("Registration success but not found", async () => { const wrapper = mount(App, { localVue, mocks: { $axios: { post: jest.fn(() => Promise.resolve({ data: { statusText: "Notfound User" } })) }, $config: { baseURL: 'http://localhost:8000' }, $route: { query: { id: "foobar" } }, $router: { push:jest.fn() }, } }) Object.defineProperty(window, "location", { value: {} }); await wrapper.get('[data-test="password"]').setValue("testtest") await wrapper.get('[data-test="confirmPassword"]').setValue("testtest") await wrapper.get('[data-test="send"]').trigger("click") expect(wrapper.vm.$router.push).toBeCalledWith("/registerror") }); it("Registration fail", async () => { const wrapper = mount(App, { localVue, mocks: { $axios: { post: jest.fn(() => Promise.reject({ response: { data: { errors: { password: "Notfound User" } } } })) }, $config: { baseURL: 'http://localhost:8000' }, $route: { query: { id: "foobar" } } } }) Object.defineProperty(window, "location", { value: {} }); window.alert = jest.fn() await wrapper.get('[data-test="password"]').setValue("testtest") await wrapper.get('[data-test="confirmPassword"]').setValue("testtest") await wrapper.get('[data-test="send"]').trigger("click") expect(window.alert).toHaveBeenCalledWith("Notfound User") }); });
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template */ package controller.TestFeature; import dao.CourseDAO; import dao.QuizDAO; import dao.QuizResultDAO; import dao.SubscriptionDAO; import dao.UserDAO; import entity.ManageCourse; import entity.Quiz; import entity.QuizResult; import entity.Subscription; import entity.User; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.util.Vector; /** * * @author ACER */ public class QuizLesson extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try ( PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet QuizLesson</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet QuizLesson at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int quiz_id = Integer.parseInt(request.getParameter("quiz_id")); int user_id = 0; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("currUserId")) { user_id = Integer.parseInt(cookie.getValue()); } } } if (user_id == 0) { response.sendRedirect("login.jsp"); return; } else { UserDAO ud = new UserDAO(); User currUser = ud.getUserById(user_id); CourseDAO cd = new CourseDAO(); int cid = cd.getCourseidFromQuiz(quiz_id); ManageCourse checkRegisterdCourse = cd.checkCourseRegistered(cid, user_id); if (checkRegisterdCourse == null) { response.sendRedirect("courseDetails?course_id=" + cid); } else { SubscriptionDAO subScriptionDAO = new SubscriptionDAO(); Subscription currentSubscription = subScriptionDAO.GetCurrentSubscription(user_id); QuizResultDAO quizResultDAO = new QuizResultDAO(); Vector<QuizResult> quizResultList = quizResultDAO.getQuizResultByUserIdAndQuizId(user_id, quiz_id); QuizDAO quizDAO = new QuizDAO(); Quiz quiz = quizDAO.getQuizById(quiz_id); if(quiz.isQuiz_status()==false){ response.sendRedirect("UnactiveLesson.jsp"); return; } request.setAttribute("quiz", quiz); request.setAttribute("currUser", currUser); request.setAttribute("currSubscription", currentSubscription); request.setAttribute("quiz_id", quiz_id); request.setAttribute("quizResultList", quizResultList); PrintWriter out = response.getWriter(); request.getRequestDispatcher("quizLesson.jsp").forward(request, response); } } } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
// Unit 7 - Listing 3 import java.util.Scanner; public class FindNearestPoints { public static void main( String[] args ) { Scanner input = new Scanner( System.in ); System.out.print( "Enter the number of points: " ); int numberOfPoints = input.nextInt(); // Create an array to store points double[][] points = new double[ numberOfPoints ][ 2 ]; System.out.printf( "Enter %d points: " , numberOfPoints ); for( int i = 0; i < points.length; i++ ) { points[ i ][ 0 ] = input.nextDouble(); points[ i ][ 1 ] = input.nextDouble(); } // p1 and p2 are the indices in the points array int p1 = 0, p2 = 1; // Initial two points // Initialize shortestDistance double shortestDistance = distance( points[ p1 ][ 0 ], points[ p1 ][ 1 ], points[ p2 ][ 0 ], points[ p2 ][ 1 ] ); // Compute distance for every two points for( int i = 0; i < points.length; i++ ) { for( int j = i + 1; j < points.length; j++ ) { // Find distance double distance = distance( points[ i ][ 0 ], points[ i ][ 1 ], points[ j ][ 0 ], points[ j ][ 1 ] ); if( shortestDistance > distance ) { p1 = i; // Update p1 p2 = j; // Update p2 shortestDistance = distance; // Update shortestDistance } } } // Display result System.out.printf( "The closest two points are (%.2f, %.2f) and (%.2f, %.2f)." , points[ p1 ][ 0 ], points[ p1 ][ 1 ], points[ p2 ][ 0 ], points[ p2 ][ 1 ] ); } // Compute the distance between two points (x1 , y1) and (x2 , y2) public static double distance( double x1 , double y1, double x2, double y2 ) { return Math.sqrt( ( x2 - x1 ) * ( x2 - x1 ) + ( y2 - y1 ) * ( y2 - y1 ) ); } }
/* * jQuery myCart - v1.7 - 2018-03-07 * http://asraf-uddin-ahmed.github.io/ * Copyright (c) 2017 Asraf Uddin Ahmed; Licensed None */ (function ($) { "use strict"; var OptionManager = (function () { var objToReturn = {}; var _options = null; var DEFAULT_OPTIONS = { currencySymbol: '$', classCartIcon: 'my-cart-icon', classCartBadge: 'my-cart-badge', classProductQuantity: 'my-product-quantity', classProductRemove: 'my-product-remove', classCheckoutCart: 'my-cart-checkout', affixCartIcon: true, showCheckoutModal: true, numberOfDecimals: 2, cartItems: null, clickOnAddToCart: function ($addTocart) {}, afterAddOnCart: function (products, totalQuantity) {}, clickOnCartIcon: function ($cartIcon, products, totalQuantity) {}, checkoutCart: function (products, totalQuantity) { return false; }, }; var loadOptions = function (customOptions) { _options = $.extend({}, DEFAULT_OPTIONS); if (typeof customOptions === 'object') { $.extend(_options, customOptions); } }; var getOptions = function () { return _options; }; objToReturn.loadOptions = loadOptions; objToReturn.getOptions = getOptions; return objToReturn; }()); var MathHelper = (function () { var objToReturn = {}; var getRoundedNumber = function (number) { if (isNaN(number)) { throw new Error('Parameter is not a Number'); } number = number * 1; var options = OptionManager.getOptions(); return number.toFixed(options.numberOfDecimals); }; objToReturn.getRoundedNumber = getRoundedNumber; return objToReturn; }()); var ProductManager = (function () { var objToReturn = {}; /* PRIVATE */ localStorage.products = localStorage.products ? localStorage.products : ""; var getIndexOfProduct = function (id) { var productIndex = -1; var products = getAllProducts(); $.each(products, function (index, value) { if (value.id == id) { productIndex = index; return; } }); return productIndex; }; var setAllProducts = function (products) { localStorage.products = JSON.stringify(products); }; var addProduct = function (id, name, summary, quantity) { var products = getAllProducts(); products.push({ id: id, name: name, summary: summary, quantity: quantity, }); setAllProducts(products); }; /* PUBLIC */ var getAllProducts = function () { try { var products = JSON.parse(localStorage.products); return products; } catch (e) { return []; } }; var updatePoduct = function (id, quantity) { var productIndex = getIndexOfProduct(id); if (productIndex < 0) { return false; } var products = getAllProducts(); products[productIndex].quantity = typeof quantity === "undefined" ? products[productIndex].quantity * 1 + 1 : quantity; setAllProducts(products); return true; }; var setProduct = function (id, name, summary, quantity) { if (typeof id === "undefined") { console.error("id required"); return false; } if (typeof name === "undefined") { console.error("name required"); return false; } if (!$.isNumeric(quantity)) { console.error("quantity is not a number"); return false; } summary = typeof summary === "undefined" ? "" : summary; if (!updatePoduct(id)) { addProduct(id, name, summary, quantity); } }; var clearProduct = function () { setAllProducts([]); }; var removeProduct = function (id) { var products = getAllProducts(); products = $.grep(products, function (value, index) { return value.id != id; }); setAllProducts(products); }; var getTotalQuantity = function () { var total = 0; var products = getAllProducts(); $.each(products, function (index, value) { total += value.quantity * 1; }); return total; }; objToReturn.getAllProducts = getAllProducts; objToReturn.updatePoduct = updatePoduct; objToReturn.setProduct = setProduct; objToReturn.clearProduct = clearProduct; objToReturn.removeProduct = removeProduct; objToReturn.getTotalQuantity = getTotalQuantity; return objToReturn; }()); var loadMyCartEvent = function (targetSelector) { var options = OptionManager.getOptions(); var $cartIcon = $("." + options.classCartIcon); var $cartBadge = $("." + options.classCartBadge); var classProductQuantity = options.classProductQuantity; var classProductRemove = options.classProductRemove; var classCheckoutCart = options.classCheckoutCart; var idCartModal = 'my-cart-modal'; var idCartTable = 'my-cart-table'; var idEmptyCartMessage = 'my-cart-empty-message'; var classProductTotal = 'my-product-total'; var classAffixMyCartIcon = 'my-cart-icon-affix'; if (options.cartItems && options.cartItems.constructor === Array) { ProductManager.clearProduct(); $.each(options.cartItems, function () { ProductManager.setProduct(this.id, this.name, this.summary, this.quantity); }); } $cartBadge.text(ProductManager.getTotalQuantity()); if (!$("#" + idCartModal).length) { $('body').append( '<div class="modal fade bd-example-modal-lg" id="' + idCartModal + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">' + '<div class="modal-dialog modal-lg role="document">' + '<div class="modal-content">' + '<div class="modal-header">' + '<h5 class="modal-title text-tronrud-primary" id="orderModalLabel">Your order</h5>' + '<button type="button" class="close" data-dismiss="modal" aria-label="Close">' + '<span aria-hidden="true"><i class="fas fa-times"></i></span>' + '</button>' + '</div>' + '<div class="modal-body">' + '<div class="container-fluid">' + '<div class="row">' + '<div class="col-md-6 order-md-2 table-responsive">' + '<h4 class="d-flex justify-content-between align-items-center mb-3">' + '<span class="text-muted">Your cart</span>' + '<span class="badge badge-pill badge-tronrud-secondary my-cart-badge"></span>' + '</h4>' + '<ul class="list-group mb-3">' + '<table class="table table-hover table-striped" id="' + idCartTable + '"></table>' + '</ul>' + '</div>' + '<div class="col-md-6 order-md-1">' + '<h4 class="mb-3">Billing address</h4>' + '<div class="mb-3">' + '<label for="firstName">Company</label>' + '<input type="text" class="form-control" id="firstName" disabled="disabled" value="' + companySession + '">' + '</div>' + '<div class="row">' + '<div class="col-md-8 mb-3">' + '<label for="email">E-mail</label>' + '<input type="email" class="form-control" id="email" disabled="disabled" value="' + emailSession + '">' + '</div>' + '<div class="col-md-4 mb-3">' + '<label for="zip">Phone</label>' + '<input type="text" class="form-control" id="phone" disabled="disabled" value="' + phoneSession + '">' + '</div>' + '</div>' + '<div class="row">' + '<div class="col-md-8 mb-3">' + '<label for="address">Address</label>' + '<input type="text" class="form-control" id="address" disabled="disabled" value="' + adressSession + '">' + '</div>' + '<div class="col-md-4 mb-3">' + '<label for="zip">Zip</label>' + '<input type="text" class="form-control" id="zip" disabled="disabled" value="' + zipSession + '">' + '</div>' + '</div>' + '<div class="form-group">' + '<label for="fritekst">Comment</label>' + '<textarea class="form-control" id="fritekst" rows="3"></textarea>' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '<div class="modal-footer">' + '<a href="" class="btn btn-success ' + classCheckoutCart + '">' + '<i class="fas fa-check fa-lg align-middle mr-1"></i><b>Checkout</b>' + '</a>' + '</div>' + '</div>' + '</div>' + '</div>' ); } var drawTable = function () { var $cartTable = $("#" + idCartTable); $cartTable.empty(); var products = ProductManager.getAllProducts(); $.each(products, function () { $cartTable.append( '<tr title="' + this.summary + '" data-id="' + this.id + '">' + '<td class="col-10 align-middle">' + this.name + '</td>' + '<td class="col-1 align-middle" title="Quantity"><input id="numberQ" type="number" min="1" style="width:40px;" class="' + classProductQuantity + '" value="' + this.quantity + '"/></td>' + '<td class="col-1 align-middle" title="Remove from Cart" class="text-center"><a href="javascript:void(0);" class="btn btn-xs btn-rounded my-0 btn-danger ' + classProductRemove + '"><i class="fas fa-times"></i></a></td>' + '</tr>' ); }); $cartTable.append(products.length ? '<tr>' + '/<tr>' : '<div class="alert alert-danger" role="alert" id="' + idEmptyCartMessage + '">Your cart is empty</div>' ); }; var showModal = function () { drawTable(); $("#" + idCartModal).modal('show'); }; var updateCart = function () { $.each($("." + classProductQuantity), function () { var id = $(this).closest("tr").data("id"); ProductManager.updatePoduct(id, $(this).val()); }); }; /* EVENT */ if (options.affixCartIcon) { var cartIconBottom = $cartIcon.offset().top * 1 + $cartIcon.css("height").match(/\d+/) * 1; var cartIconPosition = $cartIcon.css('position'); $(window).scroll(function () { $(window).scrollTop() >= cartIconBottom ? $cartIcon.addClass(classAffixMyCartIcon) : $cartIcon.removeClass(classAffixMyCartIcon); }); } $cartIcon.click(function () { options.showCheckoutModal ? showModal() : options.clickOnCartIcon($cartIcon, ProductManager.getAllProducts(), ProductManager.getTotalQuantity()); }); $(document).on("input", "." + classProductQuantity, function () { var id = $(this).closest("tr").data("id"); var quantity = $(this).val(); $(this).parent("td").next("." + classProductTotal).text(options.currencySymbol); ProductManager.updatePoduct(id, quantity); $cartBadge.text(ProductManager.getTotalQuantity()); }); $(document).on('keypress', "." + classProductQuantity, function (evt) { if (evt.keyCode == 38 || evt.keyCode == 40) { return; } evt.preventDefault(); }); $(document).on('click', "." + classProductRemove, function () { var $tr = $(this).closest("tr"); var id = $tr.data("id"); $tr.hide(500, function () { ProductManager.removeProduct(id); drawTable(); $cartBadge.text(ProductManager.getTotalQuantity()); }); }); $(document).on('click', "." + classCheckoutCart, function () { var products = ProductManager.getAllProducts(); if (!products.length) { $("#" + idEmptyCartMessage).fadeTo('fast', 0.5).fadeTo('fast', 1.0); return; } updateCart(); var isCheckedOut = options.checkoutCart(ProductManager.getAllProducts(), ProductManager.getTotalQuantity()); if (isCheckedOut !== false) { ProductManager.clearProduct(); $cartBadge.text(ProductManager.getTotalQuantity()); $("#" + idCartModal).modal("hide"); } }); $(document).on('click', targetSelector, function () { var $target = $(this); options.clickOnAddToCart($target); var id = $target.data('id'); var name = $target.data('name'); var summary = $target.data('summary'); var quantity = $target.data('quantity'); ProductManager.setProduct(id, name, summary, quantity); $cartBadge.text(ProductManager.getTotalQuantity()); options.afterAddOnCart(ProductManager.getAllProducts(), ProductManager.getTotalQuantity()); }); }; $.fn.myCart = function (userOptions) { OptionManager.loadOptions(userOptions); loadMyCartEvent(this.selector); return this; }; })(jQuery);
# Laravel AuthSystem API Project Ovo je API projekat zasnovan na Laravelu. ## Zahtevi - PHP = 11.7 - Composer - Docker ## Instalacija 1. Preuzmite projekat kao zip datoteku sa [GitHub repozitorijuma](https://github.com/vaš_korisničko_ime/ime_repozitorijuma/archive/refs/heads/main.zip). 2. Ekstraktujte zip datoteku: ```bash unzip ime_repozitorijuma-main.zip cd ime_repozitorijuma-main ``` 3. Instalirajte PHP zavisnosti: ```bash composer install ``` 4. Kopirajte `.env.example` u `.env`: ```bash cp .env.example .env ``` 5. Generišite aplikacioni ključ: ```bash php artisan key:generate ``` ## Povezivanje sa MySQL Bazom Podataka na Dockeru (mozete i preko samog mysql ne koristeci docker) 1. Podignite MySQL kontejner koristeći Docker: ```bash docker run --name laravel_mysql -e MYSQL_ROOT_PASSWORD=vaša_lozinka -e MYSQL_DATABASE=ime_baze -e MYSQL_USER=vaše_korisničko_ime -e MYSQL_PASSWORD=vaša_lozinka -p 3306:3306 -d mysql:latest ``` 2. Uredite `.env` fajl sa vašim MySQL podešavanjima: ```ini DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=ime_baze DB_USERNAME=vaše_korisničko_ime DB_PASSWORD=vaša_lozinka ``` 3. Pokrenite migracije kako biste kreirali tabele u bazi: ```bash php artisan migrate ``` ## Pokretanje Servera 1. Pokrenite lokalni razvojni server: ```bash php artisan serve ``` Sada možete otvoriti preglednik i otići na `http://localhost:8000` kako biste videli vašu aplikaciju ili testirali API. ## Testiranje API-ja 1. Pokrenite Postman. 2. Napravite novu kolekciju ili upit u Postman-u. 3. Postavite URL na `http://localhost:8000` (ili odgovarajući endpoint). 4. Pošaljite zahteve (GET, POST, PUT, DELETE) prema potrebi i proverite odgovore. ## Kreiranje Podataka za Prvi Put (Seed) Ako želite kreirati osnovne podatke za aplikaciju, možete koristiti seeder-e: ```bash php artisan db:seed
=== VM test suite to run build in guests === == Intro == This test suite contains scripts that bootstrap various guest images that have necessary packages to build QEMU. The basic usage is documented in Makefile help which is displayed with "make vm-test". == Quick start == Run "make vm-test" to list available make targets. Invoke a specific make command to run build test in an image. For example, "make vm-build-freebsd" will build the source tree in the FreeBSD image. The command can be executed from either the source tree or the build dir; if the former, ./configure is not needed. The command will then generate the test image in ./tests/vm/ under the working directory. Note: images created by the scripts accept a well-known RSA key pair for SSH access, so they SHOULD NOT be exposed to external interfaces if you are concerned about attackers taking control of the guest and potentially exploiting a QEMU security bug to compromise the host. == QEMU binary == By default, qemu-system-x86_64 is searched in $PATH to run the guest. If there isn't one, or if it is older than 2.10, the test won't work. In this case, provide the QEMU binary in env var: QEMU=/path/to/qemu-2.10+. == Make jobs == The "-j$X" option in the make command line is not propagated into the VM, specify "J=$X" to control the make jobs in the guest. == Debugging == Add "DEBUG=1" and/or "V=1" to the make command to allow interactive debugging and verbose output. If this is not enough, see the next section. == Manual invocation == Each guest script is an executable script with the same command line options. For example to work with the netbsd guest, use $QEMU_SRC/tests/vm/netbsd: $ cd $QEMU_SRC/tests/vm # To bootstrap the image $ ./netbsd --build-image --image /var/tmp/netbsd.img <...> # To run an arbitrary command in guest (the output will not be echoed unless # --debug is added) $ ./netbsd --debug --image /var/tmp/netbsd.img uname -a # To build QEMU in guest $ ./netbsd --debug --image /var/tmp/netbsd.img --build-qemu $QEMU_SRC # To get to an interactive shell $ ./netbsd --interactive --image /var/tmp/netbsd.img sh == Adding new guests == Please look at existing guest scripts for how to add new guests. Most importantly, create a subclass of BaseVM and implement build_image() method and define BUILD_SCRIPT, then finally call basevm.main() from the script's main(). - Usually in build_image(), a template image is downloaded from a predefined URL. BaseVM._download_with_cache() takes care of the cache and the checksum, so consider using it. - Once the image is downloaded, users, SSH server and QEMU build deps should be set up: * Root password set to BaseVM.ROOT_PASS * User BaseVM.GUEST_USER is created, and password set to BaseVM.GUEST_PASS * SSH service is enabled and started on boot, $QEMU_SRC/tests/keys/id_rsa.pub is added to ssh's "authorized_keys" file of both root and the normal user * DHCP client service is enabled and started on boot, so that it can automatically configure the virtio-net-pci NIC and communicate with QEMU user net (10.0.2.2) * Necessary packages are installed to untar the source tarball and build QEMU - Write a proper BUILD_SCRIPT template, which should be a shell script that untars a raw virtio-blk block device, which is the tarball data blob of the QEMU source tree, then configure/build it. Running "make check" is also recommended.
<?php namespace App\Filament\Resources; use App\Filament\Resources\PaybillResource\Pages; use App\Filament\Resources\PaybillResource\RelationManagers; use App\Models\Paybill; use App\Models\User; use Filament\Forms; use Filament\Forms\Components\Fieldset; use Filament\Forms\Components\Select; use Filament\Forms\Components\TextInput; use Filament\Forms\Form; use Filament\Resources\Resource; use Filament\Tables; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; use Illuminate\Support\Str; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\SoftDeletingScope; class PaybillResource extends Resource { protected static ?string $model = Paybill::class; protected static ?string $navigationIcon = 'heroicon-o-wallet'; public static function form(Form $form): Form { return $form ->schema([ Fieldset::make()->schema([ Select::make('manager_name')->options(User::role('manager')->pluck('name', 'name'))->required(), TextInput::make('paybill_number')->required()->integer()->minLength(4), TextInput::make('consumer_key')->required(), TextInput::make('consumer_secret')->required() ])->columns(2) ]); } public static function table(Table $table): Table { return $table ->columns([ TextColumn::make('index')->rowIndex(), TextColumn::make('manager_name')->searchable()->sortable()->size('sm'), TextColumn::make('paybill_number')->size('sm')->searchable()->sortable(), TextColumn::make('consumer_key')->size('sm')->searchable()->formatStateUsing(fn($state) => Str::mask($state,'*',3)), TextColumn::make('consumer_secret')->size('sm')->searchable()->formatStateUsing(fn($state) => Str::mask($state,'*',3)) ]) ->filters([ // ]) ->actions([ Tables\Actions\EditAction::make(), Tables\Actions\DeleteAction::make(), ]) ->bulkActions([ Tables\Actions\BulkActionGroup::make([ Tables\Actions\DeleteBulkAction::make(), ]), ]) ->emptyStateActions([ Tables\Actions\CreateAction::make(), ]); } public static function getPages(): array { return [ 'index' => Pages\ManagePaybills::route('/'), ]; } }
<!doctype html> <html lang="zh-CN"> <head> <title>Title</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <style> input{ width: 150px; height: 20px; } body{ text-align: center; } #m3{ width: 200px; height: 50px; } </style> </head> <body> <!--author:LiuHai --> <!--github:https://github.com/SkyrinCHN --> <h3>新input type</h3> 年龄<input type="number" name="age" min="18" max="45" /> <br> 邮件<input type="email" name="myEmail"><br> 网址<input type="url" name="myurl"><br> 范围<input type="range" name="myrange"> 10 <br> 日期<input type="date" name="mydate"><br> 日期 <input type="week" name="myweek"><br> 日期 <input type="month" name="mymonth"><br> <input type="submit" value="注册"> <datalist id="list1"> <option >大头儿子</option> <option >小头爸爸</option> </datalist> 起个角色名呗: <input type="text" list="list1" ><br> <progress id="pro" value=""></progress> <br> <!-- <meter min="1" max="10" low="10" high="100" value="3"></meter> --> <meter min="0" max="100000" low="3000" high="20000" optimum="90000" value="5000," id="m3"></meter><br> 商品单价: <span>3</span> <br> 购买数量<input type="number" value="1"/><br> 计算:<output></output> <script> var pro = document.getElementById("pro"); var v= 0 ; var p = setInterval(function(){ v+=0.1; pro.value=v; if(v>0.9){ clearInterval(p); } },100) var m3 = document.getElementById("m3"); var m = 0; var i = setInterval(() => { m+=2000; m3.value=m; }, 500); if(m>99999){ clearInterval(i); } </script> </body> </html>
/**************************************************************************** FileName [ Board.js ] PackageName [ src/components ] Author [ Cheng-Hua Lu ] Synopsis [ This file generates the Board. ] Copyright [ 2022 10 ] ****************************************************************************/ import Row from "./Row"; import './css/Board.css'; import React from "react"; import CurRow from "./CurRow"; const Board = ({ turn, guesses, curGuess }) => { let index = -1; return ( <div className="Board-container"> {/* TODO 2-2: show 6 rows (map function is recommended) and defined row's key. Hint: Use `CurRow` instead of `Row` when you are passing `curGuess` into it. */} {guesses.map(guess => { index++; return ( (turn === index) ? <CurRow id={'row_' + index} key={'row_' +index} curGuess={curGuess} rowIdx={index} /> : <Row id={'row_' + index} key={'row_' + index} guess={guess} rowIdx={index} /> ) })} </div> ) }; export default Board;
"use client"; import useBetterMediaQuery from "@/hooks/use-media-query"; import { cn } from "@/lib/utils"; import { X } from "lucide-react"; import Link from "next/link"; import { useEffect, useState } from "react"; const Message: React.FC = () => { const [message, setMessage] = useState<WulkanowyMessages>(); const isDesktop = useBetterMediaQuery("(min-width: 768px)"); let hiddenMessages: number[] = []; if (typeof window !== "undefined") { hiddenMessages = JSON.parse(localStorage.getItem("hiddenMessages") || "[]") || []; } useEffect(() => { fetch("https://messages.wulkanowy.net.pl/v1.json").then((response) => { response.json().then((data: WulkanowyMessages[]) => { const filteredMessages = data.filter( (message) => !message.targetFlavor && message.priority != "LOW" && message.messageTypes.includes("GENERAL_MESSAGE"), ); const firstMessage = filteredMessages[0]; if ( firstMessage && !hiddenMessages.includes(firstMessage.id) && firstMessage.isVisible ) { setMessage(firstMessage); } }); }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const handleClose = () => { setMessage(undefined); localStorage.setItem( "hiddenMessages", JSON.stringify(hiddenMessages.concat(message?.id || [])), ); }; if (!message) return null; return ( <div data-aos={isDesktop ? "fade-up" : "fade-down"} data-aos-delay={isDesktop ? 1000 : 0} data-aos-once="true" data-aos-offset="-500" className="relative z-50 flex w-full items-center justify-center px-6 max-lg:top-6 lg:fixed lg:bottom-6" > <div className="relative flex min-h-20 items-center rounded-3xl bg-secondaryFixed text-center font-medium text-onSecondaryFixed lg:px-16"> <Link href={message.destinationUrl || ""} target="_blank" className={cn( !message.destinationUrl && "pointer-events-none cursor-default", )} > <p className="p-4">{message.content}</p> </Link> <button onClick={handleClose} className="absolute right-8 rounded-button bg-onSecondaryContainer p-2 text-onSecondaryFixed max-lg:hidden" > <X /> </button> </div> <button onClick={handleClose} className="absolute -bottom-4 right-3 rounded-button bg-onSecondaryContainer p-2 text-onSecondaryFixed lg:hidden" > <X /> </button> </div> ); }; export default Message;
# frozen_string_literal: true module RemoteDevelopment # noinspection RubyClassModuleNamingConvention, RubyInstanceMethodNamingConvention - See https://handbook.gitlab.com/handbook/tools-and-tips/editors-and-ides/jetbrains-ides/code-inspection/why-are-there-noinspection-comments/ # noinspection RubyInstanceMethodNamingConvention - See https://handbook.gitlab.com/handbook/tools-and-tips/editors-and-ides/jetbrains-ides/code-inspection/why-are-there-noinspection-comments/ module RailwayOrientedProgrammingHelpers # NOTE: Depends upon `value` being defined in the including spec def stub_methods_to_return_ok_result(*methods) methods.each do |method| allow(method).to receive(:call).with(value) { Result.ok(value) } end end # NOTE: Depends upon `value` and `err_message_context` being defined in the including spec def stub_methods_to_return_err_result(method:, message_class:) allow(method).to receive(:call).with(value) do # noinspection RubyResolve Result.err(message_class.new(err_message_context)) end end def stub_methods_to_return_value(*methods) methods.each do |method| allow(method).to receive(:call).with(value) { value } end end end end
<script> export default { layout: 'admin', middleware: ['admin-auth'], head() { return { title: `Пост | ${this.post.title}` } }, validate({params}) { return Boolean(params.id) }, async asyncData({store, params}) { const post = await store.dispatch('post/fetchAdminById', params.id) console.log(post) return {post} }, data() { return { loading: false, controls: { text: '', }, rules: { text: [ {required: true, message: 'Пожалуйста, введите текст', trigger: 'blur'}, ], } } }, methods: { onSubmit() { this.$refs.form.validate(async valid => { if (valid) { this.loading = true; const formData = { text: this.controls.text, id: this.post._id, } try { await this.$store.dispatch('post/update', formData); this.$message.success('Пост обновлен') this.loading = false } catch (e) { this.loading = false } } }) } } } </script> <template> <div class="page-wrap"> <el-breadcrumb separator="/" class="mb"> <el-breadcrumb-item to="/admin/list">Посты</el-breadcrumb-item> <el-breadcrumb-item>{{post?.title}}</el-breadcrumb-item> </el-breadcrumb> <el-form ref="form" :model="controls" :rules="rules" @submit.native.prevent="onSubmit"> <el-form-item label="Текст в формате .md или .html" prop="text"> <el-input type="textarea" resize="none" :rows="10" v-model.trim="controls.text"/> </el-form-item> <div class="mb"> <small class="mr"> <i class="el-icon-time"></i> <span style="margin-left: 10px"> {{new Date(post.date).toLocaleString()}} </span> </small> <small> <i class="el-icon-view"></i> <span > {{post.views}} </span> </small> </div> <el-form-item> <el-button round :loading="loading" native-type="submit" type="primary" >Обновить</el-button> </el-form-item> </el-form> </div> </template> <style scoped lang="less"> .page-wrap { max-width: 600px; .mr { margin-right: 2rem; } } </style>
"use strict"; /* +----------------------------------------------------------------------+ | LiteRT HTTP.js Library | +----------------------------------------------------------------------+ | Copyright (c) 2018 Fenying Studio | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://github.com/litert/http.js/blob/master/LICENSE | +----------------------------------------------------------------------+ | Authors: Angus Fenying <fenying@litert.org> | +----------------------------------------------------------------------+ */ Object.defineProperty(exports, "__esModule", { value: true }); // tslint:disable:no-console const http = require("../"); const fs = require("fs"); let router = http.createStandardRouter(); router.notFound(async function (ctx) { ctx.response.statusCode = 404; ctx.response.end("NOT FOUND"); }).get("/", async function (context) { const request = context.request; const response = context.response; response.setHeader("Content-Type", "text/html; charset=utf-8"); response.write(`Method: ${request.method}<br>`); response.write(`URL Path: ${request.path}<br>`); response.write(`Handler Path: ${request.realPath}<br>`); response.write(`Search: ${request.queryString}<br>`); response.write(`Request Host: ${request.host}<br>`); response.write(`Request Domain: ${request.hostDomain}<br>`); response.write(`Request Port: ${request.hostPort}<br>`); response.write(`Server Host: ${request.server.host}<br>`); response.write(`Server Port: ${request.server.port}<br>`); response.write(`SSL: ${request.https ? "Yes" : "No"}<br>`); response.write(`Remote IP: ${request.ip}<br>`); response.write(`Date: ${new Date(request.time).toUTCString()}<br>`); request.loadCookies(); console.log(request.cookies); }).get("/test", async function (context) { context.response.setCookie("a", "2333"); }).get("/cookies", async function (context) { context.request.loadCookies(); context.response.sendJSON(context.request.cookies); }).get("/users/{user:int}", async function (context) { context.response.write(JSON.stringify(context.request.params)); }).get("/redirection", async function (context) { context.response.redirect("/"); }).post("/content", async function (context) { context.response.write(await context.request.getContent({ type: "raw" })); context.response.write(await context.request.getContent({ type: "raw" })); context.response.end("/"); }); let cookies = http.createStandardCookiesEncoder(); let server = http.createServer({ "port": 443, "router": router, "ssl": { "key": fs.readFileSync("a.local.org-privkey.pem"), "certificate": fs.readFileSync("a.local.org-cert.pem") }, "version": 2, "plugins": { "parser:cookies": cookies } }); server.on("error", function (err) { console.log(err); }); server.start(); //# sourceMappingURL=https-2.js.map
<script setup lang="ts"> import {onMounted, reactive, ref} from "vue"; import ListElementClone from "./ListElementClone.vue"; import type {ListElementType} from "@/entities/dragAndDropType"; import {useMousePos} from "@/composable/useMousePos"; import {useEventTargetListener} from "@/composable/useEventListener"; const list1 = ref([ {id: 1, name: "Item 1"}, {id: 2, name: "Item 2"}, {id: 3, name: "Item 3"}, ]); const list2 = ref([ {id: 4, name: "Item 4"}, {id: 5, name: "Item 5"}, {id: 6, name: "Item 6"}, ]); let pageContainer = reactive({ element: null as HTMLElement | null, offsetX: 0, offsetY: 0, }); let cloneDraggedElement = reactive({ element: null as HTMLElement | null, }); onMounted(() => { pageContainer.element = document.querySelector(".drop_down_clone_container")!; }); const {x, y} = useMousePos(); const mouseMove = () => { let xOffset = x.value - pageContainer.offsetX; let yOffset = y.value - pageContainer.offsetY; if (cloneDraggedElement.element) { //cloneDraggedElement.element.style.transform = `translateX(${xOffset}px) translateY(${yOffset}px)`; } }; const selectItemToDrag = (event: MouseEvent, item: ListElementType) => { event.preventDefault(); window.addEventListener("mousemove", mouseMove); let selectedItem = document.getElementById(item.id.toString()); pageContainer.offsetX = pageContainer.element?.getBoundingClientRect().x!; pageContainer.offsetY = pageContainer.element?.getBoundingClientRect().y!; createClone(item); }; const onMouseUp = () => { window.removeEventListener("mousemove", mouseMove); // if (cloneDraggedElement.element && cloneDraggedElement.element.parentNode) { // cloneDraggedElement.element.parentNode.removeChild(cloneDraggedElement.element); // cloneDraggedElement.element = null; // } }; useEventTargetListener(window, "mouseup", onMouseUp); const createClone = (item: ListElementType) => { let selectedItem = document.getElementById(item.id.toString()); // Get the position of the original element // let xOffset = x.value - pageContainer.offsetX; // let yOffset = y.value - pageContainer.offsetY; let xOffset = 0; let yOffset = 0; if (selectedItem) { cloneDraggedElement.element = selectedItem.cloneNode(true) as HTMLElement; cloneDraggedElement.element.classList.add("list_item-cloned"); //cloneDraggedElement.element.style.transform = `translateX(${xOffset}px) translateY(${yOffset}px)`; let rect = selectedItem.getBoundingClientRect(); let xOffset = rect.left - pageContainer.element?.getBoundingClientRect().left!; let yOffset = rect.top - pageContainer.element?.getBoundingClientRect().top!; cloneDraggedElement.element.style.left = `${xOffset}px`; cloneDraggedElement.element.style.top = `${yOffset}px`; if (pageContainer.element instanceof Element) { pageContainer.element.appendChild(cloneDraggedElement.element); } } }; </script> <template> <div class="drop_down_clone_container"> <section :class="['list-clone']"> <h2>Clone List 1</h2> <list-element-clone v-for="item in list1" v-on:mousedown="(event: MouseEvent) => selectItemToDrag(event, item)" :key="item.id" :item="item" /> </section> <section :class="['list-clone']"> <h2>Clone List 2</h2> <list-element-clone v-for="item in list2" v-on:mousedown.prevent="(event: MouseEvent) => selectItemToDrag(event, item)" :key="item.id" :item="item" /> </section> </div> </template> <style lang="scss" scoped> .list_item-cloned { position: absolute; z-index: 1; text-align: center; width: 249px; padding: 0.5rem; border: 1px solid #969696; border-radius: 0.5rem; background-color: #e1e0e0; cursor: grab; &:active { cursor: grabbing; } // transition: opacity 0.25s ease-in-out, transform 0.1s ease-in-out; } .drop_down_clone_container { display: flex; flex-direction: column; align-items: center; gap: 2rem; padding-block: 2rem; background-color: #e1e0e0; } .list-clone { display: flex; flex-direction: column; align-items: center; gap: 1rem; border-radius: 0.5rem; border: 1px solid #969696; padding: 1rem 1rem; width: 20rem; } h2 { font-size: 1.5rem; border-bottom: 1px solid #969696; margin-bottom: 1rem; width: 90%; } </style>
import { _decorator, Component, Node } from 'cc'; import { GameObject } from '../GameObjects/GameObject'; import GameObjectType from '../Enums/GameObjectType'; import ColorType from '../Enums/ColorType'; const { ccclass, property } = _decorator; interface Level { type: string; color: string; x: number; y: number; angle: number; path: string; imagePath: string; blockers?: number[]; blockerPrefabPath?: string; blockerPath?: string; } @ccclass('Rings') export class Rings extends Component { @property({ type: Node, tooltip: 'the node that must contain only gameobjects for the download' }) ringHolder: Node = null; @property({ type: Node, tooltip: 'will download json with the level setting' }) downloadBtn: Node = null; private _rings: Node[] = []; protected start() { if (this.downloadBtn) { this.downloadBtn.on(Node.EventType.TOUCH_START, this.onDown, this); } if (this.ringHolder) this._rings = this.ringHolder.children; } /* set all the parameters for making a json file*/ private _downLoadJson() { const ringPositions = this._rings.map((node) => { const go = node.getComponent(GameObject); if (go) { const type = GameObjectType[go.type]; const color = ColorType[go.color]; const x = Math.floor(node.position.x); const y = Math.floor(node.position.y); const angle = Math.floor(node.angle); const path = `prefabs/${type}`; const imagePath = `images/${type.toLowerCase()}/${type.toLowerCase()}_${color.toLowerCase()}/spriteFrame`; const blockers = go.blockers ? go.blockers.children.map((node) => node.angle) : []; const blockerPrefabPath = 'prefabs/SingleBlocker'; const blockerPath = `images/blockers_single/single_blocker_${color.toLowerCase()}/spriteFrame`; let level: Level = { type: type, color: color, x: x, y: y, angle: angle, path: path, imagePath: imagePath, }; if (blockers.length > 0) { level.blockers = blockers; level.blockerPrefabPath = blockerPrefabPath; level.blockerPath = blockerPath; } return level; } }); const content = JSON.stringify(ringPositions); let downloadElement = document.createElement('a'); let file = new Blob([content], { type: 'application/json' }); downloadElement.href = URL.createObjectURL(file); const name = 'LevelRings.json'; downloadElement.download = name; downloadElement.click(); } private onDown(): void { this._downLoadJson(); } }
import 'dart:convert'; import 'package:http/http.dart' as https; import '../../../export.dart'; class NetworkService { static final NetworkService _instance = NetworkService._init(); static NetworkService get instance => _instance; NetworkService._init(); Future<dynamic> http<T extends IBaseModel>( String path, IBaseModel model, Methods method, { Object? body, Map<String, dynamic>? queryParameters, }) async { var url = Uri.https(AppConstants.baseURL, path, queryParameters); //LocaleManager.instance.setString(PreferencesKeys.accessToken, ''); TODO Giriş yapıldığında token cihaza kaydedilcek String accessToken = LocaleManager.instance.getString(PreferencesKeys.accessToken) ?? ''; var headers = { 'content-type': 'application/json', 'Authorization': 'Bearer $accessToken', }; https.Response? response; switch (method) { case Methods.get: response = await https.get(url, headers: headers).timeout( const Duration(seconds: AppConstants.responseTimeout), onTimeout: () => https.Response('Timeout', 408), ); break; case Methods.post: response = await https .post(url, headers: headers, body: jsonEncode(body)) .timeout( const Duration(seconds: AppConstants.responseTimeout), onTimeout: () => https.Response('Timeout', 408), ); break; case Methods.put: response = await https .put(url, headers: headers, body: jsonEncode(body)) .timeout( const Duration(seconds: AppConstants.responseTimeout), onTimeout: () => https.Response('Timeout', 408), ); break; case Methods.delete: response = await https .put(url, headers: headers, body: jsonEncode(body)) .timeout( const Duration(seconds: AppConstants.responseTimeout), onTimeout: () => https.Response('Timeout', 408), ); break; default: } if (response!.statusCode == 200) { return jsonBodyParser<T>(model, response.body); } else if (response.statusCode == 401) { // TODO logout ve token' ı sil } else if (response.statusCode == 408) { return Get.offAndToNamed(NavigationConstants.connectionError); } else { // Hata mesajını ekrana göster Get.Snackbar() return jsonBodyParser<T>(model, response.body); } } dynamic jsonBodyParser<T>(IBaseModel model, String body) { final Map<String, dynamic> jsonBody = jsonDecode(body); return model.fromJson(jsonBody); } }
use arbitrary::Arbitrary; use serde::{Deserialize, Serialize}; use std::sync::Arc; pub mod arena; #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Arbitrary, Serialize, Deserialize)] pub struct Label(Arc<String>); #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Arbitrary, Serialize, Deserialize)] pub enum Type { Top, Int, Arr(Arc<Type>, Arc<Type>), And(Arc<Type>, Arc<Type>), Rcd(Label, Arc<Type>), } impl Default for Type { fn default() -> Self { Type::Top } } impl Type { pub fn is_arr(&self) -> bool { if let Type::Arr(_, _) = self { true } else { false } } } #[derive( Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash, Arbitrary, Serialize, Deserialize, )] pub enum AbstrMode { AbstrLabHide, AbstrGeneral, } #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Arbitrary, Serialize, Deserialize)] pub enum Expr { Top, Int(i64), Query, Abstr(AbstrMode, Arc<Expr>), Close { env: Arc<Expr>, expr: Arc<Expr> }, Apply(Arc<Expr>, Arc<Expr>), Merge(Arc<Expr>, Arc<Expr>), Annot(Arc<Expr>, Arc<Type>), Label(Label, Arc<Expr>), Fetch(Arc<Expr>, Label), } impl Default for Expr { fn default() -> Self { Expr::Top } } impl Expr { pub fn merge(&self, other: &Expr) -> Expr { Expr::Merge(Arc::new(self.clone()), Arc::new(other.clone())) } pub fn is_abstr(&self) -> bool { if let Expr::Abstr(_, _) = self { true } else { false } } pub fn is_arr_annot_abstr(&self) -> bool { if let Expr::Annot(expr, ty) = self { ty.is_arr() && expr.is_abstr() } else { false } } pub fn is_closure(&self) -> bool { if let Expr::Close { env, expr } = self { env.is_val() && expr.is_arr_annot_abstr() } else { false } } pub fn is_closure_subtype_of(&self, c: &Type, d: &Type) -> bool { if self.is_closure() { let Expr::Close { env: _, expr } = self else { return false; }; let Expr::Annot(_, ty) = &**expr else { return false; }; let Type::Arr(a, b) = &**ty else { return false }; subty(c, a) && subty(b, d) } else { false } } pub fn is_val(&self) -> bool { match self { Expr::Top | Expr::Int(_) => true, Expr::Merge(a, b) => a.is_val() && b.is_val(), Expr::Label(_, e) => e.is_val(), _ => self.is_closure(), } } pub fn is_rec(&self, lab: &Label) -> bool { if let Expr::Label(el, e) = self { el == lab && e.is_val() } else { false } } } #[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Arbitrary, Serialize, Deserialize)] pub enum Error { General(String), NonValEnv, NonValEval, StuckEval, StuckCast, } impl From<String> for Error { fn from(value: String) -> Self { Error::General(value) } } pub fn subty(a: &Type, b: &Type) -> bool { match (a, b) { // S-Z (Type::Int, Type::Int) => true, // S-TOP (_, Type::Top) => true, // S-ARR (Type::Arr(a1, a2), Type::Arr(b1, b2)) => subty(b1, a1) && subty(a2, b2), // S-ANDL // S-ANDR (Type::And(a1, a2), a3) => subty(a1, a3) || subty(a2, a3), // S-AND (a1, Type::And(a2, a3)) => subty(a1, a2) && subty(a1, a3), // S-RCD (Type::Rcd(l1, e1), Type::Rcd(l2, e2)) => l1 == l2 && subty(e1, e2), _ => false, } } pub fn ordinary(x: &Type) -> bool { match x { // O-INT Type::Int => true, // O-ARROW Type::Arr(_, b) => ordinary(b), // O-RCD Type::Rcd(_, b) => ordinary(b), _ => false, } } pub fn toplike(x: &Type) -> bool { match x { // TL-TOP Type::Top => true, // TL-ARR Type::And(a, b) => toplike(a) && toplike(b), // TL-ARR Type::Arr(_, b) => toplike(b), // TL-RCD Type::Rcd(_, b) => toplike(b), _ => false, } } // "Common Ordinary Super Types" pub fn cost(a: &Type, b: &Type) -> bool { match (a, b) { // COST-INT (Type::Int, Type::Int) => true, // COST-ANDL // COST-ANDR (Type::And(a, b), c) => cost(a, c) || cost(b, c), // COST-RANDL // COST-RANDR (a, Type::And(b, c)) => cost(a, b) || cost(a, c), // COST-ARR (Type::Arr(_a, b), Type::Arr(_c, d)) => cost(b, d), // COST-RCD (Type::Rcd(_, x), Type::Rcd(_, y)) => cost(x, y), _ => false, } } // Algorithmic disjointness pub fn disj(a: &Type, b: &Type) -> bool { !cost(a, b) } // Value generator for top-like types pub fn valgen(ty: &Type) -> Result<Expr, Error> { match ty { Type::Top => Ok(Expr::Top), Type::Int => Err(Error::StuckCast), Type::Arr(_, b) => { let expr = Arc::new(valgen(b)?); let abstr_expr = Arc::new(Expr::Abstr(AbstrMode::AbstrGeneral, expr)); let env = Arc::new(Expr::Top); let expr = Arc::new(Expr::Annot(abstr_expr, Arc::new(ty.clone()))); Ok(Expr::Close { env, expr }) } Type::And(a, b) => Ok(Expr::Merge(Arc::new(valgen(a)?), Arc::new(valgen(b)?))), Type::Rcd(lab, ty) => Ok(Expr::Label(lab.clone(), Arc::new(valgen(ty)?))), } } pub fn cast(val: &Expr, ty: &Type) -> Result<Expr, Error> { match (val, ty) { // CASTING-INT (Expr::Int(_), Type::Int) => Ok(val.clone()), // CASTING-TOP (_, Type::Top) => Ok(val.clone()), (Expr::Close { env, expr }, Type::Arr(c, d)) if val.is_closure_subtype_of(c, d) => { let Expr::Annot(e, cloty) = &**expr else { return Err(Error::StuckCast); }; let Type::Arr(a, _) = &**cloty else { return Err(Error::StuckCast); }; if toplike(d) { // CASTING-ARROWTL valgen(ty) } else { // CASTING-ARROW // TODO: modes let new_ty = Arc::new(Type::Arr(a.clone(), d.clone())); let new_annot_expr = Arc::new(Expr::Annot(e.clone(), new_ty)); Ok(Expr::Close { env: env.clone(), expr: new_annot_expr, }) } } // CASTING-MERGEVL and CASTING-MERGEVL (Expr::Merge(a, b), _) if ordinary(ty) => { if let Ok(c) = cast(a, ty) { Ok(c) } else if let Ok(c) = cast(b, ty) { Ok(c) } else { Err(Error::StuckCast) } } // CASTING-AND (_, Type::And(a, b)) => Ok(Expr::Merge( Arc::new(cast(val, a)?), Arc::new(cast(val, b)?), )), // CASTING-RCD (Expr::Label(elab, e), Type::Rcd(tlab, t)) if elab == tlab => { Ok(Expr::Label(elab.clone(), Arc::new(cast(e, t)?))) } _ => Err(Error::StuckCast), } } pub fn step(env: &Expr, expr: &Expr) -> Result<Expr, Error> { if !env.is_val() { return Err(Error::NonValEnv); } if expr.is_val() { return Ok(expr.clone()); } match expr { // STEP-CTX Expr::Query => Ok(env.clone()), // STEP-ANNOV Expr::Annot(v, t) if v.is_val() => cast(v, t), // STEP-MERGER Expr::Merge(v, e) if v.is_val() => { let env_with_v = env.merge(v); let ev = step(&env_with_v, e)?; Ok(v.merge(&ev)) } // STEP-CLOSURE e if e.is_arr_annot_abstr() => Ok(Expr::Close { env: Arc::new(env.clone()), expr: Arc::new(e.clone()), }), // STEP-BOX Expr::Close { env: env1, expr: expr1, } if env1.is_val() && !expr.is_closure() => step(env1, expr1), // STEP-BOXV Expr::Close { env: env1, expr: expr1, } if env1.is_val() && expr1.is_val() => Ok((**expr1).clone()), // STEP-BETA Expr::Apply(clo, arg) if clo.is_closure() && arg.is_val() => { let Expr::Close { env: env1, expr: expr1, } = &**clo else { return Err(Error::StuckEval); }; let Expr::Annot(abstr, ty) = &**expr1 else { return Err(Error::StuckEval); }; let Expr::Abstr(_mode, body) = &**abstr else { return Err(Error::StuckEval); }; let Type::Arr(_, b) = &**ty else { return Err(Error::StuckEval); }; // TODO: modes let new_env = env1.merge(arg); let new_annot = Expr::Annot(body.clone(), b.clone()); Ok(Expr::Close { env: Arc::new(new_env), expr: Arc::new(new_annot), }) } // STEP-PROJV Expr::Fetch(e, lab) if e.is_rec(lab) => { let Expr::Label(_, el) = &**e else { return Err(Error::StuckEval); }; Ok((**el).clone()) } // STEP-EVAL Expr::Annot(e, t) => Ok(Expr::Annot(Arc::new(step(env, e)?), t.clone())), Expr::Merge(a, b) => Ok(Expr::Merge(Arc::new(step(env, a)?), b.clone())), Expr::Label(lab, e) => Ok(Expr::Label(lab.clone(), Arc::new(step(env, e)?))), Expr::Fetch(e, lab) => Ok(Expr::Fetch(Arc::new(step(env, e)?), lab.clone())), Expr::Apply(clo, arg) if !clo.is_val() => { Ok(Expr::Apply(Arc::new(step(env, clo)?), arg.clone())) } Expr::Apply(clo, arg) => Ok(Expr::Apply(clo.clone(), Arc::new(step(env, arg)?))), Expr::Close { env: env1, expr } => Ok(Expr::Close { env: Arc::new(step(env, env1)?), expr: expr.clone(), }), _ => Err(Error::StuckEval), } }
--- layout: post type: socratic title: "Socratic Seminar 44" meetup: https://www.meetup.com/chibitdevs/events/hsqwssyfckbrb/ --- ## V3 bitcoin transactions! <https://bitcoinops.org/en/topics/version-3-transaction-relay/> <https://github.com/bitcoin/bitcoin/pull/25038/files#diff-8fe49384f6ab8be91802eb5d0f528fa521e301440b76508f6911d0dd2ae2cebfR1> Version 3 transaction relay is a proposal to allow transactions to opt-in to a modified set of transaction relay policies designed to prevent pinning attacks. Combined with package relay, these policies help enable the use of dynamic feerates with LN onchain transactions. ### Project tracking <https://github.com/bitcoin/bitcoin/issues/27463> **Credit:** glowzow ## Securing a $100MM Lightning node <https://acinq.co/blog/securing-a-100M-lightning-node> After years of R&D on how to secure our Lightning node, we have settled on a combination of AWS Nitro Enclaves (an Isolated Compute Environment) and Ledger Nano (a signing device with a trusted display). This setup offers what we believe is the best trade-off between security, flexibility, performance, and operational complexity for running a professional Lightning node. ## Phoenix deploys splicing! <https://acinq.co/blog/phoenix-splicing-update> TL; DR: Splicing changes the game. Phoenix now manages a single dynamic channel, no more 1% fee on inbound liquidity, better predictability and control, trustless swaps. The new fee schedule is detailed here. ## Wallet Scrutiny <https://walletscrutiny.com> <https://walletscrutiny.com/methodology/?tests-we-run/all/> The WalletScrutiny team is a small, non-profit collection of privacy and security-focused engineers helping everyone from bitcoin newcomers to full-fledged cypherpunks make informed decisions about how they store and send their bitcoin. So it’s only fitting to be as transparent about ourselves as we encourage wallet developers to be. ## A Technical Walkthrough of Hash Time Locked Contracts and Lightning Channel Operations <https://lightning.engineering/posts/2023-06-28-channel-normal-op/> **Credit:** Elle Mouton This post will walk through the different operations of a Lightning channel by following a long-running example with plenty of explanatory diagrams. First, we explore how Hash Time Locked Contracts (HTLCs) are added to a channel and how channel peers commit to a new state including these HTLCs. Next, we discuss how a channel’s normal flow is re-established after a disconnection. And finally, we finish with how a cooperative channel closure happens. ## New ECDSA cryptanalysis <https://eprint.iacr.org/2023/841.pdf> **Credit:** Dylan Rowe, Joachim Breitner, and Nadia Heninger This paper describes a cryptanalytic attack that allows for secret key recovery when observing ECDSA signatures that use a certain kind of structured nonce. Using the standard deterministic nonce construction avoids this attack.
import java.util.Scanner; abstract class Calc{ protected int a; protected int b; abstract void setValue(int a, int b); abstract int calculate(); } class Add extends Calc{ public void setValue(int a, int b) { super.a = a; super.b = b; } public int calculate() { return a + b; } } class Sub extends Calc{ public void setValue(int a, int b) { super.a = a; super.b = b; } public int calculate() { return a - b; } } class Mul extends Calc{ public void setValue(int a, int b) { super.a = a; super.b = b; } public int calculate() { return a * b; } } class Div extends Calc{ public void setValue(int a, int b) { super.a = a; super.b = b; } public int calculate() { return a / b; } } public class java_11 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("두 정수와 연산자를 입력하세요 >> "); int a = scanner.nextInt(); int b = scanner.nextInt(); String op = scanner.next(); switch(op) { case "+": Add add = new Add(); add.setValue(a, b); System.out.print(add.calculate()); break; case "-": Sub sub = new Sub(); sub.setValue(a, b); System.out.print(sub.calculate()); break; case "*": Mul mul = new Mul(); mul.setValue(a, b); System.out.print(mul.calculate()); break; case "/": Div div = new Div(); div.setValue(a, b); System.out.print(div.calculate()); break; } scanner.close(); } }
import * as React from 'react'; import { hCaptchaLoader, initSentry } from '@hcaptcha/loader'; import { getFrame, getMountElement } from './utils.js'; import { breadcrumbMessages, scopeTag } from "./constants"; class HCaptcha extends React.Component { constructor (props) { super(props); /** * Internal reference to track hCaptcha API * * Required as window is relative to initialization in application * not where the script and iFrames have been loaded. */ this._hcaptcha = undefined; // API Methods this.renderCaptcha = this.renderCaptcha.bind(this); this.resetCaptcha = this.resetCaptcha.bind(this); this.removeCaptcha = this.removeCaptcha.bind(this); this.isReady = this.isReady.bind(this); // Event Handlers this.loadCaptcha = this.loadCaptcha.bind(this); this.handleOnLoad = this.handleOnLoad.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleExpire = this.handleExpire.bind(this); this.handleError = this.handleError.bind(this); this.handleOpen = this.handleOpen.bind(this); this.handleClose = this.handleClose.bind(this); this.handleChallengeExpired = this.handleChallengeExpired.bind(this); this.ref = React.createRef(); this.apiScriptRequested = false; this.sentryHub = null; this.state = { isApiReady: false, isRemoved: false, elementId: props.id, captchaId: '' } } componentDidMount () { // Once captcha is mounted intialize hCaptcha - hCaptcha const element = getMountElement(this.props.scriptLocation); const frame = getFrame(element); this._hcaptcha = frame.window.hcaptcha || undefined; const isApiReady = typeof this._hcaptcha !== 'undefined'; this.sentryHub = initSentry(this.props.sentry, scopeTag); this.sentryHub.addBreadcrumb({ category: scopeTag.value, message: breadcrumbMessages.mounted, }); /* * Check if hCaptcha has already been loaded, * If Yes, render the captcha * If No, create script tag and wait to render the captcha */ if (isApiReady) { this.setState( { isApiReady: true }, () => { this.renderCaptcha(); } ); return; } this.loadCaptcha(); } componentWillUnmount() { const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (!this.isReady()) { return; } // Reset any stored variables / timers when unmounting hcaptcha.reset(captchaId); hcaptcha.remove(captchaId); this.sentryHub.addBreadcrumb({ category: scopeTag.value, message: breadcrumbMessages.unmounted, }); } shouldComponentUpdate(nextProps, nextState) { // Prevent component re-rendering when these internal state variables are updated if (this.state.isApiReady !== nextState.isApiReady || this.state.isRemoved !== nextState.isRemoved) { return false; } return true; } componentDidUpdate(prevProps) { // Prop Keys that could change const keys = ['sitekey', 'size', 'theme', 'tabindex', 'languageOverride', 'endpoint']; // See if any props changed during component update const match = keys.every( key => prevProps[key] === this.props[key]); // If they have changed, remove current captcha and render a new one if (!match) { this.removeCaptcha(() => { this.renderCaptcha(); }); } } loadCaptcha() { if (this.apiScriptRequested) { return; } const { apihost, assethost, endpoint, host, imghost, languageOverride: hl, reCaptchaCompat, reportapi, sentry, custom, loadAsync, scriptLocation, cleanup = true, } = this.props; const mountParams = { render: 'explicit', apihost, assethost, endpoint, hl, host, imghost, recaptchacompat: reCaptchaCompat === false? 'off' : null, reportapi, sentry, custom, loadAsync, scriptLocation, cleanup }; hCaptchaLoader(mountParams) .then(this.handleOnLoad, this.handleError) .catch(this.handleError); this.apiScriptRequested = true; } renderCaptcha(onReady) { const { isApiReady } = this.state; if (!isApiReady) return; const renderParams = Object.assign({ "open-callback" : this.handleOpen, "close-callback" : this.handleClose, "error-callback" : this.handleError, "chalexpired-callback": this.handleChallengeExpired, "expired-callback" : this.handleExpire, "callback" : this.handleSubmit, }, this.props, { hl: this.props.hl || this.props.languageOverride, languageOverride: undefined }); const hcaptcha = this._hcaptcha; //Render hCaptcha widget and provide necessary callbacks - hCaptcha const captchaId = hcaptcha.render(this.ref.current, renderParams); this.setState({ isRemoved: false, captchaId }, () => { onReady && onReady(); }); } resetCaptcha() { const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (!this.isReady()) { return; } // Reset captcha state, removes stored token and unticks checkbox hcaptcha.reset(captchaId) this.sentryHub.addBreadcrumb({ category: scopeTag.value, message: breadcrumbMessages.reset, }); } removeCaptcha(callback) { const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (!this.isReady()) { return; } this.setState({ isRemoved: true }, () => { hcaptcha.remove(captchaId); callback && callback() }); this.sentryHub.addBreadcrumb({ category: scopeTag.value, message: breadcrumbMessages.removed, }); } handleOnLoad () { this.setState({ isApiReady: true }, () => { try { const element = getMountElement(this.props.scriptLocation); const frame = getFrame(element); this._hcaptcha = frame.window.hcaptcha; // render captcha and wait for captcha id this.renderCaptcha(() => { // trigger onLoad if it exists const { onLoad } = this.props; if (onLoad) onLoad(); }); } catch (error) { this.sentryHub.captureException(error); } }); } handleSubmit (event) { const { onVerify } = this.props; const { isRemoved, captchaId } = this.state; const hcaptcha = this._hcaptcha; if (typeof hcaptcha === 'undefined' || isRemoved) return const token = hcaptcha.getResponse(captchaId) //Get response token from hCaptcha widget const ekey = hcaptcha.getRespKey(captchaId) //Get current challenge session id from hCaptcha widget if (onVerify) onVerify(token, ekey) //Dispatch event to verify user response } handleExpire () { const { onExpire } = this.props; const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (!this.isReady()) { return; } hcaptcha.reset(captchaId) // If hCaptcha runs into error, reset captcha - hCaptcha if (onExpire) onExpire(); this.sentryHub.addBreadcrumb({ category: scopeTag.value, message: breadcrumbMessages.expired, }); } handleError (event) { const { onError } = this.props; const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (this.isReady()) { // If hCaptcha runs into error, reset captcha - hCaptcha hcaptcha.reset(captchaId); } if (onError) onError(event); } isReady () { const { isApiReady, isRemoved } = this.state; return isApiReady && !isRemoved; } handleOpen () { if (!this.isReady() || !this.props.onOpen) { return; } this.props.onOpen(); } handleClose () { if (!this.isReady() || !this.props.onClose) { return; } this.props.onClose(); } handleChallengeExpired () { if (!this.isReady() || !this.props.onChalExpired) { return; } this.props.onChalExpired(); } execute (opts = null) { try { const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (!this.isReady()) { return; } if (opts && typeof opts !== "object") { opts = null; } return hcaptcha.execute(captchaId, opts); } catch (error) { this.sentryHub.captureException(error); } } setData (data) { const { captchaId } = this.state; const hcaptcha = this._hcaptcha; if (!this.isReady()) { return; } if (data && typeof data !== "object") { data = null; } hcaptcha.setData(captchaId, data); } getResponse() { const hcaptcha = this._hcaptcha; return hcaptcha.getResponse(this.state.captchaId); } getRespKey() { const hcaptcha = this._hcaptcha; return hcaptcha.getRespKey(this.state.captchaId) } render () { const { elementId } = this.state; return <div ref={this.ref} id={elementId}></div>; } } export default HCaptcha;
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class TranslationService { private language = new BehaviorSubject<string>('en'); private translations = new BehaviorSubject<any>({}); currentLanguage = this.language.asObservable(); currentTranslations = this.translations.asObservable(); constructor(private http: HttpClient) { this.loadTranslations('en'); } changeLanguage(lang: string) { this.language.next(lang); this.loadTranslations(lang); } private loadTranslations(lang: string) { this.http.get(`/assets/i18n/${lang}.json`).subscribe( (translations: any) => { this.translations.next(translations); }, (error) => { console.error(`Error loading ${lang} translations`, error); } ); } }
<?php namespace App\Http\Controllers; use App\Models\Post; use Intervention\Image\Facades\Image; use Illuminate\Http\Request; class PostsController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $users = auth()->user()->following()->pluck('profiles.user_id'); //$posts = Post::whereIn('user_id', $users)->orderBy('created_at', 'DESC')->get(); $posts = Post::whereIn('user_id', $users)->latest()->with('user')->paginate(2); //dd($posts); return view('posts.index', compact('posts')); } public function create() { return view('posts.create'); } public function store() { $data = request()->validate([ 'another' => '', 'caption' => 'required', 'image' => ['required','image'], ]); $imagePath = request('image')->store('uploads','public'); $image = Image::make(public_path("storage/{$imagePath}"))->fit(1200,1200); $image->save(); auth()->user()->posts()->create([ 'caption' => $data['caption'], 'image' => $imagePath, ]); //\App\Models\Post::create($data); //$post = new \App\Post(); // $post->caption = $data['caption']; // $post->save(); // $post->image = $data['image']; //dd(request()->all()); return redirect('/profile/' . auth()->user()->id); } public function show(\App\Models\Post $post) { //dd($post); return view('posts.show', compact('post')); } }