text
stringlengths
184
4.48M
**free // WATSONTR3R: This is a demo of Watson's Language Translator V3 // using input/output with JSON documents. // // Requires HTTPAPI and YAJL. // This version uses DATA-INTO and the YAJL generator // subprocedures. // ctl-opt option(*srcstmt) bnddir('HTTPAPI':'YAJL'); /copy version.rpgleinc /copy httpapi_h /copy yajl_h dcl-f WATSONTR3D workstn indds(dspf); dcl-Ds dspf qualified; F3Exit ind pos(3); end-Ds; fromLang = 'en'; toLang = 'es'; dou dspf.F3Exit = *on; exfmt screen1; if dspf.F3exit = *on; leave; endif; fromLang = %lower(fromLang); toLang = %lower(toLang); toText = translate( fromLang: toLang: %trim(fromText) ); enddo; *inlr = *on; return; /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // translate: // Use IBM Watson's Language Translator API to translate text between // two human languages. // // @param char(2) 2-char language to translate from (en=english) // @param char(2) 2-char language to translate to (fr=french,en=spanish) // @param varchar(1000) text to translate // // @return varchar(1000) the translated text. /// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ dcl-proc translate; dcl-pi *n varchar(1000); fromLang char(2) const; tolang char(2) const; fromText varchar(1000) const; end-pi; dcl-s url varchar(2000); dcl-s request varchar(2000); dcl-s response varchar(5000); dcl-s httpstatus int(10); dcl-ds result qualified; dcl-ds translations dim(1); translation varchar(1000); end-ds; word_count int(10); character_count int(10); end-ds; yajl_genOpen(*off); yajl_beginObj(); // { yajl_addChar('source': fromLang); // "source": "en", yajl_addChar('target': toLang); // "target": "fr", yajl_beginArray('text'); // "text": [ yajl_addChar(fromText ); // "String here" yajl_endArray(); // ] yajl_endObj(); // } request = yajl_copyBufStr(); yajl_genClose(); http_debug(*on: '/tmp/watson-diagnostic-log.txt'); http_setOption('local-ccsid': '0'); http_setOption('network-ccsid': '1208'); http_setAuth( HTTP_AUTH_BASIC : 'apikey' : 'YOUR IBM CLOUD KEY HERE'); url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' + '/instances/f7b6e575-01c4-4b1b-916a-3a79652d0f52' + '/v3/translate?version=2018-05-01'; monitor; response = http_string('POST': url: request: 'application/json'); http_error(*omit: httpstatus); httpcode = %char(httpstatus); on-error; httpcode = http_error(); endmon; data-into result %DATA(response) %PARSER('YAJLINTO'); return result.translations(1).translation; end-Proc;
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import * as serviceWorker from './serviceWorker'; import { BrowserRouter } from 'react-router-dom'; import thunk from 'redux-thunk' import { createStore, applyMiddleware } from "redux"; import { Provider } from "react-redux"; import reducers from './reducers'; const creatreStoreWithMiddleware = applyMiddleware(thunk)(createStore) const store = createStore(reducers); ReactDOM.render(( <BrowserRouter> <Provider store={creatreStoreWithMiddleware(reducers)}> <App /> </Provider> </BrowserRouter> ), document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
import fs from 'fs'; import path from 'path'; import util from 'util'; import mime from 'mime'; import { Client } from 'minio'; import { tempFolder } from '@config/upload'; interface ISaveOptions { folder?: string; overrideName?: string; makePublic?: boolean; } interface IHeaders { ContentType?: string; 'x-amz-acl'?: string; } export default class StorageProvider { private minioClient: Client; constructor() { if ( !process.env.MIN_IO_HOST || !process.env.MIN_IO_PORT || !process.env.MIN_IO_ACCESS_KEY || !process.env.MIN_IO_SECRET_KEY || !process.env.MIN_IO_USE_SSL ) { throw Error('MISSING MIN IO VARIABLES'); } this.minioClient = new Client({ endPoint: process.env.MIN_IO_HOST, port: Number(process.env.MIN_IO_PORT), useSSL: true, accessKey: process.env.MIN_IO_ACCESS_KEY, secretKey: process.env.MIN_IO_SECRET_KEY, }); } public async getFile(file: string, folder?: string): Promise<string> { const expiry = 2 * 60 * 60; let path: string; if (folder) { path = folder + '/' + file; } else { path = file; } return new Promise((resolve, reject) => { this.minioClient.presignedGetObject( process.env.MIN_IO_BUCKET || 'aurora', path, expiry, (err, result) => { if (err) { console.log(err); return reject('File not found'); } return resolve(result); }, ); }); } public async saveFile(file: string, options?: ISaveOptions): Promise<string> { let folder: string | undefined = ''; let overrideName: string | undefined = ''; if (options) { folder = options?.folder; overrideName = options?.overrideName; } const originalPath = path.resolve(tempFolder, file); const headers: IHeaders = {}; const ContentType = mime.getType(originalPath); if (!ContentType) { throw new Error('File not found'); } headers.ContentType = ContentType; if (options?.makePublic) { headers['x-amz-acl'] = 'public-read'; } let filePath: string; if (folder) { filePath = folder + '/' + file; } else { filePath = file; } if (overrideName) { const [, fileExtension] = file.split('.'); filePath = filePath.replace(file, overrideName + '.' + fileExtension); } return new Promise((resolve, reject) => { this.minioClient.fPutObject( process.env.MIN_IO_BUCKET || 'aurora', filePath, originalPath, headers, async function (error) { if (error) { await util.promisify(fs.unlink)(originalPath); return reject(); } await util.promisify(fs.unlink)(originalPath); return resolve(file); }, ); }); } public async deleteFile(file: string, folder?: string): Promise<void> { let filePath: string; if (folder) { filePath = folder + '/' + file; } else { filePath = file; } await this.minioClient.removeObject( process.env.MIN_IO_BUCKET || 'aurora', filePath, ); } }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* client.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rlaforge <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/07/30 02:09:24 by rlaforge #+# #+# */ /* Updated: 2023/07/30 02:09:24 by rlaforge ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CLIENT_HPP #define CLIENT_HPP #include <string> class Client{ public: Client(int clientFd); //Constructor Client(const Client &src); //Copy Constructor Client & operator=(const Client &rhs); //Assignement Value Operator ~Client(); //Destructor std::string &getNickname() {return _nickname;}; std::string &getUsername() {return _username;}; const int &getUserFd() const {return _fd;}; std::string &getPassword() {return _password;}; bool isAuth() {return _authentified;}; void setNickname(std::string nickname); void setUsername(std::string username); void setPassword(std::string password); void setAuth(bool status); void clearInfo(); private : bool _authentified; const int _fd; std::string _nickname; std::string _username; std::string _password; }; #endif
<?php namespace App\Http\Controllers\Back; use App\Http\Controllers\Controller; use App\Models\Category; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; class CategoryController extends Controller { public function index(){ $user = auth()->user(); if($user->role == 'admin'){ $category = Category::latest()->get(); } else { $category = Category::where('user_id', $user->id)->latest()->get(); } return view('category.index',compact('category')); } public function create(){ $category = Category::all(); return view('category.create',compact('category')); } public function store(Request $request){ $request->validate([ 'name' =>'required', ]); $category = new Category(); $category->user_id = Auth::user()->id; $category->name = $request->name; $category->slug = Str::slug($request->name); $category->save(); $notification = array( 'message' => 'Category Created Successfully', 'alert-type' =>'success' ); return redirect()->route('categories.index')->with($notification); } public function edit($id){ $category = Category::findOrFail($id); return view('category.edit',compact('category')); } public function update(Request $request,$id){ Category::findOrFail($id)->update([ 'name'=>$request->name, 'slug'=>Str::slug($request->name), ]); $notification = array( 'message' => 'Category Created Successfully', 'alert-type' =>'success' ); return redirect()->route('categories.index')->with($notification); } public function delete($id){ // $category = Category::findOrFail($id); $category = Category::with('links')->findOrFail($id); $category->delete(); $notification = array( 'message' => 'Category Created Successfully', 'alert-type' =>'success' ); return redirect()->route('categories.index')->with($notification); } public function inactiveCategory($id){ Category::findOrFail($id)->update([ 'is_active' => 0 ]); $notification = array( 'message' => 'Category Inactive Successfully', 'alert-type' =>'success' ); return redirect()->route('categories.index')->with($notification); } public function activeCategory($id){ Category::findOrFail($id)->update([ 'is_active' => 1 ]); $notification = array( 'message' => 'Category Active Successfully', 'alert-type' =>'success' ); return redirect()->route('categories.index')->with($notification); } }
package by.it.group251004.kirlitsa.lesson07; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Scanner; /* Задача на программирование: расстояние Левенштейна https://ru.wikipedia.org/wiki/Расстояние_Левенштейна http://planetcalc.ru/1721/ Дано: Две данных непустые строки длины не более 100, содержащие строчные буквы латинского алфавита. Необходимо: Решить задачу МЕТОДАМИ ДИНАМИЧЕСКОГО ПРОГРАММИРОВАНИЯ Итерационно вычислить расстояние редактирования двух данных непустых строк Sample Input 1: ab ab Sample Output 1: 0 Sample Input 2: short ports Sample Output 2: 3 Sample Input 3: distance editing Sample Output 3: 5 */ public class B_EditDist { int isCharEqual(Character a, Character b) { return a.equals(b) ? 0 : 1; } int getDistanceEdinting(String one, String two) { //!!!!!!!!!!!!!!!!!!!!!!!!! НАЧАЛО ЗАДАЧИ !!!!!!!!!!!!!!!!!!!!!!!!! int[][] arrAnswer = new int[one.length() + 1][two.length() + 1]; for (int i = 0; i < arrAnswer.length; i++) arrAnswer[i][0] = i; for (int i = 0; i < arrAnswer[0].length; i++) arrAnswer[0][i] = i; for (int i = 1; i < arrAnswer.length; i++) for (int j = 1; j < arrAnswer[0].length; j++) { int diff = isCharEqual(one.charAt(i - 1), two.charAt(j - 1)); arrAnswer[i][j] = Math.min(arrAnswer[i - 1][j] + 1, Math.min(arrAnswer[i][j - 1] + 1, arrAnswer[i - 1][j - 1] + diff)); } //!!!!!!!!!!!!!!!!!!!!!!!!! КОНЕЦ ЗАДАЧИ !!!!!!!!!!!!!!!!!!!!!!!!! return arrAnswer[one.length()][two.length()]; } public static void main(String[] args) throws FileNotFoundException { String root = System.getProperty("user.dir") + "/src/"; InputStream stream = new FileInputStream(root + "by/it/a_khmelev/lesson07/dataABC.txt"); B_EditDist instance = new B_EditDist(); Scanner scanner = new Scanner(stream); System.out.println(instance.getDistanceEdinting(scanner.nextLine(),scanner.nextLine())); System.out.println(instance.getDistanceEdinting(scanner.nextLine(),scanner.nextLine())); System.out.println(instance.getDistanceEdinting(scanner.nextLine(),scanner.nextLine())); } }
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var authentication_service_1 = require('../user/authentication.service'); var UpvoteComponent = (function () { function UpvoteComponent(authService) { this.authService = authService; this.vote = new core_1.EventEmitter(); } Object.defineProperty(UpvoteComponent.prototype, "voted", { set: function (val) { this.iconColor = val ? 'red' : 'white'; }, enumerable: true, configurable: true }); UpvoteComponent.prototype.onClick = function () { this.vote.emit({}); }; __decorate([ core_1.Input(), __metadata('design:type', Object), __metadata('design:paramtypes', [Object]) ], UpvoteComponent.prototype, "voted", null); __decorate([ core_1.Input(), __metadata('design:type', Number) ], UpvoteComponent.prototype, "count", void 0); __decorate([ core_1.Output(), __metadata('design:type', Object) ], UpvoteComponent.prototype, "vote", void 0); UpvoteComponent = __decorate([ core_1.Component({ selector: 'upvote', styleUrls: ['app/event/upvote.component.css'], template: "\n <div class = \"votingWidgetContainer pointable\" (click) = \"onClick()\">\n <div class = \"well votingWidget\">\n <div class = \"votingButton\">\n <i class =\"glyphicon glyphicon-heart\" [style.color]=\"iconColor\"></i>\n </div>\n <div class = \"badge badge-inverse votingCount\">\n <div>{{count}}</div>\n </div>\n </div>\n </div>\n " }), __metadata('design:paramtypes', [authentication_service_1.AuthService]) ], UpvoteComponent); return UpvoteComponent; }()); exports.UpvoteComponent = UpvoteComponent; //# sourceMappingURL=upvote.component.js.map
import React from "react"; import ReactECharts from "echarts-for-react"; export default function Pointxy(props) { // 假设有两组数据分别是 data1 和 data2 const data1 = props.data_xy.before_data; // 第一组数据的坐标点 props.before_data const data2 = props.data_xy.result_data; // 第二组数据的坐标点 //类别名 props.resourceFormat const dataline = []; //连线数组 data1.forEach((item, index) => { let arr1 = []; arr1.push(item); arr1.push(data2[index]); dataline.push(arr1); }); const addLine = () => { for (let i = 0; i < dataline.length; i++) { option.series.push({ type: "line", name: "Moving track", data: dataline[i], lineStyle: { width: 2, color: getColorByIndex(i), // 线条颜色 }, symbolSize: 0, }); } }; function getColorByIndex(index) { const colors = [ "#6c50f3", "#00ffff", "#00ff00", "yellow", "#FF0087", "#FFBF00", ]; return colors[index]; } // 配置散点图的基本参数 const option = { title: { text: "Changing Trends", bottom: 10, left: "center", textStyle: { color: "rgb(143 123 251)", fontSize: "10px", fontFamily: "Fieldstones-ExtraBold-BF64e566a80554d", }, }, grid: { containLabel: true, // 将坐标轴标签的宽度计算在内 }, backgroundColor: "rgb(214 216 254)", legend: { top: 5, left: "center", itemWidth: 9, itemHeight: 9, data: [ "Before processing", "After processing", { name: "Moving track", icon: "none" }, ], textStyle: { fontFamily: "Fieldstones-ExtraBold-BF64e566a80554d", color: "grey", fontSize: "10px", }, itemStyle: { color: "rgb(143 123 251)", }, }, tooltip: { show: true, formatter: "coordinate : ( {c} ) " }, toolbox: { show: true, feature: { saveAsImage: { title: false } }, }, xAxis: { axisLine: { // 改变x轴颜色 lineStyle: { color: "rgb(143 123 251)", }, }, axisTick: { show: false, }, axisLabel: { // 改变x轴字体颜色和大小 formatter: function (value) { // 将数值改为以 10 的 n 次方形式展示 // 判断数值是否为负数 if (value < 0) { value = -value; // 取绝对值 var exponent = Math.floor(Math.log10(value)); var base = value / Math.pow(10, exponent); if (exponent === 0) { return "-" + base.toFixed(1); } else if (exponent === 1) { return "-" + base.toFixed(1) + "e"; } return "-" + base.toFixed(1) + "e" + exponent; } else if (value > 0) { var exponent = Math.floor(Math.log10(value)); var base = value / Math.pow(10, exponent); if (exponent === 0) { return base.toFixed(1); } else if (exponent === 1) { return base.toFixed(1) + "e"; } return base.toFixed(1) + "e" + exponent; } else { return 0; } }, textStyle: { fontSize: "10px", fontFamily: "Fieldstones-ExtraBold-BF64e566a80554d", color: "grey", }, }, splitLine: { lineStyle: { color: "#E9E9E9", }, }, }, yAxis: { axisLine: { // 改变y轴颜色 lineStyle: { color: "rgb(143 123 251)", }, }, axisTick: { show: false, }, axisLabel: { formatter: function (value) { // 将数值改为以 10 的 n 次方形式展示 // 判断数值是否为负数 if (value < 0) { value = -value; // 取绝对值 var exponent = Math.floor(Math.log10(value)); var base = value / Math.pow(10, exponent); if (exponent === 0) { return "-" + base.toFixed(1); } else if (exponent === 1) { return "-" + base.toFixed(1) + "e"; } return "-" + base.toFixed(1) + "e" + exponent; } else if (value > 0) { var exponent = Math.floor(Math.log10(value)); var base = value / Math.pow(10, exponent); if (exponent === 0) { return base.toFixed(1); } else if (exponent === 1) { return base.toFixed(1) + "e"; } return base.toFixed(1) + "e" + exponent; } else { return 0; } }, textStyle: { fontSize: "10px", fontFamily: "Fieldstones-ExtraBold-BF64e566a80554d", color: "grey", }, }, splitLine: { lineStyle: { color: "#E9E9E9", }, }, }, series: [ { name: "Before processing", type: "scatter", data: data1.map(function (item, index) { return { value: item, itemStyle: { color: getColorByIndex(index), }, }; }), symbolSize: 9, symbol: "circle", itemStyle: { color: "#6c50f3", borderWidth: 2, borderColor: "#fff", }, }, { name: "After processing", type: "scatter", data: data2.map(function (item, index) { return { value: item, itemStyle: { color: getColorByIndex(index), }, }; }), symbolSize: 9, symbol: "diamond", itemStyle: { color: "#6c50f3", borderWidth: 2, borderColor: "#fff", }, }, ], }; addLine(); return ( <ReactECharts option={option} notMerge={true} lazyUpdate={true} theme={"AI隐私差分"} style={{ width: "100%", height: "100%" }} resize /> ); }
package com.fanji.android.thread.ruler import com.fanji.android.thread.RulerCounter import com.fanji.android.thread.RulerLifecycleManager /** * > 用于编译插件替换 Kotlin 实现,请勿直接使用 * * Creates a thread that runs the specified [block] of code. * * @param start if `true`, the thread is immediately started. * @param isDaemon if `true`, the thread is created as a daemon thread. The Java Virtual Machine exits when * the only threads running are all daemon threads. * @param contextClassLoader the class loader to use for loading classes and resources in this thread. * @param name the name of the thread. * @param priority the priority of the thread. * * @author 蒋世德 @ fanji inc * @email [email protected] * @since 21-6-1 下午2:33 */ fun thread( start: Boolean = true, isDaemon: Boolean = false, contextClassLoader: ClassLoader? = null, name: String? = null, priority: Int = -1, block: () -> Unit ): Thread { // 这里触发的线程创建,名字定义成 ThreadKt val counter = RulerCounter.getCounter("ThreadKt") val thread = object : RulerThread(name, "ThreadKt") { // 覆盖 RulerThread.run() 的实现 override fun run() { counter.incrementAndGet() RulerLifecycleManager.onThreadBeginInternal(this) try { block() } finally { counter.decrementAndGet() RulerLifecycleManager.onThreadEndInternal(this) } } } if (isDaemon) thread.isDaemon = true if (priority > 0) thread.priority = priority if (contextClassLoader != null) thread.contextClassLoader = contextClassLoader if (start) thread.start() return thread }
#include <Arduino.h> #include <U8g2lib.h> #ifdef U8X8_HAVE_HW_SPI #include <SPI.h> #endif #ifdef U8X8_HAVE_HW_I2C #include <Wire.h> #endif #define DEG_TO_RAD 0.017453292519943295769236907684886 U8G2_SSD1306_128X64_NONAME_2_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE); float angle(float angle_deg) { float value = DEG_TO_RAD * (90 + angle_deg); return value; } void u8g2_prepare(void) { u8g2.setFontRefHeightExtendedText(); u8g2.setDrawColor(1); u8g2.setFontPosTop(); u8g2.setFontDirection(0); } void u8g2_compass() { u8g2.setFont(u8g2_font_6x10_tf); float bearing_deg = Message_Receive.Compass_Heading; // Angle of Buoy in degrees Compass System float course_deg = Message_Receive.CourseToDestination; // Angle of Waypoint in degrees Compass System float distance = Message_Receive.DistanceToDestination; int radius_Compass = 30; int radius_Pointer = 2; int center_compass_x = 128 - radius_Compass - 3; int center_compass_y = 32; String bearing_txt = String(bearing_deg,3) + "\xB0"; String course_txt = String(course_deg,3) + "\xB0"; String distance_txt = String(distance,3) + " m"; u8g2.drawStr(0, 0, "Bearing"); u8g2.drawStr(0, 10, bearing_txt.c_str()); u8g2.drawStr(0, 22, "Course"); u8g2.drawStr(0, 32, course_txt.c_str()); u8g2.drawStr(0, 44, "Distance"); u8g2.drawStr(0, 54, distance_txt.c_str()); u8g2.drawCircle(center_compass_x, center_compass_y, radius_Compass); u8g2.drawLine(center_compass_x, center_compass_y, center_compass_x - (radius_Compass - 4)*cos(angle(bearing_deg)), center_compass_y - (radius_Compass - 4)*sin(angle(bearing_deg))); u8g2.drawDisc(center_compass_x - (radius_Compass)*cos(angle(course_deg)), center_compass_y - (radius_Compass)*sin(angle(course_deg)), radius_Pointer); u8g2.drawStr(-3 + center_compass_x - (radius_Compass - 6)*cos(angle(0)), -5 + center_compass_y - (radius_Compass - 6)*sin(angle(0)), "N"); u8g2.drawStr(-3 + center_compass_x - (radius_Compass - 6)*cos(angle(90)), -5 + center_compass_y - (radius_Compass - 6)*sin(angle(90)), "E"); u8g2.drawStr(-3 + center_compass_x - (radius_Compass - 6)*cos(angle(180)), -5 + center_compass_y - (radius_Compass - 6)*sin(angle(180)), "S"); u8g2.drawStr(-3 + center_compass_x - (radius_Compass - 6)*cos(angle(270)), -5 + center_compass_y - (radius_Compass - 6)*sin(angle(270)), "W"); } void u8g2_gps() { u8g2.setFont(u8g2_font_9x15_tf); float Destination_Latitude = Message_Transmit.Destination_Latitude/1e7; // Angle of Buoy in degrees Compass System float Destination_Longitude = Message_Transmit.Destination_Longitude/1e7; // Angle of Waypoint in degrees Compass System String Latitude_txt = String(Destination_Latitude,3) + "\xB0"; String Longitude_txt = String(Destination_Longitude,3) + "\xB0"; u8g2.drawStr(0, 0, "Latitude"); u8g2.drawStr(0, 10, Latitude_txt.c_str()); u8g2.drawStr(0, 22, "Longitude"); u8g2.drawStr(0, 32, Longitude_txt.c_str()); } void setup_Display() { u8g2.begin(); } void Display() { u8g2.firstPage(); do { u8g2_prepare(); u8g2_compass(); } while ( u8g2.nextPage() ); } void Display_GPS() { u8g2.firstPage(); do { u8g2_prepare(); u8g2_gps(); } while ( u8g2.nextPage() ); }
import { SortOrder } from "components/Table/type"; import { useCallback, useState } from "react"; export interface FilterState { term: string gender: "male" | "female" | "" sortOrder: SortOrder sortBy: string page: number } /** * hooks to handle filter state, * use for updating and resetting filter state */ const useFilter = () => { const [filter, setFilter] = useState<FilterState>({ term: "", gender: "", sortOrder: "", sortBy: "", page: 1, }) const updateFilter = useCallback((setter: keyof typeof filter, value: any) => { setFilter(prevState => ({ ...prevState, [setter]: value, })) }, []); const resetFilter = () => { setFilter({ term: "", gender: "", sortOrder: "", sortBy: "", page: 1 }) } return { filter, updateFilter, resetFilter } } export default useFilter;
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // SPDX-License-Identifier: MIT // Publisher Callback Service definition // // The prototype definitions for a Publisher utilizing the Pub Sub Service. syntax = "proto3"; package publisher; // The service that a publisher implements to provide necessary functionality // for communication from the Pub Sub Service. service PublisherCallback { // Method used by the Pub Sub Service to provide the publisher with topic // information so the publisher can make informed choices with topic // management. rpc ManageTopicCallback (ManageTopicRequest) returns (ManageTopicResponse); } // Representation of a request that provides context for a publisher to manage // a specified topic. message ManageTopicRequest { // The name of the dynamically generated topic. string topic = 1; // Context informing publisher of actions to take on a topic. string action = 2; } // Empty object indicating a successfull call of `ManageTopicCallback`. message ManageTopicResponse { }
import cv2 import numpy as np from sort.tracker import SortTracker import math import multiprocessing import time def count_ppl(duration): speeds = [] counts = [] # Load YOLO net = cv2.dnn.readNet('./models/yolov3.weights', './models/yolov3.cfg') layer_names = net.getLayerNames() output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()] classes = ["person"] # Initialize SORT tracker tracker = SortTracker() # Start capturing video from the camera cap = cv2.VideoCapture(1) width = cap.get(3) # float `width` height = cap.get(4) # float `height` diag = math.sqrt((width) ** 2 + (height) ** 2) hashmap = {} start_time = time.time() while True: # Capture frame-by-frame speed = 0 ret, frame = cap.read() if not ret: break height, width, _ = frame.shape # Convert the frame to a blob and pass through the network blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False) net.setInput(blob) outs = net.forward(output_layers) # Information to put on the frame class_ids = [] confidences = [] boxes = [] # Analyze the outs array for out in outs: for detection in out: scores = detection[5:] class_id = np.argmax(scores) confidence = scores[class_id] if confidence > 0.5: # Object detected center_x = int(detection[0] * width) center_y = int(detection[1] * height) w = int(detection[2] * width) h = int(detection[3] * height) # Rectangle coordinates x = int(center_x - w / 2) y = int(center_y - h / 2) boxes.append([x, y, w, h]) confidences.append(float(confidence)) class_ids.append(class_id) indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4) # Convert YOLO detections to SORT format (x, y, w, h) detections = [] for i in range(len(boxes)): if i in indexes: x, y, w, h = boxes[i] detections.append([x, y, x + w, y + h,1,1]) # Update SORT tracker with current frame detections try: track_bbs_ids = tracker.update(np.array(detections),"") except: pass # Drawing tracked objects on the image items = 0 for track in track_bbs_ids: # print(track) # exit(0) x, y, w, h, track_id,_,_ = track if track_id in hashmap.keys(): items += 1 counts.append(items) old_x, old_y = hashmap[track_id] dist = math.sqrt((old_x - x) ** 2 + (old_y - y) ** 2) speed += dist speeds.append(speed) hashmap[track_id] = (x,y) cv2.rectangle(frame, (int(x), int(y)), (int(w), int(h)), (255, 0, 0), 2) cv2.putText(frame, f"ID {track_id}", (int(x), int(y - 10)), 0, 0.5, (255, 0, 0), 2) # Display the resulting frame cv2.imshow('Frame', frame) # Break the loop if cv2.waitKey(1) & 0xFF == ord('q') or time.time() - start_time > duration: break # When everything is done, release the capture cap.release() cv2.destroyAllWindows() return (avg(counts),avg(speeds)) def avg(lst): if len(lst): return sum(lst) / len(lst) else: return 0 if __name__ == "__main__": queue = multiprocessing.Queue() duration = 5 process = multiprocessing.Process(target=count_ppl, args=(duration, queue)) process.start() # Non-blocking wait while process.is_alive(): # Here, you can execute other tasks in a non-blocking manner print("Waiting for process to complete...") time.sleep(1) # Sleep for a short duration to prevent busy waiting # Process has finished, now retrieve the data count,speed = queue.get() if not queue.empty() else None # count_ppl()
/* * Copyright (C) 2019 The Android Open Source 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.android.server.display.color; import android.annotation.UserIdInt; import android.util.ArrayMap; import android.util.SparseArray; import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; import com.android.server.display.color.ColorDisplayService.ColorTransformController; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; class AppSaturationController { private final Object mLock = new Object(); /** * A package name has one or more userIds it is running under. Each userId has zero or one * saturation level, and zero or more ColorTransformControllers. */ @GuardedBy("mLock") private final Map<String, SparseArray<SaturationController>> mAppsMap = new HashMap<>(); @VisibleForTesting static final float[] TRANSLATION_VECTOR = {0f, 0f, 0f}; /** * Add an {@link WeakReference<ColorTransformController>} for a given package and userId. */ boolean addColorTransformController(String packageName, @UserIdInt int userId, WeakReference<ColorTransformController> controller) { synchronized (mLock) { return getSaturationControllerLocked(packageName, userId) .addColorTransformController(controller); } } /** * Set the saturation level ({@code ColorDisplayManager#SaturationLevel} constant for a given * package name and userId. */ public boolean setSaturationLevel(String callingPackageName, String affectedPackageName, @UserIdInt int userId, int saturationLevel) { synchronized (mLock) { return getSaturationControllerLocked(affectedPackageName, userId) .setSaturationLevel(callingPackageName, saturationLevel); } } /** * Dump state information. */ public void dump(PrintWriter pw) { synchronized (mLock) { pw.println("App Saturation: "); if (mAppsMap.size() == 0) { pw.println(" No packages"); return; } final List<String> packageNames = new ArrayList<>(mAppsMap.keySet()); Collections.sort(packageNames); for (String packageName : packageNames) { pw.println(" " + packageName + ":"); final SparseArray<SaturationController> appUserIdMap = mAppsMap.get(packageName); for (int i = 0; i < appUserIdMap.size(); i++) { pw.println(" " + appUserIdMap.keyAt(i) + ":"); appUserIdMap.valueAt(i).dump(pw); } } } } /** * Retrieve the SaturationController for a given package and userId, creating all intermediate * connections as needed. */ private SaturationController getSaturationControllerLocked(String packageName, @UserIdInt int userId) { return getOrCreateSaturationControllerLocked(getOrCreateUserIdMapLocked(packageName), userId); } /** * Retrieve or create the mapping between the app's given package name and its userIds (and * their SaturationControllers). */ private SparseArray<SaturationController> getOrCreateUserIdMapLocked(String packageName) { if (mAppsMap.get(packageName) != null) { return mAppsMap.get(packageName); } final SparseArray<SaturationController> appUserIdMap = new SparseArray<>(); mAppsMap.put(packageName, appUserIdMap); return appUserIdMap; } /** * Retrieve or create the mapping between an app's given userId and SaturationController. */ private SaturationController getOrCreateSaturationControllerLocked( SparseArray<SaturationController> appUserIdMap, @UserIdInt int userId) { if (appUserIdMap.get(userId) != null) { return appUserIdMap.get(userId); } final SaturationController saturationController = new SaturationController(); appUserIdMap.put(userId, saturationController); return saturationController; } @VisibleForTesting static void computeGrayscaleTransformMatrix(float saturation, float[] matrix) { float desaturation = 1.0f - saturation; float[] luminance = {0.231f * desaturation, 0.715f * desaturation, 0.072f * desaturation}; matrix[0] = luminance[0] + saturation; matrix[1] = luminance[0]; matrix[2] = luminance[0]; matrix[3] = luminance[1]; matrix[4] = luminance[1] + saturation; matrix[5] = luminance[1]; matrix[6] = luminance[2]; matrix[7] = luminance[2]; matrix[8] = luminance[2] + saturation; } private static class SaturationController { private static final int FULL_SATURATION = 100; private final List<WeakReference<ColorTransformController>> mControllerRefs = new ArrayList<>(); private final ArrayMap<String, Integer> mSaturationLevels = new ArrayMap<>(); private float[] mTransformMatrix = new float[9]; private boolean setSaturationLevel(String callingPackageName, int saturationLevel) { if (saturationLevel == FULL_SATURATION) { mSaturationLevels.remove(callingPackageName); } else { mSaturationLevels.put(callingPackageName, saturationLevel); } if (!mControllerRefs.isEmpty()) { return updateState(); } return false; } private boolean addColorTransformController( WeakReference<ColorTransformController> controller) { clearExpiredReferences(); mControllerRefs.add(controller); if (!mSaturationLevels.isEmpty()) { return updateState(); } return false; } private int calculateSaturationLevel() { int saturationLevel = FULL_SATURATION; for (int i = 0; i < mSaturationLevels.size(); i++) { final int level = mSaturationLevels.valueAt(i); if (level < saturationLevel) { saturationLevel = level; } } return saturationLevel; } private boolean updateState() { computeGrayscaleTransformMatrix(calculateSaturationLevel() / 100f, mTransformMatrix); boolean updated = false; final Iterator<WeakReference<ColorTransformController>> iterator = mControllerRefs .iterator(); while (iterator.hasNext()) { WeakReference<ColorTransformController> controllerRef = iterator.next(); final ColorTransformController controller = controllerRef.get(); if (controller != null) { controller.applyAppSaturation(mTransformMatrix, TRANSLATION_VECTOR); updated = true; } else { // Purge cleared refs lazily to avoid accumulating a lot of dead windows iterator.remove(); } } return updated; } private void clearExpiredReferences() { final Iterator<WeakReference<ColorTransformController>> iterator = mControllerRefs .iterator(); while (iterator.hasNext()) { WeakReference<ColorTransformController> controllerRef = iterator.next(); final ColorTransformController controller = controllerRef.get(); if (controller == null) { iterator.remove(); } } } private void dump(PrintWriter pw) { pw.println(" mSaturationLevels: " + mSaturationLevels); pw.println(" mControllerRefs count: " + mControllerRefs.size()); } } }
<?php /** * Functions for registering and setting theme widgets. This file loads an abstract class to help * build widgets, and loads individual widget classes for building widgets into the backend and * loading their template for displaying in frontend * * 'init' hook is too late to load widgets since 'widgets_init' is used to initialize widgets. * Since this file is hooked at 'after_setup_theme' (priority 14), we can safely load widgets here. * * @package chromaticfw * @subpackage framework * @since chromaticfw 1.0.0 */ /** * Loads all available widgets for the theme. Since these are extended classes of 'ChromaticFw_WP_Widget', hence * this function should only be called 'ChromaticFw_WP_Widget' class has been defined. * * @since 1.0.0 * @access public */ function chromaticfw_load_widgets() { /* Loads all available widgets for the theme. */ foreach ( glob( trailingslashit( CHROMATICFW_THEMEDIR ) . "admin/widget-*.php" ) as $filename ) { include_once( $filename ); } } /** * Load widget stylesheets and scripts for the backend. * * @since 1.1 * @access public */ if ( is_admin() ) { function chromaticfw_enqueue_admin_widget_styles_scripts( $hook ) { if ( 'widgets.php' == $hook ): /* Get the minified suffix */ $suffix = chromaticfw_get_min_suffix(); /* Enqueue Styles */ wp_enqueue_style( 'chromaticfw-font-awesome' ); wp_enqueue_style( 'chromaticfw-admin-widgets', trailingslashit( CHROMATICFW_CSS ) . "admin-widgets{$suffix}.css", array(), CHROMATICFW_VERSION ); /* Enqueue Scripts */ wp_enqueue_script( 'chromaticfw-admin-widgets', trailingslashit( CHROMATICFW_JS ) . "admin-widgets{$suffix}.js", array( 'jquery' ), CHROMATICFW_VERSION, true ); // Load in footer to maintain script heirarchy endif; } add_action( 'admin_enqueue_scripts', 'chromaticfw_enqueue_admin_widget_styles_scripts' ); } /** * Abstract Widgets Class for creating and displaying widgets. This file is only loaded if the theme supports * the 'chromaticfw-core-widgets' feature. * * @credit() Derived from Vantage theme code by Greg Priday http://SiteOrigin.com * Licensed under GPL * * @since 1.0.0 * @access public */ abstract class ChromaticFw_WP_Widget extends WP_Widget { protected $form_options; protected $repeater_html; /** * Register the widget and load the Widget options * * @since 1.0.0 */ function __construct( $id, $name, $widget_options = array(), $control_options = array(), $form_options = array() ) { $this->form_options = $form_options; parent::WP_Widget( $id, $name, $widget_options, $control_options ); $this->initialize(); } /** * Initialize this widget in whatever way we need to. Runs before rendering widget or form. * * @since 1.0.0 */ function initialize(){ } /** * Display the widget. * * @since 1.0.0 * @param array $args * @param array $instance */ function widget( $args, $instance ) { $args = wp_parse_args( $args, array( 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) ); $defaults = array(); foreach( $this->form_options as $option ) { if ( isset( $option['id'] ) ) { $defaults[ $option['id'] ] = ( isset( $option['std'] ) ) ? $option['std'] : ''; } } $instance = wp_parse_args( $instance, $defaults ); echo $args['before_widget']; $title = ( !empty( $instance['title'] ) ) ? apply_filters( 'widget_title', $instance['title'] ) : ''; $this->display_widget( $instance, $args['before_title'], $title, $args['after_title'] ); echo $args['after_widget']; } /** * Echo the widget content * Subclasses should over-ride this function to generate their widget code. * Convention: Subclasses should include the template from the theme/widgets folder. * * @since 1.0.0 * @param array $args */ function display_widget( $instance, $before_title = '', $title='', $after_title = '' ) { die('function ChromaticFw_WP_Widget::display_widget() must be over-ridden in a sub-class.'); } /** * Update the widget instance. * * @param array $new_instance * @param array $old_instance * @return array|void */ /*public function update( $new_instance, $old_instance ) { return $new_instance; }*/ /** * Display the widget form. * * @since 1.0.0 * @param array $instance * @return string|void */ public function form( $instance ) { $form_id = 'chromaticfw-widget-form-' . md5( uniqid( rand(), true ) ); $class_name = str_replace( '_', '-', strtolower( get_class($this) ) ); ?> <div class="chromaticfw-widget-form chromaticfw-widget-form-<?php echo esc_attr( $class_name ) ?>" id="<?php echo $form_id ?>" data-class="<?php echo get_class($this) ?>"> <?php if ( !empty( $this->widget_options['help'] ) ) : ?> <div class="chromaticfw-widget-form-help"><?php echo $this->widget_options['help']; ?></div> <?php endif; foreach( $this->form_options as $key => $field ) { $field = wp_parse_args( (array) $field, array( 'name' => '', 'desc' => '', 'id' => '', 'type' => '', 'settings' => array(), 'std' => '', 'options' => array(), 'fields' => array(), ) ); if ( empty( $field['id'] ) || empty( $field['type'] ) ) continue; $value = false; if ( isset( $instance[ $field['id'] ] ) ) $value = $instance[ $field['id'] ]; elseif ( !empty( $field['std'] ) ) $value = $field['std']; $this->render_field( $field, $value, false ); } ?> <script type="text/javascript"> ( function($){ if (typeof window.chromaticfw_widget_helper == 'undefined') window.chromaticfw_widget_helper = {}; <?php /*if (typeof window.chromaticfw_widget_helper["<?php echo get_class($this) ?>"] == 'undefined')*/ // This creates unexpected results as the script is first instancized in template widget __i__ ?> window.chromaticfw_widget_helper["<?php echo get_class($this) ?>"] = <?php echo json_encode( $this->repeater_html ) ?>; if (typeof $.fn.chromaticfwSetupWidget != 'undefined') { $('#<?php echo $form_id ?>').chromaticfwSetupWidget(); } } )( jQuery ); </script> </div><?php } /** * Render a form field * * @since 1.0.0 * @param $field * @param $value * @param $repeater */ function render_field( $field, $value, $repeater = array() ){ extract( $field, EXTR_SKIP ); ?><div class="chromaticfw-widget-field chromaticfw-widget-field-type-<?php echo ( strlen( $type ) < 15 ) ? sanitize_html_class( $type ) : 'custom' ?> chromaticfw-widget-field-<?php echo sanitize_html_class( $id ) ?>"><?php if ( !empty( $name ) && $type != 'checkbox' && $type != 'separator' && $type != 'group' ) { ?> <label for="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>"><?php echo $name ?>:</label> <?php } switch( $type ) { case 'text' : if ( isset( $settings['size'] ) && is_numeric( $settings['size'] ) ) { $size = ' size="' . $settings['size'] . '"'; $class = ''; } else { $size = ''; $class = ' widefat'; } ?><input type="text" name="<?php echo $this->chromaticfw_get_field_name( $id, $repeater ) ?>" id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>" value="<?php echo esc_attr( $value ) ?>" class="chromaticfw-widget-input<?php echo $class; ?>" <?php echo $size; ?> /><?php break; case 'textarea' : if ( isset( $settings['rows'] ) && is_numeric( $settings['rows'] ) ) { $rows = intval( $settings['rows'] ); } else { $rows = 4; } ?><textarea name="<?php echo $this->chromaticfw_get_field_name( $id, $repeater ) ?>" id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>" class="widefat chromaticfw-widget-input" rows="<?php echo $rows; ?>"><?php echo esc_textarea( $value ) ?></textarea><?php break; case 'separator' : ?><div class="chromaticfw-widget-field-separator"></div><?php break; case 'checkbox': ?><label for="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>"> <input type="checkbox" name="<?php echo $this->chromaticfw_get_field_name( $id, $repeater ) ?>" id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>" class="chromaticfw-widget-input" <?php checked( !empty( $value ) ) ?> /> <?php echo $name ?> </label><?php break; case 'select': ?><select name="<?php echo $this->chromaticfw_get_field_name( $id, $repeater ) ?>" id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>" class="chromaticfw-widget-input widefat"> <?php foreach( $options as $k => $v ) : ?> <option value="<?php echo esc_attr($k) ?>" <?php selected($k, $value) ?>><?php echo esc_html($v) ?></option> <?php endforeach; ?> </select><?php break; case 'radio': case 'images': ?><ul id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>-list" class="chromaticfw-widget-list chromaticfw-widget-list-<?php echo $type ?>"> <?php foreach( $options as $k => $v ) : ?> <li class="chromaticfw-widget-list-item"> <input type="radio" class="chromaticfw-widget-input" name="<?php echo $this->chromaticfw_get_field_name( $id, $repeater ) ?>" id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) . '-' . sanitize_html_class( $k ) ?>" value="<?php echo esc_attr($k) ?>" <?php checked( $k, $value ) ?>> <label for="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) . '-' . sanitize_html_class( $k ) ?>"><?php echo ( 'radio' === $type ) ? $v : "<img class='chromaticfw-widget-image-picker-img' src='" . esc_url( $v ) . "'>" ?></label> </li> <?php endforeach; ?> </ul><?php break; case 'icon': ?><input id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) ?>" class="chromaticfw-of-icon" name="<?php echo $this->chromaticfw_get_field_name( $id, $repeater ) ?>" type="hidden" value="<?php echo esc_attr( $value ) ?>" /> <div id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) . '-icon-picked' ?>" class="chromaticfw-of-icon-picked"><i class="fa <?php echo esc_attr( $value ) ?>"></i><span><?php _e( 'Select Icon', 'chromaticfw' ) ?></span></div> <div id="<?php echo $this->chromaticfw_get_field_id( $id, $repeater ) . '-icon-picker-box' ?>" class="chromaticfw-of-icon-picker-box"> <div class="chromaticfw-of-icon-picker-list"><i class="fa fa-ban chromaticfw-of-icon-none" data-value="0" data-category=""><span><?php _e( 'Remove Icon', 'chromaticfw' ) ?></span></i></div><?php // @todo remove dependency on ChromaticFw Options fw. This will be automatically resolved once Widgets fw is transformed to ChromaticFw Options Extension in future. if ( class_exists( 'ChromaticFw_Options_Helper' ) ) : $section_icons = ChromaticFw_Options_Helper::icons('icons'); foreach ( ChromaticFw_Options_Helper::icons('sections') as $s_key => $s_title ) { ?> <h4><?php echo $s_title ?></h4> <div class="chromaticfw-of-icon-picker-list"><?php foreach ( $section_icons[$s_key] as $i_key => $i_class ) { $selected = ( $value == $i_class ) ? ' selected' : ''; ?><i class='fa <?php echo $i_class . $selected; ?>' data-value='<?php echo $i_class; ?>' data-category='<?php echo $s_key ?>'></i><?php } ?> </div><?php } endif; ?> </div><?php break; case 'group': $repeater[] = $id; ?><div class="chromaticfw-widget-field-group" data-id="<?php echo esc_attr( $id ) ?>"> <?php if ( !empty( $name ) ): ?> <div class="chromaticfw-widget-field-group-top"> <h3><?php echo $name ?></h3> </div> <?php endif; ?> <?php $item_name = isset( $options['item_name'] ) ? $options['item_name'] : ''; ?> <div class="chromaticfw-widget-field-group-items"> <?php if ( !empty( $value ) ) { foreach( $value as $k =>$v ) { $this->render_group( $k, $v, $fields, $item_name, $repeater ); } } ?> </div> <?php ob_start(); $this->render_group( 975318642, array(), $fields, $item_name, $repeater ); $html = ob_get_clean(); $this->repeater_html[$id] = $html; ?> <div id="add-<?php echo rand(1000, 9999); ?>" class="chromaticfw-widget-field-group-add" data-iterator="<?php echo is_array( $value ) ? max( array_keys( $value ) ) : 0; ?>"><?php _e('Add', 'chromaticfw') ?></div> </div> <?php break; default: echo str_replace( array( '%id%', '%class%', '%name%', '%value%' ), array( $this->chromaticfw_get_field_id( $id, $repeater ), 'chromaticfw-widget-input', $this->chromaticfw_get_field_name( $id, $repeater ), $value ), $type ); break; } if ( ! empty( $desc ) ) { echo '<div class="chromaticfw-widget-field-description"><small>' . esc_html( $desc ) . '</small></div>'; } ?></div><?php } /** * Render a group field * * @since 1.0.0 * @param $field * @param $value * @param $repeater */ function render_group( $key, $value, $fields, $item_name = '', $repeater = array() ){ if ( empty( $fields ) ) return; $repeater[] = intval( $key ); ?> <div class="chromaticfw-widget-field-group-item"> <div class="chromaticfw-widget-field-group-item-top"> <div class="chromaticfw-widget-field-remove">X</div> <h4><i class="fa fa-caret-down"></i> <?php echo esc_html( $item_name ) ?></h4> </div> <div class="chromaticfw-widget-field-group-item-form"> <?php foreach( $fields as $field ) { $field = wp_parse_args( (array) $field, array( 'name' => '', 'desc' => '', 'id' => '', 'type' => '', 'settings' => array(), 'std' => '', 'options' => array(), 'fields' => array(), ) ); $this->render_field( $field, isset( $value[ $field['id'] ] ) ? $value[ $field['id'] ] : false, $repeater ); } ?> </div> </div><?php } /** * @since 1.0.0 * @param $id * @param array $repeater * @return mixed|string */ public function chromaticfw_get_field_name( $id, $repeater = array() ) { if ( empty( $repeater ) ) return $this->get_field_name( $id ); else { $repeater_extras = ''; foreach( $repeater as $r ) $repeater_extras .= '[' . $r . ']'; $repeater_extras .= '[' . esc_attr( $id ) . ']'; $name = $this->get_field_name('{{{FIELD_NAME}}}'); $name = str_replace( '[{{{FIELD_NAME}}}]', $repeater_extras, $name ); return $name; } } /** * Get the ID of this field. * * @since 1.0.0 * @param $id * @param array $repeater * @return string */ public function chromaticfw_get_field_id( $id, $repeater = array() ) { if ( empty( $repeater ) ) return $this->get_field_id( $id ); else { $ids = $repeater; $ids[] = $id; return $this->get_field_id( implode( '-', $ids ) ); } } /** * Helper function to get a list for option values * * @since 1.0.0 * @param $post_type * @param $number Set to -1 to show all * @see: http://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters * @return array */ // @todo more post types and taxonomies static function get_wp_list( $post_type = 'page', $number = false ) { $number = intval( $number ); if ( false === $number || empty( $number ) ) { $number = CHROMATICFW_ADMIN_LIST_ITEM_COUNT; if ( $post_type == 'page' ) { static $options_pages = array(); // cache if ( empty( $options_pages ) ) $options_pages = self::get_pages( $number ); return $options_pages; } } else { if ( $post_type == 'page' ) { $pages = self::get_pages( $number ); return $pages; } } } /** * Helper function to get a list of taxonomies * * @since 1.1.1 * @param $taxonomy * @return array */ static function get_tax_list( $taxonomy = 'category' ) { static $options_tax = array(); // cache if ( empty( $options_tax[ $taxonomy ] ) ) $options_tax[ $taxonomy ] = get_terms( $taxonomy, array( 'fields' => 'id=>name' ) ); return $options_tax[ $taxonomy ]; } /** * Get pages array * * @since 1.0.0 * @param int $number Set to -1 for all pages * @param string $post_type for custom post types * @return array */ static function get_pages( $number, $post_type = 'page' ){ // Doesnt allow -1 as $number // $options_pages_obj = get_pages("sort_column=post_parent,menu_order&number=$number"); // $options_pages[''] = __( 'Select a page:', 'chromaticfw' ); $options_pages = array(); $number = intval( $number ); $the_query = new WP_Query( array( 'post_type' => $post_type, 'posts_per_page' => $number, 'orderby' => 'post_title', 'order' => 'ASC' ) ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); $options_pages[ get_the_ID() ] = get_the_title(); endwhile; wp_reset_postdata(); endif; return $options_pages; } } /* Loads all available widget classes for the theme. */ chromaticfw_load_widgets();
import React, { useState, useEffect } from "react"; import { nanoid } from "nanoid"; import ContactsList from './contact/ContactsList'; import Filter from './filter/Filter'; import Form from './form/Form'; import { Container } from './App.styled' const App = () => { const [contacts, setContacts] = useState([ { id: 'id-1', name: 'Rosie Simpson', number: '459-12-56' }, { id: 'id-2', name: 'Hermione Kline', number: '443-89-12' }, { id: 'id-3', name: 'Eden Clements', number: '645-17-79' }, { id: 'id-4', name: 'Annie Copeland', number: '227-91-26' }, ]); const [filter, setFilter] = useState(''); useEffect(() => { const storedContacts = localStorage.getItem('contacts'); if (storedContacts) { setContacts(JSON.parse(storedContacts)); } }, []); useEffect(() => { localStorage.setItem('contacts', JSON.stringify(contacts)); }, [contacts]); const handleAddContact = (name, number) => { const newContact = { id: nanoid(), name, number }; setContacts(prevContacts => [...prevContacts, newContact]); }; const handleDeleteContact = (contactId) => { setContacts(prevContacts => prevContacts.filter((contact) => contact.id !== contactId) ); }; const handleFilterChange = (event) => { setFilter(event.target.value); }; const filteredContacts = contacts.filter((contact) => contact.name.toLowerCase().includes(filter.toLowerCase()) ); return ( <Container> <h1>Phonebook</h1> <Form onAddContact={handleAddContact} contacts={contacts} /> <h2>Contacts</h2> <Filter filter={filter} onFilterChange={handleFilterChange} /> <ContactsList contacts={filteredContacts} onDeleteContact={handleDeleteContact} /> </Container> ); }; export default App;
import { Signal, WritableSignal, computed, signal } from '@angular/core'; export class SignalStore<T> { readonly state: WritableSignal<T>; // readonly state = signal({} as T); // constructor() {} constructor(initialState: T) { this.state = signal(initialState); } /** * Returns a reactive value for a property on the state. * This is used when the consumer needs the signal for * specific part of the state. * * @param key - the key of the property to be retrieved */ public select<K extends keyof T>(key: K): Signal<T[K]> { return computed(() => this.state()[key]); } /** * This is used to set a new value for a property * * @param key - the key of the property to be set * @param data - the new data to be saved */ public set<K extends keyof T>(key: K, data: T[K]) { this.state.update((currentValue: T) => ({ ...currentValue, [key]: data })); } /** * Sets values for multiple properties on the store * This is used when there is a need to update multiple * properties in the store * * @param partialState - the partial state that includes * the new value to be saved */ public setState(partialState: Partial<T>): void { this.state.update(currentValue => ({ ...currentValue, ...partialState })); } }
/* * Mavuno: A Hadoop-Based Text Mining Toolkit * * 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 edu.isi.mavuno.extract; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.log4j.Logger; import edu.isi.mavuno.util.ContextPatternStatsWritable; import edu.isi.mavuno.util.ContextPatternWritable; import edu.isi.mavuno.util.MavunoUtils; /** * @author metzler * */ public class CombineSplits extends Configured implements Tool { private static final Logger sLogger = Logger.getLogger(CombineSplits.class); public CombineSplits(Configuration conf) { super(conf); } private static class MyMapper extends Mapper<ContextPatternWritable, ContextPatternStatsWritable, ContextPatternWritable, ContextPatternStatsWritable> { /* identity mapper */ } private static class MyReducer extends Reducer<ContextPatternWritable, ContextPatternStatsWritable, ContextPatternWritable, ContextPatternStatsWritable> { private final ContextPatternStatsWritable mContextStats = new ContextPatternStatsWritable(); private boolean mPatternSplits = false; private boolean mContextSplits = false; private boolean mFullSplits = false; @Override public void setup(Reducer<ContextPatternWritable, ContextPatternStatsWritable, ContextPatternWritable, ContextPatternStatsWritable>.Context context) { Configuration conf = context.getConfiguration(); mPatternSplits = false; mContextSplits = false; mFullSplits = false; String splitKey = conf.get("Mavuno.CombineSplits.SplitKey"); if("pattern".equals(splitKey)) { mPatternSplits = true; } else if("context".equals(splitKey)) { mContextSplits = true; } else if("pattern+context".equals(splitKey)) { mFullSplits = true; } else { throw new RuntimeException("Invalid SplitKey in CombineSplits! -- " + splitKey); } } @Override public void reduce(ContextPatternWritable key, Iterable<ContextPatternStatsWritable> values, Reducer<ContextPatternWritable, ContextPatternStatsWritable, ContextPatternWritable, ContextPatternStatsWritable>.Context context) throws IOException, InterruptedException { long totalMatchCount = 0L; long totalPatternCount = 0L; long totalContextCount = 0L; double totalWeight = 0.0; for(ContextPatternStatsWritable p : values) { //System.out.println(key + "\t" + p); totalMatchCount += p.matches; totalPatternCount += p.globalPatternCount; totalContextCount += p.globalContextCount; totalWeight = p.weight; } mContextStats.matches = totalMatchCount; mContextStats.weight = totalWeight; if(mPatternSplits) { mContextStats.globalPatternCount = totalPatternCount; if(key.getPattern().equals(ContextPatternWritable.ASTERISK)) { mContextStats.globalContextCount = totalContextCount; return; } } else if(mContextSplits) { mContextStats.globalContextCount = totalContextCount; if(key.getContext().equals(ContextPatternWritable.ASTERISK)) { mContextStats.globalPatternCount = totalPatternCount; return; } } else if(mFullSplits) { mContextStats.globalPatternCount = totalPatternCount; mContextStats.globalContextCount = totalContextCount; } context.write(key, mContextStats); } } /* (non-Javadoc) * @see org.apache.hadoop.util.Tool#run(java.lang.String[]) */ @Override public int run(String[] args) throws ClassNotFoundException, InterruptedException, IOException { MavunoUtils.readParameters(args, "Mavuno.CombineSplits", getConf()); return run(); } public int run() throws ClassNotFoundException, InterruptedException, IOException { Configuration conf = getConf(); String examplesPath = MavunoUtils.getRequiredParam("Mavuno.CombineSplits.ExamplesPath", conf); String exampleStatsPath = MavunoUtils.getRequiredParam("Mavuno.CombineSplits.ExampleStatsPath", conf); String splitKey = MavunoUtils.getRequiredParam("Mavuno.CombineSplits.SplitKey", conf).toLowerCase(); int numSplits = conf.getInt("Mavuno.CombineSplits.TotalSplits", 1); String outputPath = MavunoUtils.getRequiredParam("Mavuno.CombineSplits.OutputPath", conf); sLogger.info("Tool name: CombineSplits"); sLogger.info(" - Examples path: " + examplesPath); sLogger.info(" - Example stats path: " + exampleStatsPath); sLogger.info(" - Split key: " + splitKey); sLogger.info(" - Total splits: " + numSplits); sLogger.info(" - Output path: " + outputPath); Job job = new Job(conf); job.setJobName("CombineSplits"); job.setJarByClass(CombineSplits.class); for(int split = 0; split < numSplits; split++) { FileInputFormat.addInputPath(job, new Path(examplesPath + "/" + split)); } if(MavunoUtils.pathExists(conf, exampleStatsPath)) { FileInputFormat.addInputPath(job, new Path(exampleStatsPath)); } FileOutputFormat.setOutputPath(job, new Path(outputPath)); job.setInputFormatClass(SequenceFileInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); FileOutputFormat.setCompressOutput(job, true); SequenceFileOutputFormat.setOutputCompressionType(job, SequenceFile.CompressionType.BLOCK); job.setMapOutputKeyClass(ContextPatternWritable.class); if("pattern".equals(splitKey)) { job.setSortComparatorClass(ContextPatternWritable.Comparator.class); } else if("context".equals(splitKey)) { job.setSortComparatorClass(ContextPatternWritable.IdPatternComparator.class); } else if("pattern+context".equals(splitKey)) { job.setSortComparatorClass(ContextPatternWritable.Comparator.class); } else { throw new RuntimeException("Invalid SplitKey in CombineSplits! -- " + splitKey); } job.setMapOutputValueClass(ContextPatternStatsWritable.class); job.setOutputKeyClass(ContextPatternWritable.class); job.setOutputValueClass(ContextPatternStatsWritable.class); job.setMapperClass(MyMapper.class); job.setReducerClass(MyReducer.class); job.waitForCompletion(true); return 0; } }
// // KeyboardReactable.swift // JustBoard // // Created by JinwooLee on 5/23/24. // import UIKit import RxCocoa import RxSwift // 키보드의 등장에 반응하여 ScrollView UI 변화 protocol KeyboardReactable: AnyObject { var scrollView: UIScrollView! { get set } var loadBag: DisposeBag { get set } } extension KeyboardReactable where Self: UIViewController { /// 키보드가 올라와 있는 상황에서 키보드 밖의 영역을 터치하면 키보드가 사라지도록 동작 func setTapGesture() { let tap = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } /// 키보드가 올라간 만큼 화면도 같이 스크롤 func setKeyboardNotification() { let keyboardWillShow = NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification) let keyboardWillHide = NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification) keyboardWillShow .asDriver(onErrorRecover: { _ in .never()}) .drive(onNext: { [weak self] noti in self?.handleKeyboardWillShow(noti) }).disposed(by: loadBag) keyboardWillHide .asDriver(onErrorRecover: { _ in .never()}) .drive(onNext: { [weak self] noti in self?.handleKeyboardWillHide() }).disposed(by: loadBag) } private func handleKeyboardWillShow(_ notification: Notification) { guard let userInfo = notification.userInfo, let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return } let contentInset = UIEdgeInsets( top: 0.0, left: 0.0, bottom: keyboardFrame.size.height, right: 0.0) scrollView.contentInset = contentInset scrollView.scrollIndicatorInsets = contentInset } private func handleKeyboardWillHide() { let contentInset = UIEdgeInsets.zero scrollView.contentInset = contentInset scrollView.scrollIndicatorInsets = contentInset } }
import { useState, useEffect, useCallback } from 'react'; const fetchCurrentWeather = (locationName) => { return fetch( `https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0003-001?Authorization=CWB-5DE01DD1-3DCA-4AFF-85A7-6D78002F1B20&locationName=${locationName}` ) .then((response) => response.json()) .then((data) => { const locationData = data.records.location[0]; if (locationData) { const weatherElements = locationData.weatherElement.reduce( (neededElements, item) => { if (['WDSD', 'TEMP', 'HUMD'].includes(item.elementName)) { neededElements[item.elementName] = item.elementValue; } return neededElements; }, {} ); return { observationTime: locationData.time.obsTime, locationName: locationData.locationName, temperature: weatherElements.TEMP, windSpeed: weatherElements.WDSD, humid: weatherElements.HUMD, }; } else { return { observationTime: '', locationName: 'No data', temperature: 'No data', windSpeed: 'No data', humid: 'No data', }; } }); }; const fetchWeatherForecast = (cityName) => { return fetch( `https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=CWB-5DE01DD1-3DCA-4AFF-85A7-6D78002F1B20&locationName=${cityName}` ) .then((response) => response.json()) .then((data) => { const locationData = data.records.location[0]; if (locationData) { const weatherElements = locationData.weatherElement.reduce( (neededElements, item) => { if (['Wx', 'PoP', 'CI'].includes(item.elementName)) { neededElements[item.elementName] = item.time[0].parameter; } return neededElements; }, {} ); return { description: weatherElements.Wx.parameterName, weatherCode: weatherElements.Wx.parameterValue, rainPossibility: weatherElements.PoP.parameterName, comfortability: weatherElements.CI.parameterName, }; } else { return { description: 'No data', weatherCode: 'No data', rainPossibility: 'No data', comfortability: 'No data', }; } }); }; const useWeatherApi = (currentLocation) => { const { locationName, cityName } = currentLocation; const [weatherElement, setWeatherElement] = useState({ observationTime: new Date(), locationName: '', humid: 0, temperature: 0, windSpeed: 0, description: '', weatherCode: 0, rainPossibility: 0, comfortability: '', isLoading: true,//初次進來網站時,一開始的 isLoading 會是 true }); const fetchData = useCallback(() => { const fetchingData = async () => { const [currentWeather, weatherForecast] = await Promise.all([ //「觀測」天氣資料拉取 API 用的地區名稱 fetchCurrentWeather(locationName), //「預測」天氣資料拉取 API 用的地區名稱 fetchWeatherForecast(cityName), ]); //待 fetchData 的資料都回來之後,isLoading 會變成 false setWeatherElement({ ...currentWeather, ...weatherForecast, isLoading: false, }); }; // for 重新loading 狀態 - fetchData 實際開始向 API 拉取資料(fetchingData)前,先把 isLoading 的狀態設成 true setWeatherElement(prevState => { return { ...prevState, isLoading: true }; }); fetchingData(); }, [locationName, cityName]); useEffect(() => { fetchData(); }, [fetchData]); return [weatherElement, fetchData]; } export default useWeatherApi;
import 'package:flutter/animation.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main(){ runApp(MaterialApp(home: SimpleAnimation(),)); } class SimpleAnimation extends StatefulWidget { const SimpleAnimation({super.key}); @override State<SimpleAnimation> createState() => _SimpleAnimationState(); } class _SimpleAnimationState extends State<SimpleAnimation> with SingleTickerProviderStateMixin { Animation<double>? animation; AnimationController? animationController; @override void initState() { animationController=AnimationController(vsync: this,duration: Duration(seconds: 1)); animation=Tween<double>(begin: 12.0,end: 100.0).animate(animationController!)..addListener(() { setState(() { }); }); } @override Widget build(BuildContext context) { return Scaffold( body: ListView( children: [ Container( margin: EdgeInsets.all(20), child: Text("Hello All", style: TextStyle(fontSize: animation?.value),),), ElevatedButton(onPressed: () => zoomIn(), child: const Text("increase text size")) ], ), ); } void zoomIn() { animationController!.forward(); } }
#include <stdio.h> #include <stdlib.h> /* Uso do algoritmo Union Find para detectar os ciclos. https://en.wikipedia.org/wiki/Disjoint-set_data_structure*/ int findParent(int parent[], int component) { if (parent[component] == component) return component; return parent[component] = findParent(parent, parent[component]); } void conjuntoUniao(int u, int v, int parent[], int rank[], int n) { u = findParent(parent, u); v = findParent(parent, v); if (rank[u] < rank[v]) { parent[u] = v; } else if (rank[u] > rank[v]) { parent[v] = u; } else { parent[v] = u; rank[u]++; } } void kruskal(int n, int edge[n][3]) { int parent[n]; int rank[n]; for (int i = 0; i < n; i++) { parent[i] = i; rank[i] = 0; } int mstWeight = 0; int v1, v2, wt; for (int i = 0; i < n; i++) { v1 = findParent(parent, edge[i][0]); v2 = findParent(parent, edge[i][1]); wt = edge[i][2]; if (v1 != v2) { conjuntoUniao(v1, v2, parent, rank, n); mstWeight += wt; } } printf("%d\n", mstWeight); } int main() { int nVertices; /*Programa só funciona para até 100 arestas.*/ int elist[100][3]; scanf("%d", &nVertices); int nEdges = 0; /* Lê aresta por aresta, já atribuindo às posições na matriz.*/ while (scanf("%d %d %d", &elist[nEdges][0], &elist[nEdges][1], &elist[nEdges][2]) != EOF) nEdges++; kruskal(nEdges, elist); return 0; }
From: [email protected] (Sergio Demian Lerner) Date: Fri, 7 Apr 2017 17:52:17 -0300 Subject: [bitcoin-dev] BIP Proposal: Inhibiting a covert optimization on the Bitcoin POW function Message-ID: <CAKzdR-rzb6oBq01DQM530pdgNUjzc79yjtYp_HAyF5GZpBPnFw@mail.gmail.com> <pre> BIP: TBD Layer: Consensus Title: Inhibiting a covert optimization on the Bitcoin POW function Author: Sergio Demian Lerner <sergio.d.lerner at gmail.com> Status: Draft Type: Standards Track Created: 2016-04-07 License: PD </pre> ==Abstract== This proposal inhibits the covert use of a known optimization in Bitcoin Proof of Work function. The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. ==Motivation== Due to a design oversight the Bitcoin proof of work function has a potential optimization which can allow a rational miner to save up-to 30% of their energy costs (though closer to 20% is more likely due to implementation overheads). Timo Hanke and Sergio Demian Lerner applied for a patent on this optimization. The company "Sunrise Tech Group, Llc" has offered to license it to any interested party in the past. Sunrise Tech Group has been marketing their patent licenses under the trade-name ASICBOOST. The document takes no position on the validity or enforceability of the patent. There are two major ways of taking advantage of this optimization, as described by the patent: One way which is highly detectable and is not in use on the network today and a covert way which has significant interaction and potential interference with the Bitcoin protocol. The covert mechanism is not easily detected except through its interference with the protocol. In particular, the protocol interactions of the covert method can block the implementation of virtuous improvements such as segregated witness. The use of this optimization could result in a big payoff, but the actual sum depends on the degree of research, investment and effort put into designing the improved cores. On the above basis the potential for covert use of this optimization in the covert form and interference with useful improvements presents a danger to the Bitcoin system. ==Background== The general idea of this optimization is that SHA2-256 is a merkle damgard hash function which consumes 64 bytes of data at a time. The Bitcoin mining process repeatedly hashes an 80-byte 'block header' while incriminating a 32-bit nonce which is at the end of this header data. This means that the processing of the header involves two runs of the compression function run-- one that consumes the first 64 bytes of the header and a second which processes the remaining 16 bytes and padding. The initial 'message expansion' operations in each step of the SHA2-256 function operate exclusively on that step's 64-bytes of input with no influence from prior data that entered the hash. Because of this if a miner is able to prepare a block header with multiple distinct first 64-byte chunks but identical 16-byte second chunks they can reuse the computation of the initial expansion for multiple trials. This reduces power consumption. There are two broad ways of making use of this optimization. The obvious way is to try candidates with different version numbers. Beyond upsetting the soft-fork detection logic in Bitcoin nodes this has little negative effect but it is highly conspicuous and easily blocked. The other method is based on the fact that the merkle root committing to the transactions is contained in the first 64-bytes except for the last 4 bytes of it. If the miner finds multiple candidate root values which have the same final 32-bit then they can use the optimization. To find multiple roots with the same trailing 32-bits the miner can use efficient collision finding mechanism which will find a match with as little as 2^16 candidate roots expected, 2^24 operations to find a 4-way hit, though low memory approaches require more computation. An obvious way to generate different candidates is to grind the coinbase extra-nonce but for non-empty blocks each attempt will require 13 or so additional sha2 runs which is very inefficient. This inefficiency can be avoided by computing a sqrt number of candidates of the left side of the hash tree (e.g. using extra nonce grinding) then an additional sqrt number of candidates of the right side of the tree using transaction permutation or substitution of a small number of transactions. All combinations of the left and right side are then combined with only a single hashing operation virtually eliminating all tree related overhead. With this final optimization finding a 4-way collision with a moderate amount of memory requires ~2^24 hashing operations instead of the >2^28 operations that would be require for extra-nonce grinding which would substantially erode the benefit of the optimization. It is this final optimization which this proposal blocks. ==New consensus rule== Beginning block X and until block Y the coinbase transaction of each block MUST either contain a BIP-141 segwit commitment or a correct WTXID commitment with ID 0xaa21a9ef. (See BIP-141 "Commitment structure" for details) Existing segwit using miners are automatically compatible with this proposal. Non-segwit miners can become compatible by simply including an additional output matching a default commitment value returned as part of getblocktemplate. Miners SHOULD NOT automatically discontinue the commitment at the expiration height. ==Discussion== The commitment in the left side of the tree to all transactions in the right side completely prevents the final sqrt speedup. A stronger inhibition of the covert optimization in the form of requiring the least significant bits of the block timestamp to be equal to a hash of the first 64-bytes of the header. This would increase the collision space from 32 to 40 or more bits. The root value could be required to meet a specific hash prefix requirement in order to increase the computational work required to try candidate roots. These change would be more disruptive and there is no reason to believe that it is currently necessary. The proposed rule automatically sunsets. If it is no longer needed due to the introduction of stronger rules or the acceptance of the version-grinding form then there would be no reason to continue with this requirement. If it is still useful at the expiration time the rule can simply be extended with a new softfork that sets longer date ranges. This sun-setting avoids the accumulation of technical debt due to retaining enforcement of this rule when it is no longer needed without requiring a hard fork to remove it. == Overt optimization == A BIP for avoiding erroneous warning messages when miners use the overt version of the optimization was proposed several years ago, in order to deter the covert use of the optimization. But that BIP was rejected. However, in light of the current discoveries, that BIP could be reconsidered. The over optimization does not generally interfere with improvements in the protocol. ==Backward compatibility== ==Implementation== ==Acknowledgments== Greg Maxwell <greg at xiph.org> for the original report, which contained several errors that were corrected in the present proposal. ==Copyright== This document is placed in the public domain. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://lists.linuxfoundation.org/pipermail/bitcoin-dev/attachments/20170407/46d4d476/attachment-0001.html>
import React, { Component } from 'react'; import styled, { ThemeProvider } from 'styled-components'; import { Game } from '../components/Game'; import { mapKeyCodeToDirection } from '../constants/directions'; import { gameInit } from '../controller/gameInit'; import { move } from '../controller/move'; import { GameSettings } from '../components/GameSettings'; import { ScoreBoard } from '../components/ScoreBoard'; import { Container } from '../components/Container'; import { dark, light } from '../../../themes'; import { GameOver } from '../components/GameOver'; import { BEST_SCORE_LS_KEY } from '../config'; interface State { size: number; cells: number[][]; score: number; bestScore: number; selectedTheme: string; gameOver: boolean; } const BEST_SCORE = Number.parseInt( localStorage.getItem(BEST_SCORE_LS_KEY) || '0', ); export class GameMain extends Component<unknown, State> { state: State = { cells: gameInit(4), score: 0, bestScore: BEST_SCORE, size: 4, selectedTheme: 'light', gameOver: false, }; componentDidMount() { document.addEventListener('keydown', this.handleKeyPress); } componentWillUnmount() { document.removeEventListener('keydown', this.handleKeyPress); } newGame = () => { this.setState((state) => ({ ...state, cells: gameInit(state.size), score: 0, gameOver: false, })); }; handleKeyPress = (event: KeyboardEvent) => { const { gameOver } = this.state; if (!gameOver && mapKeyCodeToDirection[event.code]) { const { cells, score, bestScore, gameOver } = move( this.state.cells, mapKeyCodeToDirection[event.code], ); this.setState({ cells, score, bestScore, gameOver, }); localStorage.setItem(BEST_SCORE_LS_KEY, bestScore.toString()); } }; changeTheme = () => { this.setState((state) => ({ ...state, selectedTheme: state.selectedTheme === 'light' ? 'dark' : 'light', })); }; render() { const { cells, score, bestScore, size, selectedTheme, gameOver } = this.state; return ( <ThemeProvider theme={this.state.selectedTheme === 'light' ? light : dark} > <Container> <Wrapper> <ScoreBoard score={score} bestScore={bestScore} /> <GameSettings selectedTheme={selectedTheme} changeTheme={this.changeTheme} newGame={this.newGame} /> </Wrapper> <Wrapper> {gameOver && <GameOver />} <Game cells={cells} size={size} /> </Wrapper> </Container> </ThemeProvider> ); } } const Wrapper = styled.div` flex: 1; padding: 10px; flex-direction: column; `;
import React from 'react'; import '../styles/App.scss'; import Header from './Header'; import GoodList from './GoodList'; import Footer from './Footer'; import { BrowserRouter, Routes, Route } from 'react-router-dom'; import GoodDetails from './GoodDetails'; class App extends React.Component { render() { return ( <div className="App"> <Header /> <div className="app-body"> <BrowserRouter> <Routes> <Route index element={<GoodList />} /> <Route path="/home" element={<GoodList />} /> <Route path="/details/:id" element={<GoodDetails />} /> </Routes> </BrowserRouter> </div> <Footer /> </div> ); } } export default App;
import 'package:flutter/material.dart'; const Color primaryColor = Color(0xFF497DF9); const Color secondaryColor = Color(0xFF497DF9); // const Color a1 = Color(0xFF252531); const Color textcolor = Color(0xFFffffff); const Color background_color = Color(0xFF252531); const Color tab_color = Color(0xFFffffff); const Color text_color_gray = Color(0xFF808080); const Color bg_inner_recycler_screen = Color(0xFF2a2d36); const Color black = Color(0xFF000000); const Color gray = Color(0xFFA8A8A8); const Color green = Color(0xFF32CD32); const Color gray1 = Color(0xFFDFDFE1); const Color transparent = Color(0x00ffffff); const Color pink = Color(0xFFF54D6E); const Color orange = Color(0xFFf17501); const Color megenta = Color(0xFF2cb0bd); // final ThemeData lightTheme = _buildLightTheme(); final ThemeData darkTheme = _buildDarkTheme(); BuildContext context; ThemeData _buildLightTheme() { final ColorScheme colorScheme = const ColorScheme.light().copyWith( primary: primaryColor, secondary: secondaryColor, ); final ThemeData base = ThemeData( appBarTheme: AppBarTheme( color: Colors.white, brightness: Brightness.dark, elevation: 0), tabBarTheme: TabBarTheme( unselectedLabelColor: Color(0xFF787878), ), bottomAppBarTheme: BottomAppBarTheme( elevation: 0, color: Colors.white, ), textTheme: new TextTheme( headline1: TextStyle( color: Color(0xFF000000), ), headline2: TextStyle( color: Color(0xFF787878), ), headline3: TextStyle( color: Color(0xFFC2C2C2), ), headline4: TextStyle( color: Color(0x80C2C2C2), ), headline5: TextStyle( color: Color(0x40C2C2C2), ), headline6: TextStyle( color: Color(0x20C2C2C2), ), caption: TextStyle( color: Color(0xFF000000), ), subtitle1: TextStyle( color: Color(0xFF000000), ), subtitle2: TextStyle( color: Color(0xFFFFFFFF), ), // headline2: TextStyle( // color: Color(0xFFF2F2F2), // ), //For button Text Color bodyText1: TextStyle(color: Color(0xFFFFFFFF)), ), primaryTextTheme: TextTheme( headline1: TextStyle( color: Color(0xFF787878), ), headline2: TextStyle( color: Color(0xFFC2C2C2), ), headline3: TextStyle( color: Color(0x80C2C2C2), ), headline4: TextStyle( color: Color(0x40C2C2C2), ), headline5: TextStyle( color: Color(0xFFECEFF1), ), headline6: TextStyle( color: Color(0x20C2C2C2), ), ), accentTextTheme: TextTheme( headline1: TextStyle(color: Color(0xFFEF716b)), headline2: TextStyle(color: Color(0xFF0c0b52)), headline3: TextStyle(color: Color(0xFF66658a)), headline4: TextStyle(color: Color(0xAA5c5c8a)), headline5: TextStyle(color: Color(0xFF497DF9)), headline6: TextStyle(color: Color(0xFF49BB5F)), subtitle1: TextStyle(color: Color(0xFF3b5998)), subtitle2: TextStyle(color: Color(0xFFFBC02D)), bodyText1: TextStyle( color: Color(0xFFFFFFFF), ), bodyText2: TextStyle( color: Color(0x20C2C2C2), ), ), accentIconTheme: IconThemeData(color: Color(0xFF000000)), buttonTheme: ButtonThemeData( colorScheme: colorScheme, buttonColor: Color(0xFF000000), textTheme: ButtonTextTheme.primary, highlightColor: Colors.transparent, splashColor: Colors.transparent, height: 40, ), //This For button buttonColor: Color(0xFF000000), // dividerTheme: DividerThemeData( // color: Color(0x80C2C2C2), // ), dividerColor: Color(0x80C2C2C2), inputDecorationTheme: InputDecorationTheme( border: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide(width: 1, color: Color(0xFFFAFAFA))), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide( width: 1, color: Color(0xFFC2C2C2), )), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide(width: 1, color: Color(0xFFBDBDBD))), focusedErrorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide(width: 0.5, color: Color(0xFFBDBDBD))), errorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide(width: 0.5, color: Color(0xFFBDBDBD))), disabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(4), borderSide: BorderSide(width: 0.5, color: Color(0xFFBDBDBD))), ), primarySwatch: myColor, //cursorColor: Color(0xFF00004d), hintColor: Color(0xFFC2C2C2), fontFamily: "regular", brightness: Brightness.light, accentColorBrightness: Brightness.light, colorScheme: colorScheme, primaryColor: primaryColor, indicatorColor: Colors.white, toggleableActiveColor: Color(0xFFe57373), splashColor: Colors.transparent, highlightColor: Colors.transparent, // splashFactory: InkRipple.splashFactory, accentColor: secondaryColor, errorColor: const Color(0xFFB00020), //My canvasColor: Color(0xFFFFFFFF), scaffoldBackgroundColor: Color(0xFFFFFFFF), backgroundColor: const Color(0xFFFFFFFF), bottomAppBarColor: Color(0xFFFFFFFF), cardColor: Color(0xFFFFFFFF), ); return base; } ThemeData _buildDarkTheme() { final ColorScheme colorScheme = const ColorScheme.dark().copyWith( primary: primaryColor, secondary: secondaryColor, ); final ThemeData base = ThemeData( appBarTheme: AppBarTheme(color: Colors.black, brightness: Brightness.light), primaryIconTheme: IconThemeData(color: Colors.white), iconTheme: IconThemeData(color: Color(0xFFFFFFFF)), textTheme: TextTheme( caption: TextStyle(color: Color(0xFFFFFFFF)), subtitle1: TextStyle( color: Color(0xFF787878), ), subtitle2: TextStyle( color: Color(0xFFC2C2C2), ), headline1: TextStyle( color: Color(0x80C2C2C2), ), headline2: TextStyle( color: Color(0xFFF2F2F2), ), headline3: TextStyle( color: Color(0xFFF2F2F2), ), //For button Text Color bodyText1: TextStyle(color: Color(0xFF000000)), //These 3 for devider headline4: TextStyle( color: Color(0xFFC2C2C2), ), headline5: TextStyle( color: Color(0x80C2C2C2), ), headline6: TextStyle( color: Color(0x20C2C2C2), ), ), accentTextTheme: TextTheme( subtitle1: TextStyle( color: Color(0xFFdb4437), ), subtitle2: TextStyle( color: Color(0xFF3b5998), ), headline1: TextStyle(color: Color(0xFFFF6F00)), headline2: TextStyle(color: Color(0xFF000000)), bodyText1: TextStyle( color: Color(0xFFFFFFFF), ), bodyText2: TextStyle( color: Color(0xFFFFFFFF), ), ), accentIconTheme: IconThemeData(color: Color(0xFFFFFFFF)), popupMenuTheme: PopupMenuThemeData(color: Color(0xFF252531)), buttonTheme: ButtonThemeData( colorScheme: colorScheme, buttonColor: Color(0xFFFFFFFF), textTheme: ButtonTextTheme.primary, highlightColor: Colors.transparent, splashColor: Colors.transparent, height: 40, ), //This For button buttonColor: Color(0xFFFFFFFF), dividerColor: Color(0x80C2C2C2), inputDecorationTheme: InputDecorationTheme( border: UnderlineInputBorder( borderSide: BorderSide(width: 1, color: Color(0xFFFAFAFA))), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( width: 1, color: Color(0xFFC2C2C2), )), focusedBorder: UnderlineInputBorder( borderSide: BorderSide(width: 1, color: Color(0xFFBDBDBD))), focusedErrorBorder: UnderlineInputBorder( borderSide: BorderSide(width: 0.5, color: Color(0xFFBDBDBD))), errorBorder: UnderlineInputBorder( borderSide: BorderSide(width: 0.5, color: Color(0xFFBDBDBD))), disabledBorder: UnderlineInputBorder( borderSide: BorderSide(width: 0.5, color: Color(0xFFBDBDBD))), ), //cursorColor: Color(0xFFFFFFFF), hintColor: Color(0xFFC2C2C2), fontFamily: "regular", brightness: Brightness.light, accentColorBrightness: Brightness.light, primaryColor: primaryColor, indicatorColor: Colors.white, toggleableActiveColor: Color(0xFF00E676), splashColor: Colors.transparent, highlightColor: Colors.transparent, splashFactory: InkRipple.splashFactory, accentColor: secondaryColor, errorColor: const Color(0xFFB00020), dialogBackgroundColor: Color(0xFF424242), primarySwatch: myColor, primaryColorDark: const Color(0xFF000000), primaryColorLight: secondaryColor, // canvasColor: const Color(0xFF000000), scaffoldBackgroundColor: const Color(0xFF000000), backgroundColor: const Color(0xFFFFFFFF), cardColor: Color(0xFF2a2d36), ); return base; } //final changeColor = ChangeColor(); const MaterialColor myColor = const MaterialColor(0xFF497DF9, const <int, Color>{ 50: const Color(0xFF497DF9), 100: const Color(0xFF497DF9), 200: const Color(0xFF497DF9), 300: const Color(0xFF497DF9), 400: const Color(0xFF497DF9), 500: const Color(0xFF497DF9), 600: const Color(0xFF497DF9), 700: const Color(0xFF497DF9), 800: const Color(0xFF497DF9), 900: const Color(0xFF497DF9), });
def countPerfectSubarrays(nums): from collections import defaultdict nums_count = defaultdict(int) # 用于存储数组中每个元素的数量 window_count = defaultdict(int) # 用于存储窗口中每个元素的数量 for num in nums: nums_count[num] += 1 perfect_count = 0 # 完全子数组的数量 left, right = 0, 0 # 定义滑动窗口的左右边界 while right < len(nums): window_count[nums[right]] += 1 # 将右边界的元素添加到窗口中 while len(nums_count) == len(window_count): # 如果窗口是完全子数组 print(left, right) perfect_count += len(nums) - right # 计算满足条件的子数组数量 window_count[nums[left]] -= 1 # 移除左边界的元素 if window_count[nums[left]] == 0: # 如果某个元素的数量变为0,删除这个元素 del window_count[nums[left]] left += 1 # 左边界右移 right += 1 # 右边界右移 return perfect_count # 这个问题可以通过枚举所有可能的组合来解决。我们需要找到所有可能的字符串, # 这些字符串是由输入字符串 a、b 和 c 通过一定的顺序组合并可能的插入其他字符得到的。 # 然后我们选择长度最短的字符串,如果长度相同,则选择字典序最小的字符串。 # 具体步骤如下: # 首先,我们需要定义一个函数 merge(s1, s2) 来合并两个字符串。 # 该函数找到 s1 和 s2 的最长公共后缀和前缀,然后返回合并的结果。例如 merge("abc", "bcd") 返回 "abcd"。 # 然后,我们对三个字符串的所有可能的顺序进行枚举。 # 总共有 6 种可能的顺序,即 (a, b, c),(a, c, b),(b, a, c),(b, c, a),(c, a, b),(c, b, a)。 # 对于每一种顺序,我们使用 merge 函数来合并这三个字符串,并保存结果。 # 最后,我们找出所有结果中长度最短的字符串。 # 如果长度相同,则选择字典序最小的字符串。 # 这个方法的时间复杂度是 O(n^2),其中 n 是输入字符串的最大长度 # 。因为我们需要枚举所有可能的顺序,并且 merge 函数的时间复杂度是 O(n^2)。 # 但是由于输入字符串的长度通常不会太长,所以这个方法在实践中是可行的。 from itertools import permutations def merge(s1, s2): # Special case: if one string is a substring of the other if s1 in s2: return s2 if s2 in s1: return s1 # Find the longest common suffix of s1 and prefix of s2 for i in range(len(s1) + 1): if s2.startswith(s1[i:]): return s1[:i] + s2 return s1 + s2 def shortest_supersequence(a, b, c): ans = None # Enumerate all possible orders for s1, s2, s3 in permutations((a, b, c)): # Merge the strings in the current order cur = merge(merge(s1, s2), s3) # If this is the first result or it's better than the current best result if ans is None or len(cur) < len(ans) or (len(cur) == len(ans) and cur < ans): ans = cur return ans # # Test the function with the provided examples # print(shortest_supersequence("abc", "bca", "aaa")) # Output: "aaabca" # print(shortest_supersequence("ab", "ba", "aba")) # Output: "aba" # print(shortest_supersequence("cab", "a", "b")) # Output: "aba" class Solution: def countSteppingNumbers(self, low: str, high: str) -> int: MOD = 10**9 + 7 prefix = [[0]*10 for _ in range(11)] dp = [[0]*10 for _ in range(11)] for i in range(10): dp[1][i] = 1 for i in range(1, 10): prefix[1][i] = prefix[1][i-1] + dp[1][i] for i in range(2, 11): for j in range(10): if j > 0: dp[i][j] += dp[i-1][j-1] if j < 9: dp[i][j] += dp[i-1][j+1] dp[i][j] %= MOD prefix[i][j] = prefix[i][j-1] + dp[i][j] prefix[i][j] %= MOD def calc(x): if x == 0: return 0 s = str(x) n = len(s) last_digit = int(s[0]) res = 0 for i in range(1, n): res += prefix[i][9] for i in range(1, last_digit): res += dp[n][i] for i in range(1, n): curr_digit = int(s[i]) if abs(last_digit-curr_digit) != 1: break for j in range(last_digit): res += dp[n-i][j] last_digit = curr_digit if i == n-1: res += 1 res %= MOD return res return (calc(int(high)) - calc(int(low) - 1)) % MOD # 减1是因为我们需要包含low本身 # 测试一下 sol = Solution() print(sol.countSteppingNumbers("20", "21")) # 输出应该是1
 'VB.Net -Exception Handling 'An exception Is a problem that arises during the execution Of a program. An exception Is a response To an exceptional circumstance that arises While a program Is running, such As an attempt To divide by zero. 'Exceptions provide a way To transfer control from one part Of a program To another. VB.Net exception handling Is built upon four keywords: Try, Catch, Finally And Throw. 'Try : A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks. 'Catch: A program catches an exception With an exception handler at the place In a program where you want To handle the problem. The Catch keyword indicates the catching Of an exception. 'Finally : The Finally block Is used to execute a given set of statements, whether an exception Is thrown Or Not thrown. For example, If you open a file, it must be closed whether an exception Is raised Or Not. 'Throw: A program throws an exception When a problem shows up. This Is done Using a Throw keyword. 'Syntax 'Assuming a block will raise an exception, a method catches an exception Using a combination Of the Try And Catch keywords. A Try/Catch block Is placed around the code that might generate an exception. Code within a Try/Catch block Is referred To As Protected code, And the syntax For Using Try/Catch looks Like the following 'Try ' [ tryStatements ] ' [ Exit Try ] '[ Catch [ exception [ As type ] ] [ When expression ] ' [ catchStatements ] ' [ Exit Try ] ] '[ Catch ... ] '[ Finally ' [ finallyStatements ] ] 'End Try 'You can list down multiple Catch statements To Catch different type Of exceptions In Case your Try block raises more than one exception In different situations. 'Exception Classes In .Net Framework 'In the .Net Framework, exceptions are represented by classes. The exception classes in .Net Framework are mainly directly Or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException And System.SystemException classes. 'The System.ApplicationException Class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this Class. 'The System.SystemException Class Is the base Class For all predefined system exception. 'The following table provides some Of the predefined exception classes derived from the Sytem.SystemException Class: 'Exception Class Description 'System.IO.IOException Handles I/O errors. 'System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range. 'System.ArrayTypeMismatchException Handles errors generated when type Is mismatched with the array type. 'System.NullReferenceException Handles errors generated from deferencing a null object. 'System.DivideByZeroException Handles errors generated from dividing a dividend with zero. 'System.InvalidCastException Handles errors generated during typecasting. 'System.OutOfMemoryException Handles errors generated from insufficient free memory. 'System.StackOverflowException Handles errors generated from stack overflow. 'Handling Exceptions 'VB.Net provides a structured solution to the exception handling problems in the form of try And catch blocks. Using these blocks the core program statements are separated from the error-handling statements. 'These error handling blocks are implemented using the Try, Catch And Finally keywords. Following Is an example of throwing an exception when dividing by zero condition occurs Module Module1 Sub division(ByVal num1 As Integer, ByVal num2 As Integer) Dim result As Integer Try result = num1 \ num2 Catch e As DivideByZeroException Console.WriteLine("Exception caught: {0}", e) Finally Console.WriteLine("Result: {0}", result) End Try End Sub Sub Main() division(25, 0) Console.ReadKey() End Sub End Module 'When the above code Is compiled And executed, it produces the following result: 'Exception caught : System.DivideByZeroException : Attempted to divide by zero. 'at... 'Result: 0
/* |-------------------------------------------------------------------------- | Routes file |-------------------------------------------------------------------------- | | The routes file is used for defining the HTTP routes. | */ import UserController from '#controllers/user.controller' import router from '@adonisjs/core/services/router' import { middleware } from './kernel.js' import CustomerController from '#controllers/customer.controller' import ProductController from '#controllers/product.controller' import SellController from '#controllers/sell.controller' router.post('signup', [UserController, 'store']) router.post('login', [UserController, 'login']) router .group(() => { router .group(() => { router.post('/', [CustomerController, 'store']) router.get('/', [CustomerController, 'index']) router.get(':id', [CustomerController, 'show']) router.delete(':id', [CustomerController, 'delete']) router.put(':id', [CustomerController, 'update']) }) .prefix('customer') router .group(() => { router.post('/', [ProductController, 'store']) router.get('/', [ProductController, 'index']) router.get(':id', [ProductController, 'show']) router.delete(':id', [ProductController, 'delete']) router.put(':id', [ProductController, 'update']) }) .prefix('product') router .group(() => { router.post('/', [SellController, 'store']) }) .prefix('sell') }) .use(middleware.auth({ guards: ['api'] }))
package com.task_management_system.Repository.DAO; import com.task_management_system.Entity.Member; import com.task_management_system.Repository.AsMemberRepository; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.sql.*; import java.util.*; @Repository @ConditionalOnProperty(name = "app.use_source", havingValue = "dao") public class MemberDAO implements AsMemberRepository { private final DataSource dataSource; public MemberDAO(DataSource dataSource) { this.dataSource = dataSource; } @Override public Optional<Member> findById(UUID id) { try (PreparedStatement statement = this.dataSource.getConnection().prepareStatement("SELECT * FROM member WHERE id = ?")) { statement.setObject(1, id); ResultSet result = statement.executeQuery(); if (result.next()) { return Optional.of(this.build(result)); } return Optional.empty(); } catch (SQLException ex) { throw new RuntimeException(ex); } } @Override public Iterable<Member> findAll() { try (PreparedStatement statement = this.dataSource.getConnection().prepareStatement("SELECT * FROM member")) { ResultSet result = statement.executeQuery(); List<Member> members = new ArrayList<>(); while (result.next()) { members.add(this.build(result)); } return members; } catch (SQLException ex) { throw new RuntimeException(ex); } } @Override public Member save(Member member) { try ( PreparedStatement statement = this.dataSource.getConnection().prepareStatement( "INSERT INTO member (name) VALUES (?)", Statement.RETURN_GENERATED_KEYS ) ) { statement.setString(1, member.getName()); statement.executeUpdate(); ResultSet result = statement.getGeneratedKeys(); if (result.next()) { member.setId(result.getObject("id", UUID.class)); } return member; } catch (SQLException ex) { throw new RuntimeException(ex); } } @Override public void delete(Member member) { try (PreparedStatement statement = this.dataSource.getConnection().prepareStatement("DELETE FROM member WHERE id = ?")) { statement.setObject(1, member.getId()); statement.executeUpdate(); } catch (SQLException ex) { throw new RuntimeException(ex); } } @Override public boolean isExistByName(String name) { try ( PreparedStatement statement = this.dataSource.getConnection().prepareStatement( "SELECT COUNT(id) > 0 AS count FROM member WHERE LOWER(name) = ?" ) ) { statement.setString(1, name); ResultSet result = statement.executeQuery(); if (result.next()) { return result.getBoolean("count"); } return false; } catch (SQLException ex) { throw new RuntimeException(ex); } } @Override public boolean isExistByName(String name, UUID existMemberId) { try ( PreparedStatement statement = this.dataSource.getConnection().prepareStatement( "SELECT COUNT(id) > 0 AS count FROM member WHERE LOWER(name) = ? AND id != ?" ) ) { statement.setString(1, name); statement.setObject(2, existMemberId); ResultSet result = statement.executeQuery(); if (result.next()) { return result.getBoolean("count"); } return false; } catch (SQLException ex) { throw new RuntimeException(ex); } } private Member build(ResultSet result) throws SQLException { return Member.builder() .id(result.getObject("id", UUID.class)) .name(result.getString("name")) .tasks(new ArrayList<>()) .build() ; } }
@extends('layouts.front') @section('content') <div class="card w-100 shadow-sm border-0"> <div class="card-body bg-success"> <div class="d-flex align-items-center justify-content-center"> @include('templates.navbar') </div> </div> </div> <article class="container p-3 p-md-5 text-secondary"> <h1 class="text-center text-success">Política de Cookies</h1> <hr> <p> En esta web recopilo y utilizo la información según indico en mi política de privacidad. Una de las formas en las que recopiló información es a través del uso de la tecnología llamada “cookies”. En <a href="{{ route('home') }}">andrestelocambia.com</a> se utilizan cookies para varias cosas. </p> <h2 class="text-success"> ¿Qué es una cookie? </h2> <p> Una "cookie" es una pequeña cantidad de texto que se almacena en tu navegador (como Chrome de Google o Safari de Apple) cuando navegas por la mayoría de los sitios web. </p> <h2 class="text-success"> ¿Qué NO es una cookie? </h2> <p> No es un virus, ni un troyano, ni un gusano, ni spam, ni spyware, ni abre ventanas pop-up. </p> <h2 class="text-success"> ¿Qué información almacena una cookie? </h2> <p> Las cookies no suelen almacenar información sensible sobre usted, como tarjetas de crédito o datos bancarios, fotografías o información personal, etc. Los datos que guardan son de carácter técnico, estadísticos, preferencias personales, personalización de contenidos, etc. </p> <p> El servidor web no le asocia a usted como persona sino a su navegador web. De hecho, si usted navega habitualmente con el navegador Chrome y prueba a navegar por la misma web con el navegador Firefox, verá que la web no se da cuenta que es usted la misma persona porque en realidad está asociando la información al navegador, no a la persona. </p> <h2 class="text-success"> ¿Qué tipo de cookies existen? </h2> <ul> <li> <strong>Cookies técnicas:</strong> Son las más elementales y permiten, entre otras cosas, saber cuándo está navegando un humano o una aplicación automatizada, cuándo navega un usuario anónimo y uno registrado, tareas básicas para el funcionamiento de cualquier web dinámica. </li> <li> <strong>Cookies de análisis:</strong> Recogen información sobre el tipo de navegación que está realizando, las secciones que más utiliza, productos consultados, franja horaria de uso, idioma, etc. </li> <li> <strong>Cookies publicitarias:</strong> Muestran publicidad en función de su navegación, su país de procedencia, idioma, etc. </li> </ul> <h2 class="text-success"> ¿Qué son las cookies propias y las de terceros? </h2> <p> Las cookies propias son las generadas por la página que está visitando y las de terceros son las generadas por servicios o proveedores externos como Mailchimp, Facebook, Twitter, Google adsense, etc. </p> <h2 class="text-success"> ¿Qué cookies utiliza esta web? </h2> <p> Esta web utiliza cookies propias y de terceros. En este sitio web se utilizan las siguientes cookies que se detallan a continuación: </p> <h4 class="text-success"> Cookies propias </h4> <ul> <li> <strong>Inicio de sesión:</strong> Las cookies para iniciar sesión te permiten entrar y salir de tu cuenta de <a href="{{ route('home') }}">andrestelocambia.com</a>. </li> <li> <strong>Personalización:</strong> Las cookies me ayudan a recordar con qué personas o sitios web has interactuado, para que pueda mostrarte contenido relacionado. </li> <li> <strong>Preferencias:</strong> Las cookies me permiten recordar tus ajustes y preferencias, como el idioma preferido y tu configuración de privacidad. </li> <li> <strong>Seguridad:</strong> Utilizo cookies para evitarte riesgos de seguridad. Principalmente para detectar cuándo alguien está intentando piratear tu cuenta de <a href="{{ route('home') }}">andrestelocambia.com</a>. </li> </ul> <h2 class="text-success"> ¿Se pueden eliminar las cookies? </h2> <p> Sí, y no sólo eliminar, también bloquear, de forma general o particular para un dominio específico. </p> <p> Para eliminar las cookies de un sitio web debe ir a la configuración de su navegador y allí podrá buscar las asociadas al dominio en cuestión y proceder a su eliminación. </p> <h2 class="text-success"> Más información sobre las cookies </h2> <p> Puedes consultar el reglamento sobre cookies publicado por la Agencia Española de Protección de Datos en su “Guía sobre el uso de las cookies” y obtener más información sobre las cookies en Internet, <a href="http://www.aboutcookies.org/" target="_blank" rel="noopener noreferrer">http://www.aboutcookies.org/</a>. </p> <p> Si desea tener un mayor control sobre la instalación de cookies, puede instalar programas o complementos a su navegador, conocidos como herramientas de “Do Not Track”, que le permitirán escoger aquellas cookies que desea permitir. </p> </article> @include('templates.footer') @endsection
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; import { Title } from '@angular/platform-browser'; import { ErrorHandlerService } from '../../core/services/errorHandler.service'; import { confirmPasswordValidator } from '../../core/validators/confirm-password-validator'; import { catchError, EMPTY, filter, Observable } from 'rxjs'; import { MessageService } from 'primeng/api'; import { Select, Store } from '@ngxs/store'; import { ChangePasswordAction, UpdateUserProfileAction } from '../state/auth.actions'; import { AuthState } from '../state/auth.state'; import { User } from '../auth.model'; import { FileOptions } from '@shared/components/file-uploader/file-uploader.component'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; @UntilDestroy() @Component({ selector: 'app-user-settings', templateUrl: './user-settings.component.html', styleUrls: ['./user-settings.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class UserSettingsComponent implements OnInit { message: { type: string; message: string; }; @Select(AuthState.current) user$: Observable<User> currentUser: any; public date: string; constructor( private handler: ErrorHandlerService, private title: Title, private formBuilder: UntypedFormBuilder, private _ms: MessageService, private _store: Store, private _cd: ChangeDetectorRef) { } image: File; updateProfileForm: UntypedFormGroup; changePasswordForm: UntypedFormGroup; imgForm: UntypedFormGroup; spinEditProfile = false; spinChangePassword = false; ngOnInit(): void { this.title.setTitle('User Settings'); this.user$.pipe(filter(result => result ? true : false), untilDestroyed(this)) .subscribe(user => { this.initUpdateProfile(user); this.initForm(); this._cd.detectChanges() }); } onUpload(event: FileOptions): void { if (event.isDelete) { this.updateProfileForm.controls.image.setValue(null); } this.image = event.value; } onSubmit(): void { this.updateProfileForm.markAllAsTouched(); if (this.updateProfileForm.valid) { this.spinEditProfile = !this.spinEditProfile; this._store.dispatch(new UpdateUserProfileAction(this.updateProfileForm.getRawValue(), this.image)) .pipe( catchError((e) => { this.handler.validation(e, this.updateProfileForm); this.spinEditProfile = false; this._cd.detectChanges(); return EMPTY; })) .subscribe(user => { this.spinEditProfile = false; this._ms.add({ severity: 'success', detail: 'User profile has been successfully updated!' }); this._cd.detectChanges(); }) } } initForm(): void { this.changePasswordForm = this.formBuilder.group({ newPassword: ['', [Validators.required]], confirmPassword: ['', [Validators.required]], }, { validators: confirmPasswordValidator('confirmPassword', 'newPassword') }) } initUpdateProfile(user: User): void { this.updateProfileForm = this.formBuilder.group({ firstName: [user.firstName, [Validators.required] ], lastName: [user.lastName, [Validators.required] ], username: [{ value: user.username, disabled: true }, [Validators.required]], image: [user.image, []], email: [{ value: user.email, disabled: true }, [Validators.required, Validators.email]], birthday: [user.birthday ? new Date(user.birthday) : null, []], phone: [user.phone], }); } changePassword(): void { this.changePasswordForm.markAllAsTouched(); if (this.changePasswordForm.valid) { this.spinChangePassword = true; this._store.dispatch(new ChangePasswordAction(this.changePasswordForm.getRawValue())) .pipe(catchError(e => { this.spinChangePassword = false; this.handler.validation(e, this.changePasswordForm); return EMPTY; }), untilDestroyed(this) ) .subscribe(() => { this.spinChangePassword = false; this._ms.add({ severity: 'success', detail: 'Password has been successfully changed!' }) this.changePasswordForm.reset(); this._cd.detectChanges(); }); } } }
use crate::data::{NowPlaying, ResponseType}; use crate::{Client, SubsonicError}; impl Client { /// reference: http://www.subsonic.org/pages/api.jsp#getNowPlaying pub async fn get_now_playing(&self) -> Result<NowPlaying, SubsonicError> { let body = self.request("getNowPlaying", None, None).await?; if let ResponseType::NowPlaying { now_playing } = body.data { Ok(now_playing) } else { Err(SubsonicError::Submarine(String::from( "expected type NowPlaying but found wrong type", ))) } } } mod tests { #[test] fn conversion_now_playing() { let response_body = r##" { "subsonic-response": { "status": "ok", "version": "1.16.1", "type": "navidrome", "serverVersion": "0.49.3 (8b93962f)", "nowPlaying": { "entry": [ { "id": "abd3c3bc92c3985e2ff77f9a36edcfa9", "parent": "9c1fd785e88b12723f758f2f31b516d8", "isDir": false, "title": "Showdown (radio edit)", "album": "Showdown", "artist": "Pendulum", "track": 2, "year": 2009, "genre": "Dance", "coverArt": "mf-abd3c3bc92c3985e2ff77f9a36edcfa9_647723e6", "size": 4341006, "contentType": "audio/ogg", "suffix": "ogg", "duration": 203, "bitRate": 167, "path": "Pendulum/Showdown/02 - Showdown (radio edit).ogg", "discNumber": 1, "created": "2023-05-31T10:50:41.85017274Z", "albumId": "9c1fd785e88b12723f758f2f31b516d8", "artistId": "bb8b3b51eb16a9a78b8d3e57cdc30e62", "type": "music", "isVideo": false, "username": "eppixx", "minutesAgo": 0, "playerId": 1, "playerName": "NavidromeUI" } ] } } }"##; let response = serde_json::from_str::<crate::data::OuterResponse>(response_body) .unwrap() .inner; if let crate::data::ResponseType::NowPlaying { now_playing } = response.data { assert_eq!( now_playing.entry.first().unwrap().child.album.as_deref(), Some("Showdown") ); assert_eq!(now_playing.entry.first().unwrap().username, "eppixx"); } else { panic!("wrong type {:?}", response.data); } } }
import { Directive, HostListener, Output, Input, EventEmitter, ElementRef } from "@angular/core"; @Directive({ selector: "[paginationOverflowDetect]" }) export class PaginationOverflowDirective { @Output() public overflowing = new EventEmitter<Event>(); @Output() public notOverflowing = new EventEmitter<Event>(); @Input() public curPage: number; private oldPage: number = 0; public ngOnInit(): void { this.oldPage = this.curPage; setInterval(() => { if (this.curPage != this.oldPage) this.oldPage = this.curPage; this.overflowCheck(); }, 100); } public constructor( public element: ElementRef ) {} @HostListener("window:load") public onLoad(): void { this.overflowCheck(); } @HostListener("window:resize") public onResize(): void { this.overflowCheck(); } private overflowCheck(): void { if (this.element.nativeElement.scrollWidth > this.element.nativeElement.clientWidth) this.overflowing.emit(); else this.notOverflowing.emit(); } }
import React, { ReactNode, MouseEvent, SyntheticEvent, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { Button } from '@digdir/design-system-react'; import { MenuElipsisVerticalIcon, ArrowUpIcon, ArrowDownIcon, PencilIcon, TrashIcon, } from '@navikt/aksel-icons'; import { AltinnMenu, AltinnMenuItem } from 'app-shared/components'; import { useFormLayoutSettingsQuery } from '../../../../hooks/queries/useFormLayoutSettingsQuery'; import { useUpdateLayoutOrderMutation } from '../../../../hooks/mutations/useUpdateLayoutOrderMutation'; import { useUpdateLayoutNameMutation } from '../../../../hooks/mutations/useUpdateLayoutNameMutation'; import { useStudioUrlParams } from 'app-shared/hooks/useStudioUrlParams'; import { useSelector } from 'react-redux'; import { useDeleteLayoutMutation } from '../../../../hooks/mutations/useDeleteLayoutMutation'; import type { IAppState } from '../../../../types/global'; import { Divider } from 'app-shared/primitives'; import { AltinnConfirmDialog } from 'app-shared/components'; import { useSearchParams } from 'react-router-dom'; import { firstAvailableLayout } from '../../../../utils/formLayoutsUtils'; import { InputPopover } from './InputPopover'; import { deepCopy } from 'app-shared/pure'; import { useAppContext } from '../../../../hooks/useAppContext'; export type NavigationMenuProps = { /** * The name of the page */ pageName: string; pageIsReceipt: boolean; }; /** * @component * Displays the buttons to move a page accoridon up or down, edit the name and delete the page * * @property {string}[pageName] - The name of the page * * @returns {ReactNode} - The rendered component */ export const NavigationMenu = ({ pageName, pageIsReceipt }: NavigationMenuProps): ReactNode => { const { t } = useTranslation(); const { org, app } = useStudioUrlParams(); const { selectedLayoutSet } = useAppContext(); const invalidLayouts: string[] = useSelector( (state: IAppState) => state.formDesigner.layout.invalidLayouts, ); const invalid = invalidLayouts.includes(pageName); const { data: formLayoutSettings } = useFormLayoutSettingsQuery(org, app, selectedLayoutSet); const layoutOrder = formLayoutSettings?.pages.order; const disableUp = layoutOrder.indexOf(pageName) === 0; const disableDown = layoutOrder.indexOf(pageName) === layoutOrder.length - 1; const { mutate: updateLayoutOrder } = useUpdateLayoutOrderMutation(org, app, selectedLayoutSet); const { mutate: deleteLayout } = useDeleteLayoutMutation(org, app, selectedLayoutSet); const { mutate: updateLayoutName } = useUpdateLayoutNameMutation(org, app, selectedLayoutSet); const [menuAnchorEl, setMenuAnchorEl] = useState<null | HTMLElement>(null); const [isConfirmDeleteDialogOpen, setIsConfirmDeleteDialogOpen] = useState<boolean>(); const [isEditDialogOpen, setIsEditDialogOpen] = useState<boolean>(); const [searchParams, setSearchParams] = useSearchParams(); const selectedLayout = searchParams.get('layout'); const onPageSettingsClick = (event: MouseEvent<HTMLButtonElement>) => setMenuAnchorEl(event.currentTarget); const onMenuClose = (_event: SyntheticEvent) => setMenuAnchorEl(null); const onMenuItemClick = (event: SyntheticEvent, action: 'up' | 'down' | 'edit' | 'delete') => { if (action === 'delete') { setIsConfirmDeleteDialogOpen((prevState) => !prevState); } else if (action === 'edit') { setIsEditDialogOpen((prevState) => !prevState); } else { if (action === 'up' || action === 'down') { updateLayoutOrder({ layoutName: pageName, direction: action }); } setMenuAnchorEl(null); } }; const handleConfirmDelete = () => { deleteLayout(pageName); if (selectedLayout === pageName) { const layoutToSelect = firstAvailableLayout(pageName, layoutOrder); setSearchParams({ layout: layoutToSelect }); } }; const handleSaveNewName = (newName: string) => { updateLayoutName({ oldName: pageName, newName }); setSearchParams({ ...deepCopy(searchParams), layout: newName }); }; return ( <div> <Button icon={<MenuElipsisVerticalIcon />} onClick={onPageSettingsClick} variant='tertiary' title={t('general.options')} size='small' /> <AltinnMenu anchorEl={menuAnchorEl} open={Boolean(menuAnchorEl)} onClose={onMenuClose}> {!pageIsReceipt && ( <AltinnMenuItem onClick={(event) => !(disableUp || invalid) && onMenuItemClick(event, 'up')} disabled={disableUp || invalid} text={t('ux_editor.page_menu_up')} icon={ArrowUpIcon} id='move-page-up-button' testId='move-page-up-button-test-id' /> )} {!pageIsReceipt && ( <AltinnMenuItem onClick={(event) => !(disableDown || invalid) && onMenuItemClick(event, 'down')} disabled={disableDown || invalid} text={t('ux_editor.page_menu_down')} icon={ArrowDownIcon} id='move-page-down-button' testId='move-page-down-button-test-id' /> )} <InputPopover oldName={pageName} layoutOrder={layoutOrder} saveNewName={handleSaveNewName} onClose={() => { setIsEditDialogOpen(false); setMenuAnchorEl(null); }} open={isEditDialogOpen} trigger={ <AltinnMenuItem onClick={(event) => onMenuItemClick(event, 'edit')} text={t('ux_editor.page_menu_edit')} icon={PencilIcon} id='edit-page-button' disabled={invalid} /> } /> <Divider marginless /> <AltinnConfirmDialog open={isConfirmDeleteDialogOpen} confirmText={t('ux_editor.page_delete_confirm')} onConfirm={() => { handleConfirmDelete(); setMenuAnchorEl(null); }} onClose={() => { setIsConfirmDeleteDialogOpen(false); setMenuAnchorEl(null); }} trigger={ <AltinnMenuItem onClick={(event) => onMenuItemClick(event, 'delete')} text={t('ux_editor.page_menu_delete')} icon={TrashIcon} id='delete-page-button' /> } > <p>{t('ux_editor.page_delete_text')}</p> <p>{t('ux_editor.page_delete_information')}</p> </AltinnConfirmDialog> </AltinnMenu> </div> ); };
import React, { useEffect, useState } from "react"; import Autocomplete from "@mui/material/Autocomplete"; import { getAvailableListings } from "../database/listing"; import TextField from "@mui/material/TextField"; import Stack from "@mui/material/Stack"; import filter from 'lodash/filter'; import { getHost } from '../database/settings'; import Skeleton from '@mui/material/Skeleton'; import ImageListItemBar from '@mui/material/ImageListItemBar'; import LocationOnOutlinedIcon from '@mui/icons-material/LocationOnOutlined'; import LocalShippingOutlinedIcon from '@mui/icons-material/LocalShippingOutlined'; import IconButton from '@mui/material/IconButton'; import InputAdornment from '@mui/material/InputAdornment'; import SearchIcon from '@mui/icons-material/Search'; import SortIcon from '@mui/icons-material/Sort'; import MenuItem from '@mui/material/MenuItem'; import FormControl from '@mui/material/FormControl'; import Select from '@mui/material/Select'; import { useNavigate } from "react-router-dom"; import Grid from "@mui/material/Grid"; import { Box } from "@mui/material"; import Button from "@mui/material/Button"; import ImageIcon from '@mui/icons-material/Image'; export default function Marketplace() { const [listings, setListings] = useState(); const [host, setHost] = useState(); const [loading, setLoading] = useState(false); const [filterKey, setFilterKey] = useState(""); const navigate = useNavigate(); const handleSort = (event) => { const val = event.target.value; console.log(val); var sort = []; if (val === 2) { sort = [...listings].sort((a, b) => b.price - a.price) } else { sort = [...listings].sort((a, b) => a.price - b.price) } setListings(sort) }; /* fetches the listings from local database */ useEffect(() => { setLoading(true); getAvailableListings() .then((data) => { console.log(`results:`, data); const sort = [...data].sort((a, b) => b.created_at - a.created_at) return setListings(sort); }) .catch((e) => { console.error(`Couldn't get listings: ${e}`); }); return; }, []); useEffect(() => { getHost() .then((data) => { setHost(data); console.log(`Retrieved host successfully ${JSON.stringify(data)}`); setLoading(false); }).catch((e) => { console.error(`Couldn't get host: ${e}`); }); }, []); function marketplaceFilter(o) { return (o.status === 'unchecked' || o.status === 'available'); } function handleSearch(e) { setFilterKey(e.target.value); } if (listings) { return ( <Box mt={2} sx={{ flexGrow: 1 }}> <Autocomplete id="free-solo-demo" freeSolo options={listings.map((option) => option.title)} renderInput={(params) => <TextField {...params} onChange={(e) => handleSearch(e)} placeholder={"search..."} InputProps={{ startAdornment: ( <InputAdornment position="start"> <SearchIcon /> </InputAdornment> ), endAdornment: ( <InputAdornment position="start"> <FormControl variant="standard" sx={{ fontSize: "10px" }} fullWidth> <Select id="sort-marketplace" onChange={handleSort} label="Sort by" value="" className="select-sort" IconComponent={SortIcon} > <MenuItem value={1}>lowest price</MenuItem> <MenuItem value={2}>highest price</MenuItem> </Select> </FormControl> </InputAdornment> ) }} />} /> {loading ? <> <Skeleton animation="wave" variant="circular" width={40} height={40} /> <Skeleton animation="wave" height={8} width="80%" style={{ marginBottom: 6 }} /> </> // : <ListingList link='/listing' listings={filter(listings, o => marketplaceFilter(o)).filter((i)=>i.title.includes(filterKey))} /> : <> <Grid container mt={1} rowSpacing={2} columnSpacing={{ xs: 2, sm: 3, md: 3 }}> {filter(listings, o => marketplaceFilter(o)).filter((i) => i.title.toLowerCase().includes(filterKey.toLowerCase())).map((item, ind) => ( <Grid item xs={6} sx={{ position: 'relative' }}> <div style={{ maxWidth: "200px", height: "150px", overflow: "hidden" }}> {item.image === "" ? <Box onClick={() => item.created_by_pk !== host.pk ? navigate(`/listing/${item.listing_id}`) : navigate(`/seller/listing/${item.listing_id}`)} sx={{ backgroundColor: '#c6c6c6', borderRadius:'5px', display: 'flex', justifyContent: 'center', alignContent: 'center', flexDirection: 'column', flexWrap: 'wrap', height: '100%'}}><ImageIcon></ImageIcon></Box> : <img onClick={() => item.created_by_pk !== host.pk ? navigate(`/listing/${item.listing_id}`) : navigate(`/seller/listing/${item.listing_id}`)} src={`${item.image.split("(+_+)")[0]}`} srcSet={`${item.image.split("(+_+)")[0]}`} alt={item.title} loading="lazy" style={{ width: "100%", height: "100%", borderRadius: "5px", objectFit: "cover" }} />} </div> <div style={{ position: "absolute", left: '15px', top: '15px' }}> {item.created_by_pk === host.pk ? <Button size="small" sx={{ color: 'black', background: "rgba(255,255,255,0.7)" }} >YOUR ITEM</Button> : null} </div> <div style={{ position: "absolute", right: '3px', marginTop: '-37px' }}> {item.collection === 'true' && (item.status === 'available' || item.status === 'pending' || item.status === 'unchecked') ? <IconButton size="small" sx={{ color: '#333333', background: "rgba(255,255,255,0.7)" }} > <LocationOnOutlinedIcon fontSize="2px" /> </IconButton> : null} {item.delivery === 'true' && (item.status === 'available' || item.status === 'pending' || item.status === 'unchecked') ? <IconButton size="small" sx={{ ml: "3px", color: '#333333', background: "rgba(255,255,255,0.7)" }} > <LocalShippingOutlinedIcon fontSize="2px" /> </IconButton> : null} {item.transmission_type === "collection" && (item.status === 'sold' || item.status === 'in_progress') ? <IconButton size="small" sx={{ color: '#333333', background: "rgba(255,255,255,0.7)" }} > <LocationOnOutlinedIcon fontSize="2px" /> </IconButton> : null} {item.transmission_type === "delivery" && (item.status === 'sold' || item.status === 'in_progress') ? <IconButton size="small" sx={{ color: '#333333', background: "rgba(255,255,255,0.7)" }} > <LocalShippingOutlinedIcon fontSize="2px" /> </IconButton> : null} </div> <ImageListItemBar title={"$M" + item.price} subtitle={<span>{item.title}</span>} position="below" /> </Grid> ))} </Grid> </> } </Box> ); } else { return ( <Stack mt={2} spacing={2}> <Skeleton mt={2} variant="rectangular" width='100%' height={60} /> <Skeleton variant="text" sx={{ fontSize: '1rem' }} /> <Skeleton animation="wave" variant="circular" width={40} height={40} /> </Stack> ) } }
# Load necessary modules Import-Module Microsoft.Online.SharePoint.PowerShell -Force Import-Module Microsoft.Graph -Force # Prompt for tenant domain name and credentials $TenantDomain = Read-Host -Prompt "Enter your tenant domain (e.g., 'yourtenant' for 'yourtenant-admin.sharepoint.com')" $AdminSiteURL = "https://$TenantDomain-admin.sharepoint.com" # Connect to SharePoint Online Connect-SPOService -Url $AdminSiteURL # Authenticate to Microsoft Graph $GraphAppId = Read-Host -Prompt "Enter your Graph App ID" $GraphTenantId = Read-Host -Prompt "Enter your Graph Tenant ID" $GraphClientSecret = Read-Host -Prompt "Enter your Graph Client Secret" $tokenBody = @{ grant_type = "client_credentials" scope = "https://graph.microsoft.com/.default" client_id = $GraphAppId client_secret = $GraphClientSecret } $tokenResponse = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$GraphTenantId/oauth2/v2.0/token" -ContentType "application/x-www-form-urlencoded" -Body $tokenBody $AccessToken = $tokenResponse.access_token # Function to fetch sharing information from Microsoft Graph function Get-GraphData { param ( [Parameter(Mandatory = $true)] [string]$Uri, [Parameter(Mandatory = $true)] [string]$AccessToken ) $headers = @{ Authorization = "Bearer $AccessToken" Accept = "application/json" } $response = Invoke-RestMethod -Method Get -Uri $Uri -Headers $headers return $response.value } # Retrieve all SharePoint Online sites and sort them by Title $Sites = Get-SPOSite -Limit All | Sort-Object Title # Initialize a list to store external sharing information $ExternalSharingInfo = [System.Collections.Generic.List[Object]]::new() # Counter for tracking progress $Counter = 0 # Iterate through each site and retrieve sharing information ForEach ($Site in $Sites) { $Counter++ Write-Host ("Checking Site {0}/{1}: {2}" -f $Counter, $Sites.Count, $Site.Title) $SiteId = (Get-SPOSite -Identity $Site.Url).Id $Uri = "https://graph.microsoft.com/v1.0/sites/$SiteId/drives" $Drives = Get-GraphData -Uri $Uri -AccessToken $AccessToken ForEach ($Drive in $Drives) { $DriveItemsUri = "https://graph.microsoft.com/v1.0/drives/$($Drive.id)/items/root/children" $DriveItems = Get-GraphData -Uri $DriveItemsUri -AccessToken $AccessToken ForEach ($Item in $DriveItems) { if ($Item.shared.sharedWith) { $InvitedBy = $Item.lastModifiedBy.user.displayName $SharedWith = ($Item.shared.sharedWith | ForEach-Object { $_.user.displayName }) -join ", " $ExternalSharingInfo.Add([PSCustomObject]@{ FileName = $Item.name InvitedBy = $InvitedBy SharedWith = $SharedWith SiteURL = $Site.Url }) } } } } # Function to generate HTML report with color styling function Generate-HTMLReport { param ( [Parameter(Mandatory = $true)] [array]$ExternalSharingInfo ) $html = @" <html> <head> <style> body { font-family: Arial, sans-serif; color: black; } h2 { color: black; } table { width: 100%; border-collapse: collapse; } th { background-color: DarkOrange; color: black; padding: 8px; text-align: left; } td { border: 1px solid #ddd; padding: 8px; } tr:nth-child(even) { background-color: #f2f2f2; } tr:hover { background-color: #ddd; } </style> </head> <body> <h2>External File Sharing Report</h2> <table> <tr> <th>File Name</th> <th>Invited By</th> <th>Shared With</th> <th>Site URL</th> </tr> "@ foreach ($item in $ExternalSharingInfo) { $html += @" <tr> <td>$($item.FileName)</td> <td>$($item.InvitedBy)</td> <td>$($item.SharedWith)</td> <td>$($item.SiteURL)</td> </tr> "@ } $html += @" </table> </body> </html> "@ return $html } # Generate HTML report $HTMLReport = Generate-HTMLReport -ExternalSharingInfo $ExternalSharingInfo # Get the script directory $ScriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path $ReportPath = Join-Path -Path $ScriptDirectory -ChildPath "ExternalFileSharingReport.html" # Save HTML report to a file $HTMLReport | Out-File -FilePath $ReportPath Write-Output "Report generated at $ReportPath"
import { BOARD_COLUMNS, BOARD_ROWS, CENTRAL_CASE_POSITION, INVALID_INDEX, PLAYER_AI_INDEX } from '@app/classes/constants'; import { CustomRange } from '@app/classes/range'; import { BoardPattern, Orientation, PatternInfo, PossibleWords } from '@app/classes/scrabble-board-pattern'; import { PlayerAIService } from '@app/services/player-ai.service'; import { Level } from '@common/level'; import { PlayerAI } from './player-ai.model'; export class PlaceLetterStrategy { dictionary: string[]; pointingRange: CustomRange; private board: string[][][]; constructor() { this.pointingRange = { min: 1, max: 18 }; // TODO constante ? this.board = []; } async execute(playerAiService: PlayerAIService): Promise<void> { const playerAi = playerAiService.playerService.players[PLAYER_AI_INDEX] as PlayerAI; const level = playerAiService.gameSettingsService.gameSettings.level; const isFirstRound = playerAiService.placeLetterService.isFirstRound; const scrabbleBoard = playerAiService.placeLetterService.scrabbleBoard; this.dictionary = await playerAiService.communicationService .getGameDictionary(playerAiService.gameSettingsService.gameSettings.dictionary) .toPromise(); let allPossibleWords: PossibleWords[]; let matchingPointingRangeWords: PossibleWords[] = []; this.initializeArray(scrabbleBoard); const patterns = this.generateAllPatterns(playerAi.getHand(), isFirstRound); allPossibleWords = this.generateAllWords(this.dictionary, patterns); allPossibleWords = this.removeIfNotEnoughLetter(allPossibleWords, playerAi); if (isFirstRound) { allPossibleWords.forEach((word) => (word.startIndex = CENTRAL_CASE_POSITION.x)); } else { allPossibleWords = this.removeIfNotDisposable(allPossibleWords); } allPossibleWords = await playerAiService.calculatePoints(allPossibleWords); playerAiService.sortDecreasingPoints(allPossibleWords); matchingPointingRangeWords = playerAiService.filterByRange(allPossibleWords, this.pointingRange); if (level === Level.Expert) await this.computeResults(allPossibleWords, playerAiService); if (level === Level.Beginner) await this.computeResults(matchingPointingRangeWords, playerAiService, false); playerAiService.debugService.receiveAIDebugPossibilities(allPossibleWords); } private async computeResults(possibilities: PossibleWords[], playerAiService: PlayerAIService, isDifficultMode = true): Promise<void> { if (possibilities.length === 0) { playerAiService.swap(isDifficultMode); return; } const idx = 0; if (isDifficultMode) { await playerAiService.place(possibilities[idx]); possibilities.splice(0, 1); return; } const index = playerAiService.generateRandomNumber(possibilities.length); await playerAiService.place(possibilities[index]); possibilities.splice(index, 1); } private initializeArray(scrabbleBoard: string[][]): void { const array: string[][][] = new Array(Object.keys(Orientation).length / 2); array[Orientation.Horizontal] = new Array(BOARD_COLUMNS); array[Orientation.Vertical] = new Array(BOARD_ROWS); // Initialize the tridimensional array representing the scrabble board // array[dimension][line][letter] <=> array[2 dimensions][15 line/dimensions][15 tile/row] for (let i = 0; i < BOARD_ROWS; i++) { array[Orientation.Horizontal][i] = scrabbleBoard[i]; const column: string[] = []; for (let j = 0; j < BOARD_COLUMNS; j++) { column.push(scrabbleBoard[j][i]); } array[Orientation.Vertical][i] = column; } this.board = array; } private removeIfNotDisposable(allPossibleWords: PossibleWords[]): PossibleWords[] { const filteredWords: PossibleWords[] = []; const regex1 = new RegExp('(?<=[A-Za-z])(,?)(?=[A-Za-z])', 'g'); const regex2 = new RegExp('[,]', 'g'); const regex3 = new RegExp('[a-z]{1,}', 'g'); for (const word of allPossibleWords) { let line = this.board[word.orientation][word.line] .map((element: string) => { return element === '' ? ' ' : element; }) .toString(); line = line.replace(regex2, ''); const radixes = this.board[word.orientation][word.line].toString().toLowerCase().replace(regex1, '').match(regex3) as string[]; if (this.isWordFitting(line, word, radixes)) { filteredWords.push(word); } } return filteredWords; } // TODO vérifier cette fonction car perte de points au sprint 2 AQ private isWordFitting(line: string, wordToPlace: PossibleWords, radixes: string[]): boolean { const isEmptyCase = new Array<boolean>(wordToPlace.word.length); isEmptyCase.fill(true); let pattern = ''; for (const root of radixes) { const startIndex = wordToPlace.word.search(root); const endIdx = startIndex + root.length; for (let i = startIndex; i < endIdx; i++) { isEmptyCase[i] = false; } } for (let i = 0; i < isEmptyCase.length; i++) { // Construct the word skeleton by replacing empty tiles in the row by spaces // and the filled tiles by the letter value actually in the row pattern += isEmptyCase[i] ? ' ' : wordToPlace.word[i]; } // Search this skeleton in the row const start = line.search(pattern); const end = start + wordToPlace.word.length - 1; if (start === INVALID_INDEX) { return false; } // If found set the starting positing for later placing wordToPlace.startIndex = start; // If found the word must not touch the adjacent words return this.isWordOverWriting(line, start, end, wordToPlace.word.length) ? false : true; } private isWordOverWriting(line: string, startIndex: number, endIdx: number, wordLength: number): boolean { if (wordLength !== BOARD_ROWS) { const touchOtherWordByRight = startIndex === 0 && line[endIdx + 1] !== ' '; const touchOtherWordByLeft = endIdx === BOARD_ROWS && line[startIndex - 1] !== ' '; const touchOtherWordByRightOrLeft = startIndex !== 0 && endIdx !== BOARD_ROWS && line[startIndex - 1] !== ' ' && line[endIdx + 1] !== ' '; // The beginning and the end of the word must not touch another if (touchOtherWordByRight || touchOtherWordByLeft || touchOtherWordByRightOrLeft) { return true; } } return false; } private removeIfNotEnoughLetter(allPossibleWords: PossibleWords[], player: PlayerAI): PossibleWords[] { const filteredWords: PossibleWords[] = []; for (const wordObject of allPossibleWords) { let isWordValid = true; for (const letter of wordObject.word) { const regex1 = new RegExp(letter, 'g'); const regex2 = new RegExp('[,]{1,}', 'g'); const amountOfLetterNeeded: number = (wordObject.word.match(regex1) as string[]).length; const amountOfLetterPresent: number = ( this.board[wordObject.orientation][wordObject.line].toString().replace(regex2, '').match(regex1) || [] ).length; const playerAmount: number = player.playerQuantityOf(letter); if (amountOfLetterNeeded > playerAmount + amountOfLetterPresent) { // Not add the words that need more letter than available isWordValid = false; break; } } if (isWordValid) { filteredWords.push(wordObject); } } return filteredWords; } // TODO : creating console errors // Unhandled Promise rejection: dictionaryToLookAt is not iterable ; Zone: ProxyZone ; Task: jasmine.onComplete ; // Value: TypeError: dictionaryToLookAt is not iterable private generateAllWords(dictionaryToLookAt: string[], patterns: BoardPattern): PossibleWords[] { // Generate all words satisfying the patterns found const allWords: PossibleWords[] = []; for (const pattern of patterns.horizontal) { const regex = new RegExp(pattern.pattern, 'g'); for (const word of dictionaryToLookAt) { if (regex.test(word) && this.checkIfWordIsPresent(pattern.pattern, word)) { allWords.push({ word, orientation: Orientation.Horizontal, line: pattern.line, startIndex: 0, point: 0 }); } } } for (const pattern of patterns.vertical) { const regex = new RegExp(pattern.pattern, 'g'); for (const word of dictionaryToLookAt) { if (regex.test(word) && this.checkIfWordIsPresent(pattern.pattern, word)) { allWords.push({ word, orientation: Orientation.Vertical, line: pattern.line, startIndex: 0, point: 0 }); } } } return allWords; } private checkIfWordIsPresent(pattern: string, word: string): boolean { const regex = new RegExp('(?<=[*])(([a-z]*)?)', 'g'); const wordPresent = pattern.match(regex); for (let i = 0; wordPresent !== null && i < wordPresent.length; i++) { if (wordPresent[i] === word) { return false; } } return true; } private generateAllPatterns(playerHand: string, isFirstRound: boolean): BoardPattern { let horizontal: PatternInfo[] = []; let vertical: PatternInfo[] = []; if (isFirstRound) { // At first round the only pattern is the letter in the player's easel horizontal.push({ line: CENTRAL_CASE_POSITION.x, pattern: '^' + playerHand.toLowerCase() + '*$' }); vertical.push({ line: CENTRAL_CASE_POSITION.y, pattern: '^' + playerHand.toLowerCase() + '*$' }); return { horizontal, vertical }; } horizontal = this.generatePattern(Orientation.Horizontal, playerHand); vertical = this.generatePattern(Orientation.Vertical, playerHand); return { horizontal, vertical }; } private generatePattern(orientation: Orientation, playerHand: string): PatternInfo[] { const patternArray: PatternInfo[] = []; const regex1 = new RegExp('(?<=[A-Za-z])(,?)(?=[A-Za-z])', 'g'); const regex2 = new RegExp('[,]{1,}', 'g'); for (let line = 0; line < BOARD_COLUMNS; line++) { let pattern = this.board[orientation][line] .toString() .replace(regex1, '') .replace(regex2, playerHand + '*') .toLowerCase(); // If it's not an empty row if (pattern !== playerHand.toLowerCase() + '*') { pattern = '^' + pattern + '$'; patternArray.push({ line, pattern }); } } return patternArray; } }
package co.edu.uniquindio.proyectoAvanzada.Controladores; import co.edu.uniquindio.proyectoAvanzada.dto.*; import co.edu.uniquindio.proyectoAvanzada.modelo.enums.Especialidad; import co.edu.uniquindio.proyectoAvanzada.modelo.servicios.interfaces.MedicoServicios; import co.edu.uniquindio.proyectoAvanzada.modelo.servicios.interfaces.PQRServicios; import co.edu.uniquindio.proyectoAvanzada.modelo.servicios.interfaces.PacienteServicios; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/api/pacientes") @RequiredArgsConstructor public class PacienteController { private final PacienteServicios pacienteServicios; private final MedicoServicios medicoServicios; private final PQRServicios pQRServicios; @PutMapping("/editarPerfil") public ResponseEntity editarPerfil(@Valid @RequestBody PacienteDTO pacienteDTO) throws Exception{ pacienteServicios.editarPerfil(pacienteDTO); return ResponseEntity.ok().body( new MensajeDTO<>(false, "Paciente actualizado correctamete") ); } @PutMapping("/recuperarPassword") public ResponseEntity<MensajeDTO<String>> recuperarPassword(@Valid @RequestBody RecuperarPasswordDTO dto) throws Exception { pacienteServicios.recuperarPassword(dto); return ResponseEntity.ok().body(new MensajeDTO<>(false, "Contraseña actualizada correctamente")); } @DeleteMapping("/eliminar/{idPaciente}") public ResponseEntity<MensajeDTO<String>> eliminarCuenta(@PathVariable int idPaciente) throws Exception { pacienteServicios.eliminarCuenta(idPaciente); return ResponseEntity.ok().body(new MensajeDTO<>(false, "Paciente eliminado correctamente")); } @PostMapping("/enviarLinkRecuperacion") public ResponseEntity<MensajeDTO<String>> enviarLinkRecuperacion(@RequestBody Map<String, String> requestBody) throws Exception { String emailPaciente = requestBody.get("emailPaciente"); pacienteServicios.enviarLinkRecuperacion(emailPaciente); return ResponseEntity.ok().body(new MensajeDTO<>(false, "Email enviado correctamente")); } @PostMapping("/agendarCita") public ResponseEntity agendarCita(@Valid @RequestBody CitaPacienteDTO citaPacienteDTO) throws Exception { pacienteServicios.agendarCita(citaPacienteDTO); return ResponseEntity.ok().body(new MensajeDTO<>(false, "Cita agendada exitosamente")); } @PutMapping("/cambiarPassword") public ResponseEntity cambiarPassword(@RequestBody Map<String, String> requestBody) throws Exception { int idPaciente = Integer.parseInt(requestBody.get("idPaciente")); String nuevaPassword = requestBody.get("nuevaPassword"); pacienteServicios.cambiarPassword(idPaciente, nuevaPassword); return ResponseEntity.ok().body(new MensajeDTO<>(false, "Contraseña cambiada correctamente")); } @PostMapping("/responderPQRS") public ResponseEntity responderPQRS(@Valid @RequestBody GestionDTOPQRSPaciente gestionDTOPQRSPacient) throws Exception { pacienteServicios.responderPQRS(gestionDTOPQRSPacient); return ResponseEntity.ok().body(new MensajeDTO<>(false, "respuesta generada exitosamente")); } @GetMapping("/listarCitasPaciente/{idPaciente}") public ResponseEntity listarCitasPaciente(@PathVariable int idPaciente) throws Exception { return ResponseEntity.ok().body( new MensajeDTO<>(false, pacienteServicios.listarCitasPaciente(idPaciente))); } @GetMapping("/filtrarCitaPorMedico") public ResponseEntity filtrarCitaPorMedico(@RequestBody Map<String, String> requestBody) throws Exception { int idPaciente = Integer.parseInt(requestBody.get("idPaciente")); int idMedico = Integer.parseInt(requestBody.get("idMedico")); return ResponseEntity.ok().body( new MensajeDTO<>(false, pacienteServicios.filtrarCitaPorMedico (idPaciente, idMedico))); } @GetMapping("/filtrarCitaPorFecha") public ResponseEntity filtrarCitaPorFecha(@Valid @RequestBody FiltrarFechaPacienteDTO filtrarFechaPacienteDTO) throws Exception { return ResponseEntity.ok().body( new MensajeDTO<>(false, pacienteServicios.filtrarCitaPorFecha (filtrarFechaPacienteDTO))); } @GetMapping("/verDetalleCita/{idCita}") public ResponseEntity verDetalleCita(@PathVariable int idCita) throws Exception { return ResponseEntity.ok().body( new MensajeDTO<>(false, pacienteServicios.verDetalleCita(idCita))); } @GetMapping("/consultaMedicamentos/{idMedicamento}") public ResponseEntity consultaMedicamentos(@PathVariable int idMedicamento) throws Exception { return ResponseEntity.ok().body( new MensajeDTO<>(false, pacienteServicios.consultaMedicamentos (idMedicamento))); } @GetMapping("/detalle/{idPaciente}") public ResponseEntity obtenerPaciente(@PathVariable int idPaciente) throws Exception { return ResponseEntity.ok().body(new MensajeDTO<>(false, pacienteServicios.obtenerPaciente(idPaciente))); } @GetMapping("/listarMedicosEspecialidad/{nombre}") public ResponseEntity listarMedicosEspecialidad(@PathVariable Especialidad nombre) throws Exception{ return ResponseEntity.ok().body( new MensajeDTO<>(false, medicoServicios.listarMedicosEspecialidad(nombre))); } @GetMapping("/listarCitasPqrs/{idPaciente}") public ResponseEntity listarCitasPqrs(@PathVariable int idPaciente) throws Exception{ return ResponseEntity.ok().body( new MensajeDTO<>(false, pQRServicios.listarCitasPqrs(idPaciente))); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration Form</title> </head> <body> <h1>Registration Form</h1> <form> <div> <label>First Name: *</label> <input type="text" name="First_Name"> </div> <div> <label>Last Name: *</label> <input type="text" name="Last_Name"> </div> <div> <label>Email Address: *</label> <input type="text" name="Email_Address"> </div> <div> <label>Password: *</label> <input type="password" name="Password"> </div> <div> <label>Confirm Password: *</label> <input type="password" name="Confirm_Password"> </div> <div> <label>Birthday: *</label> <input type="date" name="Birthday"> </div> <div> <label>Gender Identity:</label> <input type="radio" name="gender" value="Male" id="Male"> <label for="Male">Male</label> <input type="radio" name="gender" value="Female" id="Female"> <label for="Female">Female</label> <input type="radio" name="gender" value="Non_Binary" id="Non_Binary"> <label for="Female">Non-binary</label> <input type="radio" name="gender" value="I_prefer_not_to_answer" id="I_prefer_not_to_answer"> <label for="I_prefer_not_to_answer">I prefer not to answer</label> </div> <div> <label>A short descirption about myself:</label> <textarea name="A_short_description_about_myself" cols="20" rows="3"></textarea> </div> <div> <label>Favorite Language:</label> <select name="Favorite Language:"> <option>Javascript</option> <option>HTML</option> <option>CSS</option> </select> </div> <div> <input type="checkbox" name="Yes, I would like to receive periodic email updates" id="Yes_I_would_like_to_receive_periodic_updates" checked > <label>Yes, I would like to receive periodic updates</label> </div> <div> <input type="submit" value="Create Account" > </div> <div>* Indicates a required field</div> </form> </body> </html>
package com.enaboapps.switchify.service.menu import com.enaboapps.switchify.service.SwitchifyAccessibilityService import com.enaboapps.switchify.service.menu.menus.edit.EditMenu import com.enaboapps.switchify.service.menu.menus.gestures.GesturesMenu import com.enaboapps.switchify.service.menu.menus.gestures.SwipeGesturesMenu import com.enaboapps.switchify.service.menu.menus.gestures.TapGesturesMenu import com.enaboapps.switchify.service.menu.menus.gestures.ZoomGesturesMenu import com.enaboapps.switchify.service.menu.menus.main.MainMenu import com.enaboapps.switchify.service.menu.menus.system.DeviceMenu import com.enaboapps.switchify.service.menu.menus.system.VolumeControlMenu import com.enaboapps.switchify.service.scanning.ScanMethod import com.enaboapps.switchify.service.scanning.ScanningManager /** * This class manages the menu */ class MenuManager { companion object { private var instance: MenuManager? = null /** * This function gets the instance of the menu manager */ fun getInstance(): MenuManager { if (instance == null) { instance = MenuManager() } return instance!! } } /** * The scanning manager */ private var scanningManager: ScanningManager? = null /** * The accessibility service */ private var accessibilityService: SwitchifyAccessibilityService? = null /** * The scan method to revert to when the menu is closed */ var scanMethodToRevertTo: String = ScanMethod.MethodType.CURSOR /** * The menu hierarchy */ var menuHierarchy: MenuHierarchy? = null /** * This function sets up the menu manager * @param scanningManager The scanning manager * @param accessibilityService The accessibility service */ fun setup( scanningManager: ScanningManager, accessibilityService: SwitchifyAccessibilityService ) { this.scanningManager = scanningManager menuHierarchy = MenuHierarchy(scanningManager) this.accessibilityService = accessibilityService } /** * This function resets the scan method type to the original type */ fun resetScanMethodType() { ScanMethod.isInMenu = false ScanMethod.setType(scanMethodToRevertTo) } /** * This function changes between cursor and item scan based on the current type */ fun changeBetweenCursorAndItemScan() { if (scanMethodToRevertTo == ScanMethod.MethodType.CURSOR) { scanningManager?.setItemScanType() } else { scanningManager?.setCursorType() } } /** * This function gets the name of the type to switch to (cursor or item scan) * @return The name of the type to switch to */ fun getTypeToSwitchTo(): String { return if (scanMethodToRevertTo == ScanMethod.MethodType.CURSOR) { "Item Scan" } else { "Cursor" } } /** * This function opens the main menu */ fun openMainMenu() { val mainMenu = MainMenu(accessibilityService!!) openMenu(mainMenu.build()) } /** * This function opens the device menu */ fun openDeviceMenu() { val deviceMenu = DeviceMenu(accessibilityService!!) openMenu(deviceMenu.build()) } /** * This function opens the edit menu */ fun openEditMenu() { val editMenu = EditMenu(accessibilityService!!) openMenu(editMenu.build()) } /** * This function opens the volume control menu */ fun openVolumeControlMenu() { val volumeControlMenu = VolumeControlMenu(accessibilityService!!) openMenu(volumeControlMenu.build()) } /** * This function opens the gestures menu */ fun openGesturesMenu() { val gesturesMenu = GesturesMenu(accessibilityService!!) openMenu(gesturesMenu.build()) } /** * This function opens the tap menu */ fun openTapMenu() { val tapGesturesMenu = TapGesturesMenu(accessibilityService!!) openMenu(tapGesturesMenu.build()) } /** * This function opens the swipe gestures menu */ fun openSwipeMenu() { val swipeGesturesMenu = SwipeGesturesMenu(accessibilityService!!) openMenu(swipeGesturesMenu.build()) } /** * This function opens the zoom gestures menu */ fun openZoomGesturesMenu() { val zoomGesturesMenu = ZoomGesturesMenu(accessibilityService!!) openMenu(zoomGesturesMenu.build()) } /** * This function opens the menu * @param menu The menu to open */ private fun openMenu(menu: MenuView) { // Add the menu to the hierarchy menuHierarchy?.openMenu(menu) } /** * This function closes the menu hierarchy */ fun closeMenuHierarchy() { menuHierarchy?.removeAllMenus() } }
#include "opencv2/opencv.hpp" #include "fstream" int main() { const char* input = "/home/dinhnambkhn/3dv_tutorial/bin/data/chessboard.avi"; cv::Size board_pattern(10, 7); float board_cellsize = 0.025f; bool select_images = true; bool no_selection = true; // Open a video cv::VideoCapture video; if (!video.open(input)) return -1; //number of frames int n_frames = video.get(cv::CAP_PROP_FRAME_COUNT); //frame rate double fps = video.get(cv::CAP_PROP_FPS); //show video information std::cout << "Number of frames: " << n_frames << std::endl; std::cout << "Frame rate: " << fps << std::endl; // Select images std::vector<cv::Mat> images; int num = 0; while (!no_selection) { // Grab an image from the video cv::Mat image; video >> image; if (image.empty()) break; if (select_images) { // Show the image and keep it if selected cv::imshow("3DV Tutorial: Camera Calibration", image); int key = cv::waitKey(1); if (key == 27) break; // 'ESC' key: Exit else if (key == 32) // 'Space' key: Pause { std::vector<cv::Point2f> pts; bool complete = cv::findChessboardCorners(image, board_pattern, pts); cv::Mat display = image.clone(); cv::drawChessboardCorners(display, board_pattern, pts, complete); cv::imshow("3DV Tutorial: Camera Calibration", display); key = cv::waitKey(); if (key == 27) break; // 'ESC' key: Exit else if (key == 13) images.push_back(image); // 'Enter' key: Select } } else images.push_back(image); num = images.size(); //printf("num = %d\n", num); std::cout << "num = " << num << std::endl; } //load all frames if(no_selection){ for (int i = 0; i < n_frames; i=i+10) { cv::Mat image; video >> image; if (image.empty()) break; images.push_back(image); } } video.release(); if (images.empty()) return -1; printf("video release \n"); // Find 2D corner points from the given images std::vector<std::vector<cv::Point2f>> img_points; int idx = 1; for (const auto & image : images) { std::vector<cv::Point2f> pts; if (cv::findChessboardCorners(image, board_pattern, pts)) img_points.push_back(pts); std::cout << "img_idx= " << idx << " img_points.size() = "<< pts.size() << std::endl; idx++; } if (img_points.empty()) return -1; //size of img_points // Prepare 3D points of the chess board std::vector<std::vector<cv::Point3f>> obj_points(1); for (int r = 0; r < board_pattern.height; r++) for (int c = 0; c < board_pattern.width; c++) obj_points[0].emplace_back(board_cellsize * c, board_cellsize * r, 0); obj_points.resize(img_points.size(), obj_points[0]); // Copy //obj_points size std::cout << "obj_points.size() = " << obj_points.size() << std::endl; // Calibrate the camera cv::Mat K = cv::Mat::eye(3, 3, CV_64F); cv::Mat dist_coeff = cv::Mat::zeros(4, 1, CV_64F); std::vector<cv::Mat> rvecs, tvecs; //define criteria cv::TermCriteria criteria = cv::TermCriteria(cv::TermCriteria::COUNT + cv::TermCriteria::EPS, 30, DBL_EPSILON); //calibrate camera double rms = cv::calibrateCamera(obj_points, img_points, images[0].size(), K, dist_coeff, rvecs, tvecs, cv::CALIB_FIX_K3, criteria); std::cout << "calibrateCamera rms = " << rms<< std::endl; // Report calibration results std::ofstream report("/home/dinhnambkhn/3dv_tutorial/bin/data/camera_calibration.txt"); if (!report.is_open()) return -1; report << "## Camera Calibration Results" << std::endl; report << "* The number of applied images = " << img_points.size() << std::endl; report << "* RMS error = " << rms << std::endl; report << "* Camera matrix (K) = " << std::endl << " " << K.row(0) << K.row(1) << K.row(2) << std::endl; report << "* Distortion coefficient (k1, k2, p1, p2, k3, ...) = " << std::endl << " " << dist_coeff.t() << std::endl; report.close(); return 0; }
library(tidyverse) library(ggtext) fallecimientos_ss <- readRDS("01_Datos/datos_ssalud_fallecimientos.rds") fallecimientos_ss %>% mutate(grupo_edad = case_when(between(EDAD, 0, 0) ~ "0 años", between(EDAD, 1, 10) ~ "1 a 10 años", between(EDAD, 11, 18) ~ "11 a 18 años", between(EDAD, 19, 30) ~ "19 a 30 años", between(EDAD, 31, 40) ~ "31 a 40 años", between(EDAD, 41, 50) ~ "41 a 50 años", between(EDAD, 51, 60) ~ "51 a 60 años", between(EDAD, 61, 70) ~ "61 a 70 años", between(EDAD, 71, 80) ~ "71 a 80 años", EDAD >= 81 ~ "Mayores de 80 años")) %>% group_by(grupo_edad) %>% count() %>% ungroup() %>% mutate(pp = n/sum(n)) # Datos a nivel nacional ---- # length(unique(fall_coah$ID_REGISTRO)) # Datos a nivel estado ---- fall_coah = fallecimientos_ss %>% filter(ENTIDAD_RES == "05") %>% group_by(EDAD, SEXO) %>% count() %>% ungroup() %>% mutate(grupo_edad = case_when(between(EDAD, 0, 0) ~ "0 años", between(EDAD, 1, 10) ~ "1 a 10 años", between(EDAD, 11, 18) ~ "11 a 18 años", between(EDAD, 19, 30) ~ "19 a 30 años", between(EDAD, 31, 40) ~ "31 a 40 años", between(EDAD, 41, 50) ~ "41 a 50 años", between(EDAD, 51, 60) ~ "51 a 60 años", between(EDAD, 61, 70) ~ "61 a 70 años", between(EDAD, 71, 80) ~ "71 a 80 años", EDAD >= 81 ~ "Mayores de 80 años")) %>% group_by(grupo_edad, SEXO) %>% summarise(n = sum(n, na.rm = T)) %>% ungroup() %>% mutate(n = ifelse(SEXO == 1, yes = n, no = -n)) %>% mutate(hjust = ifelse(n <= 0, 1.2, -0.2), y1 = ifelse(n <= 0, -2300, 2300), y2 = ifelse(n <= 0, n - 2300, n + 2300)) %>% group_by(SEXO) %>% mutate(pp = 100*(n/sum(n))) fall_coah %>% ggplot(aes(x = grupo_edad, y = n, fill = factor(SEXO))) + geom_col() + geom_text(aes(label = str_c(prettyNum(abs(n), big.mark = ","), "\n(", format(round(pp, 1), nsmall = 1), "%)"), hjust = hjust), family = "Mulish", # hjust = 0.5, size = 3) + scale_y_continuous(expand = expansion(c(0.4, 0.4), 0)) + coord_flip() + labs(title = "¿Cuánta gente ha fallecido por sexo y edad en Coahuila?", subtitle = "Pirámide de fallecimientos por sexo y edad al 4 de Julio del 2022", caption = "Fuente: Secretaría de Salud. Indivíduos que reportaron fecha de fallecimiento a lo largo de toda la base\ny que reportaron a la entidad 05 como su entidad de residencia. ", x = NULL, y = NULL) + theme_bw() + theme(panel.border = element_blank(), plot.subtitle = element_markdown(family = "Mulish"), plot.title = element_text(family = "Mulish", face = "bold", size = 15), axis.text.y = element_text(family = "Mulish", face = "bold", size = 10), plot.title.position = "plot", axis.text.x = element_blank(), axis.ticks = element_blank(), legend.position = "none") ggsave("03_Visualizaciones/piramide_casos_covid_sexo.png", width = 6, height = 6, device = "png") # Datos gráfica: fallecimientos_ss %>% filter(ENTIDAD_RES == "05") %>% group_by(SEXO) %>% count() %>% ungroup() %>% mutate(n/sum(n))
# ts-rest-hono <p align="center">🔥 A <a href="https://hono.dev/">hono</a> adapter for <a href="https://www.ts-rest.com">ts-rest 🔥</a></p> <p align="center"> <a href="https://www.ts-rest.com"> <img src="https://avatars.githubusercontent.com/u/109956939?s=400&u=8bf67b1281da46d64eab85f48255cd1892bf0885&v=4" height="150"></img> </a> <a href="https://hono.dev"> <img src="https://avatars.githubusercontent.com/u/98495527?s=400&v=4" height="150"> </a> </p> <p align="center">Incrementally adoptable RPC-like client and server helpers for a magical end to end typed experience + The small, simple, and ultrafast web framework for the Edges.</p> <p align="center"> <a href="https://www.npmjs.com/package/ts-rest-hono"> <img alt="GitHub Repo stars" src="https://img.shields.io/github/stars/msutkowski/ts-rest-hono"/> </a> <a href="https://www.npmjs.com/package/ts-rest-hono"> <img src="https://img.shields.io/npm/dm/ts-rest-hono"/> </a> <a href="https://www.npmjs.com/package/ts-rest-hono"> <img alt="Bundle Size" src="https://img.shields.io/bundlephobia/minzip/ts-rest-hono?label=ts-rest-hono"/> </a> </p> ### Set it up in 3 Steps! #### 1. Define your Contract. ```typescript // contract.ts import { initContract } from "@ts-rest/core"; import { z } from "zod"; const c = initContract(); export const TodoSchema = z.object({ id: z.string(), title: z.string(), completed: z.boolean(), }); export const contract = c.router({ getTodos: { method: "GET", path: "/todos", responses: { 201: TodoSchema.array(), }, summary: "Create ", }, createTodo: { method: "POST", path: "/todo", responses: { 201: TodoSchema, }, body: z.object({ title: z.string(), completed: z.boolean(), }), summary: "Creates a todo.", }, }); ``` #### 2. Initialize Server Router. ```ts // router.ts import { initServer } from "ts-rest-hono"; import { contract } from "./contract"; import { nanoid } from "nanoid"; const s = initServer(); type Todo = { id: string; title: string; completed: boolean; }; // Database const todos: Todo[] = []; export const router = s.router(contract, { getTodos: async () => { return { status: 201, body: todos, }; }, createTodo: async ({ body: { completed, title } }) => { const newTodo = { id: nanoid(), title, completed, }; todos.push(newTodo); return { status: 201, body: newTodo, }; }, }); ``` #### 3. Create Endpoints on App. ```ts // app.ts import { serve } from "@hono/node-server"; import { Hono } from "hono"; import { createHonoEndpoints } from "ts-rest-hono"; import { contract } from "./contract"; import { router } from "./router"; const app = new Hono(); app.get("/", (c) => { return c.text("🔥 Hello Hono!"); }); createHonoEndpoints(contract, router, app); // Run the server! try { serve(app, (info) => { console.log(`Listening on http://localhost:${info.port}`); }); } catch (err) { console.log(err); process.exit(1); } ``` <br /> <p align="center"> <p align="center">Finally just run <code>app.ts</code></p> <p align="center">It's that easy! Enjoy your ultra-fast typesafe API 🔥🚀</p> </p> Deno is also supported at [deno_dist](./deno_dist/).
# Flexbox ## 使用 Flex 布局执行哪些操作? * 表格可以显示为行或列。 * 并遵循文档的写入模式。 * 默认情况下,它们是单行,但也可以要求换行。 * 可以在视觉上对布局中的各个项进行重新排序,使其脱离它们在 DOM 中的顺序。 * 空间可以在项内分布,因此它们会根据父级中的可用空间变大或变小。 * 您可以使用 Box Alignment 属性在封装布局中的项和 Flex 线条周围分配空间。 * 项目本身可以在横轴上对齐。 ## 主轴和交叉轴 主轴是您的 flex-direction 属性设置的轴。如果值为 row,则主轴沿行,如果为 column,则主轴沿列。 * row:各项内容以行的形式排列。 * row-reverse:,这些项从 Flex 容器末尾排列成一行。 * column:各项内容以列的形式排列。 * column-reverse:这些项从弹性容器末端的一列开始排列。 ## 写入模式和方向 ``` direction: rtl; writing-mode: vertical-rl; ``` ## 自动换行 ``` flex-wrap: nowrap/wrap; ``` ## flex-flow 简写形式 简写形式 flex-flow 设置 flex-direction 和 flex-wrap 属性。 ``` .container { display: flex; flex-flow: column wrap; } ``` ## 控制 flex 内容内的空间 * flex-grow: 0:项不会变大。 * flex-shrink: 1:项可以缩小到小于其 flex-basis。 * flex-basis: auto:项的基本大小为 auto。 ## flex item 重新排序 ``` order: 3; ``` ## Flexbox 对齐方式概述 分配空间的属性包括: * justify-content:主轴上的空间分布情况。 * align-content:横轴上的空间分布情况。 * place-content:设置上述两个属性的简写形式。 用于对齐的属性: * align-self:在交叉轴上对齐单个项。 * align-items:将所有项作为一个组在交叉轴上对齐。 justify-content 可用的值 * flex-start:与交叉轴的起点对齐。 * flex-end:与交叉轴的终点对齐。 * center:与交叉轴的中点对齐。 * space-between:与交叉轴两端对齐,轴线之间的间隔平均分布。 * space-around:每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍。 * space-evenly:每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍。 align-content可用值多一个: * stretch(默认值):轴线占满整个交叉轴。 align-self 可用值 * flex-start * flex-end * center * stretch * baseline align-items可用值 * stretch * flex-start * flex-end * center [flex game](https://flexboxfroggy.com/)
import express, {Request, Response, response} from 'express'; import jwt from 'jsonwebtoken'; import {body} from 'express-validator'; import {User} from '../models/user'; import { BadRequestError } from '../errors/bad-request-error'; import { validateRequest } from '../middlewares/validate-request'; const router = express.Router(); router.post('/api/users/signup', [ body('email').isEmail().withMessage('Email must be valid'), body('password').trim().isLength({min: 4, max: 20}).withMessage('Password must be between 4 and 20 characters'), ], validateRequest, async (req: Request, res: Response) => { const {email, password} = req.body; const existingUser = await User.findOne({email}); if(existingUser){ throw new BadRequestError('Email in use'); } const user = User.build({email, password}); await user.save(); // Generate JWT const userJwt = jwt.sign({ id: user.id, email: user.email }, process.env.JWT_KEY!); // Store it on session object req.session = { jwt: userJwt } res.status(201).send(user); }) export {router as signupRouter}
# Summary (B2) library(dplyr) library(tidyverse) populationData <- read.csv("https://raw.githubusercontent.com/info201a-au2022/project-group-1-section-ah/main/data/populationDataset.csv") View(populationData) summary_info <- list() # number of countries summary_info$num_countries <- length(unique(populationData$Country)) # Country with the highest population in 2021 and its size summary_info$highest_population_2021 <- populationData %>% filter(Year == "2021", na.rm = TRUE) %>% filter(Population.size.in.millions == max(Population.size.in.millions, na.rm = TRUE)) %>% select(Population.size.in.millions, Country) # Country with the lowest population in 2021 and its size summary_info$lowest_population_2021 <- populationData %>% filter(Year == "2021", na.rm = TRUE) %>% filter(Population.size.in.millions == min(Population.size.in.millions, na.rm = TRUE)) %>% select(Population.size.in.millions, Country) # highest life expectancy in Asia summary_info$highest_life_expectancy_all_time <- populationData %>% filter(Life.expectancy.in.years == max(Life.expectancy.in.years, na.rm = TRUE)) %>% select(Country, Life.expectancy.in.years, Year) # lowest life expectancy in Asia summary_info$lowest_life_expectancy_all_time <- populationData %>% filter(Life.expectancy.in.years == min(Life.expectancy.in.years, na.rm = TRUE)) %>% select(Country, Life.expectancy.in.years, Year) # Average population growth percentage summary_info$avg_population_growth <- mean(population_data$Population.growth.percent, na.rm = TRUE) View(summary_info)
import { NodeTypes } from './ast' const interpolationOpenDelimiter = '{{' const interpolationCloseDelimiter = '}}' const ElementCloseDelimiter = '<' const enum TagType { Start, End, } export const baseParse = (content: string) => { const context = createparserContent(content) // 初始化的时候 标签数组 传递一个 [] return createRoot(parserChildren(context, [])) } const parserChildren = (context: { source: string }, ancestors) => { const nodes: any = [] // 循环解析 字符串。 while (!isEnd(context, ancestors)) { let node const source = context.source // 字符串是以 {{ 开头的才需要处理 if (source.startsWith(interpolationOpenDelimiter)) { // 插值 node = parseInterpolation(context) } else if (source.startsWith(ElementCloseDelimiter)) { // source[0] === '<' // element if (/[a-z]/i.test(source[1])) { node = parserElement(context, ancestors) } } // 如果前面的的两个判断都没有命中,表示是文本。 if (!node) { node = parseText(context) } nodes.push(node) } return nodes } function parseText(context: any) { let endIndex = context.source.length; // 碰到这里表示文本结束 const endTokens = ["<", "{{"]; for (let i = 0; i < endTokens.length; i++) { const idx = context.source.indexOf(endTokens[i]); if (idx !== -1 && idx < endIndex) { endIndex = idx; } } const content = parseTextData(context, endIndex); return { type: NodeTypes.TEXT, content, }; } const isEnd = (context, ancestors) => { // 1.当遇到结束标签的时候 const source = context.source if (source.startsWith('</')) { for (let i = ancestors.length - 1; i >= 0; i--) { const tag = ancestors[i].tag if (startWithEndTagOpen(source, tag)) { return true } } } // 2.context.source 有值的时候 return !context.source } function startWithEndTagOpen(source, tag) { return ( source.startsWith("</") && source.slice(2, 2 + tag.length).toLowerCase() === tag.toLowerCase() ); } function parserElement(context: any, ancestors) { // 1. 解析 tag 2.删除处理完成的string const element: any = parseTag(context, TagType.Start); ancestors.push(element); element.children = parserChildren(context, ancestors); // 当闭合一个标签之后 ancestors去除最后一个tag ancestors.pop(); if (startWithEndTagOpen(context.source, element.tag)) { parseTag(context, TagType.End); } else { throw new Error(`缺少结束标签:${element.tag}`); } return element; } function parseTag(context: any, tagType) { const match: any = /^<\/?([a-z]*[0-9]?)/i.exec(context.source); const tag = match[1]; advanceBy(context, match[0].length); advanceBy(context, 1); if (tagType === TagType.End) return; return { type: NodeTypes.ELEMENT, tag, }; } const advanceBy = (context, length) => { context.source = context.source.slice(length) } const parseTextData = (context: any, length) => { const content = context.source.slice(0, length) // 2. 推进 advanceBy(context, length) return content } // 插值 const parseInterpolation = (context) => { // {{ message }} ---> 拿到这个 message // 从第二个字符位置开始查找, 到 '}}' 结束 const closeIndex = context.source.indexOf(interpolationCloseDelimiter, interpolationOpenDelimiter.length) // 1.切 {{ 去掉 前面的 '{{' advanceBy(context, interpolationOpenDelimiter.length) const rawContentLength = closeIndex - interpolationOpenDelimiter.length // 2.切 }}之前的 xxxx}} 可能存在空格 trim去掉~ const rawContent = parseTextData(context, rawContentLength) const content = rawContent.trim() // 3.切 }} advanceBy(context, interpolationCloseDelimiter.length) return { type: NodeTypes.INTERPOLATION, content: { type: NodeTypes.SIMPLE_EXPRESSION, content } } } const createRoot = (children) => { return { children, type: NodeTypes.ROOT } } const createparserContent = (content: string) => { return { source: content } }
package item09; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by 殷鑫 on 2017/2/6. */ public final class PhoneNumber { private final short areaCode; private final short prefix; private final short lineNumber; public PhoneNumber(int areaCode, int prefix, int lineNumber) { rangeCheck(areaCode, 999, "area code"); rangeCheck(prefix, 999, "prefix"); rangeCheck(lineNumber, 9999, "line number"); this.areaCode = (short) areaCode; this.prefix = (short) prefix; this.lineNumber = (short) lineNumber; } private static void rangeCheck(int arg, int max, String name) { if (arg < 0 || arg > max) throw new IllegalArgumentException(name + ": " + arg); } @Override public boolean equals(Object obj) { if (obj == this){ return true; } if (!(obj instanceof PhoneNumber)){ return false; } PhoneNumber pn = (PhoneNumber)obj; return pn.lineNumber == lineNumber && pn.prefix == prefix && pn.areaCode == areaCode; } // @Override public int hashCode() { // int result = 17; // result = 31 * result + areaCode; // result = 31 * result + prefix; // result = 31 * result + lineNumber; // return result; // } //延迟加载 //第一次初始化完成hashCode取值 private volatile int hashCode; @Override public int hashCode() { int result = hashCode; if (result == 0) { result = 17; result = 31 * result + areaCode; result = 31 * result + prefix; result = 31 * result + lineNumber; hashCode = result; } return result; } public static void main(String[] args) { Map<PhoneNumber,String> m = new HashMap<PhoneNumber,String>(); m.put(new PhoneNumber(100,222,5300),"LION"); System.out.println(m.get(new PhoneNumber(100,222,5300))); //相同hascode为true } }
public struct MovieListResponse: Codable { enum CodingKeys: String, CodingKey { case movies = "results" } public let movies: [Movie] } extension MovieListResponse { public struct Movie: Codable { enum CodingKeys: String, CodingKey { case adult case originalLanguage = "original_language" case backdropPath = "backdrop_path" case genreIDS = "genre_ids" case id case originalTitle = "original_title" case overview, popularity case posterPath = "poster_path" case releaseDate = "release_date" case title, video case voteAverage = "vote_average" case voteCount = "vote_count" } let adult: Bool let originalLanguage: String? let backdropPath: String? let genreIDS: [Int] let id: Int let originalTitle, overview: String let popularity: Double let posterPath, releaseDate, title: String let video: Bool let voteAverage: Double let voteCount: Int } }
import { lazy } from 'react'; import { Route, Routes } from 'react-router-dom'; import { SharedLayout } from './components/SharedLayout/SharedLayout'; import { useSelector } from 'react-redux'; import { getIsLoggedIn } from './redux/auth/authSelectors'; const Products = lazy(() => import('./pages/Products')); const Cart = lazy(() => import('./pages/Cart')); const Login = lazy(() => import('./pages/Login')); const Register = lazy(() => import('./pages/Register')); function App() { const isLoggedIn = useSelector(getIsLoggedIn); return ( <Routes> <Route path="/" element={<SharedLayout />}> <Route index element={<Products />} /> <Route path="cart" element={<Cart />} /> <Route path="*" element={<Products />} /> {!isLoggedIn && <Route path="login" element={<Login />} />} {!isLoggedIn && <Route path="register" element={<Register />} />} </Route> </Routes> ); } export default App;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content="Html5 Bootstrap Template"> <meta name="author" content="Developer"> <link rel="icon" href="assets/img/favicon/favicon.ico"> <title>Bootstrap Ready Template by Developer</title> <!-- Bootstrap core css --> <link rel="stylesheet" type="text/css" href="assets/css/vendor/bootstrap/css/bootstrap.min.css" media="all"/> <!-- Font awesome --> <link rel="stylesheet" type="text/css" href="assets/css/vendor/font-awesome/css/font-awesome.min.css" media="all"/> <!-- Stylesheet for this template --> <link rel="stylesheet" type="text/css" href="style.css" media="all"/> <!-- Main Stylesheet for this template --> <link rel="stylesheet" type="text/css" href="assets/css/main.css" media="all"/> <!-- Responsive styles for this template --> <link href="assets/css/responsive.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="assets/js/html5shiv.min.js"></script> <script src="assets/js/respond.min.js"></script> <![endif]--> </head> <body id="index" class="home"> <div class="main"> <div class="main-wrap"> <div class="main-inner"> <!-- Header Start --> <header class="header"> <nav class="navbar navbar-inverse"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.html">Bootstrap theme</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="index.html">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#contact">Contact</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li role="separator" class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> </ul> </li> </ul> </div><!--/.nav-collapse --> </div> </nav> </header> <!-- /.header --> <!-- Entry content --> <div class="main-content"> <div class="main-content-inner"> <div class="main-content-wrap"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="well"> <h1> Blog Page </h1> </div> <!-- /.page-header --> </div> </div> <div class="row"> <!-- Blog content --> <div class="col-md-8"> <!-- Post loop start --> <article class="post"> <div class="entry-title"> <!-- Post title --> <h2> <a href="single.html">Intrinsicly harness end-to-end schemas</a> </h2> </div> <!-- /.entry-title --> <div class="entry-meta"> <ul class="list-unstyled list-inline"> <li><span class="glyphicon glyphicon-user"></span> by <a href="single.html">Start Bootstrap</a></li> <li><span class="glyphicon glyphicon-time"></span> Posted on August 28, 2013 at 10:00 PM </li> </ul> </div> <!-- /.entry-meta --> <div class="entry-thumb"> <img class="img-responsive" src="http://placehold.it/900x300" alt=""> </div> <!-- /.entry-thumb --> <div class="entry-content"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore, veritatis, tempora, necessitatibus inventore nisi quam quia repellat ut tempore laborum possimus eum dicta id animi corrupti debitis ipsum officiis rerum.</p> <a class="btn btn-primary" href="single.html">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> </div> <!-- /.entry-content --> </article> <!-- /.post --> <!-- Post loop start --> <article class="post"> <div class="entry-title"> <!-- Post title --> <h2> <a href="single.html">Intrinsicly harness end-to-end schemas</a> </h2> </div> <!-- /.entry-title --> <div class="entry-meta"> <ul class="list-unstyled list-inline"> <li><span class="glyphicon glyphicon-user"></span> by <a href="single.html">Start Bootstrap</a></li> <li><span class="glyphicon glyphicon-time"></span> Posted on August 28, 2013 at 10:00 PM </li> </ul> </div> <!-- /.entry-meta --> <div class="entry-thumb"> <img class="img-responsive" src="http://placehold.it/900x300" alt=""> </div> <!-- /.entry-thumb --> <div class="entry-content"> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolore, veritatis, tempora, necessitatibus inventore nisi quam quia repellat ut tempore laborum possimus eum dicta id animi corrupti debitis ipsum officiis rerum.</p> <a class="btn btn-primary" href="single.html">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> </div> <!-- /.entry-content --> </article> <!-- /.post --> <!-- Post Navigation --> <div class="post-pagination"> <ul class="pagination"> <li class="disabled"><a href="#" aria-label="Previous"><i class="fa fa-angle-double-left" aria-hidden="true"></i></a></li> <li class="active"><a href="#">1<span class="sr-only">(current)</span></a> </li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#" aria-label="Next"><i class="fa fa-angle-double-right" aria-hidden="true"></i></a></li> </ul> </div> <!-- /.entry-thumb --> </div> <!-- Blog Sidebar --> <div class="col-md-4"> <!-- Blog Search Well --> <div class="well"> <h4>Blog Search</h4> <div class="input-group"> <input type="text" class="form-control"> <span class="input-group-btn"> <button class="btn btn-default" type="button"> <span class="glyphicon glyphicon-search"></span> </button> </span> </div> <!-- /.input-group --> </div> <!-- Blog Categories Well --> <div class="well"> <h4>Blog Categories</h4> <div class="row"> <div class="col-lg-6"> <ul class="list-unstyled"> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> </ul> </div> <!-- /.col-lg-6 --> <div class="col-lg-6"> <ul class="list-unstyled"> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> <li><a href="#">Category Name</a> </li> </ul> </div> <!-- /.col-lg-6 --> </div> <!-- /.row --> </div> <!-- Side Widget Well --> <div class="well"> <h4>Side Widget Well</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.</p> </div> </div> </div> <!-- /.row --> </div> <!-- /.container --> </div> <!-- /.main-content-wrap --> </div> <!-- /.main-content-inner --> </div> <!-- /.main-content --> <!-- Footer Section --> <footer class="footer"> <div class="footer-wrap"> <div class="footer-inner"> <div class="container"> <div class="row"> <div class="col-md-6"> <p>Copyright &copy; Your Website 2014</p> </div> <!-- /.col-md-6 --> <div class="col-md-6"> <ul class="list-unstyled list-inline text-right"> <li><a href="#"><i class="fa fa-google"></i></a></li> <li><a href="#"><i class="fa fa-facebook"></i></a></li> <li><a href="#"><i class="fa fa-twitter"></i></a></li> <li><a href="#"><i class="fa fa-instagram"></i></a></li> <li><a href="#"><i class="fa fa-skype"></i></a></li> <li><a href="#"><i class="fa fa-linkedin"></i></a></li> <li><a href="#"><i class="fa fa-reddit"></i></a></li> </ul> </div> <!-- /.col-md-6 --> </div> <!-- /.row --> </div> </div> </div> </footer> <!-- /.footer --> </div> </div> </div> <!-- Bootstrap core JavaScript <!-- Placed at the end of the document so the pages load faster --> <script src="assets/js/jquery.min.js"></script> <script src="assets/css/vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Custom js --> <script src="assets/js/script.js"></script> </body> </html>
Database SQL – VIEW จาการใช้งาน SQL Select statement จะเห็นว่า ในบางครั้งเรามักจะมี Select statement ที่ต้องใช้งานประจำ เพื่อดึงข้อมูลออกมาในรูปแบบที่ต้องการ เราสามารถใช้ SQL View นี้ช่วยได้ โดย SQL VIEW จะทำการเก็บรูปแบบการ query หรือ SQL Select statement ที่เราตั้งไว้ใน SQL VIEW ซึ่งสามารถทำได้ตั้งแต่ query ข้อมูลทั้งหมดของ TABLE รวมถึงการทำ SQL Join, SQL Union, SQL Intersect และ SQL Except ที่ ผลลัพธุ์ออกมาในรูปแบบตาราง หรือ table คุณสมบัติของ VIEW สร้างโครงสร้างของข้อมูลในรูปแบบที่ user ใช้งานปกติจาก table ปรับเปลี่ยนข้อมูลภายใน TABLE ให้แสดงออกมาในรูปแบบที่ต้องการ โดยไม่กระทบกับข้อมูลหลัก สรุปข้อมูลจาก table ในรูปแบบของ report ที่ user ต้องการ รูปแบบการสร้าง VIEW (Syntax) การใช้งาน SQL View สามรถสร้างได้จากรูปแบบของ SQL Select statement ที่ต้องการ โดยสามารถสร้างจาก table เดียว หรือ หลาย TABLE ก็ได้ แต่ต้องมีสิทธิ์ในการเข้าถึงข้อมูลภายใต้ table นั้น (GRANT VIEW) CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition]; CREATE VIEW emp AS SELECT ssn,fname,lname,salary FROM employee WHERE salary > (SELECT AVG(salary) FROM employee); SELECT * from emp; CREATE VIEW works AS SELECT ssn,fname,lname,dname,pname,hours FROM employee,works_on,project,department WHERE ssn = essn AND pno = pnumber AND dno = dnumber; SELECT * FROM works; SELECT pname,GROUP_CONCAT(fname) FROM works GROUP BY pname;
// @DFS for connected components import java.util.*; public class connectedComponentsDfs { static class Edge { int source; int destination; int weight; public Edge(int s, int d, int w) { this.source = s; this.destination = d; this.weight = w; } } static void createGraph(ArrayList<Edge> graph[]) { for (int i = 0; i < graph.length; i++) { graph[i] = new ArrayList<>(); } graph[0].add(new Edge(0, 1, 1)); graph[1].add(new Edge(1, 0, 1)); graph[1].add(new Edge(1, 2, 1)); graph[2].add(new Edge(2, 1, 1)); graph[3].add(new Edge(3, 4, 1)); graph[4].add(new Edge(4, 3, 1)); System.out.println("graph created"); } public static void dfsUtil(ArrayList<Edge> graph[], int curr, boolean vis[]) { // O(V+E) vis[curr] = true; System.out.print(curr + " "); for (int i = 0; i < graph[curr].size(); i++) { Edge e = graph[curr].get(i); if (!vis[e.destination]) { dfsUtil(graph, e.destination, vis); } } } public static void dfs(ArrayList<Edge> graph[]) { boolean vis[] = new boolean[graph.length]; for (int i = 0; i < graph.length; i++) { if (!vis[i]) { dfsUtil(graph, i, vis); System.out.println(); } } } public static void main(String[] args) { int V = 5; ArrayList<Edge> graph[] = new ArrayList[V]; createGraph(graph); dfs(graph); } }
import NavBar from "./components/shared/NavBar/NavBar"; import AppRoutes from "./utils/routes"; import { useEffect, useState } from "react"; import { PcConfiguration, Toast } from "./utils/models"; import axios from "axios"; import { Footer } from "./components/shared/Footer"; function App() { let [pcConfiguration, setPcConfiguration] = useState(PcConfiguration); const [user, setUser] = useState(null); useEffect(() => { const token = JSON.parse(localStorage.getItem("token")); console.log(pcConfiguration); if (!token && JSON.parse(localStorage.getItem("loggedUser"))) { localStorage.removeItem("loggedUser"); } setUser(JSON.parse(localStorage.getItem("loggedUser"))); if (token !== null) { getUserInfo(token); } }, []); async function getUserInfo(token) { const config = { headers: { Authorization: `Bearer ${token}` } }; axios .get("http://localhost:5198/api/user/userInfo", config) .then((response) => { console.log(response); console.log(response.data); setUser(response.data); console.log(JSON.stringify(response.data)); localStorage.setItem("loggedUser", JSON.stringify(response.data)); }) .catch((err) => { console.log(err); if (err.response && err.response.status === 401) { console.log("Unauthorized access!"); localStorage.removeItem("token"); localStorage.removeItem("loggedUser"); localStorage.removeItem("localEditedConfiugration"); window.location.reload(); } else { console.log("Error occurred:", err); localStorage.removeItem("token"); localStorage.removeItem("loggedUser"); localStorage.removeItem("localEditedConfiugration"); window.location.reload(); } }); } return ( <div className="flex flex-col h-screen"> <header className="top-0"> <NavBar loggedUser={user} /> </header> <main className="flex-1"> <AppRoutes pcConfiguration={pcConfiguration} setPcConfiguration={setPcConfiguration} loggedUser={user} /> </main> <Footer /> </div> ); } export default App;
<mat-tree [dataSource]="dataSource" [treeControl]="treeControl"> <mat-tree-node *matTreeNodeDef="let node;" matTreeNodeToggle matTreeNodePadding (mouseover)="onMouseHover(node)" (mouseout)="onMouseOut(node)"> <div class="chkbox_block"> <mat-checkbox class="checklist-leaf-node" [checked]="checklistSelection.isSelected(node)" (change)="todoLeafItemSelectionToggle(node)">{{node.name}}</mat-checkbox> <button (click)="addNewCategoryPressed(node)" *ngIf="!node.showInput" class="add-icon-btn"> <mat-icon>add</mat-icon> </button> </div> <div class="input_block" *ngIf="node.showInput"> <mat-form-field class="full-wid"> <input class="mrgn-t-none" [(ngModel)]="node.newChildVal" matInput placeholder="Name" type="text" required="true"> </mat-form-field> <button mat-raised-button mat-button-sm color="primary" class="mat-button btn-sm mat-button-base mat-primary" [disabled]="!node.newChildVal" (click)="SaveCategoryName(node)">Save</button> <button mat-raised-button mat-button-sm color="danger" class="mat-button mat-button-base mat-warn" (click)="CancelCategoryAdd(node)">Cancel</button> </div> </mat-tree-node> <mat-tree-node *matTreeNodeDef="let node;when: hasChild" matTreeNodePadding (mouseover)="onMouseHover(node)" (mouseout)="onMouseOut(node)"> <div class="chkbox_block"> <mat-icon matTreeNodeToggle [attr.aria-label]="'Toggle ' + node.name"> <mat-icon class="mat-icon-rtl-mirror"> {{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}} </mat-icon> </mat-icon> <mat-checkbox class="checklist-leaf-node" [checked]="checklistSelection.isSelected(node)" (change)="todoLeafItemSelectionToggle(node)">{{node.name}}</mat-checkbox> <button (click)="addNewCategoryPressed(node)" *ngIf="!node.showInput" class="add-icon-btn"> <mat-icon>add</mat-icon> </button> </div> <div class="input_block" *ngIf="node.showInput"> <mat-form-field class="full-wid"> <input class="mrgn-t-none" [(ngModel)]="node.newChildVal" matInput placeholder="Name" type="text" required="true"> </mat-form-field> <button mat-raised-button mat-button-sm color="primary" class="mat-button btn-sm mat-button-base mat-primary" [disabled]="!node.newChildVal" (click)="SaveCategoryName(node)">Save</button> <button mat-raised-button mat-button-sm color="danger" class="mat-button mat-button-base mat-warn" (click)="CancelCategoryAdd(node)">Cancel</button> </div> </mat-tree-node> </mat-tree>
{% extends 'base.html.twig' %} {% block title %}{{ 'navbar.home'|trans }}{% endblock %} {% block body %} <!-- Hero Section Begin --> <section class="hero"> <div class="hero__slider owl-carousel"> <div class="hero__items set-bg" data-setbg="img/hero/hero-1.jpg"> <div class="container"> <div class="row"> <div class="col-xl-5 col-lg-7 col-md-8"> <div class="hero__text"> <h6>Naruto {{ 'home.collection' | trans }}</h6> <h2>Sasuke Uchiwa</h2> <p>Sasuke Uchiwa (うちはサスケ, Uchiha Sasuke), {{ 'home.sasuke' | trans }}</p> <a href="#" class="primary-btn">{{ 'home.shopnow' | trans }}<span class="arrow_right"></span></a> </div> </div> </div> </div> </div> <div class="hero__items set-bg" data-setbg="img/hero/hero-2.jpg"> <div class="container"> <div class="row"> <div class="col-xl-5 col-lg-7 col-md-8"> <div class="hero__text"> <h6>Dragon Ball {{ 'home.collection' | trans }}</h6> <h2>Son Goku</h2> <p>Son Gokû (孫そん悟ご空くう, Son Gokū), {{ 'home.goku' | trans }}</p> <a href="#" class="primary-btn">{{ 'home.shopnow' | trans }}<span class="arrow_right"></span></a> </div> </div> </div> </div> </div> </div> </section> <!-- Hero Section End --> <!-- Banner Section Begin --> <section class="banner spad"> <div class="container"> <div class="row"> <div class="col-lg-7 offset-lg-4"> <div class="banner__item"> <div class="banner__item__pic"> <img src="img/banner/banner-1.jpg" alt=""> </div> <div class="banner__item__text"> <h2>Vêtements</h2> <a href="{{ path ('app_shop') }}?categorie=vetements">{{ 'home.shopnow'|trans }}</a> </div> </div> </div> <div class="col-lg-5"> <div class="banner__item banner__item--middle"> <div class="banner__item__pic"> <img src="img/banner/banner-2.jpg" alt=""> </div> <div class="banner__item__text"> <h2>Figurines</h2> <a href="{{ path ('app_shop') }}?categorie=figurines">{{ 'home.shopnow'|trans }}</a> </div> </div> </div> </div> </div> </section> <!-- Banner Section End --> <!-- Product Section Begin --> <section class="product spad"> <div class="container"> <div class="row"> <div class="col-lg-12"> <ul class="filter__controls"> <li data-filter=".new">{{ 'shop.new_arrivals'|trans }}</li> <li data-filter=".popular">{{ 'shop.populars'|trans }}</li> </ul> </div> </div> <div class="row product__filter"> {% for p in products%} <div class="col-lg-3 col-md-6 col-sm-6 col-md-6 col-sm-6 mix {{p.tags}}"> {{ include('shop/_product_preview.html.twig', {'p': p}) }} </div> {% endfor %} </div> </div> </section> <!-- Product Section End --> <!-- Instagram Section Begin --> <section class="categories spad"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="instagram__pic"> <div class="instagram__pic__item set-bg" data-setbg="img/instagram/instagram-1.jpg"></div> <div class="instagram__pic__item set-bg" data-setbg="img/instagram/instagram-2.jpg"></div> <div class="instagram__pic__item set-bg" data-setbg="img/instagram/instagram-3.jpg"></div> <div class="instagram__pic__item set-bg" data-setbg="img/instagram/instagram-4.jpg"></div> <div class="instagram__pic__item set-bg" data-setbg="img/instagram/instagram-5.jpg"></div> <div class="instagram__pic__item set-bg" data-setbg="img/instagram/instagram-6.jpg"></div> </div> </div> <div class="col-lg-4"> <div class="instagram__text"> <h2>Instagram</h2> <p>Vous pouvez nous retrouver sur Instagram sous le pseudo de "MangaMania.shopFr" pour des infos et concours exclusifs !</p> <h3>#MangaMania</h3> </div> </div> </div> </div> </section> <!-- Instagram Section End --> <!-- Latest Blog Section Begin --> <section class="latest spad"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="section-title"> <span>{{ 'home.latest_news'|trans }}</span> <h2>Manga'Actu</h2> </div> </div> </div> <div class="row"> {% for a in articles %} <div class="col-lg-4 col-md-6 col-sm-6"> <div class="blog__item"> <div class="blog__item__pic set-bg" data-setbg="{{asset('uploads/articles/' ~ a.picture)}}"></div> <div class="blog__item__text"> <span><img src="{{ asset('img/icon/calendar.png') }}" alt="">{{ a.createdAt ? a.createdAt|date('l F o') : '' }}</span> <h5>{{ a.title }}</h5> <a href="{{path('app_article_detail',{'slug' : a.slug})}}">{{ 'blog.readmore' | trans }}</a> </div> </div> </div> {% endfor %} </div> </div> </section> <!-- Latest Blog Section End --> <!-- Footer Section Begin --> {% endblock %}
// This header has all the (extern) declarations of the globals. // "extern" means "this is instantiated somewhere, but here's what the name // means. #include "globals.h" #include "hardware.h" // We need to actually instantiate all of the globals (i.e. declare them once // without the extern keyword). That's what this file does! // Hardware initialization: Instantiate all the things! uLCD_4DGL uLCD(p9,p10,p11); // LCD Screen (tx, rx, reset) //SDFileSystem sd(p5, p6, p7, p8, "sd"); // SD Card(mosi, miso, sck, cs) Serial pc(USBTX,USBRX); // USB Console (tx, rx) MMA8452 acc(p28, p27, 100000); // Accelerometer (sda, sdc, rate) DigitalIn button1(p21); // Pushbuttons (pin) DigitalIn button2(p22); DigitalIn button3(p23); DigitalIn button4(p24); AnalogOut DACout(p18); // Speaker (pin) PwmOut speaker(p26); wave_player waver(&DACout); int b1Pressed, b2Pressed, b3Pressed, b4Pressed = 0; // Some hardware also needs to have functions called before it will set up // properly. Do that here. int hardware_init() { // Crank up the speed uLCD.baudrate(3000000); pc.baud(115200); //Initialize pushbuttons button1.mode(PullUp); button2.mode(PullUp); button3.mode(PullUp); button4.mode(PullUp); return ERROR_NONE; } GameInputs read_inputs() { GameInputs in; acc.readXYZGravity(&(in.ax), &(in.ay), &(in.az)); // Debounce buttons if (!button1 && !b1Pressed) { in.b1 = true; } else { in.b1 = false; } b1Pressed = !button1; if (!button2 && !b2Pressed) { in.b2 = true; } else { in.b2 = false; } b2Pressed = !button2; if (!button3 && !b3Pressed) { in.b3 = true; } else { in.b3 = false; } b3Pressed = !button3; if (!button4 && !b4Pressed) { in.b4 = true; } else { in.b4 = false; } b4Pressed = !button4; return in; }
using System; using System.Collections.Generic; using System.Linq; using AutoFixture; using FluentAssertions; using FluentValidation; using LooseFunds.Shared.Platforms.Kraken.Models.Common; using LooseFunds.Shared.Platforms.Kraken.Models.Requests; using LooseFunds.Shared.Platforms.Kraken.Models.Requests.Validators; using NUnit.Framework; namespace LooseFunds.Shared.Platforms.Kraken.Tests.Models.Requests.Validators; [Category("UnitTests")] public class GetTickerInformationRequestValidatorTests { private readonly Fixture _fixture = new(); private readonly GetTickerInformationRequestValidator _validator = new(); [Test] public void GetTickerInformationRequestValidator_returns_valid_for_valid_request() { //Arrange var getTickerInformation = new GetTickerInformation(_fixture.CreateMany<Pair>().ToList()); //Act var result = _validator.Validate(getTickerInformation); //Assert result.IsValid.Should().BeTrue(); result.Errors.Should().BeEmpty(); } [Test] public void GetTickerInformationRequestValidator_throws_argument_null_exception_when_pairs_are_null() { Assert.Throws<ArgumentNullException>(() => { var _ = new GetAssetInfo(null); }); } [Test] public void GetTickerInformationRequestValidator_throws_validation_exception_when_pairs_are_empty() { Assert.Throws<ValidationException>(() => { var _ = new GetAssetInfo(new List<Asset>()); }); } }
<template> <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="580px" draggable append-to-body > <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="paramsProps.row" @submit.enter.prevent="handleSubmit" > <el-form-item label="角色名称" prop="roleName"> <el-input v-model="paramsProps.row.roleName" placeholder="请填写角色名称" clearable ></el-input> </el-form-item> <el-form-item label="备注" prop="remark"> <el-input v-model="paramsProps.row.remark" placeholder="请填写备注" :rows="2" type="textarea" clearable ></el-input> </el-form-item> </el-form> <template #footer> <el-button @click="visible = false"> 取消</el-button> <el-button type="primary" @click="handleSubmit"> 确定</el-button> </template> </el-dialog> </template> <script setup lang="ts"> import { ref } from 'vue' import { ElMessage } from 'element-plus' defineOptions({ name: 'RoleForm' }) const rules = ref({ roleName: [{ required: true, message: '请填写角色名称' }] }) const visible = ref(false) const paramsProps = ref<View.DefaultParams>({ title: '', row: {}, api: undefined, getTableList: undefined }) // 接收父组件传过来的参数 const acceptParams = (params: View.DefaultParams) => { paramsProps.value = params visible.value = true } // 提交数据(新增/编辑) const ruleFormRef = ref() const handleSubmit = () => { ruleFormRef.value!.validate(async (valid: boolean) => { if (!valid) return try { await paramsProps.value.api!(paramsProps.value.row) ElMessage.success({ message: `${paramsProps.value.title}成功!` }) paramsProps.value.getTableList!() visible.value = false } catch (error) { console.log(error) } }) } defineExpose({ acceptParams }) </script> <style scoped lang="scss"></style>
<div class="row"> <div class="col-sm-12"> <div class="card form-card"> <div class="card-header"> <div class="d-flex align-items-center justify-content-between"> <span>Jobs Posted</span> <button mat-stroked-button class="btn-main" (click)="openPostJobDialog()"> <div class="d-flex align-items-center justify-content-between"> <span class="material-symbols-outlined"> add </span> <div class="fw-bold">Add Job</div> </div> </button> </div> </div> <div class="card-body"> <table mat-table [dataSource]="dataSource" class="dashboard-table" matSort> <ng-container matColumnDef="srNo"> <th mat-header-cell *matHeaderCellDef class="srno" mat-sort-header>Sr. No. </th> <td mat-cell *matCellDef="let element" class="srno"> {{element.srNo}} </td> </ng-container> <ng-container matColumnDef="job_Title"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Job Title </th> <td mat-cell *matCellDef="let element"> {{element.job_Title}} </td> </ng-container> <ng-container matColumnDef="job_Location"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Job Location </th> <td mat-cell *matCellDef="let element" class="text-break"> {{element.job_Location}} </td> </ng-container> <ng-container matColumnDef="date_of_Posting"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Date of Posting </th> <td mat-cell *matCellDef="let element"> {{element.date_of_Posting | date: 'dd-MM-yyyy'}} </td> </ng-container> <ng-container matColumnDef="date_of_Application"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Last Date of Application </th> <td mat-cell *matCellDef="let element"> {{element.date_of_Application | date: 'dd-MM-yyyy'}} </td> </ng-container> <ng-container matColumnDef="publish"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Publish </th> <td mat-cell *matCellDef="let element"> <mat-slide-toggle [checked]="element.publish && (element.flag == 1)" (click)="onClickToggle(element)" matTooltip="{{ element.publish == true ? 'Publish' : 'Unpublish'}}"> </mat-slide-toggle> </td> </ng-container> <ng-container matColumnDef="actions"> <th mat-header-cell *matHeaderCellDef> Actions </th> <td mat-cell *matCellDef="let element"> <div class="d-flex align-items-center"> <button mat-icon-button (click)="openDialog1(element)" matTooltip="View"> <span class="material-symbols-outlined"> visibility </span> </button> <button mat-icon-button class="text-warning" (click)="openPostJobDialog(element)" matTooltip="Edit"> <span class="material-symbols-outlined"> edit </span> </button> <button mat-icon-button class="text-danger" (click)="openDeleteDialog(element.jobpostId)" matTooltip="Delete"> <span class="material-symbols-outlined"> delete </span> </button> </div> </td> </ng-container> <tr class="mat-row p-2 w-100" *matNoDataRow col> <td class="alert alert-danger text-center m-2 mt-2" colspan="9">No Data Found </td> </tr> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> </div> <ng-container *ngIf="totalCount > 10"> <mat-paginator [length]="totalCount" [pageSize]="10" showFirstLastButtons (page)="paginationEvent($event)" aria-label="Select page of GitHub search results"></mat-paginator> </ng-container> </div> </div> </div>
//go:build integration /* Real-time Online/Offline Charging System (OCS) for Telecom & ISP environments Copyright (C) ITsysCOM GmbH This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ package registrarc import ( "bytes" "errors" "os/exec" "path" "testing" "time" "github.com/cgrates/birpc" "github.com/cgrates/birpc/context" "github.com/cgrates/birpc/jsonrpc" "github.com/cgrates/cgrates/config" "github.com/cgrates/cgrates/engine" "github.com/cgrates/cgrates/utils" ) var ( dspNodeDir string dspNodeCfgPath string dspNodeCfg *config.CGRConfig dspNodeCmd *exec.Cmd dspNodeRPC *birpc.Client node1Dir string node1CfgPath string node1Cmd *exec.Cmd dsphNodeTest = []func(t *testing.T){ testDsphNodeInitCfg, testDsphNodeInitDB, testDsphNodeStartEngine, testDsphNodeLoadData, testDsphNodeBeforeDsphStart, testDsphNodeStartAll, testDsphNodeStopEngines, testDsphNodeStopDispatcher, } ) func TestDspNodeHosts(t *testing.T) { switch *utils.DBType { case utils.MetaMySQL: node1Dir = "registrarc_node_id" dspNodeDir = "registrars_node_id" case utils.MetaInternal, utils.MetaPostgres, utils.MetaMongo: t.SkipNow() default: t.Fatal("Unknown Database type") } for _, stest := range dsphNodeTest { t.Run(dspNodeDir, stest) } } func testDsphNodeInitCfg(t *testing.T) { dspNodeCfgPath = path.Join(*utils.DataDir, "conf", "samples", "registrarc", dspNodeDir) node1CfgPath = path.Join(*utils.DataDir, "conf", "samples", "registrarc", node1Dir) var err error if dspNodeCfg, err = config.NewCGRConfigFromPath(dspNodeCfgPath); err != nil { t.Error(err) } } func testDsphNodeInitDB(t *testing.T) { if err := engine.InitDataDb(dspNodeCfg); err != nil { t.Fatal(err) } if err := engine.InitStorDb(dspNodeCfg); err != nil { t.Fatal(err) } } func testDsphNodeStartEngine(t *testing.T) { var err error if dspNodeCmd, err = engine.StopStartEngine(dspNodeCfgPath, *utils.WaitRater); err != nil { t.Fatal(err) } dspNodeRPC, err = newRPCClient(dspNodeCfg.ListenCfg()) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal("Could not connect to rater: ", err.Error()) } } func testDsphNodeLoadData(t *testing.T) { loader := exec.Command("cgr-loader", "-config_path", dspNodeCfgPath, "-path", path.Join(*utils.DataDir, "tariffplans", "registrarc2"), "-caches_address=") output := bytes.NewBuffer(nil) outerr := bytes.NewBuffer(nil) loader.Stdout = output loader.Stderr = outerr if err := loader.Run(); err != nil { t.Log(loader.Args) t.Log(output.String()) t.Log(outerr.String()) t.Fatal(err) } } func testDsphNodeGetNodeID() (id string, err error) { var status map[string]any if err = dspNodeRPC.Call(context.Background(), utils.DispatcherSv1RemoteStatus, utils.TenantWithAPIOpts{ Tenant: "cgrates.org", APIOpts: map[string]any{}, }, &status); err != nil { return } return utils.IfaceAsString(status[utils.NodeID]), nil } func testDsphNodeBeforeDsphStart(t *testing.T) { if _, err := testDsphNodeGetNodeID(); err == nil || err.Error() != utils.ErrDSPHostNotFound.Error() { t.Errorf("Expected error: %s received: %v", utils.ErrDSPHostNotFound, err) } } func testDsphNodeStartAll(t *testing.T) { var err error if node1Cmd, err = engine.StartEngine(node1CfgPath, *utils.WaitRater); err != nil { t.Fatal(err) } if nodeID, err := testDsphNodeGetNodeID(); err != nil { t.Fatal(err) } else if nodeID != "NODE1" { t.Errorf("Expected nodeID: %q ,received: %q", "NODE1", nodeID) } } func testDsphNodeStopEngines(t *testing.T) { if err := node1Cmd.Process.Kill(); err != nil { t.Fatal(err) } time.Sleep(2 * time.Second) if _, err := testDsphNodeGetNodeID(); err == nil || err.Error() != utils.ErrDSPHostNotFound.Error() { t.Errorf("Expected error: %s received: %v", utils.ErrDSPHostNotFound, err) } } func testDsphNodeStopDispatcher(t *testing.T) { if err := engine.KillEngine(*utils.WaitRater); err != nil { t.Error(err) } } func newRPCClient(cfg *config.ListenCfg) (c *birpc.Client, err error) { switch *utils.Encoding { case utils.MetaJSON: return jsonrpc.Dial(utils.TCP, cfg.RPCJSONListen) case utils.MetaGOB: return birpc.Dial(utils.TCP, cfg.RPCGOBListen) default: return nil, errors.New("UNSUPPORTED_RPC") } }
/* $Id: blast_seqalign.hpp 140187 2008-09-15 16:35:34Z camacho $ * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * * Author: Christiam Camacho * */ /// @file blast_seqalign.hpp /// Utility function to convert internal BLAST result structures into /// objects::CSeq_align_set objects. #ifndef ALGO_BLAST_API___BLAST_SEQALIGN__HPP #define ALGO_BLAST_API___BLAST_SEQALIGN__HPP #include <corelib/ncbistd.hpp> #include <algo/blast/api/blast_aux.hpp> #include <algo/blast/core/blast_hits.h> #include <algo/blast/api/blast_seqinfosrc_aux.hpp> #include <objects/seqalign/Seq_align.hpp> /** @addtogroup AlgoBlast * * @{ */ BEGIN_NCBI_SCOPE USING_SCOPE(objects); BEGIN_SCOPE(blast) /// Forward declaration class ILocalQueryData; /// Remaps Seq-align offsets relative to the query Seq-loc. /// Since the query strands were already taken into account when CSeq_align /// was created, only start position shifts in the CSeq_loc's are relevant in /// this function. /// @param sar Seq-align for a given query [in] [out] /// @param query The query Seq-loc [in] void RemapToQueryLoc(CRef<CSeq_align> sar, const CSeq_loc & query); /// Constructs an empty Seq-align-set containing an empty discontinuous /// seq-align, and appends it to a previously constructed Seq-align-set. /// @param sas Pointer to a Seq-align-set, to which new object should be /// appended (if not NULL). /// @return Resulting Seq-align-set. CSeq_align_set* CreateEmptySeq_align_set(CSeq_align_set* sas); void BLASTHspListToSeqAlign(EBlastProgramType program, BlastHSPList* hsp_list, CRef<CSeq_id> query_id, CRef<CSeq_id> subject_id, Int4 query_length, Int4 subject_length, bool is_ooframe, const vector<int> & gi_list, vector<CRef<CSeq_align > > & sa_vector); void BLASTUngappedHspListToSeqAlign(EBlastProgramType program, BlastHSPList* hsp_list, CRef<CSeq_id> query_id, CRef<CSeq_id> subject_id, Int4 query_length, Int4 subject_length, const vector<int> & gi_list, vector<CRef<CSeq_align > > & sa_vector); /// Convert traceback output into Seq-align format. /// /// This converts the traceback stage output into a standard /// Seq-align. The result_type argument indicates whether the /// seqalign is for a database search or a sequence comparison /// (eDatabaseSearch or eSequenceComparison). The seqinfo_src /// argument is used to translate oids into Seq-ids. /// /// @param hsp_results /// Results of a traceback search. [in] /// @param local_data /// The queries used to perform the search. [in] /// @param seqinfo_src /// Provides sequence identifiers and meta-data. [in] /// @param program /// The type of search done. [in] /// @param gapped /// True if this was a gapped search. [in] /// @param oof_mode /// True if out-of-frame matches are allowed. [in] /// @param subj_masks /// If applicable, it'll be populated with subject masks that intersect the /// HSPs (each element corresponds to a query) [in|out] /// @param result_type /// Specify how to arrange the results in the return value. [in] TSeqAlignVector LocalBlastResults2SeqAlign(BlastHSPResults * hsp_results, ILocalQueryData & local_data, const IBlastSeqInfoSrc& seqinfo_src, EBlastProgramType program, bool gapped, bool oof_mode, vector<TSeqLocInfoVector>& subj_masks, EResultType result_type = eDatabaseSearch); END_SCOPE(blast) END_NCBI_SCOPE /* @} */ #endif /* ALGO_BLAST_API___BLAST_SEQALIGN__HPP */
/* * Copyright (C) 2018 The Android Open Source 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 android.autofillservice.cts; import static android.autofillservice.cts.testcore.Helper.ID_PASSWORD; import static android.autofillservice.cts.testcore.Helper.ID_USERNAME; import static com.android.compatibility.common.util.ShellUtils.runShellCommand; import static com.android.compatibility.common.util.ShellUtils.tap; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assume.assumeTrue; import android.app.Activity; import android.app.ActivityTaskManager; import android.autofillservice.cts.activities.LoginActivity; import android.autofillservice.cts.activities.MultiWindowEmptyActivity; import android.autofillservice.cts.activities.MultiWindowLoginActivity; import android.autofillservice.cts.commontests.AutoFillServiceTestCase; import android.autofillservice.cts.testcore.AutofillActivityTestRule; import android.autofillservice.cts.testcore.CannedFillResponse; import android.autofillservice.cts.testcore.Helper; import android.graphics.Rect; import android.platform.test.annotations.AppModeFull; import android.server.wm.TestTaskOrganizer; import android.view.View; import com.android.compatibility.common.util.AdoptShellPermissionsRule; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import java.util.concurrent.TimeoutException; @AppModeFull(reason = "This test requires android.permission.MANAGE_ACTIVITY_TASKS") public class MultiWindowLoginActivityTest extends AutoFillServiceTestCase.AutoActivityLaunch<MultiWindowLoginActivity> { private LoginActivity mActivity; private TestTaskOrganizer mTaskOrganizer; @Override protected AutofillActivityTestRule<MultiWindowLoginActivity> getActivityRule() { return new AutofillActivityTestRule<MultiWindowLoginActivity>( MultiWindowLoginActivity.class) { @Override protected void afterActivityLaunched() { mActivity = getActivity(); mTaskOrganizer = new TestTaskOrganizer(); } }; } @Override protected void cleanAllActivities() { MultiWindowEmptyActivity.finishAndWaitDestroy(); } @Override protected TestRule getMainTestRule() { return RuleChain.outerRule(new AdoptShellPermissionsRule()).around(getActivityRule()); } @Before public void setup() { assumeTrue("Skipping test: no split multi-window support", ActivityTaskManager.supportsSplitScreenMultiWindow(mActivity)); } @After public void tearDown() { mTaskOrganizer.unregisterOrganizerIfNeeded(); } /** * Touch a view and expect autofill window change */ protected void tapViewAndExpectWindowEvent(View view) throws TimeoutException { mUiBot.waitForWindowChange(() -> tap(view)); } /** * Touch specific position on device display and expect autofill window change. */ protected void tapPointAndExpectWindowEvent(int x, int y) { mUiBot.waitForWindowChange(() -> runShellCommand("input touchscreen tap %d %d", x, y)); } protected String runAmStartActivity(String activity) { return runShellCommand("am start %s/%s", mPackageName, activity); } protected void amStartActivity(Class<? extends Activity> activity2) { // it doesn't work using startActivity(intent), have to go through shell command. runAmStartActivity(activity2.getName()); } @Test public void testSplitWindow() throws Exception { enableService(); // Set expectations. sReplier.addResponse(new CannedFillResponse.CannedDataset.Builder() .setField(ID_USERNAME, "dude") .setField(ID_PASSWORD, "sweet") .setPresentation(createPresentation("The Dude")) .build()); // Trigger auto-fill. mActivity.onUsername(View::requestFocus); sReplier.getNextFillRequest(); mUiBot.assertDatasets("The Dude"); // split window and launch EmptyActivity, note that LoginActivity will be recreated. MultiWindowLoginActivity.expectNewInstance(false); MultiWindowEmptyActivity.expectNewInstance(true); mTaskOrganizer.putTaskInSplitPrimary(mActivity.getTaskId()); mUiBot.waitForIdleSync(); MultiWindowLoginActivity loginActivity = MultiWindowLoginActivity.waitNewInstance(); amStartActivity(MultiWindowEmptyActivity.class); MultiWindowEmptyActivity emptyActivity = MultiWindowEmptyActivity.waitNewInstance(); mTaskOrganizer.putTaskInSplitSecondary(emptyActivity.getTaskId()); // Make sure both activities are showing mUiBot.assertShownByRelativeId(Helper.ID_USERNAME); // MultiWindowLoginActivity mUiBot.assertShownByRelativeId(MultiWindowEmptyActivity.ID_EMPTY); // No dataset as LoginActivity loses window focus mUiBot.assertNoDatasets(); // EmptyActivity will have window focus assertThat(emptyActivity.hasWindowFocus()).isTrue(); // LoginActivity username field is still focused but window has no focus assertThat(loginActivity.getUsername().hasFocus()).isTrue(); assertThat(loginActivity.hasWindowFocus()).isFalse(); // Make LoginActivity to regain window focus and fill ui is expected to show tapViewAndExpectWindowEvent(loginActivity.getUsername()); mUiBot.assertNoDatasetsEver(); assertThat(emptyActivity.hasWindowFocus()).isFalse(); // Tap on EmptyActivity and fill ui is gone. Rect emptyActivityBounds = mTaskOrganizer.getSecondaryTaskBounds(); // Because tap(View) will get wrong physical start position of view while in split screen // and make bot cannot tap on emptyActivity, so use task bounds and tap its center. tapPointAndExpectWindowEvent(emptyActivityBounds.centerX(), emptyActivityBounds.centerY()); mUiBot.assertNoDatasetsEver(); assertThat(emptyActivity.hasWindowFocus()).isTrue(); // LoginActivity username field is still focused but window has no focus assertThat(loginActivity.getUsername().hasFocus()).isTrue(); assertThat(loginActivity.hasWindowFocus()).isFalse(); } }
package avro import ( "testing" "github.com/matryer/is" ) func TestRecord_Type(t *testing.T) { is := is.New(t) r := Record{} is.Equal(r.Type(), "record") // record type is "record" } func TestRecord_Valid(t *testing.T) { is := is.New(t) r := Record{} is.True(r.Valid() != nil) // nameless record should be invalid r.Name = "Test" is.NoErr(r.Valid()) // named record with no fields should be valid r.Fields = []Field{ {Name: ""}, } is.True(r.Valid() != nil) // having a nameless field should be invalid r.Fields[0].Name = "Test" is.True(r.Valid() != nil) // having a typeless field should be invalid r.Fields[0].Type = mockValidNamedSchema is.NoErr(r.Valid()) // having a named, typed field should be valid invalidDefault := interface{}(0) r.Fields[0].Default = &invalidDefault is.True(r.Valid() != nil) // field with invalid default should be invalid r.Fields[0].Default = nil r.Fields[0].Order = "__WRONG__" is.True(r.Valid() != nil) // field with invalid order should be invalid r.Fields[0].Order = "ascending" is.NoErr(r.Valid()) // field with valid order should be valid r.Fields[0].Type = mockInvalidNamedSchema is.True(r.Valid() != nil) // having a field with invalid schema should be invalid } func TestRecord_Validate(t *testing.T) { is := is.New(t) r := Record{} is.True(r.Validate(map[string]interface{}{}) != nil) // invalid schema cannot validate r = Record{ NameFields: NameFields{ Name: "Test", }, Fields: []Field{ {Name: "X", Type: mockValidNamedSchema}, }, } type custom struct { X int } is.NoErr(r.Validate(custom{mockValue})) // valid struct is.NoErr(r.Validate(&custom{mockValue})) // valid pointer to struct is.True(r.Validate(custom{0}) != nil) // invalid struct is.True(r.Validate(nil) != nil) // nil should be invalid type customTag struct { Y int `avro:"X"` } is.NoErr(r.Validate(customTag{mockValue})) // should get name from struct tag type invalid struct { Z int } is.True(r.Validate(invalid{mockValue}) != nil) // missing field should be invalid validMSI := map[string]interface{}{"X": mockValue} is.NoErr(r.Validate(validMSI)) // valid msi is.NoErr(r.Validate(&validMSI)) // pointer to valid msi is.NoErr(r.Validate(map[string]int{"X": mockValue})) // valid custom map is.True(r.Validate(map[string]int{"X": 0}) != nil) // custom map with invalid field value is.True(r.Validate(map[string]int{ "X": mockValue, "Y": mockValue, }) != nil) // custom map with non-existing field invalidMSI := map[string]interface{}{"__WRONG__": mockValue} is.True(r.Validate(invalidMSI) != nil) // invalid field name should be invalid invalidMSI = map[string]interface{}{"X": 0} is.True(r.Validate(invalidMSI) != nil) // invalid field value should be invalid nilMSI := map[string]interface{}(nil) is.True(r.Validate(nilMSI) != nil) // nil msi should be invalid is.True(r.Validate(&nilMSI) != nil) // nil msi pointer should be invalid badMap := map[int]interface{}{} is.True(r.Validate(badMap) != nil) // map without string key should be invalid is.True(r.Validate(0) != nil) // invalid type should be invalid }
import './Header.css'; /* import { useState } from 'react'; */ import logo from '../../images/LOGO1.svg' import SearchForm from '../SearchForm/SearchForm'; import { Link, useNavigate } from 'react-router-dom'; import Navigation from '../Navigation/Navigation'; export default function Header({ width, pathname, cart, faves, onSearch, isLoggedIn }) { const navigate = useNavigate(); function handleFavClick() { navigate('/favorite'); } function handleCartClick() { navigate('/cart'); } function handleProfileClick() { if (isLoggedIn) { navigate('/profile'); } else { navigate('/signin'); } } return( <header className="header"> { !pathname.includes('admin') ? <div className="header__container"> { width < 1440 && <div className="header__top"> <Navigation pathname={pathname} /> </div> } <div className="header__bottom"> <div className="header__links"> <Link to="/" className="header__logo-link"> <img className="header__logo" src={logo} alt="Логотип" /> </Link> <button className="header__phone-button" type="button" /> <p className="header__phone-number">+ 7 (999) 545-23-43</p> </div> { width < 1440 ? <SearchForm additional="search-form_type_header" onSearch={onSearch} pathname={pathname} /> : <Navigation pathname={pathname} /> } <div className="header__profile-buttons"> { width >= 1440 && <SearchForm additional="search-form_type_header" onSearch={onSearch} /> } <div className="header__favorites"> <button className="header__fav-button" type="button" onClick={handleFavClick} /> <span className="header__item-number">{faves.length}</span> </div> <div className="header__shopping-cart"> <button className="header__cart-button" type="button" onClick={handleCartClick} /> <span className="header__item-number">{cart.length}</span> </div> <div className="header__profile"> <button className="header__profile-button" type="button" onClick={handleProfileClick} /> {/* <span className="header__notification"></span> */} </div> </div> </div> </div> : <div className="header__container header__container_admin"> <Navigation pathname={pathname} /> <SearchForm additional="search-form_type_admin" onSearch={onSearch} /> </div> } </header> ); };
import { DataSource, Entity, EntityCallbacks, FireCMSContext, SaveEntityProps, User } from "../../types"; /** * @category Hooks and utilities */ export type SaveEntityWithCallbacksProps<M extends Record<string, any>> = SaveEntityProps<M> & { callbacks?: EntityCallbacks<M>; onSaveSuccess?: (updatedEntity: Entity<M>) => void; onSaveFailure?: (e: Error) => void; onPreSaveHookError?: (e: Error) => void; onSaveSuccessHookError?: (e: Error) => void; }; /** * This function is in charge of saving an entity to the datasource. * It will run all the save callbacks specified in the collection. * It is also possible to attach callbacks on save success or error, and callback * errors. * * If you just want to save the data without running the `onSaveSuccess`, * `onSaveFailure` and `onPreSave` callbacks, you can use the `saveEntity` method * in the datasource ({@link useDataSource}). * * @param collection * @param path * @param entityId * @param callbacks * @param values * @param previousValues * @param status * @param dataSource * @param context * @param onSaveSuccess * @param onSaveFailure * @param onPreSaveHookError * @param onSaveSuccessHookError * @see useDataSource * @category Hooks and utilities */ export declare function saveEntityWithCallbacks<M extends Record<string, any>, UserType extends User>({ collection, path, entityId, values, previousValues, status, dataSource, context, onSaveSuccess, onSaveFailure, onPreSaveHookError, onSaveSuccessHookError }: SaveEntityWithCallbacksProps<M> & { dataSource: DataSource; context: FireCMSContext<UserType>; }): Promise<void>;
package br.com.gile.leilao.service; import br.com.gile.leilao.dao.LeilaoDao; import br.com.gile.leilao.model.Lance; import br.com.gile.leilao.model.Leilao; import br.com.gile.leilao.model.Usuario; import org.junit.Assert; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; class FinalizarLeilaoServiceTest { private FinalizarLeilaoService service; @Mock private LeilaoDao leilaoDao; @Mock private EnviadorDeEmails enviadorDeEmails; @BeforeEach public void beforEach(){ MockitoAnnotations.initMocks(this); this.service = new FinalizarLeilaoService(leilaoDao, enviadorDeEmails); } @Test void deveriaFinalizarUmLeilao(){ List<Leilao> leiloes = leiloes(); Mockito.when(leilaoDao.buscarLeiloesExpirados()).thenReturn(leiloes); service.finalizarLeiloesExpirados(); Leilao leilao = leiloes.get(0); Assert.assertTrue(leilao.isFechado()); Assert.assertEquals(new BigDecimal("900"), leilao.getLanceVencedor().getValor()); //Verifica se o método salvar foi chamado Mockito.verify(leilaoDao).salvar(leilao); } @Test void deveriaEnviarUmEmailParaOVencedorDoLeilao(){ List<Leilao> leiloes = leiloes(); Mockito.when(leilaoDao.buscarLeiloesExpirados()).thenReturn(leiloes); service.finalizarLeiloesExpirados(); Leilao leilao = leiloes.get(0); Lance lanceVendedor = leilao.getLanceVencedor(); //Verifica se o método enviarEmailVencedorLeilaos foi chamado Mockito.verify(enviadorDeEmails).enviarEmailVencedorLeilao(lanceVendedor); } @Test void naoDeveriaEnviarUmEmailParaOVencedorDoLeilaoEmCasoDeErroAoEncerrarOLeilao(){ List<Leilao> leiloes = leiloes(); Mockito.when(leilaoDao.buscarLeiloesExpirados()).thenReturn(leiloes); Mockito.when(leilaoDao.salvar(Mockito.any())).thenThrow(RuntimeException.class); try { service.finalizarLeiloesExpirados(); //Verifica se o método enviarEmailVencedorLeilaos não foi chamado Mockito.verifyNoInteractions(enviadorDeEmails); }catch (Exception e){} } private List<Leilao> leiloes(){ List<Leilao> lista = new ArrayList<>(); Leilao leilao = new Leilao("Celular", new BigDecimal("500"), new Usuario("Gile")); Lance primeiro = new Lance(new Usuario("Fulano"), new BigDecimal("600")); Lance segundo = new Lance(new Usuario("Ciclano"), new BigDecimal("900")); leilao.propoe(primeiro); leilao.propoe(segundo); lista.add(leilao); return lista; } }
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, NgZone, OnDestroy, OnInit } from '@angular/core'; import { Chart } from '@antv/g2'; import { Random } from 'mockjs'; import { NzSafeAny } from 'ng-zorro-antd/core/types'; import { NzMessageService } from 'ng-zorro-antd/message'; import { WebsocketService } from 'src/app/services/websocket.service'; @Component({ selector: 'app-dashboard-main', templateUrl: './main.component.html', styleUrls: ['./main.component.less'] }) export class DashboardMainComponent implements OnInit, OnDestroy { messages = []; connection: any; message: any; chart!: Chart; year = new Date().getFullYear(); status = { i1: false, i2: false, i3: true }; stat = { item1: 0, item2: 0, item3: 0 }; constructor( private msg: NzMessageService, private ngZone: NgZone, private cdr: ChangeDetectorRef, private webSocketService: WebsocketService ) {} ngOnInit(): void { // 连接websocket 接收消息 this.connection = this.webSocketService.getMessages().subscribe((data: any) => { if (data.ctype == 'irst') { this.stat.item3 = data.data; } }); } sendms() { this.webSocketService.sendMessage(Math.random().toString()); } updateStatus(type: string, value: boolean): void { this.msg.info(`${type}: ${value}`); } render(er: ElementRef): void { this.ngZone.runOutsideAngular(() => this.init(er.nativeElement)); } private init(container: HTMLElement): void { const chart = (this.chart = new Chart({ container, autoFit: true, height: 300 })); chart.scale('value', { nice: true }); chart .interval() .position('month*value') .color('name', ['#00c1de', '#ff8a00', '#5D7092']) .adjust([ { type: 'dodge', marginRatio: 0 } ]); chart.interaction('active-region'); chart.tooltip({ showMarkers: false, shared: true // TODO: https://github.com/antvis/component/pull/160 // offset: 50, // htmlContent: (title: string, items: any[]) => { // const item1Price = +items[0].value; // const item2Price = +items[1].value; // const other = items[0].point._origin.other; // return `<div class="g2-tooltip chart-tooltip"> // <div class="g2-tooltip-title" style="margin-bottom: 4px;">${title}</div> // <div class="arrow"><span></span></div> // <div class="content"> // <p>项目一:${item1Price}</p> // <p>项目二:${item2Price}</p> // <p>其他金额:${other}</p> // <p>计算公式:${item1Price} + ${item2Price} = ${item1Price + item2Price}</p> // </div> // </div>`; // }, }); this.attachData(); } ngOnDestroy(): void { this.connection.unsubscribe(); // 组件销毁取消订阅 } private mockData(): NzSafeAny[] { // Mock data const data: any[] = []; for (let i = 0; i < 12; i++) { data.push( { name: '项目1', month: `${i + 1}月`, value: Random.integer(1, 1000) }, { name: '项目2', month: `${i + 1}月`, value: Random.integer(1, 1000) }, { name: '项目3', month: `${i + 1}月`, value: Random.integer(1, 1000) } ); } return data; } private attachData(): void { const { chart } = this; const data = this.mockData(); chart.changeData(data); this.stat.item1 = data.filter(w => w.name === '项目1').reduce((prev, cur) => (prev += cur.value), 0); this.stat.item2 = data.filter(w => w.name === '项目2').reduce((prev, cur) => (prev += cur.value), 0); this.stat.item3 = data.filter(w => w.name === '项目3').reduce((prev, cur) => (prev += cur.value), 0); this.cdr.detectChanges(); } }
package com.mdt.LeetCode.Easy; /** * Easy * <p> * You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. * <p> * You can either start from the step with index 0, or the step with index 1. * <p> * Return the minimum cost to reach the top of the floor. * <p> * date: 6/26/22 */ public class P746MinCostClimbingStairs { /** * nick's solution * <p> * if you allow to modify the array * * @param cost * @return */ public int minCostClimbingStairs(int[] cost) { for (var i = 2; i < cost.length; i++) cost[i] += Math.min(cost[i - 1], cost[i - 2]); return Math.min(cost[cost.length - 1], cost[cost.length - 2]); } /** * nick's solution * <p> * another approach: dynamic programming (DP) TODO why? * * @param cost * @return */ public int minCostClimbingStairs2(int[] cost) { var step1 = 0; var step2 = 0; for (var i = cost.length - 1; i >= 0; i--) { var currentStep = cost[i] + Math.min(step1, step2); step1 = step2; step2 = currentStep; } return Math.min(step1, step2); } }
import { Count, CountSchema, Filter, FilterExcludingWhere, repository, Where, } from '@loopback/repository'; import { post, param, get, getModelSchemaRef, patch, put, del, requestBody, response, } from '@loopback/rest'; import {TipoOferta} from '../models'; import {TipoOfertaRepository} from '../repositories'; export class TipoOfertaController { constructor( @repository(TipoOfertaRepository) public tipoOfertaRepository : TipoOfertaRepository, ) {} @post('/tipo-ofertas') @response(200, { description: 'TipoOferta model instance', content: {'application/json': {schema: getModelSchemaRef(TipoOferta)}}, }) async create( @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(TipoOferta, { title: 'NewTipoOferta', exclude: ['id'], }), }, }, }) tipoOferta: Omit<TipoOferta, 'id'>, ): Promise<TipoOferta> { return this.tipoOfertaRepository.create(tipoOferta); } @get('/tipo-ofertas/count') @response(200, { description: 'TipoOferta model count', content: {'application/json': {schema: CountSchema}}, }) async count( @param.where(TipoOferta) where?: Where<TipoOferta>, ): Promise<Count> { return this.tipoOfertaRepository.count(where); } @get('/tipo-ofertas') @response(200, { description: 'Array of TipoOferta model instances', content: { 'application/json': { schema: { type: 'array', items: getModelSchemaRef(TipoOferta, {includeRelations: true}), }, }, }, }) async find( @param.filter(TipoOferta) filter?: Filter<TipoOferta>, ): Promise<TipoOferta[]> { return this.tipoOfertaRepository.find(filter); } @patch('/tipo-ofertas') @response(200, { description: 'TipoOferta PATCH success count', content: {'application/json': {schema: CountSchema}}, }) async updateAll( @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(TipoOferta, {partial: true}), }, }, }) tipoOferta: TipoOferta, @param.where(TipoOferta) where?: Where<TipoOferta>, ): Promise<Count> { return this.tipoOfertaRepository.updateAll(tipoOferta, where); } @get('/tipo-ofertas/{id}') @response(200, { description: 'TipoOferta model instance', content: { 'application/json': { schema: getModelSchemaRef(TipoOferta, {includeRelations: true}), }, }, }) async findById( @param.path.string('id') id: string, @param.filter(TipoOferta, {exclude: 'where'}) filter?: FilterExcludingWhere<TipoOferta> ): Promise<TipoOferta> { return this.tipoOfertaRepository.findById(id, filter); } @patch('/tipo-ofertas/{id}') @response(204, { description: 'TipoOferta PATCH success', }) async updateById( @param.path.string('id') id: string, @requestBody({ content: { 'application/json': { schema: getModelSchemaRef(TipoOferta, {partial: true}), }, }, }) tipoOferta: TipoOferta, ): Promise<void> { await this.tipoOfertaRepository.updateById(id, tipoOferta); } @put('/tipo-ofertas/{id}') @response(204, { description: 'TipoOferta PUT success', }) async replaceById( @param.path.string('id') id: string, @requestBody() tipoOferta: TipoOferta, ): Promise<void> { await this.tipoOfertaRepository.replaceById(id, tipoOferta); } @del('/tipo-ofertas/{id}') @response(204, { description: 'TipoOferta DELETE success', }) async deleteById(@param.path.string('id') id: string): Promise<void> { await this.tipoOfertaRepository.deleteById(id); } }
# 您应该理解的基本 JavaScript 概念 > 原文:<https://javascript.plainenglish.io/the-essential-javascript-concepts-that-you-should-understand-ff2b8546c868?source=collection_archive---------8-----------------------> ## 为了成功发展和通过工作面试 ![](img/da79f80252047191bbeeb22527f6414e.png) 作为任何级别的 JavaScript 开发人员,您都需要理解它的基本概念和一些帮助我们开发代码的新想法。在本文中,我们将回顾 16 个基本概念。所以事不宜迟,让我们开始吧。 ## 索引 核心概念 * 动态的 * 参考值与值 * 相等运算符(==)与相同运算符(===) * 范围 * 提升 * 关闭 * IIEF * 复试 * 高阶函数 ES6+ * 扩展语法 * 解构 * Rest 语法 * 班级 * 承诺 * 异步等待 * 箭头功能 ## 核心概念 ## 动态的 我们认为 JavaScript 是一种动态语言,因为它有动态的方面。在 JavaScript 中,几乎所有东西都是动态的,例如,所有变量都是动态的,甚至代码也是动态的。动态类型化意味着变量的类型是在运行时确定的,不需要在使用变量之前显式声明变量。在 JavaSCript 中,你也可以在运行时用 eval()函数创建新的变量。但是,eval()是一个危险的函数,完全不鼓励使用。 ## 参考与价值 在 JS 中,我们有对象(函数、数组)和原始数据类型(字符串、数字、布尔、空和未定义)。基本数据类型总是通过值传递,对象通过引用传递。 原始值是不可变的,这意味着一旦创建,它们就不能被修改,我们创建了原始对象的副本。相反,通过引用,我们创建了一个到原文的链接。 阅读更多关于不变性的重要性:[理解 JavaScript 中的不变性](https://medium.com/javascript-in-plain-english/understanding-immutability-in-javascript-b10b0345086e)。 按值: ``` const value= 'Hello world!'; value[0] = 'P';console.log(value); //Hello world, not Pello world! ``` 通过引用: ``` const car1 = { brand: 'Ford', model: 'Mustang W-Code' }**const car2 = car1;**car2.model= '**Thunderbird**';console.log(car1 === car2); //trueconsole.log(car1); //{brand: 'Ford', model: '**Thunderbird**'} ``` ## 相等运算符(==)与相同运算符(===) “==”和“===”运算符之间的主要区别在于,“==”通过类型强制来比较变量,而===使用严格相等来比较变量,并且我们比较的类型和值必须相同。 例子 ``` 10 === 10 //true10 == "10" //true (Although 10 is a number and the "10" a string) ``` ## 范围 这个概念是许多新开发人员最难理解的概念之一。几乎所有编程语言最基本的范例之一是在变量中存储值的能力。 但是这些变量存在于哪里呢?它们存放在哪里?我们的程序如何得到它们?最后,什么是范围? “范围”是我们代码中标识符有效的区域。 在 JavaScript 中,我们有四种类型的作用域: * 全局范围范围:对所有对象可见(变量) * 函数作用域:在函数中可见(var) * 块范围(ES6+):在块内可见(let,const) * 模块(ES6+):在模块内可见 ## 提升 提升是一种机制,其中变量和函数声明在代码执行之前被移动到它们的“作用域”的顶部,因此,变量可能在它们的声明之前实际上是可用的。 示例: ``` a = 10; //Assign 10 to "a"console.log(a); //10var a; //Declare the "a" variable ``` ## 关闭 闭包是一个函数的混合体,它被捆绑在一起(封闭在一起),并引用其周围的状态,这使您可以从内部函数访问外部函数的作用域。 示例: ``` function foo() { let myVar = 'Hello!!'; //myVar is a local variable created by foo function alertMyVar() { //alertMyVar() is the closure alert(name); //Alert use the variable declared in the parent function } alertMyVar(); } foo(); ``` foo()函数创建一个名为 myVar 的局部变量和一个名为 alertMyVar()的函数。alertMyVar()函数是一个**内部函数**,它定义在 foo()函数内部,并且只在 foo()函数体中可用。alertMyVar() **可以访问外部函数**的变量,所以 alertMyVar()可以访问父函数中声明的变量 MyVar。 ## 生活 立即调用的函数表达式(IIFE)是一个在函数创建后立即运行函数的过程。IIFEs 非常有用,因为它们防止污染全局环境,允许公共访问方法,同时维护函数内部定义的变量的隐私。 示例: ``` (function() { let name= "Hello world!"; alert(name); } )();//Hello world! ``` 总之,我们使用生命主要是因为隐私。在 IIFE 函数中声明的任何变量都不能从外界获得。 ## 复试 在 JavaScript 中,回调是作为参数传递给其他函数的函数,然后在外部函数中调用。回调也是闭包,传递给它的函数是在另一个函数内部执行的函数,就好像回调是在包含函数中定义的一样。 ``` function runAsyncFunction(param1, callback) { //Do some stuff, //for example download //data for a externan URL. //After a while... result = 100; callback(result); }runAsyncFunction(10, (r) => {...}));//.. //Execute other tasks //while the runAsyncFunction //is running asynchronously. ``` 回调的问题是代码有很多回调,很难直观地得到正确的结果,代码最终看起来如下例所示: ![](img/139fff1ed1351a2117418518d70e0b02.png) Callbacks-Hell ## 高阶函数 高阶函数是接收其他函数作为参数或返回函数作为结果的函数。它们在 JavaScript 中被广泛使用,如。filter(),。map(),。减少()或。forEach()函数。 考虑下面的例子: ``` const myArray = [1,2,3,4]; const myMultiplyFuncion = (n) => n*2;newArray = myArray.map(myMultiplyFuncion); console.log(newArray); //[2, 4, 6, 8] ``` **这里的高阶函数是。map(** ) **函数**接受 myMultiplyFuncion 并返回一个新数组,其中的值乘以 2。 此外,JavaScript 允许函数返回其他函数作为结果。记住函数只是简单的对象,它们可以像任何附加值一样被返回。 虽然这个例子有点傻,因为您可以直接使用 str.toUpperCase(),但它展示了一个函数如何返回另一个函数: ``` const myToUpperCasse = function(str) { return str.toUpperCase(); };console.log(myToUpperCasse("hello world!")); //HELLO WORLD! ``` ## ES6+ ## 扩展语法 我们使用扩展操作符“…”将单个元素从数组中取出。 语法:some function(…iterable obj); 考虑下一个例子: ``` const myArray = [1,2,3,4,5,6,7,8]; const min = Math.min(...myArray); console.log(min); //1 ``` 我们不能用 myArray 直接应用 Math.min,因为它不接受数组作为参数;它将单个元素作为参数。使用 spread 语法,我们可以这样做。 在下一个示例中,我们使用数组元素作为函数的参数: ``` function sum(a, b, c) { return a + b + c; }const numbers = [1, 2, 3];console.log(sum(...numbers)); //6 ``` 串联数组: ``` let myArray1 = [1, 2, 3]; let myArray2 = [4, 5, 6];concatenatedArray = [...arr1, ...arr2]; console.log(concatenatedArray); //[1,2,3,4,5,6] ``` 组合对象: ``` const myObj1= { name: "Rick" }; const myObj2= { age:40, year: 1980 };const mergedObj = { ...myObj1, ...myObj2 };console.log(mergedObj); //{name: "Rick", age: 40, year: 1980} ``` ## 解构 析构是一个 JavaScript 表达式,它可以将对象或数组中的值属性提取到不同的变量中: ``` let var1, var2; [var1, var2] = [1, 2];console.log(var1); //1console.log(var2); //2...const myConst= ['1', '2', '3']; const [n1, n2, n3] = myConst;console.log(n1); //"1" console.log(n2); //"2" console.log(n3); //"3" ``` 我们也可以很容易地交换变量: ``` let var1 = 1; let var2 = 2;[var1, var2] = [var2, var1]; console.log(var1); //3 console.log(var2); //1 ``` ## Rest 语法 rest 语法允许我们将几个参数表示为一个数组。 语法:function f(a,b,…theArgs){ //做一些事情。 } ``` function sum(...theArgs) { return theArgs[0] + theArgs[5]; }sum(**1**, 2, 3, 4, 5, **6**); //7 ``` 只有最后一个参数可以是“rest 参数”: ``` function sum(a, b, ...theArgs) { console.log(a);//1 console.log(b);//2return theArgs[0] + theArgs[3]; }sum(1**,** 2, 3, 4, 5, 6);//a:1,b:2 //9 -> (theArgs[0]:3 + theArgs[3]:6) ``` ## 班级 Javascript 类是现有的基于原型的继承和构造函数之上的**语法糖**。 使用构造器模式: ``` function ConstructorCar (brand, model) { this.brand = brand; this.model = model; }ConstructorCar.prototype.isFord = function (brand) { return this.brand === "Ford"; };myCar = new ConstructorCar("Ford", "Sierra"); console.log(myCar.isFord("Ford")); //true ``` 用 isBMW()方法扩展我们的构造函数: ``` ConstructorCar.**prototype**.isBMW = function (brand) { return this.brand === "BMW"; };myCarBWM = new ConstructorCar("BMW", "505"); console.log(myCarBWM.isBMW("BMW")); //true ``` 使用类别语法的对等用法: ``` class Car { constructor(brand, model) { this.brand = brand; this.model = model; }isFord(brand){ return this.brand === "Ford"; }}myCar = new Car("Ford", "Sierra"); console.log(myCar.isFord("Ford")); //true ``` 用 isBmw()方法扩展该类: ``` class CarBMW **extends** Car{ constructor(brand, model) { super(brand,model); } isBMW(brand){ return this.brand === brand; } }myCar1 = new CarBMW("Ford", "Sierra"); console.log(myCar1.isFord("Ford")); //truemyCar2 = new CarBMW("BMW", "505"); console.log(myCar2.isBMW("BMW")); //true ``` ## 承诺 承诺是一个值的代理,代表解决或拒绝的未来操作的结果。它允许您将处理程序与异步操作相关联,并且是避免使用回调的替代方法。 Promises 立即返回一个 promise 对象,您使用“Then”方法传递异步函数完成时要采取的操作。 使用他们的<then>方法,承诺可以被连锁。每个链接的函数返回一个新的承诺,表示链中另一个异步步骤的完成。</then> 承诺总是处于这些状态之一: * “待定”:初始状态。 * “已完成”:表示操作成功完成。 * “拒绝”:表示操作失败。 与我们使用承诺回调的例子一样: ![](img/88b42d72a638d9df3523dff401d28c95.png) Promises example image ## 异步等待 Async/Await 是 ES2017 中的新功能,它可以帮助我们为异步任务编写完全同步的代码。 与 promises 相比,它的主要优点是带有“异步函数”的代码的语法和结构与使用标准同步函数相似,并且与我们顺序思考的方式相当。 异步函数可以包含<awaits>表达式,用于暂停异步函数的执行,并等待传递的承诺的解析。当承诺被解析后,将恢复异步函数的执行并返回结果值。</awaits> 相同的 promises 示例,但是使用了 Async/await: 注意:您需要将包含它的函数定义为 async。 ![](img/bdac91f1a7eed34c8f14ee48a9c7aa37.png) Async/await example image. Promises 和 Async/Await 实现了同样的事情,但是 Async/Await 使得处理异步代码更加自然。两者都消除了回调的需要和著名的回调地狱。 你可以阅读我的关于 JavaScript 异步代码的完整文章,见:“[JavaScript 中从回调到异步等待的旅程。](https://medium.com/javascript-in-plain-english/javascript-a-fast-trip-for-dummies-from-callbacks-to-es6-async-await-a61b0a4b0bed)” ## 箭头功能 箭头函数在语法上是常规函数的紧凑替代物;与常规函数不同,箭头函数不绑定“this”对象。相反,“this”对象是词汇绑定的,保持其原始上下文。 注意,箭头函数表达式不适合作为方法,它们不能用作构造函数或递归函数,但在 map()、reduce()或 filter()等函数中非常有用 ``` const sum = function(a, b){ return a + b; }Equivalent arrow function:const sum = (a,b) => a+b; ``` 具有过滤功能: ``` let array = [1,2,3,4,5] let newArray = array.filter( e => e > 2); //[3,5,5] ``` ## 结论 在本文中,我们已经看到了我认为的 JavaScript 的一些基本部分。我们仍然需要讨论“这个”对象或者原型和继承,但是考虑到它的复杂性,我将把它留到另一篇文章中,在那里我将详细解释它们。 我希望你喜欢这篇文章。非常感谢你阅读我! ## 简明英语笔记 你知道我们有四种出版物吗?给他们一个 follow 来表达爱意:[**JavaScript in Plain English**](https://medium.com/javascript-in-plain-english)[**AI in Plain English**](https://medium.com/ai-in-plain-english)[**UX in Plain English**](https://medium.com/ux-in-plain-english)[**Python in Plain English**](https://medium.com/python-in-plain-english)**—谢谢,继续学习!** **此外,我们总是有兴趣帮助推广好的内容。如果您有一篇文章想要提交给我们的任何出版物,请发送电子邮件至[**submissions @ plain English . io**](mailto:[email protected])**,附上您的媒体用户名和您感兴趣的内容,我们将会回复您!****
/* -*- Mode: C++; tab-width: 3; indent-tabs-mode: nil c-basic-offset: 3 -*- */ // vim:cindent:ts=3:sw=3:et:tw=80:sta: /***************************************************************** phui-cpr beg * * phui - flexible user interface subsystem * phui is (C) Copyright 2002 by * Chad Austin, Josh Carlson, Johnathan Gurley, * Ben Scott, Levi Van Oort * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile: Driver.h,v $ * Date modified: $Date: 2005-01-25 17:28:50 $ * Version: $Revision: 1.3 $ * ----------------------------------------------------------------- * ************************************************************** phui-cpr-end */ #ifndef PHUI_DRIVER_H #define PHUI_DRIVER_H #include <phui/Input.h> #include <phui/Point.h> #include <phui/RootWidget.h> #include <phui/Widget.h> #include <string> namespace phui { /** * The interface that all drivers must adhere to. This defines * a bridge that connects the low level input handling/drawing * library to phui. * @note Drivers should be written to operate in two modes: * standalone and module. In standalone mode, the driver * will take care of _EVERYTHING_ GUI related, ie, it * will setup the Root Window using the driver-dependant * API, setup the event handlers, etc. In module mode, * the driver will assume that the driver-dependant setup * has been handled by the user. It will only handle the * creation and destruction of phui components. For the sake * of simplicity, drivers should default to standalone mode. */ class Driver { public: /** * Gets the name of this driver. * * @return the name of the driver. */ virtual std::string getDriverName() = 0; /** * Gets the version number of this driver as a string. * * @return the version number of this driver. */ virtual std::string getDriverVersion() = 0; /** * Registers the root widget of the gui. * * @param root the root widget of this gui. */ virtual void registerRoot(RootWidgetPtr root) = 0; // Event Handlers /** * Signals that a key has been pressed. * * @param key the key that has been pressed. */ virtual void onKeyDown(InputKey key) = 0; /** * Signals that a key has been released. * * @param key the key that has been released. */ virtual void onKeyUp(InputKey key) = 0; /** * Signals that a mouse button has been pressed. * * @param button the button that has been pressed. * @param point the location of the mouse cursor at the time of * the button press. */ virtual void onMouseDown(InputButton button, const Point& p) = 0; /** * Signals that a mouse button has been released. * * @param button the button that has been released. * @param point the location of the mouse cursor at the time of * the button release. */ virtual void onMouseUp(InputButton button, const Point& p) = 0; /** * Signals that the mouse cursor has been moved. * * @param point the point that the mouse cursor has been moved * to. */ virtual void onMouseMove(const Point& p) = 0; /** * Starts the driver; only meaningful in standalone mode. * * @note Once start is called, the function will not return until * the application is closed through phui. */ virtual void start() = 0; /** * Tells the driver to update phui; only meaningful in module mode. */ virtual void update() = 0; /** * Checks to see whether the driver is running in standalone mode or * module mode. * * @return true if the driver is in standalone mode, false if it is * in module mode. */ virtual bool isStandalone() = 0; }; } #endif
import React, { useContext, useEffect, useState } from "react" import Page from "./Page" import Axios from "axios" import { Link, useNavigate, useParams } from "react-router-dom" import StateContext from "../../StateContext" import DispatchContext from "../../DispatchContext" import { useImmerReducer } from "use-immer" import Select from "react-select" import dayjs from "dayjs" import { DatePicker } from "@mui/x-date-pickers" import reactCSS from "reactcss" import { SketchPicker } from "react-color" function PlanModal(props) { const navigate = useNavigate() const appDispatch = useContext(DispatchContext) const appState = useContext(StateContext) const currentDate = dayjs() const appName = useParams().id const { plan } = props const initialState = { Plan_MVP_name: { value: plan.Plan_MVP_name }, Plan_startDate: { initial: dayjs(dayjs(plan.Plan_startDate).format("YYYY-MM-DD")), value: plan.Plan_startDate ? dayjs(plan.Plan_startDate).format("YYYY-MM-DD") : null }, Plan_endDate: { initial: dayjs(dayjs(plan.Plan_endDate).format("YYYY-MM-DD")), value: plan.Plan_endDate ? dayjs(plan.Plan_endDate).format("YYYY-MM-DD") : null }, Plan_app_Acronym: appName, submitCount: 0, displayColorPicker: false, color: plan.Color ? plan.Color : "fffff" } function ourReducer(draft, action) { switch (action.type) { case "Plan_MVP_name": draft.Plan_MVP_name = action.value return case "Plan_startDate": draft.Plan_startDate.value = action.value return case "Plan_endDate": draft.Plan_endDate.value = action.value return case "Plan_app_Acronym": draft.Plan_app_Acronym = action.value return case "toggleColorPicker": draft.displayColorPicker = !draft.displayColorPicker return case "changeColor": draft.color = action.color.hex console.log(draft.color) return case "submitForm": // // check if email has no errors and unique & password has no errors and unique // if (!draft.email.hasErrors && !draft.password.hasErrors) { // draft.submitCount++; // } // // check if email is empty & password has no errors and unique // if (draft.email.optional && !draft.password.optional && !draft.password.hasErrors) { // draft.submitCount++; // } // // check if email has no errors and unique & password is empty // if (!draft.email.optional && draft.password.optional && !draft.email.hasErrors) { // draft.submitCount++; // } // // check if email has no errors and unique & password is empty // if (draft.email.optional && draft.password.optional) { // draft.submitCount++; // } // //if has errors give error message // if (draft.email.hasErrors || draft.password.hasErrors) { // appDispatch({ type: "flashMessagesError", value: "There was an error creating user. Check inputs" }); // } return case "RESET": return initialState } } const [state, dispatch] = useImmerReducer(ourReducer, initialState) async function handleSubmit(e) { e.preventDefault() try { const response = await Axios.post("/update-plan", { Plan_MVP_name: state.Plan_MVP_name.value, Plan_startDate: state.Plan_startDate.value, Plan_endDate: state.Plan_endDate.value, Plan_app_Acronym: state.Plan_app_Acronym, Color: state.color }) // no need :"" if same as the title console.log("Plan was update") appDispatch({ type: "closePlanModal" }) //close modal appDispatch({ type: "planEdited" }) //refresh app page api call appDispatch({ type: "flashMessages", value: "CONGRATS! YOU HAVE UPDATED A PLAN" }) } catch (e) { console.log("there was a problem") } } const styles = reactCSS({ default: { color: { width: "36px", height: "14px", borderRadius: "2px", background: state.color }, swatch: { padding: "5px", background: "#fff", borderRadius: "1px", boxShadow: "0 0 0 1px rgba(0,0,0,.1)", display: "inline-block", cursor: "pointer" }, popover: { position: "absolute", zIndex: "2" }, cover: { position: "fixed", top: "0px", right: "0px", bottom: "0px", left: "0px" } } }) useEffect(() => { document.addEventListener("keyup", searchKeyPressHandler) return () => document.removeEventListener("keyup", searchKeyPressHandler) }, []) //closing edit with escape key function searchKeyPressHandler(e) { if (e.keyCode == 27) { appDispatch({ type: "closePlanModal" }) } } return ( <div className="search-overlay"> <Page title="Edit plan"> <span onClick={(e) => appDispatch({ type: "closePlanModal" })} className="close-live-search"> <i className="fas fa-times-circle"></i> </span> <div className="card mt-5 appModal" style={{ width: "80%", margin: "auto" }}> <div className="container py-5"> <form onSubmit={handleSubmit}> <div className="form-row"> <div className="col-md-6 mb-3"> <label htmlFor="post-title" className="text-muted mb-1"> <small>Plan_MVP_name</small> </label> <input disabled value={state.Plan_MVP_name.value} autoFocus name="title" id="post-title" className="form-control form-control" type="text" placeholder="" autoComplete="off" /> {/* color picker */} <div className="mt-2"> <div style={styles.swatch} onClick={() => dispatch({ type: "toggleColorPicker" })}> <div style={styles.color} /> </div> {state.displayColorPicker ? ( <div style={styles.popover}> <div style={styles.cover} onClick={() => dispatch({ type: "toggleColorPicker" })} /> <SketchPicker color={state.color} onChange={(color) => dispatch({ type: "changeColor", color })} /> </div> ) : null} </div> </div> <div className="col-sm-2 mb-3"> <label htmlFor="post-title" className="text-muted mb-1"> <small>Plan_app_Acronym</small> </label> <input value={state.Plan_app_Acronym} disabled autoFocus name="title" id="post-title" className="form-control form-control" type="text" placeholder="" autoComplete="off" /> </div> </div> <div className="form-row mb-3"> <div className="col col-md-4"> <label htmlFor="post-title" className="text-muted mb-1"></label> <DatePicker defaultValue={state.Plan_startDate.initial} views={["year", "month", "day"]} onChange={(newValue) => dispatch({ type: "Plan_startDate", value: dayjs(newValue?.$d).format("YYYY-MM-DD HH:mm:ss") })} label="Plan_startDate" />{" "} </div> <div className="col col-md-4 "> <label htmlFor="post-title" className="text-muted mb-1"></label> <DatePicker defaultValue={state.Plan_endDate.initial} views={["year", "month", "day"]} onChange={(newValue) => dispatch({ type: "Plan_endDate", value: dayjs(newValue?.$d).format("YYYY-MM-DD HH:mm:ss") })} label="Plan_endDate" /> </div> </div> <button className="btn btn-primary">Update Plan</button> </form> </div> </div> </Page> </div> ) } export default PlanModal
import assert from 'node:assert' export class HTTPError<T = number> extends Error { errno?: T status: number constructor(message?: string, errno?: T, status?: number) { super(message ?? 'HTTP Error') this.name = 'HTTPError' this.status = status ?? 500 this.errno = errno } } export class ClientError<T = number> extends HTTPError<T> { constructor(message?: string, errno?: T, status?: number) { super(message ?? 'Client Error', errno, status ?? 400) assert(this.status >= 400 && this.status < 500) this.name = 'ClientError' } } export class ServerError<T = number> extends HTTPError<T> { constructor(message?: string, errno?: T, status?: number) { super(message ?? 'Server Error', errno, status ?? 500) assert(this.status >= 500 && this.status < 600) this.name = 'ServerError' } } export class BadRequestError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Bad Request', errno, 400) this.name = 'BadRequestError' } } export class UnauthorizedError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Unauthorized', errno, 401) this.name = 'UnauthorizedError' } } export class PaymentRequiredError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Payment Required', errno, 402) this.name = 'PaymentRequiredError' } } export class ForbiddenError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Forbidden', errno, 403) this.name = 'ForbiddenError' } } export class NotFoundError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Not Found', errno, 404) this.name = 'NotFoundError' } } export class MethodNotAllowedError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Method Not Allowed', errno, 405) this.name = 'MethodNotAllowedError' } } export class NotAcceptableError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Not Acceptable', errno, 406) this.name = 'NotAcceptableError' } } export class ProxyAuthenticationRequiredError< T = number, > extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Proxy Authentication Required', errno, 407) this.name = 'ProxyAuthenticationRequiredError' } } export class RequestTimeoutError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Request Timeout', errno, 408) this.name = 'RequestTimeoutError' } } export class ConflictError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Conflict', errno, 409) this.name = 'ConflictError' } } export class GoneError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Gone', errno, 410) this.name = 'GoneError' } } export class LengthRequiredError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Length Required', errno, 411) this.name = 'LengthRequiredError' } } export class PreconditionFailedError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Precondition Failed', errno, 412) this.name = 'PreconditionFailedError' } } export class PayloadTooLargeError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Payload Too Large', errno, 413) this.name = 'PayloadTooLargeError' } } export class URITooLongError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'URI Too Long', errno, 414) this.name = 'URITooLongError' } } export class UnsupportedMediaTypeError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Unsupported Media Type', errno, 415) this.name = 'UnsupportedMediaTypeError' } } export class RangeNotSatisfiableError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Range Not Satisfiable', errno, 416) this.name = 'RangeNotSatisfiableError' } } export class ExpectationFailedError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Expectation Failed', errno, 417) this.name = 'ExpectationFailedError' } } export class ImaTeapotError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? "I'm a Teapot", errno, 418) this.name = 'ImaTeapotError' } } export class MisdirectedRequestError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Misdirected Request', errno, 421) this.name = 'MisdirectedRequestError' } } export class UnprocessableEntityError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Unprocessable Entity', errno, 422) this.name = 'UnprocessableEntityError' } } export class LockedError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Locked', errno, 423) this.name = 'LockedError' } } export class FailedDependencyError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Failed Dependency', errno, 424) this.name = 'FailedDependencyError' } } export class TooEarlyError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Too Early', errno, 425) this.name = 'TooEarlyError' } } export class UpgradeRequiredError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Upgrade Required', errno, 426) this.name = 'UpgradeRequiredError' } } export class PreconditionRequiredError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Precondition Required', errno, 428) this.name = 'PreconditionRequiredError' } } export class TooManyRequestsError<T = number> extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Too Many Requests', errno, 429) this.name = 'TooManyRequestsError' } } export class RequestHeaderFieldsTooLargeError< T = number, > extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Request Header Fields Too Large', errno, 431) this.name = 'RequestHeaderFieldsTooLargeError' } } export class UnavailableForLegalReasonsError< T = number, > extends ClientError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Unavailable For Legal Reasons', errno, 451) this.name = 'UnavailableForLegalReasonsError' } } export class InternalServerError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Internal Server Error', errno, 500) this.name = 'InternalServerError' } } export class NotImplementedError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Not Implemented', errno, 501) this.name = 'NotImplementedError' } } export class BadGatewayError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Bad Gateway', errno, 502) this.name = 'BadGatewayError' } } export class ServiceUnavailableError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Service Unavailable', errno, 503) this.name = 'ServiceUnavailableError' } } export class GatewayTimeoutError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Gateway Timeout', errno, 504) this.name = 'GatewayTimeoutError' } } export class HTTPVersionNotSupportedError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'HTTP Version Not Supported', errno, 505) this.name = 'HTTPVersionNotSupportedError' } } export class VariantAlsoNegotiatesError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Variant Also Negotiates', errno, 506) this.name = 'VariantAlsoNegotiatesError' } } export class InsufficientStorageError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Insufficient Storage', errno, 507) this.name = 'InsufficientStorageError' } } export class LoopDetectedError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Loop Detected', errno, 508) this.name = 'LoopDetectedError' } } export class BandwidthLimitExceededError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Bandwidth Limit Exceeded', errno, 509) this.name = 'BandwidthLimitExceededError' } } export class NotExtendedError<T = number> extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Not Extended', errno, 510) this.name = 'NotExtendedError' } } export class NetworkAuthenticationRequiredError< T = number, > extends ServerError<T> { constructor(message?: string, errno?: T) { super(message ?? 'Network Authentication Required', errno, 511) this.name = 'NetworkAuthenticationRequiredError' } } export function createHTTPError<T = number>( status: number, message?: string, errno?: T, ): HTTPError<T> { switch (status) { case 400: return new BadRequestError<T>(message, errno) case 401: return new UnauthorizedError<T>(message, errno) case 402: return new PaymentRequiredError<T>(message, errno) case 403: return new ForbiddenError<T>(message, errno) case 404: return new NotFoundError<T>(message, errno) case 405: return new MethodNotAllowedError<T>(message, errno) case 406: return new NotAcceptableError<T>(message, errno) case 407: return new ProxyAuthenticationRequiredError<T>(message, errno) case 408: return new RequestTimeoutError<T>(message, errno) case 409: return new ConflictError<T>(message, errno) case 410: return new GoneError<T>(message, errno) case 411: return new LengthRequiredError<T>(message, errno) case 412: return new PreconditionFailedError<T>(message, errno) case 413: return new PayloadTooLargeError<T>(message, errno) case 414: return new URITooLongError<T>(message, errno) case 415: return new UnsupportedMediaTypeError<T>(message, errno) case 416: return new RangeNotSatisfiableError<T>(message, errno) case 417: return new ExpectationFailedError<T>(message, errno) case 418: return new ImaTeapotError<T>(message, errno) case 421: return new MisdirectedRequestError<T>(message, errno) case 422: return new UnprocessableEntityError<T>(message, errno) case 423: return new LockedError<T>(message, errno) case 424: return new FailedDependencyError<T>(message, errno) case 425: return new TooEarlyError<T>(message, errno) case 426: return new UpgradeRequiredError<T>(message, errno) case 428: return new PreconditionRequiredError<T>(message, errno) case 429: return new TooManyRequestsError<T>(message, errno) case 431: return new RequestHeaderFieldsTooLargeError<T>(message, errno) case 451: return new UnavailableForLegalReasonsError<T>(message, errno) case 500: return new InternalServerError<T>(message, errno) case 501: return new NotImplementedError<T>(message, errno) case 502: return new BadGatewayError<T>(message, errno) case 503: return new ServiceUnavailableError<T>(message, errno) case 504: return new GatewayTimeoutError<T>(message, errno) case 505: return new HTTPVersionNotSupportedError<T>(message, errno) case 506: return new VariantAlsoNegotiatesError<T>(message, errno) case 507: return new InsufficientStorageError<T>(message, errno) case 508: return new LoopDetectedError<T>(message, errno) case 509: return new BandwidthLimitExceededError<T>(message, errno) case 510: return new NotExtendedError<T>(message, errno) case 511: return new NetworkAuthenticationRequiredError<T>(message, errno) } return new InternalServerError<T>( message ?? `Unknown status ${status}`, errno, ) } export function rethrow<S extends Error, D extends Error>( Src: new (message?: string) => S, Dst: new (message?: string) => D, ): (err: unknown) => never { return (err) => { throw err instanceof Src ? new Dst(err.message) : err } } export function supress<E extends Error, V>( Err: new (message?: string) => E, value?: V, ): (err: unknown) => V | undefined { return (err) => { if (err instanceof Err) return value throw err } }
package sv.edu.udb.form; import javax.swing.*; import sv.edu.udb.beans.AbonoBeans; import sv.edu.udb.datos.AbonoDatos; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; public class Abono extends JFrame{ private JPanel abonoPanel; private JRadioButton $500RadioButton; private JRadioButton $50RadioButton; private JRadioButton $10RadioButton; private JRadioButton $100RadioButton; private JRadioButton $20RadioButton; private JButton abonarButton; private JComboBox cuentasCombo; private JButton menuButton; private Menu menuForm; public Abono(String dui) { this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setContentPane(abonoPanel); this.pack(); this.setLocationRelativeTo(null); AbonoDatos abonoDatos = new AbonoDatos(); List<String> cuentas = abonoDatos.getCuentasByDUI(dui); for (String cuenta : cuentas) { // Formatear el número de cuenta para agregar ceros a la izquierda String formattedCuenta = String.format("%010d", Integer.parseInt(cuenta)); cuentasCombo.addItem(formattedCuenta); } $10RadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); $20RadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); $50RadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); $100RadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); $500RadioButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); abonarButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Verificar si se ha seleccionado una cuenta en el ComboBox if (cuentasCombo.getSelectedItem() == null) { JOptionPane.showMessageDialog(null, "Por favor, seleccione una cuenta."); return; } // Obtener el valor del radio button seleccionado double cantidad = 0.0; // Valor predeterminado if ($10RadioButton.isSelected()) { cantidad = 10.0; } else if ($20RadioButton.isSelected()) { cantidad = 20.0; } else if ($50RadioButton.isSelected()) { cantidad = 50.0; } else if ($100RadioButton.isSelected()) { cantidad = 100.0; } else if ($500RadioButton.isSelected()) { cantidad = 500.0; } // Obtener el número de cuenta seleccionado desde el combo box String numeroCuenta = (String) cuentasCombo.getSelectedItem(); if (numeroCuenta != null && cantidad > 0.0) { // Crear un objeto AbonoBeans con los datos del abono AbonoBeans abono = new AbonoBeans(Long.parseLong(numeroCuenta), "abono", cantidad); // Llamar a la clase AbonoDatos para realizar el abono AbonoDatos abonoDatos = new AbonoDatos(); boolean abonoExitoso = abonoDatos.realizarAbono(abono); if (abonoExitoso) { JOptionPane.showMessageDialog(null, "Abono exitoso."); // Cerrar la ventana de abono dispose(); menuForm = new Menu(dui); // Pasa el DUI como argumento menuForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Puedes ajustar esto según tus necesidades menuForm.setSize(800, 600); // Ajusta el tamaño según tus necesidades menuForm.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Error en el abono."); // Aquí manejar el caso de error } } else { JOptionPane.showMessageDialog(null, "Selecciona una cuenta y un monto de abono válido."); // Aquí manejar el caso de selección incorrecta } } }); menuButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); // Abrir la ventana del menú menuForm = new Menu(dui); // Pasa el DUI como argumento menuForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); menuForm.setSize(800, 600); menuForm.setVisible(true); } }); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Abono abonoForm = new Abono("DUI_DEFAULT"); abonoForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); abonoForm.setSize(500, 500); abonoForm.setVisible(true); } }); } }
"use strict";Object.defineProperty(exports, "__esModule", { value: true });var _createClass = function () {function defineProperties(target, props) {for (var i = 0; i < props.length; i++) {var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);}}return function (Constructor, protoProps, staticProps) {if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;};}();var _react = require("react");var _react2 = _interopRequireDefault(_react); var _robeReactCommons = require("robe-react-commons"); var _Application = require("robe-react-commons/lib/application/Application");var _Application2 = _interopRequireDefault(_Application);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _objectWithoutProperties(obj, keys) {var target = {};for (var i in obj) {if (keys.indexOf(i) >= 0) continue;if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;target[i] = obj[i];}return target;}function _classCallCheck(instance, Constructor) {if (!(instance instanceof Constructor)) {throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self, call) {if (!self) {throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call && (typeof call === "object" || typeof call === "function") ? call : self;}function _inherits(subClass, superClass) {if (typeof superClass !== "function" && superClass !== null) {throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;}var Application = function (_ShallowComponent) {_inherits(Application, _ShallowComponent); /** * defaultProps * @static */ function Application(props) {_classCallCheck(this, Application);var _this = _possibleConstructorReturn(this, (Application.__proto__ || Object.getPrototypeOf(Application)).call(this, props));_this.isLoaded = false; _this.componentWillReceiveProps(props);return _this; } /** * PropTypes of the component * @static */_createClass(Application, [{ key: "componentWillReceiveProps", value: function componentWillReceiveProps(props) {this.state = { upgrade: this.previousLang !== props.language }; } //TODO: Commondaki methodların buradan ulaşılabilmesi. }, { key: "render", value: function render() { if (this.state.upgrade) { return _react2.default.createElement("span", null); }var _props = this.props,language = _props.language,newProps = _objectWithoutProperties(_props, ["language"]); return _react2.default.createElement("div", newProps, this.props.children); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { this.upgradeIfNeeded(); } }, { key: "componentDidMount", value: function componentDidMount() { this.upgradeIfNeeded(); } }, { key: "upgradeIfNeeded", value: function upgradeIfNeeded( lang) {var _this2 = this; var language = lang || this.props.language; if (this.state.upgrade) { if (_robeReactCommons.Assertions.isString(language)) { try { System.import("./assets/" + language).then(function (langMap) { _Application2.default.loadI18n(langMap); _this2.isLoaded = true; _this2.setState({ upgrade: false }); _robeReactCommons.Cookies.put("language", language); }). catch(function (err) { if (lang) { throw err; } _robeReactCommons.Cookies.remove("language"); _this2.upgradeIfNeeded(_robeReactCommons.Cookies.get("language", "en_US.json")); }); } catch (error) { _robeReactCommons.Cookies.remove("language"); } } else { _Application2.default.loadI18n(this.props.language); this.setState({ upgrade: false }); } } } }]);return Application;}(_robeReactCommons.ShallowComponent);Application.propTypes = { language: _react2.default.PropTypes.string };Application.defaultProps = { language: _robeReactCommons.Cookies.get("language", "en_US.json") };exports.default = Application;
<template> <div id="city-list-wrapper"> <div class="page-header"> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="#"> Home </a> </li> <li class="breadcrumb-item active"> <a href="/admin/cities/"> Cities </a> </li> </ol> <div class="action-buttons"> <div class="search"> <div class="input-group mb-3"> <select id="searchFilter" v-model="searchFilter"> <option value="city_name"> City Name </option> <option value="city_code"> City Code </option> </select> <input type="text" class="form-control" placeholder="Search" aria-label="" v-model="searchQuery" aria-describedby="basic-addon2" @keyup="search" @mouseleave="search"/> </div> </div> </div> </div> <hr> <div class="content p-20"> <div class="d-flex justify-content-end"> <button class="btn btn-primary" @click.stop.prevent="addCity()"> Add City </button> </div> <loading-screen ref="loadingScreen"> <table class="table table-borderless"> <thead> <tr class="header"> <th> <a href="javascript:;" @click="sort('city_name')"> City <i class="fa" :class="{ 'fa-caret-up' : sortDirection, 'fa-caret-down' : !sortDirection }" v-if="currentSort == 'city_name'" ></i> </a> </th> <th> <a href="javascript:;" @click="sort('city_code')"> City Code <i class="fa" :class="{ 'fa-caret-up' : sortDirection, 'fa-caret-down' : !sortDirection }" v-if="currentSort == 'city_code'" ></i> </a> </th> <th></th> </tr> </thead> <tbody> <tr v-for="( value , key ) in cities.data" :key="key" class="pointer"> <td @click="goToCity( value.city_id )" class="align-middle"> {{value.city_name}} </td> <td @click="goToCity( value.city_id )" class="align-middle"> {{value.city_code}} </td> <td class="light-dark align-middle"> <div class="dropdown"> <button class="btn btn-default" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <i class="icon-menu"></i> </button> <ul class="dropdown-menu" aria-labelledby="dropdownMenu1"> <li class="dropdownList"> <a class="black" href="javascript:" @click="openCityDeletionModal( value.city_id )"> <i class="icon-trash"></i> Delete </a> </li> </ul> </div> </td> </tr> </tbody> </table> </loading-screen> <pagination :data="cities" @pagination-change-page="getResults" :limit="5"> </pagination> </div> <div id="deleteCityModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h4 class="modal-title"></h4> </div> <div class="modal-body"> <i class="icon-warning icon-2x" style="color: orange;"></i> Are you sure you want to delete city {{ city.city_name }}? </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" @click="triggerDeleteCity"> Delete </button> <button type="button" class="btn btn-default" data-dismiss="modal"> Cancel </button> </div> </div> </div> </div> </div> </template> <script> import LoadingScreen from 'vue-loading-screen'; import Pagination from 'laravel-vue-pagination'; export default { name: 'city-list', components: { LoadingScreen, Pagination, }, data() { return { cities: {}, city: { city_name: '', city_code: '', }, searchQuery : '', searchFilter: 'city_name', pageLimit: 10, currentSort: 'city_name', sortDirection: true, //true = ASC, false = DESC /**** pagination data ***/ endpoints: { cities: '/ajax/cities', city: '/ajax/city', } } }, methods: { async getResults(page) { if (typeof page === 'undefined') { page = 1; } await axios .get(`${this.endpoints.cities}?page=${page}`, { params : { searchQuery : this.searchQuery, searchFilter: this.searchFilter, pageLimit : this.pageLimit, currentSort : this.currentSort, sortDirection : this.sortDirection } }) .then(result => { let response = result.data; if (response.success) { this.cities = response.data.cities; } else { this.$notify.error({ title: 'Error', message: response.message, }); } }) .catch(error => { this.$notify.error({ title: 'Error', message: 'Something went wrong', }); }); }, citySelected(city_id) { this.city = _.find(this.cities.data, {city_id}); }, openCityDeletionModal(city_id) { this.citySelected(city_id); $('#deleteCityModal').modal(); }, triggerDeleteCity() { this.$refs.loadingScreen.load(this.deleteCity()); }, async deleteCity() { await axios .delete(this.endpoints.city, { params: { cid: this.city.city_id } }) .then(result => { let response = result.data; if (response.success) { _.remove(this.cities, { city_id: this.cities.city_id }); $('#deleteCityModal').modal('toggle'); this.$notify.success({ title: 'Deleted', message: 'City deleted', }); this.$refs.loadingScreen.load(this.getResults()); } else { this.$notify.error({ title: 'Error', message: response.message, }); } }) .catch(error => { this.$notify.error({ title: 'Error', message: 'Something went wrong', }); }); }, goToCity(city_id) { location.href = `/admin/cities/${city_id}`; }, addCity() { location.href = '/admin/cities/create'; }, resetCity() { this.city = { city_name: '', city_code: '', }; }, search() { this.$refs.loadingScreen.load(this.getResults()); }, sort(attribute) { this.currentSort = attribute; this.sortDirection = !this.sortDirection; this.$refs.loadingScreen.load(this.getResults()); }, }, mounted() { this.$refs.loadingScreen.load(this.getResults()); } } </script>
import { Link, NavLink } from "@remix-run/react"; type PaginationProps = { totalCount: number; pageName1: string; pageName2?: string; currentNumber?: number; }; export const Pagination = ({ totalCount, currentNumber, pageName1 }: PaginationProps) => { const PER_PAGE = 5; const LAST_PAGE = Math.ceil(totalCount / PER_PAGE); const range = (start: number, end: number) => [...Array(end - start + 1)].map((_, i) => start + i); if (pageName1 === "page") { return ( <ul className="pagenation flex items-center justify-center py-8"> {currentNumber! > 1 ? ( <Link to={`/page/${currentNumber! - 1}`}> <li className="flex h-[50px] w-[50px] items-center justify-center rounded-l-md border-[1px] border-r-0 border-[#3F3F45] text-lg duration-500 hover:bg-[#52525B]"> <img src="/icons/chevrons-left.svg" alt="previousPage" /> </li> </Link> ) : null} {range(1, Math.ceil(totalCount / PER_PAGE)).map((number, index) => ( <NavLink key={index} className={({ isActive }) => (isActive ? "active" : "")} to={`/page/${number}`} > <li className="flex h-[50px] w-[50px] items-center justify-center border-[1px] border-r-0 border-[#3F3F45] text-lg duration-500 hover:bg-[#52525B]"> {number} </li> </NavLink> ))} {currentNumber! !== LAST_PAGE ? ( <Link to={`/page/${currentNumber! + 1}`}> <li className="flex h-[50px] w-[50px] items-center justify-center rounded-r-md border-[1px] border-[#3F3F45] text-lg duration-500 hover:bg-[#52525B]"> <img src="/icons/chevrons-right.svg" alt="nextPage" /> </li> </Link> ) : null} </ul> ); } else { return ( <ul className="pagenation flex items-center justify-center py-8"> {currentNumber! > 1 ? ( <Link to={`/${pageName1}/${currentNumber! - 1}`}> <li className="flex h-[50px] w-[50px] items-center justify-center rounded-l-md border-[1px] border-r-0 border-[#3F3F45] text-lg duration-500 hover:bg-[#52525B]"> <img src="/icons/chevrons-left.svg" alt="previousPage" /> </li> </Link> ) : null} {range(1, Math.ceil(totalCount / PER_PAGE)).map((number, index) => ( <NavLink key={index} className={({ isActive }) => (isActive ? "active" : "")} to={`/${pageName1}/${number}`} > <li className="flex h-[50px] w-[50px] items-center justify-center border-[1px] border-r-0 border-[#3F3F45] text-lg duration-500 hover:bg-[#52525B]"> {number} </li> </NavLink> ))} {currentNumber! !== LAST_PAGE ? ( <Link to={`/${pageName1}/${currentNumber! + 1}`}> <li className="flex h-[50px] w-[50px] items-center justify-center rounded-r-md border-[1px] border-[#3F3F45] text-lg duration-500 hover:bg-[#52525B]"> <img src="/icons/chevrons-right.svg" alt="nextPage" /> </li> </Link> ) : null} </ul> ); } };
function [tc, dt] = event_fitted_fir(D, e_spec, bin_length, bin_no, opts) % method to compute fitted event time courses using FIR % FORMAT [tc, dt] = event_fitted_fir(D, e_spec, bin_length, bin_no, opts) % % (defaults are in []) % D - design % e_spec - 2 by N array specifying events to combine % with row 1 giving session number % and row 2 giving event number in session % This may in due course become an object type % bin_length - duration of time bin for FIR in seconds [TR] % bin_no - number of time bins [24 seconds / TR] % opts - structure, containing fields with options % 'single' - if field present, gives single FIR % This option removes any duration information, and % returns a simple per onset FIR model, where 1s in the % design matrix corresponds to 1 event at the given % offset. % 'percent' - if field present, gives results as percent % of block means % % Returns % tc - fitted event time course, averaged over events % dt - time units (seconds per row in tc = bin_length) % % Here, just some notes to explain 'single' and 'stacked' FIR models. Imagine % you have an event of duration 10 seconds, and you want an FIR model. To % make things simple, let's say the TR is 1 second, and that a standard % haemodynamic response function (HRF) lasts 24 seconds. % % In order to do the FIR model, there are two ways to go. The first is to % make an FIR model which estimates the signal (say) at every second (TR) % after event onset, where your model (Impulse Response) lasts long enough % to capture the event and its HRF response - say 10+24 = 24 seconds. This % is what I will call a 'single' FIR model. Another approach - and this is % what SPM does by default - is to think of the 10 second event as a (say) % 10 events one after the other, each starting 1 second after the last. % Here the FIR model estimates the effect of one of these 1 second events, % and the length of your FIR model (Impulse response) is just the length of % the HRF (24 seconds). This second approach I will call a 'stacked' FIR % model, because the events are stacking up one upon another. % % The single and stacked models are the same thing, if you specify a % duration of 0 for all your events. If your events have different % durations, it is very difficult to model the event response sensibly with % a single FIR, because, for the later FIR time bins, some events will have % stopped, and activity will be dropping to baseline, whereas other events % will still be continuing. In this case the stacked model can make sense, % as it just models longer events as having more (say) 1 second events. % However, if your events have non-zero durations, but each duration is the % same, then it may be that you do not want the stacked model, because your % interest is in the event time course across the whole event, rather than % some average response which pools together responses in the start middle % and end of your actual event response, as the stacked model does. In such % a case, you may want to switch to a single FIR model. % % There is an added problem for the stacked models, which is what to do % about the actual height of the regressors. That problem also requires % a bit of exposition which I hope to get down to in due course. % % $Id$ if nargin < 2 error('Need event specification'); end if nargin < 3 bin_length = []; end if nargin < 4 bin_no = []; end if nargin < 5 opts = []; end if ~is_fmri(D) | isempty(e_spec) tc = []; dt = []; return end if ~is_mars_estimated(D) error('Need a MarsBaR estimated design'); end if size(e_spec, 1) == 1, e_spec = e_spec'; end [SN EN] = deal(1, 2); e_s_l = size(e_spec, 2); if isempty(bin_length) bin_length = tr(D); end if isempty(bin_no) bin_no = 25/bin_length; end bin_no = round(bin_no); % build a simple FIR model subpartition (X) %------------------------------------------ dt = bf_dt(D); blk_rows = block_rows(D); oX = design_matrix(D); [n_t_p n_eff] = size(oX); y = summary_data(data(D)); y = apply_filter(D, y); n_rois = size(y, 2); tc = zeros(bin_no, n_rois); blk_mns = block_means(D); % for each session for s = 1:length(blk_rows) sess_events = e_spec(EN, e_spec(SN, :) == s); brX = blk_rows{s}; iX_out = []; X = []; n_s_e = length(sess_events); if isempty(n_s_e), break, end for ei = 1:n_s_e e = sess_events(ei); % New design bit for FIR model for this trial type Xn = event_x_fir(D, [s e]', bin_length, bin_no, opts); % Columns from original design that need to be removed iX_out = [iX_out event_cols(D, [s e])]; % Columns in new design matrix for basic FIR model iX_in(ei,:) = size(X, 2) + [1:size(Xn,2)]; X = [X Xn]; end % put into previous design for this session, and filter %------------------------------------------------------ iX0 = [1:n_eff]; iX0(iX_out) = []; aX = [X oX(brX,iX0)]; KX = apply_filter(D, aX, struct('sessions', s)); % Reestimate to get FIR time courses %------------------------------------------------------ xX = spm_sp('Set',KX); pX = spm_sp('x-',xX); betas = pX*y(brX,:); tc_s = betas(1:size(X,2), :); % Sum over events tc_s = reshape(tc_s, bin_no, n_s_e, n_rois); tc_s = squeeze(sum(tc_s, 2)); % Do percent if necessary if isfield(opts, 'percent'), tc_s = tc_s / blk_mns(s) * 100; end % Sum over sessions tc = tc + tc_s; end tc = tc / e_s_l; dt = bin_length;
#pragma once #include "Geometry/Vector3.h" class Filter { public: // Filter Interface virtual ~Filter() {} Filter(const Vector2f& radius) : radius(radius), invRadius(Vector2f(1 / radius.x(), 1 / radius.y())) {} virtual Float Evaluate(const Point2f& p) const = 0; // Filter Public Data const Vector2f radius, invRadius; }; class BoxFilter : public Filter { public: BoxFilter(const Vector2f& radius) : Filter(radius) {} Float Evaluate(const Point2f& p) const; }; class TriangleFilter : public Filter { public: TriangleFilter(const Vector2f& radius) : Filter(radius) { } Float Evaluate(const Point2f& p) const override; }; class GaussianFilter : public Filter { public: // GaussianFilter Public Methods GaussianFilter(const Vector2f& radius, Float alpha) : Filter(radius), alpha(alpha), expX(std::exp(-alpha * radius.x() * radius.x())), expY(std::exp(-alpha * radius.y() * radius.y())) {} Float Evaluate(const Point2f& p) const; private: // GaussianFilter Private Data const Float alpha; const Float expX, expY; // GaussianFilter Utility Functions Float Gaussian(Float d, Float expv) const { return std::max((Float)0, Float(std::exp(-alpha * d * d) - expv)); } };
--- title: "Your Favorite Movies: Analysis 1" subtitle: "An Example for 431 Project A" author: "Thomas E. Love, Ph.D." date: last-modified format: html: toc: true number-sections: true date-format: iso embed-resources: true code-overflow: wrap theme: materia --- # R Packages ```{r} #| message: false library(Hmisc) library(janitor) library(naniar) library(xfun) ## or, if you prefer use library(sessioninfo) library(googlesheets4) library(gt) library(gtExtras) library(mosaic) library(car) # for Box-Cox library(broom) library(patchwork) library(tidyverse) theme_set(theme_bw()) knitr::opts_chunk$set(comment = NA) ``` # Data Ingest ```{r} gs4_deauth() movies1 <- read_sheet("https://docs.google.com/spreadsheets/d/1qJnQWSjXyOXFZOO8VZixpgZWbraUW66SfP5hE5bKW4k") |> select(film_id, film, imdb_stars, imdb_pct10) |> mutate(film_id = as.character(film_id)) dim(movies1) ``` # CWRU Colors I decided to show off here and make use of some of the [2023 official CWRU colors](https://case.edu/brand/visual-identity/color). - Note that once I've named these in this way, based on their hexadecimal representations, I do not include quotes around them in ggplot-based plots. ```{r} ## CWRU colors cwru_blue <- '#003071' cwru_darkblue <- '#09143A' cwru_trueblue <- '#007AB8' cwru_lightblue <- '#A6D2E6' cwru_darkgray <- '#999999' cwru_lightgray <- '#D3D3D3' cwru_terracottaorange <- '#D63D1F' cwru_fallyellow <- '#E69E40' cwru_bluegreen <- '#377E72' cwru_violetpurple <- '#692C95' cwru_vividgreen <- '#61A530' ``` # An Important Message I wrote this document to help you get a feel for what we are looking for in Analysis 1 for Project A, and to make the scope of that work a bit clearer. Use **your own words**, not mine, in preparing your analytic work for Project A. Thanks. # Research Question For movies in our sample of "favorite movies", how strong is the relationship between the proprietary IMDB star rating and the percentage of IMDB reviewers who rated the movie 10? # Analysis ## Variables The two key variables we are studying in this analysis are quantitative, and we are interested in the association between them. Our **outcome** is `imdb_stars`, which is a proprietary rating available for each film on IMDB, identified on a scale from 1 (lowest) to 10 (highest). Our **predictor** is `imdb_pct10`, which is the percentage of user ratings, across the world, which rated the movie as a 10 on the 1-10 scale. Each is identified in R a quantitative variable, and neither display any missing values within our sample, so we have a complete set of `r nrow(movies1)` movies. ::: {.callout-tip} ## What to do about missing data In Project A, I would begin Analysis 1 by either filtering to complete cases or singly imputing any missing values. You should make a statement about what you are assuming about the missing data mechanism (either MCAR or MAR is reasonable - do not assume MNAR in Project A, no matter how compelling an argument might be) if you have missing values. If you don't have missing values in the variables used in this analysis, there is no reason to specify a missing data mechanism or do any filtering or imputation. ::: ## Summaries ### Graphical Summaries of the Outcome-Predictor Association Here is an initial plot of the data, before considering any transformations. ```{r} ggplot(movies1, aes(x = imdb_pct10, y = imdb_stars)) + geom_point(col = "black") + geom_smooth(method = "lm", col = cwru_trueblue, formula = y ~ x, se = TRUE) + geom_smooth(method = "loess", col = cwru_darkblue, formula = y ~ x, se = FALSE) + labs(x = "% of Ratings that are 10 out of 10", y = "IMDB Stars", title = "Favorite Movies Sample for Fall 2023", caption = str_glue("Pearson correlation = ", round_half_up(cor(movies1$imdb_pct10, movies1$imdb_stars), 3)), subtitle = "% of 10s and Stars seem to move together") ``` The association between "% of 10s" and "star rating" appears to have a positive slope, and be fairly strong (with a Pearson correlation of `r round_half_up(cor(movies1$imdb_pct10, movies1$imdb_stars), 3)`. The loess smooth suggests there is some potential for non-linearity, and some of the films (especially those with relatively low star ratings) are poorly fit by the simple linear regression model shown in red above. ::: {.callout-tip} ## What I would show In Project A, if you choose to use a transformation, I would show only two scatterplots in this section: the one of the raw outcome-predictor relationship, and the one with the transformation you choose to employ, rather than showing all possibilities as I have done here. In Project A, if you choose not to use a transformation, I would again show only two scatterplots: the one of the raw outcome-predictor relationship, and the one transformation that you felt was best among those you considered. Do not show us all of the plots you fit. ::: Given the curve in the loess smooth, I attempted several transformations of the outcome. The most appealing transformation I found was to take the square of the outcome, shown in the lower right of the four plots below. ```{r} p1 <- ggplot(movies1, aes(x = imdb_pct10, y = imdb_stars)) + geom_point() + geom_smooth(method = "lm", col = cwru_trueblue, formula = y ~ x, se = FALSE) + labs(title = "imdb_stars vs. imdb_pct10") p2 <- ggplot(movies1, aes(x = imdb_pct10, y = log(imdb_stars))) + geom_point() + geom_smooth(method = "lm", col = cwru_trueblue, formula = y ~ x, se = FALSE) + labs(title = "log(imdb_stars) vs. imdb_pct10") p3 <- ggplot(movies1, aes(x = imdb_pct10, y = 1/imdb_stars)) + geom_point() + geom_smooth(method = "lm", col = cwru_trueblue, formula = y ~ x, se = FALSE) + labs(title = "1/imdb_stars vs. imdb_pct10") p4 <- ggplot(movies1, aes(x = imdb_pct10, y = imdb_stars^2)) + geom_point() + geom_smooth(method = "lm", col = cwru_trueblue, formula = y ~ x, se = FALSE) + labs(title = "imdb_stars^2 vs. imdb_pct10") (p1 + p2) / (p3 + p4) ``` I decided that the value of the square transformation of the outcome was pretty minimal in this setting, relative to the increased difficulty it created in interpreting the results, so I opted not to make a transformation. ::: {.callout-tip} ## Should I use / show the Box-Cox plot? Basically, I would suggest that you use the Box-Cox plot to suggest a potential transformation of the outcome if you want to, but please do not feel obligated. If you use the plot to make your transformation decision, though, you should show it. ::: Note that the Box-Cox approach in this setting (as shown below) suggests trying the square of our outcome as a transformation, since the $\lambda$ value near 2 maximizes the log-likelihood. That doesn't mean I have to do it. ```{r} boxCox(movies1$imdb_stars ~ movies1$imdb_pct10) ``` ::: {.callout-tip} ## Should I consider transforming the predictor as well? Another approach I might have taken was to consider transforming both the outcome and the predictor. Were I to do that in Project A, I think I would restrict myself to using the same transformation on each variable, as shown below, but again, I would not display any of these transformations unless they were the transformation I chose to use, or they were the best transformation of the data (even though I decided not to use it) ::: Here are the plots I developed to consider a transformation of both the outcome and the predictor. ```{r} p5 <- ggplot(movies1, aes(x = imdb_pct10, y = imdb_stars)) + geom_point() + geom_smooth(method = "lm", col = cwru_terracottaorange, formula = y ~ x, se = FALSE) + labs(title = "imdb_stars vs. imdb_pct10") p6 <- ggplot(movies1, aes(x = log(imdb_pct10), y = log(imdb_stars))) + geom_point() + geom_smooth(method = "lm", col = cwru_terracottaorange, formula = y ~ x, se = FALSE) + labs(title = "log(imdb_stars) vs. log(imdb_pct10)") p7 <- ggplot(movies1, aes(x = 1/imdb_pct10, y = 1/imdb_stars)) + geom_point() + geom_smooth(method = "lm", col = cwru_terracottaorange, formula = y ~ x, se = FALSE) + labs(title = "1/imdb_stars vs. 1/imdb_pct10") p8 <- ggplot(movies1, aes(x = imdb_pct10^2, y = imdb_stars^2)) + geom_point() + geom_smooth(method = "lm", col = cwru_terracottaorange, formula = y ~ x, se = FALSE) + labs(title = "imdb_stars^2 vs. imdb_pct10^2") (p5 + p6) / (p7 + p8) ``` I see no real benefit from any of these transformations, so I will proceed to model the original outcome (`imdb_stars`) as a function of the original predictor (`imdb_pct10`.) ### Graphical Summaries of the Outcome's Distribution Here are some plots of the sample distribution of the outcome I have selected, which is, of course, the raw `imdb_stars` variable. I would include any plots you find helpful in assessing whether a Normal distribution is a reasonable approximation for your outcome. ::: {.callout-note} Had I decided to use a transformation of the outcome, I would instead present plots of the transformed values. ::: ```{r} ## Normal Q-Q plot p1 <- ggplot(movies1, aes(sample = imdb_stars)) + geom_qq(col = cwru_blue, size = 2) + geom_qq_line(col = cwru_trueblue) + theme(aspect.ratio = 1) + labs(title = "Normal Q-Q plot", y = "IMDB Stars Rating", x = "Expectation under Standard Normal") ## Histogram with Normal density superimposed p2 <- ggplot(movies1, aes(imdb_stars)) + geom_histogram(aes(y = after_stat(density)), bins = 7, fill = cwru_blue, col = cwru_lightgray) + stat_function(fun = dnorm, args = list(mean = mean(movies1$imdb_stars, na.rm = TRUE), sd = sd(movies1$imdb_stars, na.rm = TRUE)), col = cwru_darkgray, lwd = 1.5) + labs(title = "Histogram with Normal Density", x = "IMDB Stars Rating") ## Boxplot with notch and rug p3 <- ggplot(movies1, aes(x = imdb_stars, y = "")) + geom_boxplot(fill = cwru_blue, notch = TRUE, outlier.color = cwru_blue, outlier.size = 2) + stat_summary(fun = "mean", geom = "point", shape = 23, size = 3, fill = cwru_lightgray) + geom_rug(sides = "b") + labs(title = "Boxplot with Notch and Rug", x = "IMDB Stars Rating", y = "") p1 + (p2 / p3 + plot_layout(heights = c(4,1))) + plot_annotation(title = "IMDB Stars Rating", subtitle = str_glue("Our Favorite Movies: (n = ", nrow(movies1), ")"), caption = str_glue("IMDB Stars: Sample Size = ", nrow(movies1), ", Sample Median = ", round_half_up(median(movies1$imdb_stars),1), ", Mean = ", round_half_up(mean(movies1$imdb_stars),2), " and SD = ", round_half_up(sd(movies1$imdb_stars),2))) ``` Several movies are identified here as low outliers. Here's the set of films with the five lowest IMDB stars ratings in our sample. ```{r} movies1 |> arrange(imdb_stars) |> head(5) ``` ### Numerical Summaries ```{r} key1 <- bind_rows( favstats(~ imdb_stars, data = movies1), favstats(~ imdb_pct10, data = movies1)) |> mutate(variable = c("imdb_stars", "imdb_pct10")) |> relocate(variable) key1 |> gt() |> gt_theme_dark() ``` Again, I'll note that I have no missing values to deal with in this sample. ::: {.callout-note} Had I decided to use a transformation here, I would have summarized these transformed values, as well. ::: ## Approach ### Fitted Model Here is the main model I chose to fit, which is a linear regression predicting `imdb_stars` using `imdb_pct10` across our sample of movies. ```{r} m1 <- lm(imdb_stars ~ imdb_pct10, data = movies1) tidy(m1, conf.int = TRUE, conf.level = 0.90) |> gt() |> fmt_number(columns = where(is.numeric), decimals = 3) |> gt_theme_guardian() glance(m1) |> select(r.squared, sigma, nobs) |> gt() |> fmt_number(columns = where(is.numeric), decimals = 3) |> gt_theme_guardian() ``` The fitted model equation is `imdb_stars` = 6.411 + 0.066 `imdb_pct10`. We fit the model to all 201 observations, obtaining a model $R^2$ value of 46.2% and a residual standard deviation of 0.647, as compared to the initial standard deviation of the `imdb_stars` values, which was 0.880, from our earlier numerical summaries. ### Residual Analysis ```{r} par(mfrow=c(1,2)); plot(m1, which = 1:2); par(mfrow = c(1,1)) ``` The residual plots are pretty disappointing. We have clear evidence of non-Normality in the Q-Q plot of the residuals, and some suggestion of a downward curve as the fitted values increase. So we are likely to have substantial problems with the assumptions of both linearity and Normality if we decide to use this model. The three outlying movies identified in this analysis are the three films with the largest negative residuals from the model, and are listed below. ```{r} movies1_aug <- augment(m1, data = movies1) movies1_aug |> slice(163, 61, 115) |> select(film_id, film, imdb_stars, imdb_pct10, .fitted, .resid, .std.resid) |> gt() |> gt_theme_guardian() ``` These are also the three movies with the smallest number of `imdb_stars` in the initial data. ## Conclusions ::: {.callout-note} Here, I'm just repeating the [relevant instructions from the Project A Analysis page](https://thomaselove.github.io/431-projectA-2023/analyses.html#advice-on-conclusions). Doing this work is, of course, a big part of your job. ::: For Analysis 1, you’ll write two paragraphs. In the first paragraph, you should provide a clear restatement of your research question, followed by a clear and appropriate response to your research question, motivated by your results. Most of the time, one model won’t let you come to a strong conclusion about a question of interest, and it is your job to accurately present what information can be specified as a result of the model, without overstating your conclusions. Then, write a paragraph which summarizes the key limitations of your work in Analysis 1. - If you see problems with regression assumptions in your residual plot, that would be a good thing to talk about here, for instance. - Another issue that is worth discussing is your target population, and what evidence you can describe that might indicate whether your selected states are a representative sample of the US as a whole, or perhaps some particular part of the United States. - You should also provide at least one useful “next step” that you could take to improve this analysis (just saying “get more data” isn’t a sufficient next step.) # Session Information ```{r} session_info() ```
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package it.refill.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import java.util.List; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; /** * * @author agodino */ @Entity @Table(name = "sedi_formazione") @NamedQueries(value = { @NamedQuery(name = "s.Active", query = "SELECT s FROM SediFormazione s WHERE s.stato='A' OR s.stato='A1'"), @NamedQuery(name = "s.byProgetto", query = "SELECT s FROM SediFormazione s WHERE s.progetti=:progetto") }) @JsonIgnoreProperties(value = {"progetti"}) public class SediFormazione implements Serializable { @Id @Column(name = "idsedi") @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; @Column(name = "denominazione") private String denominazione; @Column(name = "indirizzo") private String indirizzo; @Column(name = "referente") private String referente; @Column(name = "telefono") private String telefono; @Column(name = "cellulare") private String cellulare; @Column(name = "email") private String email; @ManyToOne @JoinColumn(name = "comune") private Comuni comune; @OneToMany(mappedBy = "sede", fetch = FetchType.LAZY) List<ProgettiFormativi> progetti; @ManyToOne @JoinColumn(name = "idsoggetti_attuatori") SoggettiAttuatori soggetto; @Column(name = "stato") private String stato = "DV"; @Transient String descrizionestato; public SediFormazione() { } public SediFormazione(String denominazione, String indirizzo, String referente, String telefono, String cellulare, String email, Comuni comune) { this.denominazione = denominazione; this.indirizzo = indirizzo; this.referente = referente; this.telefono = telefono; this.cellulare = cellulare; this.email = email; this.comune = comune; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public SoggettiAttuatori getSoggetto() { return soggetto; } public void setSoggetto(SoggettiAttuatori soggetto) { this.soggetto = soggetto; } public String getDenominazione() { return denominazione; } public void setDenominazione(String denominazione) { this.denominazione = denominazione; } public String getIndirizzo() { return indirizzo; } public void setIndirizzo(String indirizzo) { this.indirizzo = indirizzo; } public String getReferente() { return referente; } public void setReferente(String referente) { this.referente = referente; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getCellulare() { return cellulare; } public void setCellulare(String cellulare) { this.cellulare = cellulare; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Comuni getComune() { return comune; } public void setComune(Comuni comune) { this.comune = comune; } public List<ProgettiFormativi> getProgetti() { return progetti; } public void setProgetti(List<ProgettiFormativi> progetti) { this.progetti = progetti; } public String getStato() { return stato; } public void setStato(String stato) { this.stato = stato; } public String getDescrizionestato() { if (this.stato == null) { return ""; } else if (this.stato.equals("A")) { return "ACCREDITATA"; } else if (this.stato.equals("A1")) { return "ACCREDITATA PER MASSIMO 8 ALLIEVI"; } else if (this.stato.equals("DV")) { return "DA VALIDARE"; } else if (this.stato.equals("R")) { return "RIGETTATA"; } return ""; } public void setDescrizionestato() { if (this.stato == null) { this.descrizionestato = ""; } else if (this.stato.equals("A")) { this.descrizionestato = "ACCREDITATA"; } else if (this.stato.equals("A1")) { this.descrizionestato = "ACCREDITATA PER MASSIMO 8 ALLIEVI"; } else if (this.stato.equals("DV")) { this.descrizionestato = "DA VALIDARE"; } else if (this.stato.equals("R")) { this.descrizionestato = "RIGETTATA"; } this.descrizionestato = ""; } @Override public int hashCode() { int hash = 7; hash = 41 * hash + Objects.hashCode(this.id); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SediFormazione other = (SediFormazione) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } @Override public String toString() { return "SediFormazione{" + "id=" + id + ", denominazione=" + denominazione + ", indirizzo=" + indirizzo + ", referente=" + referente + ", telefono=" + telefono + ", cellulare=" + cellulare + ", email=" + email + ", comune=" + comune + ", progetti=" + progetti + '}'; } }
import React from 'react' export interface UseLinkProps extends React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement> { bypass?: boolean; component?: React.ReactElement | React.ReactNode | any; componentProps?: any; } export function useLink({ bypass = false, component: CustomLink, componentProps, ...rest }: UseLinkProps, children) { if (bypass === true) { return children } if (CustomLink) { return ( <CustomLink {...rest} {...componentProps}> <a {...rest}> {children} </a> </CustomLink> ) } return ( <a {...rest}> {children} </a> ) }
from flask.cli import AppGroup from .users import seed_users, undo_users from .restaurants import seed_restaurants, undo_restaurants from .reviews import seed_reviews,undo_reviews # Creates a seed group to hold our commands # So we can type `flask seed --help` seed_commands = AppGroup('seed') # Creates the `flask seed all` command @seed_commands.command('all') def seed(): seed_users() seed_restaurants() seed_reviews() # Add other seed functions here # Creates the `flask seed undo` command @seed_commands.command('undo') def undo(): undo_users() undo_restaurants() undo_reviews() # Add other undo functions here
% $Header$ \documentclass[t,14pt,mathserif]{beamer} % This file is a solution template for: % - Talk at a conference/colloquium. % - Talk length is about 20min. % - Style is ornate. % Copyright 2004 by Till Tantau <[email protected]>. % % In principle, this file can be redistributed and/or modified under % the terms of the GNU Public License, version 2. % % However, this file is supposed to be a template to be modified % for your own needs. For this reason, if you use this file as a % template and not specifically distribute it as part of a another % package/program, I grant the extra permission to freely copy and % modify this file as you see fit and even to delete this copyright % notice. \input{style.tex} \usepackage[brazil]{babel} %\usepackage[english]{babel} \usepackage{graphicx} %Package para figuras % or whatever \usepackage[utf8]{inputenc} % or whatever \usepackage{times} \usepackage[T1]{fontenc} \usepackage{tabularx} \usepackage{multirow} \usepackage{adjustbox} \usepackage{array} %\usepackage[cmex10]{amsmath} % Or whatever. Note that the encoding and the font should match. If T1 % does not look nice, try deleting the line with the fontenc. \newcommand{\semitransp}[2][35]{\color{fg!#1}#2} \title[] % (optional, use only with long paper titles) {Ferramentas para Business Report \\ com Suporte à Linguagem XBRL - \\ Revisão Sistemática da Literatura} \subtitle {Vagner Clementino} %\author[] % (optional, use only with lots of authors) %{Vagner Clementino~\inst{1}} %\and S.~Another\inst{2}} % - Give the names in the same order as the appear in the paper. % - Use the \inst{?} command only if the authors have different % affiliation. \institute[] % (optional, but mostly needed) { % \inst{1}% Departamento de Ciência da Computação\\ Universidade Federal de Minas Gerais (UFMG)\\ Empirical Software Engineering - 2015\\ %\and %\inst{2}% %Department of Theoretical Philosophy\\ %University of Elsewhere } % - Use the \inst command only if there are several affiliations. % - Keep it simple, no one is interested in your street address. \date[2015/12/16] %o(optional, should be abbreviation of conference name) %{Software Quality and Measurement 2015-1 \\Prof. Eduardo Figueiredo} % - Either use conference name or its abbreviation. % - Not really informative to the audience, more for people (including % yourself) who are reading the slides online \subject{Software Engineer} % This is only inserted into the PDF information catalog. Can be left % out. % If you have a file called "university-logo-filename.xxx", where xxx % is a graphic format that can be processed by latex or pdflatex, % resp., then you can add a logo as follows: % \pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename} % \logo{\pgfuseimage{university-logo}} % Delete this, if you do not want the table of contents to pop up at % the beginning of each subsection: \AtBeginSubsection[] { \begin{frame}<beamer>{Outline}[allowframebreaks] \tableofcontents[currentsection,currentsubsection] \end{frame} } % If you wish to uncover everything in a step-wise fashion, uncomment % the following command: %\beamerdefaultoverlayspecification{<+->} \expandafter\def\expandafter\insertshorttitle\expandafter{% \insertshorttitle\hfill% \insertframenumber\,/\,\inserttotalframenumber} \setbeamertemplate{caption}[numbered] \setbeamertemplate{bibliography item}{\insertbiblabel} \begin{document} \begin{frame} \titlepage \end{frame} \begin{frame}{Outline} \tableofcontents % You might wish to add the option [pausesections] \end{frame} % Structuring a talk is a difficult task and the following structure % may not be suitable. Here are some rules that apply for this % solution: % - Exactly two or three sections (other than the summary). % - At *most* three subsections per section. % - Talk about 30s to 2min per frame. So there should be between about % 15 and 30 frames, all told. % - A conference audience is likely to know very little of what you % are going to talk about. So *simplify*! % - In a 20min talk, getting the main ideas across is hard % enough. Leave out details, even if it means being less precise than % you think necessary. % - If you omit details that are vital to the proof/implementation, % just say so once. Everybody will be happy with that. \section{Introdução} \begin{frame}{Introdução} \begin{itemize} \item Organizações estão se tornando cada vez mais transparentes com relação às suas operações \item Informações são disponibilizadas aos stakeholders através de Relatórios de Negócio (Business Report) \end{itemize} \end{frame} \begin{frame}{Introdução} \begin{itemize} \item No Brasil, o processo de transparência dos entes públicos ainda têm o que melhorar \item Escala Brasil Transparente\footnote{Disponível em \url{http://www.cgu.gov.br/assuntos/transparencia-publica/escala-brasil-transparente}} \end{itemize} \begin{figure}[htb] \centering \includegraphics[width=.357\textwidth]{../img/ebt.eps} \end{figure} \end{frame} \section{Background} \begin{frame}{eXtensible Business Report Language - XBRL} \begin{itemize} \item \alert{XBRL} é uma linguagem para divulgação e intercâmbio de informações financeiras baseada em XML, conforme Silva et. al.\cite{xbrl_conceitos_aplicacoes}. \item Baseada nos conceitos de \alert{Taxonomia} e \alert{Documentos de Instância} \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Taxonomia em XBRL} \begin{figure}[htb] \centering \includegraphics[width=.357\textwidth]{../img/taxonomia.eps} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Exemplo de Documento XBRL} \begin{figure}[htb] \centering \includegraphics[width=\textwidth]{../img/arquivo_xsd.eps} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Relatórios de Negócio (Business Report)} \begin{itemize} \item Segundo Lymer et al.\cite{lymer1999business} é o produto final da divulgação pública de dados operacionais e financeiros de uma organização \item Prestação regular de informações para os gestores para tomada de decisão. \item Exemplos \begin{itemize} \item Capital Requirements Directives (CRD) \item Matriz de Saldos Contábeis \item Gastos com pessoal do governo federal \end{itemize} \end{itemize} \end{frame} \section{Justificativa} \begin{frame}{Justificativa} \begin{itemize} \item Secretaria do Tesouro Nacional definiu o XBRL como padrão para o envio de relatórios de prestação de contas. \item Demanda por parte das organizações de referências de qualidade sobre o assunto de \textit{XBRL}. \item \textit{Subsidiar a tomada de decisão} sobre a aquisição ou desenvolvimento de ferramentas de suporte à XBRL. \end{itemize} \end{frame} \section{Objetivo} \begin{frame}{Objetivo do Trabalho} \begin{itemize} \item Revisar a bibliografia de Engenharia de Software a fim de descobrir ferramentas para Relatórios de Negócio com suporte à XBRL, suas funcionalidades e área de atuação. \end{itemize} \end{frame} \section{Metodologia} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Protocolo da Revisão} \begin{itemize} \item Definição de um Protocolo com diretrizes para SLR, conforme Kitchenham et. al. \cite{kitchenham2009systematic} \item Foram propostas Questões de Pesquisa a serem respondidas pela SLR \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Questões de Pesquisa} \begin{itemize} \item \textbf{$Q1$}: Quais são as ferramentas para Relatórios de Negócio que suportam a XBRL? \item \textbf{$Q2$}: Quais são as funcionalidades comuns as ferramentas que possibilitem a comparação entre elas? \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Questões de Pesquisa} \begin{itemize} \item \textbf{$Q3$}: Existem casos reais de utilização da ferramenta (Estudos de Casos, Whitepapers e etc)? \item \textbf{$Q4$}: Qual setor da economia (governos, medicina, setor financeiro) a ferramenta possui histórico de utilização? \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Critérios de Inclusão e Exclusão} \begin{itemize} \item Critérios de \textit{inclusão} \begin{itemize} \item Publicado a partir de 2008. \item Estar escrito em língua inglesa. \item Artigos de Conferência, journals e Whitepapers \item Dissertações ou Teses apenas se a ferramenta proposta tenha sido implementada e testada. \end{itemize} \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Critérios de Inclusão e Exclusão} \begin{itemize} \item Critérios de \textit{exclusão} \begin{itemize} \item Trabalhos escritos em outra língua que não a inglesa \item Documentos duplicados. \item Livros \item Dissertações ou Teses em que não há implementação da ferramenta. \item Literaturas escritas antes do ano de 2008 \end{itemize} \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Seleção dos Estudos Primários} \begin{itemize} \item Base de dados conforme Brereton et. al. \cite{Brereton2007571} com pequenas alterações \end{itemize} \begin{table}[ht] \centering \resizebox{6.9cm}{!}{% \begin{tabular}{|c|l|c|c|} \hline \textbf{\#} & \multicolumn{1}{c|}{\textbf{Base de Dados}} & \textbf{Total} & \textbf{Percentual} \\ \hline 1 & IEEE Xplore & 3 & 0,74\% \\ \hline 2 & ScienceDirect & 100 & 24,57\% \\ \hline 3 & Springer Link & 6 & 1,47\% \\ \hline 4 & ACM Digital Library & 97 & 23,83\% \\ \hline 5 & Web of Science & 9 & 2,21\% \\ \hline 6 & CiteSeer & 45 & 11,06\% \\ \hline 7 & Wiley Online Library & 54 & 13,27\% \\ \hline 8 & Scopus Elsevier & 8 & 1,97\% \\ \hline 9 & EL Compendex & 9 & 2,21\% \\ \hline 10 & Google scholar & 30 & 7,37\% \\ \hline 11 & XBRL Consortium & 46 & 11,30\% \\ \hline \multicolumn{2}{|c|}{Total} & 407 & 100,00\% \\ \hline \end{tabular} } \caption{Base de dados e número de artigos} \label{tab:base-dados} \end{table} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Sentença de Busca} \begin{itemize} \item ``XBRL \textbf{AND} Business Report \textbf{AND} tool'' \item Utilização de Tabela de Sinônimos \item Um total de 407 trabalhos ao final do processo \end{itemize} \begin{table}[ht] \centering \resizebox{\textwidth}{!}{% \begin{tabular}{|c|l|} \hline \multicolumn{2}{|c|}{\textbf{DICIONÁRIO DE SINÔNIMOS}} \\ \hline \textbf{Termo Original} & \multicolumn{1}{c|}{\textbf{Sinônimo}} \\ \hline XBRL & XML OR XHTML \\ \hline tool & sofwtare OR application OR product OR project OR development \\ \hline Business Report & Finantial Report OR Data Extraction \\ \hline \end{tabular} } \caption{Dicionário de Sinônimos} \label{tab:dicionario} \end{table} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Decisão de Inclusão e Exclusão} \begin{itemize} \item Remoção de artigos duplicados através da ferramenta \textit{JabRef}\footnote{\url{http://jabref.sourceforge.net/}}. \item Remoção de livros \item Análise do título removeu de 202 artigos \item Análise do resumo resultou em 59 trabalhos \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Análise da Qualidade dos Estudos} \begin{itemize} \item Critérios de avaliação da qualidade: \begin{itemize} \item Existe uma clara definição do estudo? \item Existe avaliação da ferramenta proposta bem como discussão dos resultados? \item O estudo é capaz de responder de forma clara pelo menos 50\% das questões de pesquisa? \end{itemize} \item Estudo foi incluído se a resposta fosse ``SIM'' para pelo menos duas destas questões. \item Através deste processo 30 trabalhos foram o excluídos e 29 estudos permaneceram \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Resumo do Processo de Seleção} \begin{figure}[htb] \centering \includegraphics[width=\textwidth]{../img/graph_fases.eps} \caption{Total de artigos em cada fase da SLR}%\label{fig:fases} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Extração dos Dados} \begin{itemize} \item Extração dos dados com base nos campos exibidos na Tabela \ref{tab:campos-form}. \item Validação única (sem pair-review) \end{itemize} \begin{table}[ht] \resizebox{9.5cm}{!}{% \begin{tabular}{|c|l|l|} \hline \textbf{\#} & \multicolumn{1}{c|}{\textbf{Atributo}} & \multicolumn{1}{c|}{\textbf{Descrição}} \\ \hline 01 & Identificador do Estudo & ID único para cada estudo, por exemplo IE01 \\ \hline 02 & Data de Extração & Data no qual a extração foi conduzida (DD/MM/YYYY) \\ \hline 03 & Nome do Extrator & Nome da pessoa responsável pela extração \\ \hline 04 & Autor & Autor do estudo \\ \hline 05 & Ano & Ano de publicação do estudo \\ \hline 06 & Título & Título do Estudo \\ \hline 07 & Tipo de Publicação & Artigo de journal ou conferência, dissertação, tese ou whitepaper \\ \hline 08 & Objetivo do Estudo & Quais foram os objetivos do estudo? \\ \hline 09 & Metodologia do Estudo & Quais foram as metodologias utilizadas no estudo? \\ \hline 10 & Descobertas e Resultados & Quais foram os resultados e descobertas do estudo \\ \hline 11 & Nome da Ferramenta & Nome da ferramenta \\ \hline 12 & Desenvolvedor & Pessoa ou empresa responsável pelo desenvolvimento \\ \hline 13 & URL & Site da internet da ferramenta \\ \hline 14 & Objetivo da Ferramenta & Qual funcionalidade principal da ferramenta \\ \hline 15 & Tipo de Arquitetura da Ferramenta & Cliente/Servidor ou Web ou desktop \\ \hline 16 & Tipo de Licença da Ferramenta & Software livre ou proprietário \\ \hline 17 & Avaliação da Ferramenta & Como a ferramenta foi avaliada \\ \hline 18 & Estudo de Casos & Existe algum estudo de caso ou aplicação real da ferramenta \\ \hline 19 & Ramo de Atuação & Qual setor da economia (governos, medicina, setor financeiro) a ferramenta já foi utilizada? \\ \hline \end{tabular} } \caption{Campos do formulário de extração de dados} \label{tab:campos-form} \end{table} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Sintetização dos Dados} \begin{itemize} \item Neste trabalho o foco é na classificação e sumarização das informações com o objetivo de responder as questões de pesquisa. \item Utilizado técnicas de \textit{Estatística Descritiva} conforme descrito por Wohlin et. al\cite{wohlin2012experimentation} \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Resultados} \begin{itemize} \item $Q1$: Quais são as ferramentas para Relatórios de Negócio que suportam a XBRL? \end{itemize} \begin{table}[htb] \resizebox{7.5cm}{!}{% \begin{tabular}{|l|l|l|l|} \hline \multicolumn{1}{|c|}{\textbf{Nome da Ferramenta}} & \multicolumn{1}{c|}{\textbf{Desenvolvedor}} & \multicolumn{1}{c|}{\textbf{Arquitetura}} & \multicolumn{1}{c|}{\textbf{Licença}} \\ \hline Abax XBRL & 2H Software & Framework & Paga \\ \hline ADDACTIS Pillar3 & ADDACTIS & Cliente/Servidor & Pago \\ \hline AGUILONIUS FactsConverter & Aguilonius & Plugin Excel & Pago \\ \hline AGUILONIUS XBRL FACTORY SE & Aguilonius & Cliente/Servidor & Paga \\ \hline AMANA SmartNotes & AMANA SmartNotes & Desktop & Paga \\ \hline Arele & XBRL community & Framework & Código Aberto \\ \hline Batavia XBRL & Batavia XBRL BV & Framework & Paga. \\ \hline Calcbench & Calcbench & Web application & Paga \\ \hline DataTracks & DataTracks & Cliente/Servidor & Paga \\ \hline FinDynamics & FinDynamics & Excel Plugin & Paga \\ \hline FUJITSU Software Interstage XWand & Fujitsu & Framework & Paga \\ \hline Invoke e-Filing for Banks & Invoke & Web Application & Paga \\ \hline IRIS Carbon & IRIS Business Services Limited & Cloud & Paga \\ \hline Litix & BR-AG & Mobile & Paga \\ \hline Oracle Hyperion Disclosure Management & ORACLE & Cliente/Servidor & Paga \\ \hline ParsePort XBRL Converter & ParsePort & Web application & Paga \\ \hline ParsePort & AltaNova & Cliente/Servidor & Paga \\ \hline RegulatorWorks & XBRLWorks & Cliente/Servidor & Paga \\ \hline Reporting Standard XBRL & Reporting Standard & Desktop & Paga \\ \hline Seahorse & CoreFiling & Cliente/Servidor & Paga \\ \hline Wdesk & Workiva & Web Application & Paga \\ \hline XBRL Processing Engine (XPE) & UBPartner & Framework & Paga \\ \hline xbrlOne Data Editor & Semansys Technologies & Desktop & Paga \\ \hline XKUBED & IPHIX & Cliente/Servidor & Paga \\ \hline Yeti & CoreFiling & Web application & Paga \\ \hline XBRL Database Cluster & Argyris Argyrou , Andriy Andreev & Cliente/Servidor & N/A \\ \hline XBRL Audit Assistant & Efrim Boritz \& Won Gyun No & Desktop & N/A \\ \hline \end{tabular} } \caption{Ferramentas com Suporte à XBRL} \label{tab:ferramentas} \end{table} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{$Q2$: Resultados} \begin{itemize} \item {$Q2$: Quais são as funcionalidades comuns as ferramentas que possibilitem a comparação entre elas?} \end{itemize} \begin{figure}[htb] \centering \includegraphics[width=.85\textwidth]{../img/graph_funcionalidades.eps} \caption{Frequência das funcionalidades das ferramentas} \label{fig:funcionalidades} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Resultados} \begin{itemize} \item $Q3$: Existem casos reais de utilização da ferramenta (Estudos de Casos, Whitepapers e etc)? \begin{itemize} \item Não foi possível verificar nos estudos a avaliação prática das ferramentas. \item Há menções de clientes e de nichos de mercado no qual o sistema está inserido \item Não foi possível responder $Q3$ \end{itemize} \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Resultados} \begin{itemize} \item $Q4$: Qual setor da economia (governos, medicina, setor financeiro) a ferramenta possui histórico de utilização? \end{itemize} \begin{figure}[htb] \centering \includegraphics[width=.9\textwidth]{../img/graph_setores.eps} \caption{Setores de Atuação das Ferramentas} \label{fig:setores} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Ameaças à Validade} \begin{itemize} \item Construção \begin{itemize} \item Definição das Questões de Pesquisa \end{itemize} \item Interna \begin{itemize} \item Inexistência de Pair Review \item Processo de Seleção \end{itemize} \item Externa \begin{itemize} \item Utilização de Gray Literature \end{itemize} \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Conclusão} \begin{itemize} \item Revisão Sistemática da Literatura conforme proposto por Keele et al. \cite{keele2007guidelines} \item SLR iniciou com 407 trabalhos que após seleção resultou em 29 estudos. \item A partir destes estudos foi possível responder três das quatros questões de pesquisa propostas. \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Conclusão} \begin{itemize} \item A maioria das ferramentas que dão suporte para funcionalidades mais básicas (criação, visualização e validação de objetos de instância) \item Predonimância nos setores financeiros e bancários \item Possibilidade de Crescimento no setor público. \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Lições Aprendidas} \begin{itemize} \item Estudo piloto pode ajudar na definição das questões de pesquisa \item Processo de seleção de estudo primários pode ser melhorado \item Oportunidade para o desenvolvimento de ferramentas de suporte as SLR's \end{itemize} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}{Dúvidas} \begin{figure}[htb] \centering \includegraphics[width=.5\textwidth]{../img/questions.jpg} \end{figure} \end{frame} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \begin{frame}[allowframebreaks] \frametitle{Referências} \bibliographystyle{IEEEtranS} \bibliography{IEEEfull,bibliografia} \end{frame} \end{document}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <script src="https://unpkg.com/[email protected]"></script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-uWxY/CJNBR+1zjPWmfnSnVxwRheevXITnMqoEIeG1LJrdI0GlVs/9cVSyPYXdcSF" crossorigin="anonymous" > <style> #app { margin: 60px; display: flex; } #app > div { margin-right: 20px; } .app__buttons { display: flex; flex-direction: column; } .form-control { width: 300px; margin-bottom: 20px; } .btn { margin-bottom: 20px; } .alert { width: 300px; } </style> <title>Getters. Map-helpers</title> </head> <body> <div id="app"> <div> Имя <input class="form-control" v-model="name" /> Фамилия <input class="form-control" v-model="surname" /> Возраст <input class="form-control" v-model="age" /> <div class="app__buttons"> <button @click="onAddUser" class="btn btn-success" > Добавить пользователя </button> <button @click="onOlderThen30" class="btn btn-success" > Пользователи старше 30 </button> <button @click="onUsersByAge" class="btn btn-success" > Пользователи возраста... </button> </div> </div> <div> <div v-for="(item, index) in users" class="alert alert-success" > {{ item.name }} {{ item.surname }}. Age: {{ item.age }} </div> </div> </div> <script> const store = new Vuex.Store({ state: { users: [ { name: 'Felippe', surname: 'Massa', age: 40 }, { name: 'Fernando', surname: 'Alonso', age: 40 }, { name: 'Max', surname: 'Verstappen', age: 24 }, { name: 'Mick', surname: 'Schumacher', age: 22 }, { name: 'Lando', surname: 'Norris', age: 22 }, { name: 'George', surname: 'Russell', age: 23 }, ], }, actions: { addUser({ commit }, payload) { commit('addUser', payload); }, }, mutations: { addUser(state, newUser) { state.users.push(newUser); }, }, getters: { getUserOlderThen30: (state) => state.users.filter(({ age }) => age > 30), getUsersByAge: (state) => (currentAge) => state.users.filter(({ age }) => age === currentAge), }, }); const app = new Vue({ el: '#app', store, data() { return { name: '', surname: '', age: '', }; }, methods: { ...Vuex.mapActions([ 'addUser' ]), onAddUser() { this.addUser({ ...this.$data }); this.name = ''; this.surname = ''; this.age = ''; }, onOlderThen30() { const olderThen30Users = this.getUserOlderThen30; const text = this.getUsersText(olderThen30Users); alert(text); }, onUsersByAge() { const usersByAge = this.getUsersByAge(Number(this.age)); const text = this.getUsersText(usersByAge); alert(text); }, getUsersText(users) { return users.map((user) => Object.values(user).join(' ')).join('. '); }, }, computed: { ...Vuex.mapState([ 'users' ]), ...Vuex.mapGetters([ 'getUserOlderThen30', 'getUsersByAge' ]), }, }); </script> </body> </html>
import { Box, Stack, Typography } from '@mui/material' import React from 'react' import { motion } from 'framer-motion' import ChevronsDown from '../../../../public/vectors/chevrons-down.svg' import { scrollToTarget } from '../../../helpers/scrollToTarget' import { SlideFromLeftAppearMotion } from '../../common/motion/DefaultAppearMotion' interface IProps { h1: string; } const sxMoreButton = { cursor: 'pointer', width: 'fit-content', '&:hover': { '& > p::before': { transform: 'translateX(100%)' } } } const sxMoreButtonText = { color: 'secondary.main', position: 'relative', overflow: 'hidden', '&::before': { content: '""', position: 'absolute', height: 'calc(100% - 2px)', width: '100%', borderBottom: '2px solid var(--secondary)', transition: '.3s ease all', left: '-100%', } } export const Text = ({ h1 }: IProps) => { return ( <Box sx={{ maxWidth: { xs: '100%', md: '50ch'}, pt: { xs: 5, md: 10 }, mb: 6 }}> <SlideFromLeftAppearMotion delay={.4}> <Typography fontSize={{ xs: 16, sm: 19, md: 24 }} fontWeight={600} sx={{ color: 'secondary.main' }}>Gaferbras</Typography> </SlideFromLeftAppearMotion> <SlideFromLeftAppearMotion delay={.8}> <Typography variant='h1' sx={{ color: 'primary.main', mb: 6 }} dangerouslySetInnerHTML={{ __html: h1 }} /> </SlideFromLeftAppearMotion> <SlideFromLeftAppearMotion delay={1.2}> <Stack direction='row' alignItems='center' spacing={1} sx={sxMoreButton} onClick={() => scrollToTarget('serviços')}> <ChevronsDown /*className='float' */ /> <Typography fontSize={14} fontWeight={600} sx={sxMoreButtonText}>Conheça mais</Typography> </Stack> </SlideFromLeftAppearMotion> </Box> ) }
import { Controller, Get } from '@nestjs/common'; import { DataService } from './data.service'; import { AuthService } from "../auth/auth.service"; import {AuthenticatedUser, Roles, Public, Resource, Scopes} from 'nest-keycloak-connect'; @Controller('data') @Resource('data') export class DataController { constructor( private readonly authService: AuthService, private readonly dataService: DataService ) {} @Get('public') @Public() @Scopes('view') getPublic() { return `${this.authService.getHello()} from public`; } @Get('user') @Roles({ roles: ['user'] }) getUser(): string { return `${this.authService.getHello()} from user`; } @Get('admin') @Roles({ roles: ['admin'] }) getAdmin(): string { return `${this.authService.getHello()} from admin`; } @Get('auth') getAuth(): string { return `${this.authService.getHello()} from all`; } }
import React, { useState, useEffect } from "react"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import NavbarFluid from "./components/NavbarFluid/NavbarFluid"; import Navbar from "./components/Navbar/Navbar"; import content from "./lang/lang"; import Envelope from "./components/Envelope/Envelope"; import Comments from "./components/Comments/Comments"; import Bell from "./components/Bell/Bell"; import Events from "./components/Events/Events"; import Video from "./components/Video/Video"; import Music from "./components/Music/Music"; import Error from "./components/404/Error"; import Login from "./components/login/Login"; import Private from "./components/private/Private"; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import Home from "./components/Home/Home"; import Cloud from "./components/SidebarComponents/Cloud.jsx" const App = () => { const [langs, setLangs] = useState("en"); const [auth, setAuth] = useState(false); const user = { username: "1", password: "2", }; const useAuth = (username, password, check) => { if (check.login && check.password) { toast.error('please fill input form', { position: "top-right", autoClose: 1000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) } else { } if (user.username === username && user.password === password) { setAuth(true); console.log(auth); toast.success('logined', { position: "top-right", autoClose: 1000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) } else { setAuth(false); console.log(auth); toast.error('error', { position: "top-right", autoClose: 1000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }) } console.log('isworking'); }; return ( <> <BrowserRouter> <ToastContainer /> <NavbarFluid lang={content[langs]} setLangs={setLangs} auth={auth} isAuth={setAuth} /> <Navbar lang={content[langs]} setLangs={setLangs} auth={auth} isAuth={setAuth} /> <main> <Routes> <Route path="/" element={<Private isAuth={auth} auth={useAuth} />}> <Route path="/" element={<Home/>}/> <Route path="/Envelope" element={<Envelope lang={content[langs]} />} /> <Route path="/comments" element={<Comments lang={content[langs]} />} /> <Route path="/bell" element={<Bell lang={content[langs]} />} /> <Route path="/events" element={<Events lang={content[langs]} />} /> <Route path="/video" element={<Video lang={content[langs]} />} /> <Route path="/music" element={<Music lang={content[langs]} />} /> <Route path="/login" element={<Login auth={useAuth} lang={content[langs]} setLangs={setLangs} />} /> <Route path="/" element={<Home/>}> <Route path="/cloud" element={<Cloud/>}></Route> </Route> </Route> <Route path="*" element={<Error lang={content[langs]} />} /> </Routes> </main> </BrowserRouter> </> ); }; export default App;
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.eShopWeb.ApplicationCore.Constants; using Microsoft.eShopWeb.ApplicationCore.Interfaces; using Microsoft.IdentityModel.Tokens; namespace Microsoft.eShopWeb.Infrastructure.Identity; public class IdentityTokenClaimService : ITokenClaimsService { private readonly UserManager<ApplicationUser> _userManager; public IdentityTokenClaimService(UserManager<ApplicationUser> userManager) { _userManager = userManager; } public async Task<string> GetTokenAsync(string userName) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(AuthorizationConstants.JWT_SECRET_KEY); var user = await _userManager.FindByNameAsync(userName); var roles = await _userManager.GetRolesAsync(user); var claims = new List<Claim> { new Claim(ClaimTypes.Name, userName) }; foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims.ToArray()), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } }
// Copyright 2023 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_DEVICES_POWER_DRIVERS_FUSB302_TYPEC_PORT_STATE_MACHINE_H_ #define SRC_DEVICES_POWER_DRIVERS_FUSB302_TYPEC_PORT_STATE_MACHINE_H_ #include <lib/inspect/cpp/vmo/types.h> #include <cstdint> #include "src/devices/power/drivers/fusb302/state-machine-base.h" namespace fusb302 { class Fusb302; // Changes signaled to the Type C Port Config Channel state machine. enum class TypeCPortInput : uint32_t { kPortStateChanged = 1, kTimerFired = 2, }; // States for the Type C Port Config Channel state machine. // // The states are defined in Section 4.5.2 "CC Functional and Behavioral // Requirements" in the USB Type C spec. The state values match the // corresponding sub-section numbers in Section 4.5.2.2 "Connection State // Machine Requirements". enum class TypeCPortState : uint32_t { kSinkUnattached = 3, // Unattached.SNK kSinkAttached = 5, // Attached.SNK kSourceAttached = 9, // Attached.SRC }; // Implements the Type C Port Config Channel state machine. // // typec2.2 4.5.2 "CC Functional and Behavioral Requirements" class TypeCPortStateMachine : public StateMachineBase<TypeCPortStateMachine, TypeCPortState, TypeCPortInput> { public: // `device` must remain alive throughout the new instance's lifetime. explicit TypeCPortStateMachine(Fusb302& device, inspect::Node inspect_root) : StateMachineBase(TypeCPortState::kSinkUnattached, std::move(inspect_root), "Type C Port"), device_(device) {} TypeCPortStateMachine(const TypeCPortStateMachine&) = delete; TypeCPortStateMachine& operator=(const TypeCPortStateMachine&) = delete; ~TypeCPortStateMachine() override = default; const char* StateToString(TypeCPortState state) const override; protected: void EnterState(TypeCPortState state) override; void ExitState(TypeCPortState state) override; TypeCPortState NextState(TypeCPortInput input, TypeCPortState current_state) override; private: // The referenced instance is guaranteed to outlive this instance, because // it's owned by this instance's owner (Fusb302). Fusb302& device_; }; } // namespace fusb302 #endif // SRC_DEVICES_POWER_DRIVERS_FUSB302_TYPEC_PORT_STATE_MACHINE_H_
import Foundation protocol APIManagerProtocol { func perform(_ request: RequestProtocol, authToken: String) async throws -> Data } class APIManager: APIManagerProtocol { private let urlSession: URLSession init(urlSession: URLSession = URLSession.shared) { self.urlSession = urlSession } func perform(_ request: RequestProtocol, authToken: String = "") async throws -> Data { let urlRequest = try request.createURLRequest(authToken: authToken) let (data, response) = try await urlSession.data(for: urlRequest) guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw NetworkError.invalidServerResponse } return data } }
/* See the LICENSE.txt file for this sample’s licensing information. Abstract: The supply gauge. */ import SwiftUI import BackyardBirdsData public struct BackyardSupplyGauge: View { var backyard: Backyard var supplies: BackyardSupplies @Environment(\.layoutDirection) private var originalLayoutDirection public init(backyard: Backyard, supplies: BackyardSupplies) { self.backyard = backyard self.supplies = supplies } public var body: some View { Gauge(value: remainingDuration, in: 0...supplies.totalDuration) { gaugeLabel .environment(\.layoutDirection, originalLayoutDirection) } .gaugeStyle(.accessoryCircularCapacity) .tint(gaugeTint) .environment(\.layoutDirection, originalLayoutDirection.opposite) } @ViewBuilder var gaugeLabel: some View { switch supplies { case .food: if let birdFood = backyard.birdFood { birdFood.image .scaledToFit() .padding(-4) .transition(.scale(scale: 0.5).combined(with: .opacity)) .id(birdFood.id) } else { Image(systemName: "questionmark") } case .water: Image(systemName: "drop.fill") .foregroundStyle(.linearGradient(colors: [.mint, .cyan], startPoint: .top, endPoint: .bottom)) .imageScale(.small) } } var gaugeTint: AnyShapeStyle { switch supplies { case .food: AnyShapeStyle(Gradient(colors: [.orange, .pink])) case .water: AnyShapeStyle(Gradient(colors: [.cyan, .blue])) } } var remainingDuration: TimeInterval { max(Date.now.distance(to: backyard.expectedEmptyDate(for: supplies)), 0) } } private extension LayoutDirection { var opposite: LayoutDirection { self == .leftToRight ? .rightToLeft : .leftToRight } }
import { Connection } from "typeorm"; import createConnection from "../../../../database"; import request from "supertest"; import { app } from "../../../../app"; import { v4 as uuidV4 } from "uuid"; import { hash } from "bcryptjs"; import { response } from "express"; let connection: Connection; describe("Show user profile controller", () => { beforeAll(async () => { connection = await createConnection(); await connection.runMigrations(); }); afterAll(async () => { await connection.dropDatabase(); await connection.close(); }); it("Should be able to get user", async () => { await request(app).post("/api/v1/users").send({ name: "User 1", email: "[email protected]", password: "12345" }); await request(app).post("/api/v1/users").send({ name: "User 2", email: "[email protected]", password: "123456" }); const responseToken = await request(app).post("/api/v1/sessions").send({ email: "[email protected]", password: "12345" }); const { token } = responseToken.body; const response = await request(app).get("/api/v1/profile").send().set({ Authorization: `Bearer ${token}` }); expect(response.status).toBe(200); expect(response.body.name).toBe("User 1"); }); it("Should not be able to get user not existent", async () => { const response = await request(app).get("/api/v1/profile").send().set({ Authorization: `Bearer 123123` }); expect(response.status).toBe(401); }); });
// Copyright 2021 ByteDance Inc. // // 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 metainfo_test import ( "context" "fmt" "testing" "github.com/bytedance/gopkg/cloud/metainfo" ) func TestWithValue(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" ctx = metainfo.WithValue(ctx, k, v) assert(t, ctx != nil) x, ok := metainfo.GetValue(ctx, k) assert(t, ok) assert(t, x == v) } func TestWithValues(t *testing.T) { ctx := context.Background() k, v := "Key-0", "Value-0" ctx = metainfo.WithValue(ctx, k, v) kvs := []string{"Key-1", "Value-1", "Key-2", "Value-2", "Key-3", "Value-3"} ctx = metainfo.WithValues(ctx, kvs...) assert(t, ctx != nil) for i := 0; i <= 3; i++ { x, ok := metainfo.GetValue(ctx, fmt.Sprintf("Key-%d", i)) assert(t, ok) assert(t, x == fmt.Sprintf("Value-%d", i)) } } func TestWithPersistValues(t *testing.T) { ctx := context.Background() k, v := "Key-0", "Value-0" ctx = metainfo.WithPersistentValue(ctx, k, v) kvs := []string{"Key-1", "Value-1", "Key-2", "Value-2", "Key-3", "Value-3"} ctx = metainfo.WithPersistentValues(ctx, kvs...) assert(t, ctx != nil) for i := 0; i <= 3; i++ { x, ok := metainfo.GetPersistentValue(ctx, fmt.Sprintf("Key-%d", i)) assert(t, ok) assert(t, x == fmt.Sprintf("Value-%d", i)) } } func TestWithEmpty(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" ctx = metainfo.WithValue(ctx, k, "") assert(t, ctx != nil) _, ok := metainfo.GetValue(ctx, k) assert(t, !ok) ctx = metainfo.WithValue(ctx, "", v) assert(t, ctx != nil) _, ok = metainfo.GetValue(ctx, "") assert(t, !ok) } func TestDelValue(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" ctx = metainfo.WithValue(ctx, k, v) assert(t, ctx != nil) x, ok := metainfo.GetValue(ctx, k) assert(t, ok) assert(t, x == v) ctx = metainfo.DelValue(ctx, k) assert(t, ctx != nil) x, ok = metainfo.GetValue(ctx, k) assert(t, !ok) assert(t, metainfo.DelValue(ctx, "") == ctx) } func TestGetAll(t *testing.T) { ctx := context.Background() ss := []string{"1", "2", "3"} for _, k := range ss { ctx = metainfo.WithValue(ctx, "key"+k, "val"+k) } m := metainfo.GetAllValues(ctx) assert(t, m != nil) assert(t, len(m) == len(ss)) for _, k := range ss { assert(t, m["key"+k] == "val"+k) } } func TestRangeValues(t *testing.T) { ctx := context.Background() ss := []string{"1", "2", "3"} for _, k := range ss { ctx = metainfo.WithValue(ctx, "key"+k, "val"+k) } m := make(map[string]string, 3) f := func(k, v string) bool { m[k] = v return true } metainfo.RangeValues(ctx, f) assert(t, m != nil) assert(t, len(m) == len(ss)) for _, k := range ss { assert(t, m["key"+k] == "val"+k) } } func TestGetAll2(t *testing.T) { ctx := context.Background() ss := []string{"1", "2", "3"} for _, k := range ss { ctx = metainfo.WithValue(ctx, "key"+k, "val"+k) } ctx = metainfo.DelValue(ctx, "key2") m := metainfo.GetAllValues(ctx) assert(t, m != nil) assert(t, len(m) == len(ss)-1) for _, k := range ss { if k == "2" { _, exist := m["key"+k] assert(t, !exist) } else { assert(t, m["key"+k] == "val"+k) } } } func TestWithPersistentValue(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" ctx = metainfo.WithPersistentValue(ctx, k, v) assert(t, ctx != nil) x, ok := metainfo.GetPersistentValue(ctx, k) assert(t, ok) assert(t, x == v) } func TestWithPersistentEmpty(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" ctx = metainfo.WithPersistentValue(ctx, k, "") assert(t, ctx != nil) _, ok := metainfo.GetPersistentValue(ctx, k) assert(t, !ok) ctx = metainfo.WithPersistentValue(ctx, "", v) assert(t, ctx != nil) _, ok = metainfo.GetPersistentValue(ctx, "") assert(t, !ok) } func TestWithPersistentValues(t *testing.T) { ctx := context.Background() kvs := []string{"Key-1", "Value-1", "Key-2", "Value-2", "Key-3", "Value-3"} ctx = metainfo.WithPersistentValues(ctx, kvs...) assert(t, ctx != nil) for i := 1; i <= 3; i++ { x, ok := metainfo.GetPersistentValue(ctx, fmt.Sprintf("Key-%d", i)) assert(t, ok) assert(t, x == fmt.Sprintf("Value-%d", i)) } } func TestWithPersistentValuesEmpty(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" kvs := []string{"", v, k, ""} ctx = metainfo.WithPersistentValues(ctx, kvs...) assert(t, ctx != nil) _, ok := metainfo.GetPersistentValue(ctx, k) assert(t, !ok) _, ok = metainfo.GetPersistentValue(ctx, "") assert(t, !ok) } func TestWithPersistentValuesRepeat(t *testing.T) { ctx := context.Background() kvs := []string{"Key", "Value-1", "Key", "Value-2", "Key", "Value-3"} ctx = metainfo.WithPersistentValues(ctx, kvs...) assert(t, ctx != nil) x, ok := metainfo.GetPersistentValue(ctx, "Key") assert(t, ok) assert(t, x == "Value-3") } func TestDelPersistentValue(t *testing.T) { ctx := context.Background() k, v := "Key", "Value" ctx = metainfo.WithPersistentValue(ctx, k, v) assert(t, ctx != nil) x, ok := metainfo.GetPersistentValue(ctx, k) assert(t, ok) assert(t, x == v) ctx = metainfo.DelPersistentValue(ctx, k) assert(t, ctx != nil) x, ok = metainfo.GetPersistentValue(ctx, k) assert(t, !ok) assert(t, metainfo.DelPersistentValue(ctx, "") == ctx) } func TestGetAllPersistent(t *testing.T) { ctx := context.Background() ss := []string{"1", "2", "3"} for _, k := range ss { ctx = metainfo.WithPersistentValue(ctx, "key"+k, "val"+k) } m := metainfo.GetAllPersistentValues(ctx) assert(t, m != nil) assert(t, len(m) == len(ss)) for _, k := range ss { assert(t, m["key"+k] == "val"+k) } } func TestRangePersistent(t *testing.T) { ctx := context.Background() ss := []string{"1", "2", "3"} for _, k := range ss { ctx = metainfo.WithPersistentValue(ctx, "key"+k, "val"+k) } m := make(map[string]string, 3) f := func(k, v string) bool { m[k] = v return true } metainfo.RangePersistentValues(ctx, f) assert(t, m != nil) assert(t, len(m) == len(ss)) for _, k := range ss { assert(t, m["key"+k] == "val"+k) } } func TestGetAllPersistent2(t *testing.T) { ctx := context.Background() ss := []string{"1", "2", "3"} for _, k := range ss { ctx = metainfo.WithPersistentValue(ctx, "key"+k, "val"+k) } ctx = metainfo.DelPersistentValue(ctx, "key2") m := metainfo.GetAllPersistentValues(ctx) assert(t, m != nil) assert(t, len(m) == len(ss)-1) for _, k := range ss { if k == "2" { _, exist := m["key"+k] assert(t, !exist) } else { assert(t, m["key"+k] == "val"+k) } } } func TestNilSafty(t *testing.T) { assert(t, metainfo.TransferForward(nil) == nil) _, tOK := metainfo.GetValue(nil, "any") assert(t, !tOK) assert(t, metainfo.GetAllValues(nil) == nil) assert(t, metainfo.WithValue(nil, "any", "any") == nil) assert(t, metainfo.DelValue(nil, "any") == nil) _, pOK := metainfo.GetPersistentValue(nil, "any") assert(t, !pOK) assert(t, metainfo.GetAllPersistentValues(nil) == nil) assert(t, metainfo.WithPersistentValue(nil, "any", "any") == nil) assert(t, metainfo.DelPersistentValue(nil, "any") == nil) } func TestTransitAndPersistent(t *testing.T) { ctx := context.Background() ctx = metainfo.WithValue(ctx, "A", "a") ctx = metainfo.WithPersistentValue(ctx, "A", "b") x, xOK := metainfo.GetValue(ctx, "A") y, yOK := metainfo.GetPersistentValue(ctx, "A") assert(t, xOK) assert(t, yOK) assert(t, x == "a") assert(t, y == "b") _, uOK := metainfo.GetValue(ctx, "B") _, vOK := metainfo.GetPersistentValue(ctx, "B") assert(t, !uOK) assert(t, !vOK) ctx = metainfo.DelValue(ctx, "A") _, pOK := metainfo.GetValue(ctx, "A") q, qOK := metainfo.GetPersistentValue(ctx, "A") assert(t, !pOK) assert(t, qOK) assert(t, q == "b") } func TestTransferForward(t *testing.T) { ctx := context.Background() ctx = metainfo.WithValue(ctx, "A", "t") ctx = metainfo.WithPersistentValue(ctx, "A", "p") ctx = metainfo.WithValue(ctx, "A", "ta") ctx = metainfo.WithPersistentValue(ctx, "A", "pa") ctx = metainfo.TransferForward(ctx) assert(t, ctx != nil) x, xOK := metainfo.GetValue(ctx, "A") y, yOK := metainfo.GetPersistentValue(ctx, "A") assert(t, xOK) assert(t, yOK) assert(t, x == "ta") assert(t, y == "pa") ctx = metainfo.TransferForward(ctx) assert(t, ctx != nil) x, xOK = metainfo.GetValue(ctx, "A") y, yOK = metainfo.GetPersistentValue(ctx, "A") assert(t, !xOK) assert(t, yOK) assert(t, y == "pa") ctx = metainfo.WithValue(ctx, "B", "tb") ctx = metainfo.TransferForward(ctx) assert(t, ctx != nil) y, yOK = metainfo.GetPersistentValue(ctx, "A") z, zOK := metainfo.GetValue(ctx, "B") assert(t, yOK) assert(t, y == "pa") assert(t, zOK) assert(t, z == "tb") } func TestOverride(t *testing.T) { ctx := context.Background() ctx = metainfo.WithValue(ctx, "base", "base") ctx = metainfo.WithValue(ctx, "base2", "base") ctx = metainfo.WithValue(ctx, "base3", "base") ctx1 := metainfo.WithValue(ctx, "a", "a") ctx2 := metainfo.WithValue(ctx, "b", "b") av, ae := metainfo.GetValue(ctx1, "a") bv, be := metainfo.GetValue(ctx2, "b") assert(t, ae && av == "a", ae, av) assert(t, be && bv == "b", be, bv) } func initMetaInfo(count int) (context.Context, []string, []string) { ctx := context.Background() var keys, vals []string for i := 0; i < count; i++ { k, v := fmt.Sprintf("key-%d", i), fmt.Sprintf("val-%d", i) ctx = metainfo.WithValue(ctx, k, v) ctx = metainfo.WithPersistentValue(ctx, k, v) keys = append(keys, k) vals = append(vals, v) } return ctx, keys, vals } func benchmark(b *testing.B, api string, count int) { ctx, keys, vals := initMetaInfo(count) switch api { case "TransferForward": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.TransferForward(ctx) } case "GetValue": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = metainfo.GetValue(ctx, keys[i%len(keys)]) } case "GetAllValues": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.GetAllValues(ctx) } case "RangeValues": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { metainfo.RangeValues(ctx, func(_, _ string) bool { return true }) } case "WithValue": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.WithValue(ctx, "key", "val") } case "WithValues": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.WithValues(ctx, "key--1", "val--1", "key--2", "val--2", "key--3", "val--3") } case "WithValueAcc": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { ctx = metainfo.WithValue(ctx, vals[i%len(vals)], "val") } case "DelValue": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.DelValue(ctx, "key") } case "GetPersistentValue": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _, _ = metainfo.GetPersistentValue(ctx, keys[i%len(keys)]) } case "GetAllPersistentValues": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.GetAllPersistentValues(ctx) } case "RangePersistentValues": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { metainfo.RangePersistentValues(ctx, func(_, _ string) bool { return true }) } case "WithPersistentValue": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.WithPersistentValue(ctx, "key", "val") } case "WithPersistentValues": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.WithPersistentValues(ctx, "key--1", "val--1", "key--2", "val--2", "key--3", "val--3") } case "WithPersistentValueAcc": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { ctx = metainfo.WithPersistentValue(ctx, vals[i%len(vals)], "val") } _ = ctx case "DelPersistentValue": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.DelPersistentValue(ctx, "key") } case "SaveMetaInfoToMap": b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m := make(map[string]string) metainfo.SaveMetaInfoToMap(ctx, m) } case "SetMetaInfoFromMap": m := make(map[string]string) c := context.Background() metainfo.SaveMetaInfoToMap(ctx, m) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { _ = metainfo.SetMetaInfoFromMap(c, m) } } } func benchmarkParallel(b *testing.B, api string, count int) { ctx, keys, vals := initMetaInfo(count) switch api { case "TransferForward": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.TransferForward(ctx) } }) case "GetValue": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { var i int for pb.Next() { _, _ = metainfo.GetValue(ctx, keys[i%len(keys)]) i++ } }) case "GetAllValues": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.GetAllValues(ctx) } }) case "RangeValues": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { metainfo.RangeValues(ctx, func(_, _ string) bool { return true }) } }) case "WithValue": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.WithValue(ctx, "key", "val") } }) case "WithValues": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.WithValues(ctx, "key--1", "val--1", "key--2", "val--2", "key--3", "val--3") } }) case "WithValueAcc": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { tmp := ctx var i int for pb.Next() { tmp = metainfo.WithValue(tmp, vals[i%len(vals)], "val") i++ } }) case "DelValue": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.DelValue(ctx, "key") } }) case "GetPersistentValue": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { var i int for pb.Next() { _, _ = metainfo.GetPersistentValue(ctx, keys[i%len(keys)]) i++ } }) case "GetAllPersistentValues": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.GetAllPersistentValues(ctx) } }) case "RangePersistentValues": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { metainfo.RangePersistentValues(ctx, func(_, _ string) bool { return true }) } }) case "WithPersistentValue": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.WithPersistentValue(ctx, "key", "val") } }) case "WithPersistentValues": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.WithPersistentValues(ctx, "key--1", "val--1", "key--2", "val--2", "key--3", "val--3") } }) case "WithPersistentValueAcc": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { tmp := ctx var i int for pb.Next() { tmp = metainfo.WithPersistentValue(tmp, vals[i%len(vals)], "val") i++ } }) case "DelPersistentValue": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.DelPersistentValue(ctx, "key") } }) case "SaveMetaInfoToMap": b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { m := make(map[string]string) metainfo.SaveMetaInfoToMap(ctx, m) } }) case "SetMetaInfoFromMap": m := make(map[string]string) c := context.Background() metainfo.SaveMetaInfoToMap(ctx, m) b.ReportAllocs() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = metainfo.SetMetaInfoFromMap(c, m) } }) } } func BenchmarkAll(b *testing.B) { APIs := []string{ "TransferForward", "GetValue", "GetAllValues", "WithValue", "WithValues", "WithValueAcc", "DelValue", "GetPersistentValue", "GetAllPersistentValues", "RangePersistentValues", "WithPersistentValue", "WithPersistentValues", "WithPersistentValueAcc", "DelPersistentValue", "SaveMetaInfoToMap", "SetMetaInfoFromMap", } for _, api := range APIs { for _, cnt := range []int{10, 20, 50, 100} { fun := fmt.Sprintf("%s_%d", api, cnt) b.Run(fun, func(b *testing.B) { benchmark(b, api, cnt) }) } } } func BenchmarkAllParallel(b *testing.B) { APIs := []string{ "TransferForward", "GetValue", "GetAllValues", "WithValue", "WithValues", "WithValueAcc", "DelValue", "GetPersistentValue", "GetPersistentValues", "GetAllPersistentValues", "RangePersistentValues", "WithPersistentValue", "WithPersistentValueAcc", "DelPersistentValue", "SaveMetaInfoToMap", "SetMetaInfoFromMap", } for _, api := range APIs { for _, cnt := range []int{10, 20, 50, 100} { fun := fmt.Sprintf("%s_%d", api, cnt) b.Run(fun, func(b *testing.B) { benchmarkParallel(b, api, cnt) }) } } } func TestValuesCount(t *testing.T) { ctx := context.Background() type args struct { ctx context.Context } tests := []struct { name string args args want int }{ { name: "0", args: args{ ctx: ctx, }, want: 0, }, { name: "0", args: args{ ctx: metainfo.WithPersistentValues(ctx, "1", "1", "2", "2"), }, want: 0, }, { name: "2", args: args{ ctx: metainfo.WithValues(ctx, "1", "1", "2", "2"), }, want: 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := metainfo.CountValues(tt.args.ctx); got != tt.want { t.Errorf("ValuesCount() = %v, want %v", got, tt.want) } }) } } func TestPersistentValuesCount(t *testing.T) { ctx := context.Background() type args struct { ctx context.Context } tests := []struct { name string args args want int }{ { name: "0", args: args{ ctx: ctx, }, want: 0, }, { name: "0", args: args{ ctx: metainfo.WithValues(ctx, "1", "1", "2", "2"), }, want: 0, }, { name: "2", args: args{ ctx: metainfo.WithPersistentValues(ctx, "1", "1", "2", "2"), }, want: 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := metainfo.CountPersistentValues(tt.args.ctx); got != tt.want { t.Errorf("ValuesCount() = %v, want %v", got, tt.want) } }) } }
from behave import * from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException from os.path import join, dirname, realpath UPLOADS_PATH = join(dirname(realpath(__file__)), "test-image1.png") @given(u'the first user is signed into their account') def open_browser(context): context.driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) context.driver.implicitly_wait(5) context.driver.get("http://127.0.0.1:5000/auth/login") username_field = context.driver.find_element(By.ID, "username") username_field.send_keys("user2") pass_field = context.driver.find_element(By.ID, "password") pass_field.send_keys("Password1@") token_field = context.driver.find_element(By.ID, "token") token_field.send_keys("111111") add_button = context.driver.find_element(By.ID, "submit") add_button.click() context.driver.implicitly_wait(100) @when(u'the first user is on the "Edit Profile" page') def step_impl(context): expected_url = "http://127.0.0.1:5000/auth/index" wait = WebDriverWait(context.driver, 10) try: wait.until(lambda driver: driver.current_url == expected_url) except TimeoutException: assert False, f"Page was not redirected to {expected_url}" context.driver.get("http://127.0.0.1:5000/edit_profile") @when(u'the first user chooses a PNG picture from their local storage') def step_impl(context): upload_element = context.driver.find_element(By.ID, "profile_picture") upload_element.send_keys(UPLOADS_PATH) @when(u'the first user enters the "Submit" button') def step_impl(context): add_button = context.driver.find_element(By.ID, "submit") add_button.click() context.driver.implicitly_wait(100) @then(u'the first user will get a sucess message') def step_impl(context): success_message = context.driver.find_element(By.ID, "message") expected_message = "Your changes have been saved." assert success_message.text == expected_message, f"Expected message: '{expected_message}', but got '{success_message.text}'"
using AutoFixture; using FluentAssertions; using Newtonsoft.Json; using Xunit; #if DECIMAL namespace DecimalQuantitativeWorld.Text.Json.Tests { using DecimalQuantitativeWorld.TestAbstractions; using number = System.Decimal; #else namespace QuantitativeWorld.Text.Json.Tests { using QuantitativeWorld.TestAbstractions; using number = System.Double; #endif public class VolumeUnitJsonConverterTests : TestsBase { public VolumeUnitJsonConverterTests(TestFixture testFixture) : base(testFixture) { } [Theory] [InlineData(LinearUnitJsonSerializationFormat.AlwaysFull, "{\"Unit\":{\"Name\":\"cubic centimetre\",\"Abbreviation\":\"cm³\",\"ValueInCubicMetres\":(0\\.000001|1E-06)}}")] [InlineData(LinearUnitJsonSerializationFormat.PredefinedAsString, "{\"Unit\":\"cm³\"}")] public void SerializePredefinedUnit_ShouldReturnValidJson(LinearUnitJsonSerializationFormat serializationFormat, string expectedJsonPattern) { // arrange var unit = VolumeUnit.CubicCentimetre; var converter = new VolumeUnitJsonConverter(serializationFormat); // act string actualJson = JsonConvert.SerializeObject(new SomeUnitOwner<VolumeUnit> { Unit = unit }, converter); // assert actualJson.Should().MatchRegex(expectedJsonPattern); } [Theory] [MemberData(nameof(GetTestData), typeof(VolumeUnit), nameof(VolumeUnit.GetPredefinedUnits))] public void DeserializePredefinedUnitString_ShouldReturnValidResult(VolumeUnit expectedUnit) { // arrange string json = $@"{{ 'unit': '{expectedUnit.Abbreviation}' }}"; var converter = new VolumeUnitJsonConverter(); // act var result = JsonConvert.DeserializeObject<SomeUnitOwner<VolumeUnit>>(json, converter); // assert result.Unit.Should().Be(expectedUnit); } [Fact] public void DeserializeCustomUnit_ShouldReturnValidResult() { // arrange string json = @"{ 'name': 'some unit', 'abbreviation': 'su', 'valueInCubicMetres': 123.456 }"; var converter = new VolumeUnitJsonConverter(); // act var result = JsonConvert.DeserializeObject<VolumeUnit>(json, converter); // assert result.Name.Should().Be("some unit"); result.Abbreviation.Should().Be("su"); result.ValueInCubicMetres.Should().Be((number)123.456m); } [Fact] public void DeserializeCustomUnitAsPredefined_ShouldReturnValidResult() { // arrange var someUnit = new VolumeUnit( name: "some unit", abbreviation: "su", valueInCubicMetres: (number)123.456m); string json = @"{ 'unit': 'su' }"; var converter = new VolumeUnitJsonConverter( serializationFormat: LinearUnitJsonSerializationFormat.PredefinedAsString, tryReadCustomPredefinedUnit: (string value, out VolumeUnit predefinedUnit) => { if (value == someUnit.Abbreviation) { predefinedUnit = someUnit; return true; } predefinedUnit = default(VolumeUnit); return false; }); // act var result = JsonConvert.DeserializeObject<SomeUnitOwner<VolumeUnit>>(json, converter); // assert result.Unit.Should().Be(someUnit); } [Theory] [InlineData(LinearUnitJsonSerializationFormat.AlwaysFull)] [InlineData(LinearUnitJsonSerializationFormat.PredefinedAsString)] public void SerializeAndDeserialize_ShouldBeIdempotent(LinearUnitJsonSerializationFormat serializationFormat) { // arrange var obj = new SomeUnitOwner<VolumeUnit> { Unit = Fixture.Create<VolumeUnit>() }; var converter = new VolumeUnitJsonConverter(serializationFormat); // act string serializedObj1 = JsonConvert.SerializeObject(obj, converter); var deserializedObj1 = JsonConvert.DeserializeObject<SomeUnitOwner<VolumeUnit>>(serializedObj1, converter); string serializedObj2 = JsonConvert.SerializeObject(deserializedObj1, converter); var deserializedObj2 = JsonConvert.DeserializeObject<SomeUnitOwner<VolumeUnit>>(serializedObj2, converter); // assert deserializedObj1.Unit.Should().Be(obj.Unit); deserializedObj2.Unit.Should().Be(obj.Unit); deserializedObj2.Unit.Should().Be(deserializedObj1.Unit); serializedObj2.Should().Be(serializedObj1); } } }
import { Dispatch } from "react" import Button from "./Button" type SuccessMessageProps = { setFormSuccess: Dispatch<boolean> setEmail: Dispatch<string> setError: Dispatch<string> email: string } const SuccessMessage = ({ email, setEmail, setError, setFormSuccess, }: SuccessMessageProps) => { const handleDismissMessage = () => { setEmail("") setError("") setFormSuccess(false) } return ( <div className="bg-white h-full w-full sm:h-auto sm:w-auto sm:rounded-[30px] shadow-md inline-block sm:px-7 sm:pt-12 sm:pb-14 font-roboto"> <div className="max-w-md flex flex-col px-5 py-10 sm:px-9 sm:py-0 h-full"> <img className="h-16 w-16 mt-24 sm:mt-0" src="./icon-success.svg" /> <h1 className="mt-10 font-bold text-[56px]/[56px] text-darkSlateGrey"> Thanks for subscribing! </h1> <p className="mt-8 text-charcoalGrey"> A confirmation email has been sent to <strong>{email}</strong>. Please open it and click the button inside to confirm your subscription. </p> <Button className="mt-auto sm:mt-10" onClick={handleDismissMessage}> Dismiss message </Button> </div> </div> ) } export default SuccessMessage
import React, { useState } from 'react'; import axios from 'axios'; import 'react-quill/dist/quill.snow.css'; import { Input } from 'antd'; import QuillEditor from '../components/QuillEditor'; const AddDestination = () => { const [destinationName, setDestinationName] = useState(""); const [destinationLocation, setDestinationLocation] = useState(""); const [destinationImage, setDestinationImage] = useState(""); const [destinationDesc, setDestinationDesc] = useState(""); const [notification, setNotification] = useState(null); // Thêm state cho thông báo const { TextArea } = Input; const handleDestinationNameChange = (e) => { setDestinationName(e.target.value); }; const handleDestinationLocationChange = (e) => { setDestinationLocation(e.target.value); }; const handleDestinationImageChange = (e) => { setDestinationImage(e.target.value); }; const handleDestinationDescChange = (e) => { setDestinationDesc(e.target.value); }; const handleSubmit = async (e) => { e.preventDefault(); const newDestination = { name: destinationName, // desc: destinationDesc, mainImageLink: destinationImage, location: destinationLocation, }; // Lấy danh sách tất cả các destination từ database try { // Nếu destinationName chưa tồn tại, thực hiện yêu cầu POST để thêm destination mới vào database await axios.post("http://localhost:5000/destinations", newDestination); // Hiển thị thông báo "Thêm mới thành công" setNotification('Thêm mới thành công'); } catch (error) { console.error("Error: ", error.response); } }; return ( <div> <h4 className="mb-4">Thêm mới điểm đến</h4> {notification && ( <div className={`notification-success ${notification === 'Thêm mới thành công' ? 'success' : 'error'}`}> {notification} </div> )} <div> <form onSubmit={handleSubmit}> <div className="category-wrapper"> <div className="category-header"> <h5 className="sub-title"> Tên </h5> </div> <input type="text" className="brandname-input" value={destinationName} onChange={handleDestinationNameChange} /> </div> <div className="category-wrapper"> <div className="category-header"> <h5 className="sub-title"> Mô tả </h5> </div> {/* <TextArea className="brandDesc-input" value={destinationDesc} onChange={handleDestinationDescChange}/> */} <QuillEditor onEditorChange={handleDestinationDescChange} /> </div> <div className="category-wrapper"> <div className="category-header"> <h5 className="sub-title"> Vị trí tổng quan </h5> </div> <input type="text" className="brandname-input" value={destinationLocation} onChange={handleDestinationLocationChange} /> </div> <div className="category-wrapper"> <div className="category-header"> <h5 className="sub-title"> Link ảnh </h5> </div> <input type="text" className="brandname-input" value={destinationImage} onChange={handleDestinationImageChange} /> </div> <button className="btn btn-success border-0 rounded-3 my-5" type="submit"> Thêm mới </button> </form> </div> </div> ) } export default AddDestination;