text
stringlengths
184
4.48M
/* eslint-disable max-len */ /* eslint-disable react/jsx-one-expression-per-line */ import React, { useEffect, useRef } from 'react'; import { useSelector } from 'react-redux'; import Button from '../../common/components/Button/Button'; import Link from '../../common/components/Link/Link'; import { LinkTypes } from '../../common/components/Link/link-types'; import useAppDispatch from '../../common/hooks/useAppDispatch'; import useIntersectionObserver from '../../common/hooks/useIntersectionObserver'; import useVisiblePage from '../../common/hooks/useVisiblePage'; import { Page } from '../../common/reducers/visible-page/visible-page-types'; import { initializeYoutubeData } from '../../common/reducers/youtube/youtube-reducer'; import selectYoutube from '../../common/reducers/youtube/youtube-selectors'; import URL from '../../common/types/url-types'; import Title from '../../components/Title/Title'; import YoutubeInfo from '../../components/YoutubeInfo/YoutubeInfo'; const YouTube = () => { const ref = useRef<HTMLDivElement | null>(null); const animationRef = useRef<HTMLDivElement | null>(null); useVisiblePage(ref, Page.YOUTUBE); const animationEntry = useIntersectionObserver(animationRef, { freezeOnceVisible: true }); const dispatch = useAppDispatch(); const youtubeData = useSelector(selectYoutube()); useEffect(() => { dispatch(initializeYoutubeData()); }, []); return ( <div ref={ref} className='youtube'> <div className='youtube__description-container'> <Title title='My Youtube channel' /> <p className='youtube__description'> On my Youtube channel <b><Link href={URL.YOUTUBE}>Programación Accesible</Link></b> I share what I know about <b>frontend, coding and design</b> (in Spanish). </p> <p className='youtube__description'> It&apos;s a place where I can <b>help</b> others while I also <b>learn</b> new stuff and get to practice what I already know. Wanna have a look? </p> <Link href={URL.YOUTUBE} type={LinkTypes.BUTTON}> <Button label='Visit my Youtube channel' /> </Link> </div> <div ref={animationRef} className='youtube__billboard-container' data-animate={animationEntry?.isIntersecting}> <div className='youtube__billboard youtube__billboard-right'> <div className='youtube__billboard-content'>Programación Accesible ©</div> </div> {youtubeData.loaded && ( <div className='youtube__billboard youtube__billboard-left'> <div className='youtube__billboard-content'><YoutubeInfo {...youtubeData} /></div> </div> )} </div> </div> ); }; export default YouTube;
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { UsersService } from "../service/users.service"; import { DatePipe } from '@angular/common'; import { MatDialog } from '@angular/material/dialog'; import { UpdatepopupComponent } from "../updatepopup/updatepopup.component"; import { ToastrService } from "ngx-toastr"; import { Clipboard } from '@angular/cdk/clipboard'; interface User { firstName: string; lastName: string; birth: string; phone: string; gender: string; isAdmin: boolean; tgUserId: string; createdAt: string; updatedAt: string; } @Component({ selector: 'app-user-page', templateUrl: './user-page.component.html', styleUrls: ['./user-page.component.css'], providers: [DatePipe] }) export class UserPageComponent implements OnInit { userId: string; user: User; constructor( private route: ActivatedRoute, private userService: UsersService, private dialog: MatDialog, private clipboard: Clipboard, private toastr: ToastrService ) {} openUpdatePopup(): void { const dialogRef = this.dialog.open(UpdatepopupComponent, { width: '500px', disableClose: true, data: { userId: this.userId } }); dialogRef.afterClosed().subscribe(result => {}); } copyToClipboard(text: string) { this.clipboard.copy(text); this.toastr.success('Copied'); } ngOnInit(): void { this.userId = this.route.snapshot.params.id; this.userService.getSingleUser(this.userId).subscribe( (res: User) => { this.user = res; }, (error: any) => { console.log(error); } ); } }
import { createContext ,useState} from "react"; import axios from "axios"; const BooksContext =createContext(); function Provider({children}){ const[books,Setbooks]=useState([]); const fetchBooks=async () =>{ const response=await axios.get('http://localhost:3001/books') Setbooks(response.data); }; const editBookById=async(id,newTitle)=>{ const response=await axios.put(`http://localhost:3001/books/${id}`,{ title:newTitle }); const updatedBooks=books.map((book) =>{ if(book.id===id){ return {...book ,...response.data} } return book; }); Setbooks(updatedBooks); }; const deleteBookById=async(id)=>{ await axios.delete(`http://localhost:3001/books/${id}`); const updatedBooks=books.filter((book)=>{ return book.id!==id; }); Setbooks(updatedBooks); }; const createBook= async (title)=>{ const response=await axios.post('http://localhost:3001/books',{ title, }); const updatedBooks=[ ...books, response.data ]; Setbooks(updatedBooks); }; const valueToShare ={ books, deleteBookById, editBookById, createBook, fetchBooks, }; return ( <BooksContext.Provider value={valueToShare}> {children} </BooksContext.Provider> ); } export { Provider }; export default BooksContext;
import { BigNumber } from "@ethersproject/bignumber"; import axios from "axios"; import { useCallback, useEffect, useState } from "react"; import { VaultLiquidityMiningMap, VaultOptions, } from "shared/lib/constants/constants"; import { getSubgraphqlURI } from "shared/lib/utils/env"; import { StakingPool } from "shared/lib/models/staking"; const useStakingPool = (vaults: VaultOptions[]) => { // TODO: Global state const [stakingPools, setStakingPools] = useState<{ [key: string]: StakingPool | undefined; }>({}); const [loading, setLoading] = useState(false); const loadStakingPools = useCallback(async (vs: VaultOptions[]) => { setLoading(true); setStakingPools(await fetchStakingPools(vs)); setLoading(false); }, []); useEffect(() => { loadStakingPools(vaults); }, [vaults, loadStakingPools]); return { stakingPools, loading }; }; const fetchStakingPools = async (vaults: VaultOptions[]) => { const response = await axios.post(getSubgraphqlURI(), { query: ` { ${vaults.map( (vault) => ` ${vault.replace( /-/g, "" )}: vaultLiquidityMiningPool(id:"${VaultLiquidityMiningMap[ vault ]!.toLowerCase()}") { numDepositors totalSupply totalRewardClaimed } ` )} } `, }); return Object.fromEntries( (vaults as string[]).map((vault): [string, StakingPool | undefined] => { const data = response.data.data[vault.replace(/-/g, "")]; if (!data) { return [vault, undefined]; } return [ vault, { ...data, totalSupply: BigNumber.from(data.totalSupply), totalRewardClaimed: BigNumber.from(data.totalRewardClaimed), }, ]; }) ); }; export default useStakingPool;
import { manage } from 'manate'; import axios from 'axios'; import { message } from 'antd'; import path from 'path'; const github = axios.create({ baseURL: 'https://api.github.com', }); import CONSTS from './constants'; export interface Token { access_token: string; } export interface User { login: string; } export interface Repo { name: string; full_name: string; owner: User; } export interface Content { name: string; path: string; type: 'file' | 'dir'; sha: string; } export class Store { public token: Token | undefined = undefined; public repos: Repo[] = []; public repo: Repo | undefined = undefined; public contents: Content[] = []; public path = ''; public user: User | undefined = undefined; public host = ''; public async init() { // get host, like https://chuntaoliu.com/ github.defaults.headers.common.Authorization = `token ${this.token?.access_token}`; this.user = (await github.get('/user')).data; this.host = `https://${this.user.login}.github.io/`; global.ipc.on(CONSTS.HOST, (event: any, host: string) => { this.host = host; }); global.ipc.invoke(CONSTS.HOST, this.user.login); // get all the repos let hasNextPage = true; let page = 1; while (hasNextPage) { const r = await github.get('/user/repos', { params: { visibility: 'public', per_page: 100, page, affiliation: 'owner,collaborator', sort: 'updated', }, }); for (const repo of r.data) { if (repo.has_pages === true) { this.repos.push(repo); } } hasNextPage = r.data.length === 100; page += 1; } } public async chooseRepo(repo: Repo) { this.repo = repo; const r = await github.get(`/repos/${repo.full_name}/contents`); this.contents = r.data.filter((content: Content) => content.name !== '.gitkeep'); // get host for the current repo global.ipc.invoke(CONSTS.HOST, repo.owner.login); } public async chooseContent(content: { type: 'file' | 'dir'; path: string }) { if (content.type === 'dir') { const r = await github.get(`/repos/${this.repo.full_name}/contents/${content.path}`); this.path = content.path; this.contents = r.data.filter((content: Content) => content.name !== '.gitkeep'); } else { navigator.clipboard.writeText(`${this.host}${this.repo.name}/${content.path}`); message.success('Copied to clipboard'); } } public async upload(name: string, base64: string) { await github.put(`/repos/${this.repo?.full_name}/contents/${path.join(this.path, name)}`, { message: `Upload ${name}`, content: base64, }); this.refresh(); } public async refresh() { this.chooseContent({ type: 'dir', path: this.path }); } public async delete(content: Content) { if (content.type === 'file') { await github.delete(`/repos/${this.repo?.full_name}/contents/${content.path}`, { data: { message: `Delete ${content.name}`, sha: content.sha, }, }); this.refresh(); } else { let r = await github.get(`/repos/${this.repo?.full_name}/branches/main`); const sha = r.data.commit.sha; // get latest commit sha, it's also the latest tree sha r = await github.get(`/repos/${this.repo?.full_name}/git/trees/${sha}`, { params: { recursive: 1 } }); const tree = []; const blobs = r.data.tree.filter((item) => item.type === 'blob' && item.path.startsWith(content.path + '/')); for (const blob of blobs) { tree.push({ // delete old path: blob.path, mode: '100644', type: 'blob', sha: null, }); } r = await github.post(`/repos/${this.repo?.full_name}/git/trees`, { base_tree: sha, tree, }); // create new tree r = await github.post(`/repos/${this.repo?.full_name}/git/commits`, { message: `Delete ${content.path}/`, tree: r.data.sha, parents: [sha], }); // create new commit r = await github.patch(`/repos/${this.repo?.full_name}/git/refs/heads/main`, { sha: r.data.sha, }); // update branch to point to new commit await this.refresh(); } } public async mkdir(folderName: string) { if (folderName === '') { return; } await github.put(`/repos/${this.repo?.full_name}/contents/${path.join(this.path, folderName, '.gitkeep')}`, { message: `Create ${folderName}/`, content: '', }); this.refresh(); } public async rename(content: Content, newPath: string) { if (newPath === content.path) { return; } let r = await github.get(`/repos/${this.repo?.full_name}/branches/main`); const sha = r.data.commit.sha; // get latest commit sha, it's also the latest tree sha let message = `Rename ${content.path} to ${newPath}`; // rename file if (content.type === 'file') { r = await github.post(`/repos/${this.repo?.full_name}/git/trees`, { base_tree: sha, tree: [ { // create new path: newPath, mode: '100644', type: 'blob', sha: content.sha, }, { // delete old path: content.path, mode: '100644', type: 'blob', sha: null, }, ], }); // create new tree } else { // rename folder message = `Rename ${content.path}/ to ${newPath}/`; r = await github.get(`/repos/${this.repo?.full_name}/git/trees/${sha}`, { params: { recursive: 1 } }); const tree = []; const blobs = r.data.tree.filter((item) => item.type === 'blob' && item.path.startsWith(content.path + '/')); for (const blob of blobs) { tree.push({ // create new path: path.join(newPath + blob.path.substr(content.path.length)), mode: '100644', type: 'blob', sha: blob.sha, }); tree.push({ // delete old path: blob.path, mode: '100644', type: 'blob', sha: null, }); } r = await github.post(`/repos/${this.repo?.full_name}/git/trees`, { base_tree: sha, tree, }); // create new tree } r = await github.post(`/repos/${this.repo?.full_name}/git/commits`, { message, tree: r.data.sha, parents: [sha], }); // create new commit r = await github.patch(`/repos/${this.repo?.full_name}/git/refs/heads/main`, { sha: r.data.sha, }); // update branch to point to new commit await this.refresh(); } } const store = manage(new Store()); export default store;
const path = require('path'), http = require('http'), express = require('express'), socketio = require('socket.io'), Filter = require('bad-words'), {generateMessage, generateLocationMessage} = require("./utils/messages"), {addUser, getUser, removeUser, getUsersInRoom} = require("./utils/users"); const app = express(), server = http.createServer(app), io = socketio(server); const port = process.env.PORT || 3000, publicDirectoryPath = path.join(__dirname, "../public"); app.use(express.static(publicDirectoryPath)); io.on('connection', (socket) => { socket.on("join", (options, callback) => { const {error, user} = addUser({id: socket.id, ...options }) if(error) { return callback(error); } socket.join(user.room) socket.emit('message', generateMessage("Admin", "Welcome!")); socket.broadcast.to(user.room).emit("message", generateMessage("Admin", `${user.username} has joined.`)); io.to(user.room).emit('roomData', { room:user.room, users: getUsersInRoom(user.room) }) callback(); }) socket.on('sendMessage', (message, callback) => { const user = getUser(socket.id); const filter = new Filter(); if(filter.isProfane(message)) { return callback("Profanity is not allowed!") } io.to(user.room).emit('message', generateMessage(user.username, message)); callback(); }) socket.on('sendLocation', (position, callback) => { const user = getUser(socket.id); io.to(user.room).emit("locationMessage", generateLocationMessage(user.username,`https://www.google.com/maps?q=${position.latitude},${position.longitude}`)); callback(); }) socket.on('disconnect', () => { const user = removeUser(socket.id); if(user) { io.to(user.room).emit('message', generateMessage("Admin", `${user.username} as left.`)); io.to(user.room).emit('roomData', { room:user.room, users: getUsersInRoom(user.room) }) } }) }); // io.on server.listen(port, () => { console.log(`Server is up on port ${port}`); })
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using MvcDynamicForms.Fields; namespace MvcDynamicForms.Demo.Controllers { public class TestController : Controller { public ActionResult Index() { var form = new Form { Serialize = true }; form.Template = string.Format("<div><table>{0}</table>{1}</div>", PlaceHolders.Fields, PlaceHolders.SerializedForm); var name = new TextBox { Prompt = "Name", Required = true }; var age = new TextBox { Prompt = "Age", Required = true }; var weight = new TextBox { Prompt = "Weight", Required = true }; var strong = new CheckBox { Prompt = "I am strong!.", Required = true, Template = string.Format("<tr><th/><td>{0}{1}{2}</td></tr>", PlaceHolders.Error, PlaceHolders.Input, PlaceHolders.Prompt) }; var foods = new CheckBoxList { Prompt = "Favorite Foods", Required = true }; foods.AddChoices("Beef,Pork,Poultry,Seafood,Fruits,Vegetables"); form.AddFields(name, age, weight, strong, foods); form.SetFieldTemplates( string.Format(@"<tr><th valign=""top"">{0}</th><td>{1}{2}</td></tr>", PlaceHolders.Prompt, PlaceHolders.Error, PlaceHolders.Input), name, age, weight, foods); return View(form); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(Form form) { if (form.Validate()) { return View("Responses", form); } return View(form); } } }
--- title: Vsftpd on Arch Linux category: memo slug: vsftpd-on-arch-linux date: 2014-09-27 --- Vsftpd is one of the packages in Arch Linux offical repository. To enable SSL/TLS along with vsftpd, please do the following. ## Installation Install vsftpd via pacman ```bash pacman -S vsftpd ``` Generate an SSL cert ```bash cd /etc/ssl/certs openssl req -x509 -nodes -days 7300 -newkey rsakey:2048 -keyout /etc/ssl/certs/vsftpd.pem -out /etc/ssl/certs/vsftpd.pem chmod 600 /etc/ssl/certs/vsftpd.pem ``` Make sure the lines below are presented in the `/etc/vsftpd.conf` configure file an uncommented ```text local_enable=YES write_enable=YES ssl_enable=YES force_local_logins_ssl=YES ssl_tlsv1=YES ssl_sslv2=YES ssl_sslv3=YES rsa_cert_file=/etc/ssl/certs/vsftpd.pem rsa_private_key_file=/etc/ssl/certs/vsftpd.pem require_ssl_reuse=NO pasv_min_port=60000 pasv_max_port=65000 log_ftp_protocol=YES debug_ssl=YES ``` Fire up vsftpd and make it start at boot time ```bash systemctl enable vsftpd.service systemctl start vsftpd.service ``` ## Trouble Shooting ### Port 21 Occupied by System Default ftpd.service In some cases the system provided ftpd.service will be activated. To stop it ```bash systemctl stop ftpd.service systemctl disable ftpd.service ``` ### GnuTLS Error -15: An Unexpected TLS Packet Was Received If you uncommented `chroot_local_user=YES` in `/etc/vsftpd.conf`, your FTP client, e.g. FileZilla, will get an error that it cannot explain (decode). I think this is a bug. To workaround this bug, just comment the line and you're done.
'''Defines the Mindstorms robot class''' # pylint: disable = C0103 import math from math import sin, cos import bluetooth import numpy as np from . import robot HEADER = b'\x01\x00\x81\x9E' JOINT_LIMITS = [180, 120, 120] PORT = 1 STALL_THRESHOLD = 1 class Mindstorms(robot.Robot): '''Robot class for LEGO Mindstorms(TM) robots''' def __init__(self): self.dof = 3 self.server_socket = None self.client_socket = None self.joints = None self.last_joints = None def _receive_message(self): '''Waits for an incoming message and returns the title and the content of the received message''' data = self.client_socket.recv(1024) data = data[6:] title_length = np.fromstring(data, count=1, dtype=np.int8)[0] title = data[1 : title_length].decode('ascii') data = data[title_length + 1:] message_length = np.fromstring(data, count=1, dtype=np.int16)[0] message = data[2 : message_length + 1].decode('ascii') return title, message def _send_message(self, command, value): '''Sends a command to the robot''' message = HEADER + np.int8(len(command) + 1).tobytes() + \ bytes(command, 'ascii') + b'\x00' if isinstance(value, bool): message += np.int16(1).tobytes() if value: message += b'\x01' else: message += b'\x00' elif isinstance(value, int) or isinstance(value, float): message += np.int16(4).tobytes() + np.float32(value).tobytes() elif isinstance(value, str): message += np.int16(len(value) + 1).tobytes() + bytes(value, 'ascii') + b'\x00' message = np.int16(len(message)).tobytes() + message self.client_socket.send(message) def connect(self): '''Connects to an EV3 brick via Bluetooth''' self.server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) self.server_socket.bind(('', PORT)) self.server_socket.listen(1) print('Waiting for EV3 to connect') self.client_socket, _ = self.server_socket.accept() print('EV3 connected') def detect_soft_limits(self, signal): ''' Returns a logical array indicating which joints are software limited, depending on the current robot position and the control signal provided. ''' lower_bound = (np.asarray(self.joints) <= 0) & (signal < 0) upper_bound = (np.asarray(self.joints) >= np.array(JOINT_LIMITS)) & (signal > 0) return lower_bound | upper_bound def detect_stall(self): '''Returns True if the robot did not move since the last call''' if self.last_joints is None: self.last_joints = self.joints return False stall = True for last, curr in zip(self.last_joints, self.joints): if abs(last - curr) > STALL_THRESHOLD: stall = False self.last_joints = self.joints return stall def direct_kinematics(self): '''Returns the position of the robot's end effector''' q = [math.radians(x) for x in self.joints] r = -104 * cos(q[1]) + 123 * cos(q[1] - q[2]) + 8 * (7 + 5 * sin(q[1]) + 4 * sin(q[1] - q[2])) posx = cos(q[0]) * r posy = sin(q[0]) * r posz = 100 + 40 * cos(q[1]) + 32 * cos(q[1] - q[2]) + 104 * sin(q[1]) - 123 * sin(q[1] - q[2]) return posx, posy, posz def disconnect(self): '''Disconnects the EV3 brick''' self._send_message('END', True) self.client_socket.close() self.server_socket.close() print('EV3 disconnected') def home(self): '''Returns the robot to the home position''' self._send_message('HOME', True) self._receive_message() def read_joints(self): '''Returns the positions of all joints''' self._send_message('READ', True) _, answer = self._receive_message() self.joints = [int(val) for val in answer.split(',')] return self.joints def reset(self): '''Resets the joint measurements to zero''' self._send_message('RESET', True) def set_motor(self, motor_number, power): '''Sends a 'M' command to the robot''' if 0 < motor_number <= self.dof: self._send_message('M' + str(motor_number), np.clip(power, -100, 100))
import collections import serial MeasureScan = collections.namedtuple('MeasureScan', ['length', 'width', 'height', 'weight', 'dimweight', 'factor']) # See documentation for CubiScan 125 CS_PREFIX = bytes([0x02]) CS_SUFFIX = bytes([0x03, 0x0d, 0x0a]) def cmd(char): b2 = bytes([ord(char)]) return CS_PREFIX + b2 + CS_SUFFIX def coerce_float(s): """ >>> coerce_float('_____') >>> coerce_float('~~~~') >>> coerce_float(' 3.60') 3.6 """ # From the fine manual page 111: "This field may contain underscores, # dashes, or overscores indicating an under, unstable, or over error # condition, respectively." if s.strip('_') == '' or s.strip('-') == '' or s.strip('~') == '': return None return float(s) def convert(eventtype, payload): if chr(eventtype) in 'mMA': # Sample payload: # b'AC ,L 3.60,W12.05,H 5.10in,K 1.545,D 1.333lb,F0166,D' p = str(payload, encoding='ascii') measures = p.split(',') if len(measures) != 8: raise RuntimeError('unrecognized measurement payload') kwargs = {} # exclude initial flags and final D/I (domestic, international) for m in measures[1:-1]: if m[0] == 'L': kwargs['length'] = coerce_float(m[1:]) if m[0] == 'W': kwargs['width'] = coerce_float(m[1:]) if m[0] == 'H': kwargs['height'] = coerce_float(m[1:-2]) if m[0] == 'K': kwargs['weight'] = coerce_float(m[1:]) if m[0] == 'D': kwargs['dimweight'] = coerce_float(m[1:-2]) if m[0] == 'F': kwargs['factor'] = int(m[1:]) return chr(eventtype), MeasureScan(**kwargs) return chr(eventtype), payload class CubiScanScanner: def __init__(self, comport): self._serial = serial.Serial('COM{}'.format(comport), timeout=.25) self._queue = b'' def close(self): self._serial.close() def _parse_bytes(self): while len(self._queue) > 0: b = self._queue if len(b) < len(CS_PREFIX+CS_SUFFIX): break length = len(CS_SUFFIX)+b.find(CS_SUFFIX) rec = self._queue[:length] data = rec[len(CS_PREFIX):-len(CS_SUFFIX)] eventtype = data[1] payload = data[1:] yield (eventtype, convert(eventtype, payload)) self._queue = b[length+4:] def read_scans(self): while True: read = self._serial.read(100) self._queue += read if len(self._queue) == 0 or len(read) == 0: break if self._queue.find(CS_SUFFIX) >= 0: for _, value in self._parse_bytes(): yield value def measure(self): self._serial.write(cmd('M'))
import { userVoteToConstant } from "../constants"; import { formatDateStandard } from "../utils/dates"; import { Hub, parseHub } from "./hub"; import { AuthorProfile, RHUser, parseAuthorProfile, parseUnifiedDocument, parseUser, TopLevelDocument, UnifiedDocument, ID, RhDocumentType, ApiDocumentType, } from "./root_types"; export type CitationConsensus = { total: number; neutral: number; rejecting: number; supporting: number; }; export const parseConsensus = (raw: any): CitationConsensus => { return { total: raw.citation_count || 0, neutral: raw.neutral_count || 0, rejecting: raw.down_count || 0, supporting: raw.up_count || 0, }; }; export class Hypothesis implements TopLevelDocument { _id: ID; _authors: AuthorProfile[]; _unifiedDocument: UnifiedDocument; _hubs: Hub[]; _score: number; _createdDate: string; _discussionCount: number; _userVote?: "downvote" | "upvote" | "neutralvote" | undefined | null; _doi?: string; _title: string; _createdBy: RHUser; _datePublished?: string; _note?: any; _markdown?: string; _isReady: boolean; _boostAmount: number; _consensus: CitationConsensus | undefined; _documentType: RhDocumentType; _apiDocumentType: ApiDocumentType; constructor(raw: any) { this._authors = (raw.authors || []).map((a) => parseAuthorProfile(a)); this._unifiedDocument = parseUnifiedDocument(raw.unified_document); this._score = raw.score; this._discussionCount = raw.discussion_count || 0; this._createdDate = formatDateStandard(raw.created_date); this._datePublished = formatDateStandard(raw.created_date); this._createdBy = parseUser(raw.created_by); this._hubs = (raw.hubs || []).map((h) => parseHub(h)); this._title = raw.title; this._note = raw.note; this._boostAmount = raw.boost_amount || 0; this._id = raw.id; this._markdown = raw.full_markdown; this._isReady = raw.id ? true : false; this._documentType = "hypothesis"; this._apiDocumentType = "hypothesis"; if (raw.aggregate_citation_consensus) { this._consensus = parseConsensus(raw.aggregate_citation_consensus); } if (raw.user_vote) { this._userVote = userVoteToConstant(raw.user_vote); } if (raw.doi) { this._doi = raw.doi; } } get id(): ID { return this._id; } get unifiedDocument(): UnifiedDocument { return this._unifiedDocument; } get authors(): Array<AuthorProfile> { return this._authors; } get boostAmount(): number { return this._boostAmount; } get score(): number { return this._score; } get userVote(): "downvote" | "upvote" | "neutralvote" | undefined | null { return this._userVote; } get discussionCount(): number { return this._discussionCount; } get createdDate(): string { return this._createdDate; } get datePublished(): string | undefined { return this._datePublished; } get doi(): string | undefined { return this._doi; } get consensus(): CitationConsensus | undefined { return this._consensus; } get title(): string | undefined { return this._title; } get markdown(): string | undefined { return this._markdown; } get note(): any | undefined { return this._note; } get createdBy(): RHUser{ return this._createdBy; } get isReady(): boolean { return this._isReady; } get hubs(): Array<Hub> { return this._hubs; } get documentType(): RhDocumentType { return this._documentType; } get apiDocumentType(): ApiDocumentType { return this._apiDocumentType; } }
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <data> <variable name="vm" type="com.ramo.simplegithub.ui.UserViewModel" /> <variable name="item" type="com.ramo.simplegithub.domain.model.User" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/background"> <com.google.android.material.appbar.MaterialToolbar android:id="@+id/materialToolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:navigationIcon="@drawable/ic_back" app:title="User Detail" app:titleCentered="true" /> <ImageView android:id="@+id/imgProfilePicture" image_corner_radius="@{16}" image_url="@{item.profilePictureUrl}" android:layout_width="150dp" android:layout_height="150dp" android:layout_marginHorizontal="8dp" android:layout_marginVertical="8dp" android:adjustViewBounds="true" android:onClickListener="@{(v)-> vm.goAvatar(item.userName, item.profilePictureUrl)}" android:src="@mipmap/ic_launcher" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/materialToolbar" /> <com.google.android.material.card.MaterialCardView android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="8dp" android:background="@color/white" app:cardCornerRadius="8dp" app:contentPadding="8dp" app:layout_constraintBottom_toBottomOf="@id/imgProfilePicture" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@id/imgProfilePicture" app:layout_constraintTop_toTopOf="@id/imgProfilePicture"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.textview.MaterialTextView android:id="@+id/txtUserName" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginHorizontal="8dp" android:gravity="center" android:text="@{item.userName}" android:textColor="@color/primaryTextColor" android:textSize="18sp" android:textStyle="bold" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <com.google.android.material.textview.MaterialTextView android:id="@+id/titleFollower" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginHorizontal="8dp" android:layout_marginStart="8dp" android:text="Follower" android:textColor="@color/primaryTextColor" android:textSize="15sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@+id/txtFollower" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/txtUserName" app:layout_constraintVertical_bias="1.0" /> <com.google.android.material.textview.MaterialTextView android:id="@+id/txtFollower" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginHorizontal="8dp" android:layout_marginStart="8dp" android:text="@{Integer.toString(item.follower)}" android:textColor="@color/primaryTextColor" android:textSize="15sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@id/titleFollower" app:layout_constraintStart_toStartOf="@id/titleFollower" /> <com.google.android.material.textview.MaterialTextView android:id="@+id/titleFollowing" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginHorizontal="8dp" android:layout_marginStart="8dp" android:text="Following" android:textColor="@color/primaryTextColor" android:textSize="15sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@+id/txtFollowing" app:layout_constraintEnd_toStartOf="@id/imgFavorite" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toEndOf="@id/titleFollower" app:layout_constraintTop_toBottomOf="@id/txtUserName" app:layout_constraintVertical_bias="1.0" /> <com.google.android.material.textview.MaterialTextView android:id="@+id/txtFollowing" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginHorizontal="8dp" android:layout_marginStart="8dp" android:text="@{Integer.toString(item.following)}" android:textColor="@color/primaryTextColor" android:textSize="15sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@id/titleFollowing" app:layout_constraintStart_toStartOf="@id/titleFollowing" /> <androidx.appcompat.widget.AppCompatImageView android:id="@+id/imgFavorite" android:layout_width="36dp" android:layout_height="36dp" android:layout_marginEnd="8dp" android:adjustViewBounds="true" android:src="@{item.favorite ? @drawable/ic_favorite : @drawable/ic_favorite_round}" android:onClick="@{(v)-> vm.changeFavoriteStatus(item)}" app:layout_constraintBottom_toBottomOf="@+id/txtFollowing" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/titleFollowing" app:layout_constraintVertical_bias="0.0" /> </androidx.constraintlayout.widget.ConstraintLayout> </com.google.android.material.card.MaterialCardView> <com.google.android.material.card.MaterialCardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:background="@color/white" app:cardCornerRadius="8dp" app:contentPadding="8dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/imgProfilePicture"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Bio" android:textColor="@color/gray" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{item.bio}" android:textColor="@color/black" android:textStyle="bold" /> <Space android:layout_width="match_parent" android:layout_height="8dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Counrty" android:textColor="@color/gray" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{item.location}" android:textColor="@color/black" android:textStyle="bold" /> <Space android:layout_width="match_parent" android:layout_height="8dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Company" android:textColor="@color/gray" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{item.company}" android:textColor="@color/black" android:textStyle="bold" /> <Space android:layout_width="match_parent" android:layout_height="8dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Public Repo" android:textColor="@color/gray" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@{Integer.toString(item.publicRepos)}" android:textColor="@color/black" android:textStyle="bold" /> <Space android:layout_width="match_parent" android:layout_height="8dp" /> <com.google.android.material.button.MaterialButton android:id="@+id/btnOpenBrowser" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Open on Github" app:icon="@drawable/ic_github" app:iconSize="24dp" app:iconGravity="textStart"/> </LinearLayout> </com.google.android.material.card.MaterialCardView> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
package com.si.googleads.advice; import com.mongodb.MongoBulkWriteException; import com.mongodb.MongoSocketException; import com.si.googleads.exceptions.ApiRequestException; import com.si.googleads.exceptions.DatabaseResourceException; import com.si.googleads.response.ErrorResponse; import org.springframework.core.codec.DecodingException; import org.springframework.data.mongodb.UncategorizedMongoDbException; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.bind.support.WebExchangeBindException; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @RestControllerAdvice public class ApplicationExceptionHandler { // General Exception Handler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(Throwable.class) public Mono<ErrorResponse<?>> handleAnyUnhandledException(Throwable ex) { if (ex instanceof RuntimeException runtimeException) { Throwable cause = runtimeException.getCause(); if (cause instanceof DecodingException) { return handleDecodingException((DecodingException) cause); } } // If not handled specifically, provide a generic error response ErrorResponse<?> errorResponse = ErrorResponse.builder().message(ex.getMessage()).build(); return Mono.just(errorResponse); } // Handle DecodingException private Mono<ErrorResponse<?>> handleDecodingException(DecodingException ex) { String exceptionMessage = ex.getMessage(); // if (exceptionMessage.contains("MetricType")) { // Map<String, String> errors = new HashMap<>(); // errors.put("metrics", "Invalid value for metricTypes field. Allowed values are: " + Arrays.toString(MetricType.getAllValues())); // // ErrorResponse<?> errorResponse = ErrorResponse.builder().message("Validation Error").error(errors).build(); // // return Mono.just(errorResponse); // } // Handle other DecodingException scenarios or return a generic error response ErrorResponse<?> errorResponse = ErrorResponse.builder().message("JSON decoding error: " + exceptionMessage).build(); return Mono.just(errorResponse); } // Form Validation and Message Read Exceptions @ExceptionHandler({WebExchangeBindException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) public Mono<ErrorResponse<?>> handleValidationAndMessageReadExceptions(Exception ex) { Map<String, String> errors = new HashMap<>(); if (ex instanceof WebExchangeBindException bindException) { bindException.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); } ErrorResponse<?> errorResponse = ErrorResponse.builder().message("Validation Error").error(errors).build(); return Mono.just(errorResponse); } // Business Logic Errors @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(ApiRequestException.class) public ErrorResponse<?> handleBusinessLogicException(ApiRequestException ex) { return new ErrorResponse<>(ex.getMessage()); } // Database Exceptions @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = {MongoSocketException.class, MongoBulkWriteException.class, UncategorizedMongoDbException.class, MongoSocketException.class}) public ErrorResponse<?> handleMongoDbConnectionExceptions(Exception ex) { return new ErrorResponse<>(ex.getMessage()); } // Database Resource Exceptions @ResponseStatus(HttpStatus.NOT_FOUND) @ExceptionHandler(DatabaseResourceException.class) public ErrorResponse<?> handleDatabaseResourceException(DatabaseResourceException ex) { return new ErrorResponse<>(ex.getMessage()); } // Form Validation Exceptions @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return errors; } // Custom Authentication Error Handling public Mono<Void> handleAuthenticationError(ServerWebExchange exchange, AuthenticationException exception) { exchange.getResponse ().setStatusCode(HttpStatus.UNAUTHORIZED); exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON); // Customize your error response here String errorResponse = "{\"error\":\"Authentication failed\",\"message\":\"" + exception.getMessage() + "\"}"; return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(errorResponse.getBytes()))); } // Custom Access Denied Error Handling public Mono<Void> handleAccessDeniedError(ServerWebExchange exchange, AccessDeniedException exception) { exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON); // Customize your error response here String errorResponse = "{\"error\":\"Access denied\",\"message\":\"" + exception.getMessage() + "\"}"; return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(errorResponse.getBytes()))); } }
## Records Uniffi records are data objects whose fields are serialized and passed over the FFI. In UDL, they may be specified with the `dictionary` keyword: ```webidl dictionary OptionneurDictionnaire { string mandatory_property; string defaulted_property = "Specified by UDL or Rust"; }; ``` They are implemented as bare objects in Javascript, with a `type` declaration in Typescript. ```ts type MyRecord = { mandatoryProperty: string, defaultedProperty: string, }; ``` Using this scheme however, loses the default values provided by the UDL, or Rust. To correct this, `uniffi-bindgen-react-native` generates a companion factory object. ```ts const MyRecordFactory = { create(fields: Missing<MyRecord>) { … } defaults(): Partial<MyRecord> { … } }; ``` The `Missing<MyRecord>` type above is a little bit handwavy, but it's defined as the union of non-defaulted fields, and the partial of the defaulted fields. So, continuing with our example, the factory will be minimally happy with: ```ts const myRecord = MyRecordFactory.create({ mandatoryProperty: "Specified in Typescript" }); assert(myRecord.mandatoryProperty === "Specified in Typescript"); assert(myRecord.defaultProperty === "Specified by UDL or Rust"); ```
#pragma once #include <cstdlib> #include <algorithm> #include <iostream> template <typename T> class SimpleVector { public: SimpleVector() :begin_(nullptr), end_(nullptr), capacity_(0) {} explicit SimpleVector(size_t size){ begin_ = new T[size]; end_ = begin_ + size; capacity_ = size; } ~SimpleVector() { if (capacity_ == 1) delete begin_; else if (capacity_) delete[] begin_; begin_ = nullptr; end_ = nullptr; capacity_ = 0; } T& operator[](size_t index) { return begin_[index]; } T* begin() { return begin_; } T* end() { return end_; } size_t Size() const { return capacity_ == 0 ? 0 : end_ - begin_; } size_t Capacity() const { return capacity_; } void PushBack(const T& value){ if (!capacity_) { begin_ = new T(value); end_ = begin_ + 1; capacity_ = 1; return; } else if (capacity_ == Size()) Resize(); *end_ = value; end_++; } private: T* begin_; T* end_; size_t capacity_; void Resize () { T* temp = new T[capacity_ * 2]; std::copy (begin_, end_, temp); end_ = temp + Size(); if (capacity_ == 1) delete begin_; else delete[] begin_; begin_ = temp; capacity_ = capacity_ * 2; } };
import { HashTable } from "./helpers"; import { Question } from "./question"; import { LocalizableString } from "./localizablestring"; /** * A class that describes the Expression question type. It is a read-only question type that calculates a value based on a specified expression. * * [View Demo](https://surveyjs.io/form-library/examples/questiontype-expression/ (linkStyle)) */ export declare class QuestionExpressionModel extends Question { private expressionIsRunning; private expressionRunner; constructor(name: string); getType(): string; readonly hasInput: boolean; /* * A string that formats a question value. Use `{0}` to reference the question value in the format string. * @see displayStyle */ format: string; readonly locFormat: LocalizableString; /* * An expression used to calculate the question value. * * Refer to the following help topic for more information: [Expressions](https://surveyjs.io/form-library/documentation/design-survey-conditional-logic#expressions). */ expression: string; locCalculation(): void; unlocCalculation(): void; runCondition(values: HashTable<any>, properties: HashTable<any>): void; protected canCollectErrors(): boolean; protected hasRequiredError(): boolean; private createRunner; /* * The maximum number of fraction digits. Applies only if the `displayStyle` property is not `"none"`. Accepts values in the range from -1 to 20, where -1 disables the property. * * Default value: -1 * @see displayStyle * @see minimumFractionDigits * @see precision */ maximumFractionDigits: number; /* * The minimum number of fraction digits. Applies only if the `displayStyle` property is not `"none"`. Accepts values in the range from -1 to 20, where -1 disables the property. * * Default value: -1 * @see displayStyle * @see maximumFractionDigits */ minimumFractionDigits: number; private runIfReadOnlyValue; runIfReadOnly: boolean; readonly formatedValue: string; protected updateFormatedValue(): void; protected onValueChanged(): void; updateValueFromSurvey(newValue: any): void; protected getDisplayValueCore(keysAsText: boolean, value: any): any; /* * Specifies a display style for the question value. * * Possible values: * * - `"decimal"` * - `"currency"` * - `"percent"` * - `"date"` * - `"none"` (default) * * If you use the `"currency"` display style, you can also set the `currency` property to specify a currency other than USD. * @see currency * @see minimumFractionDigits * @see maximumFractionDigits * @see format */ displayStyle: string; /* * A three-letter currency code. Applies only if the `displayStyle` property is set to `"currency"`. * * Default value: "USD". * @see displayStyle * @see minimumFractionDigits * @see maximumFractionDigits * @see format */ currency: string; /* * Specifies whether to use grouping separators in number representation. Separators depend on the selected [locale](https://surveyjs.io/form-library/documentation/surveymodel#locale). * * Default value: `true` */ useGrouping: boolean; /* * Specifies how many decimal digits to keep in the expression value. * * Default value: -1 (unlimited) * @see maximumFractionDigits */ precision: number; private roundValue; protected getValueAsStr(val: any): string; } export declare function getCurrecyCodes(): Array<string>;
import { ArrowBack, Delete, RestartAlt, Save } from "@mui/icons-material" import { LoadingButton } from "@mui/lab" import { Autocomplete, Box, Button, Card, Container, FormControl, Grid, InputLabel, MenuItem, Select, SelectChangeEvent, TextField, Typography, } from "@mui/material" import { DatePicker } from "@mui/x-date-pickers" import { GetServerSidePropsContext } from "next" import Head from "next/head" import { ChangeEvent, WheelEvent, useState } from "react" import PageTitle from "src/components/PageTitle" import { Entity, Expense, Person, Site } from "src/constants/models" import SidebarLayout from "src/layouts/SidebarLayout" import { getExpense } from "src/lib/api/expense" import { getActivePersons } from "src/lib/api/person" import { getActiveSites } from "src/lib/api/site" import numWords from "src/lib/words" interface NewExpenseProps { sites: Site[] persons: Person[] expense: Expense } const ExpenseEdit = ({ sites, persons, expense }: NewExpenseProps) => { const [isLoading, setIsLoading] = useState(false) const [readOnly, setReadOnly] = useState(false) const [values, setValues] = useState<Expense>(expense as Expense) const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target const newValue = name === "amount" ? Number(value) : value setValues({ ...values, [name]: newValue, }) } const handleSelectChange = (event: SelectChangeEvent) => { setValues({ ...values, mode: event.target.value as string, }) } const handleDateChange = (newDate: Date | null) => { if (!newDate) return setValues({ ...values, date: newDate, }) } const handleWheel = (e: WheelEvent<HTMLDivElement>) => (e.target as EventTarget & HTMLDivElement).blur() const handleUpdateExpense = async () => { setIsLoading(true) const requestOptions = { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values), } const res = await fetch("/api/expense", requestOptions) if (res.status === 200) { setValues({ ...values, _id: (await res.json())._id, }) setReadOnly(true) } setIsLoading(false) } const handleDeleteExpense = async () => { setReadOnly(true) setIsLoading(true) const requestOptions = { method: "DELETE", } const res = await fetch(`/api/expense?id=${values._id}`, requestOptions) if (res.status === 200) { window.location.href = "/admin" } setIsLoading(false) } const props = { fullWidth: true, onChange: handleInputChange, disabled: isLoading, inputProps: { readOnly, }, } return ( <> <Head> <title>New Expense</title> </Head> <PageTitle heading="Edit Expense" subHeading="Edit a new Expense from database" /> <Container maxWidth="lg"> <Grid container direction="row" justifyContent="center" alignItems="stretch" spacing={4} > <Grid item xs={12}> <Card> <Box px={4} py={3}> <Typography variant="h4">Edit a new expense</Typography> <Grid container spacing={2} my={1}> <Grid item xs={12} md={4}> <DatePicker disabled={isLoading} readOnly={readOnly} label="Date of Expense" value={values.date} inputFormat="d MMM yyyy" onChange={handleDateChange} renderInput={(params) => ( <TextField {...params} fullWidth /> )} /> </Grid> <Grid item xs={12} md={4}> <TextField label="Expense Subject" name="subject" value={values.subject} {...props} /> </Grid> <Grid item xs={12} md={4}> <FormControl fullWidth> <InputLabel htmlFor="payment-mode"> Payment Mode </InputLabel> <Select disabled={isLoading} readOnly={readOnly} id="payment-mode" value={values.mode} onChange={handleSelectChange} name="mode" label="Payemnt Mode" > <MenuItem value="Cash">Cash</MenuItem> <MenuItem value="UPI">UPI</MenuItem> <MenuItem value="INB">INB</MenuItem> <MenuItem value="DD">DD</MenuItem> <MenuItem value="ATM">ATM</MenuItem> <MenuItem value="Cheque">Cheque</MenuItem> <MenuItem value="Other">Other</MenuItem> </Select> </FormControl> </Grid> <Grid item xs={12} md={4}> <TextField label="Expense Amount (in ₹)" name="amount" value={values.amount} helperText={numWords(values.amount)} {...props} type="number" onWheel={handleWheel} /> </Grid> <Grid item xs={12} md={8}> <TextField label="Remarks" name="remarks" value={values.remarks} multiline {...props} /> </Grid> <Grid item xs={12} md={4}> <Autocomplete disablePortal disabled={isLoading} readOnly={readOnly} id="site" options={sites} getOptionLabel={(option) => option.name} value={values.site as Site} onChange={(e, value, r) => setValues({ ...values, site: value as Entity, }) } renderInput={(params) => ( <TextField {...params} label="Site" /> )} /> </Grid> <Grid item xs={12} md={8}> <Autocomplete disablePortal disabled={isLoading} readOnly={readOnly} id="person" options={persons} getOptionLabel={(option) => option.name ? `${option.name} | ${option.contact}` : "" } value={values.person as Person} onChange={(e, value, r) => setValues({ ...values, person: value as Entity, }) } renderInput={(params) => ( <TextField {...params} label="Person" /> )} /> </Grid> <Grid item xs={12} md={4}> {readOnly && ( <Button fullWidth variant="contained" href={`/admin/expense?id=${values._id}`} startIcon={<ArrowBack />} > Go Back </Button> )} </Grid> <Grid item xs={12} md={4}> {readOnly ? ( <TextField label="Person ID" name="_id" value={values._id} {...props} /> ) : ( <LoadingButton fullWidth variant="contained" onClick={handleUpdateExpense} loading={isLoading} loadingPosition="start" startIcon={<Save />} > Update Expense </LoadingButton> )} </Grid> <Grid item xs={12} md={4}> <Button onClick={handleDeleteExpense} startIcon={<Delete />} fullWidth variant="outlined" disabled={readOnly || isLoading} > Delete Expense </Button> </Grid> </Grid> </Box> </Card> </Grid> </Grid> </Container> </> ) } ExpenseEdit.layout = SidebarLayout const getServerSideProps = async ({ res, query, }: GetServerSidePropsContext) => { res.setHeader( "Cache-Control", "public, s-maxage=10, stale-while-revalidate=59" ) const activeSites = await getActiveSites() const sites = JSON.parse(JSON.stringify(activeSites)) const activePersons = await getActivePersons() const persons = JSON.parse(JSON.stringify(activePersons)) if (activeSites.length === 0 && activePersons.length === 0) { return { notFound: true, } } const id = query.id as string if (!id) return { notFound: true } const result = await getExpense(id) if (!result) return { notFound: true } const expense = JSON.parse(JSON.stringify(result)) return { props: { sites, persons, expense, }, } } export { getServerSideProps } export default ExpenseEdit
import Backbone from 'backbone'; import HtmlUtils from 'edx-ui-toolkit/js/utils/html-utils'; import pageTpl from '../../../templates/learner_dashboard/program_header_view.underscore'; import MicroMastersLogo from '../../../images/programs/micromasters-program-details.svg'; import XSeriesLogo from '../../../images/programs/xseries-program-details.svg'; import ProfessionalCertificateLogo from '../../../images/programs/professional-certificate-program-details.svg'; class ProgramHeaderView extends Backbone.View { constructor(options) { const defaults = { el: '.js-program-header', }; // eslint-disable-next-line prefer-object-spread super(Object.assign({}, defaults, options)); } initialize() { this.breakpoints = { min: { medium: '768px', large: '1180px', }, }; this.tpl = HtmlUtils.template(pageTpl); this.render(); } getLogo() { // eslint-disable-next-line prefer-destructuring const type = this.model.get('programData').type; let logo = false; if (type === 'MicroMasters') { logo = MicroMastersLogo; } else if (type === 'XSeries') { logo = XSeriesLogo; } else if (type === 'Professional Certificate') { logo = ProfessionalCertificateLogo; } return logo; } getIsSubscribed() { const isSubscriptionEligible = this.model.get('isSubscriptionEligible'); const subscriptionData = this.model.get('subscriptionData')?.[0]; return ( isSubscriptionEligible && subscriptionData?.subscription_state === 'active' ); } render() { // eslint-disable-next-line no-undef const data = $.extend(this.model.toJSON(), { breakpoints: this.breakpoints, logo: this.getLogo(), isSubscribed: this.getIsSubscribed(), }); if (this.model.get('programData')) { HtmlUtils.setHtml(this.$el, this.tpl(data)); } } } export default ProgramHeaderView;
from typing import Callable import uvloop from pyrogram import idle from pyrogram.handlers import MessageHandler from src.custom_client import CustomClient from src.loggers import logger from src.message_emoji_manager import MessageEmojiManager from src.user_settings import UserSettings def register_msg_handler(custom_client: CustomClient, func: Callable) -> None: """ Registers message handler with a given function in a provided client """ pyrogram_response_handler: MessageHandler = MessageHandler(func) custom_client.add_handler(pyrogram_response_handler) return None def register_scheduler(custom_client: CustomClient, func: Callable) -> None: """ Registers scheduler with a given function in a provided client """ custom_client.scheduler.add_job( func=func, trigger=custom_client.scheduler.trigger, args=[custom_client], id=custom_client.name, replace_existing=True, ) custom_client.scheduler.start() return None user_settings: UserSettings = UserSettings.from_config(config_file="src/config.yaml") # uvloop.install() # https://docs.pyrogram.org/topics/speedups # seems deprecated in Python 3.12 client: CustomClient = CustomClient( name="my_app", user_settings=user_settings, sleep_threshold=0 ) message_emoji_manager: MessageEmojiManager = MessageEmojiManager() async def main(): # pragma: no cover async with client: await client.set_emoticon_picker() logger.success("Telegram auth completed successfully!") register_msg_handler(custom_client=client, func=message_emoji_manager.respond) register_scheduler(custom_client=client, func=message_emoji_manager.update) logger.success("Handlers are registered. App is ready to work.") await idle() if __name__ == "__main__": # pragma: no cover uvloop.run(client.run(main()))
package com.xiaochao.CustomerManagementSystem; public class CustomerView { private CustomerList customers = new CustomerList(10); public CustomerView() { Customer cust = new Customer("张三", '男', 30, "010-56253825", "[email protected]"); customers.addCustomer(cust); } //进入主菜单的方法 public void enterMainMenu(){ boolean isFlag = true; while(isFlag){ System.out .println("\n--------------------拼电商客户管理系统--------------------\n"); System.out.println(" 1 添 加 客 户"); System.out.println(" 2 修 改 客 户"); System.out.println(" 3 删 除 客 户"); System.out.println(" 4 客 户 列 表"); System.out.println(" 5 退 出\n"); System.out.print(" 请选择(1-5): "); char key = CMUtility.readMenuSelection(); //获取用户选择 switch(key){ case '1': addNewCustomer(); break; case '2': modifyCustomer(); break; case '3': deleteCustomer(); break; case '4': listAllCustomer(); break; case '5': System.out.println("确认是否退出(Y/N):"); char isExit = CMUtility.readConfirmSelection(); if(isExit=='Y') { isFlag = false; } break; } } } private void addNewCustomer(){ System.out.println("---------------------添加客户---------------------"); System.out.print("姓名:"); String name = CMUtility.readString(4); System.out.print("性别:"); char gender = CMUtility.readChar(); System.out.print("年龄:"); int age = CMUtility.readInt(); System.out.print("电话:"); String phone = CMUtility.readString(15); System.out.print("邮箱:"); String email = CMUtility.readString(15); Customer custs = new Customer(name,gender,age,phone,email); boolean flag = customers.addCustomer(custs); if(flag){ System.out.println("---------------------添加完成---------------------"); }else{ System.out.println("----------------记录已满,无法添加-----------------"); } } private void modifyCustomer(){ System.out.println("---------------------修改客户---------------------"); int index = 0; Customer c1 = null; for (;;) { System.out.print("请选择待修改客户编号(-1退出):"); index = CMUtility.readInt(); if (index == -1) { return; } c1 = customers.getCustomer(index - 1); if (c1 == null) { System.out.println("无法找到指定客户!"); } else break; } System.out.print("姓名(" + c1.getName() + "):"); String name = CMUtility.readString(4, c1.getName()); System.out.print("性别(" + c1.getGender() + "):"); char gender = CMUtility.readChar(c1.getGender()); System.out.print("年龄(" + c1.getAge() + "):"); int age = CMUtility.readInt(c1.getAge()); System.out.print("电话(" + c1.getPhone() + "):"); String phone = CMUtility.readString(15, c1.getPhone()); System.out.print("邮箱(" + c1.getEmail() + "):"); String email = CMUtility.readString(15, c1.getEmail()); c1 = new Customer(name, gender, age, phone, email); boolean flag = customers.replaceCustomer(index - 1, c1); if (flag) { System.out .println("---------------------修改完成---------------------"); } else { System.out.println("----------无法找到指定客户,修改失败--------------"); } } private void deleteCustomer(){ System.out.println("---------------------删除客户---------------------"); int index = 0; Customer c2 = null; for (;;) { System.out.print("请选择待删除客户编号(-1退出):"); index = CMUtility.readInt(); if (index == -1) { return; } c2 = customers.getCustomer(index - 1); if (c2 == null) { System.out.println("无法找到指定客户!"); } else break; } System.out.print("确认是否删除(Y/N):"); char yn = CMUtility.readConfirmSelection(); if (yn == 'N') return; boolean flag = customers.deleteCustomer(index - 1); if (flag) { System.out .println("---------------------删除完成---------------------"); } else { System.out.println("----------无法找到指定客户,删除失败--------------"); } } private void listAllCustomer(){ System.out.println("---------------------------客户列表---------------------------"); Customer[] custs = customers.getAllCustomers(); if (custs.length == 0) { System.out.println("没有客户记录!"); } else { System.out.println("编号\t姓名\t\t性别\t\t年龄\t\t\t电话\t\t\t\t邮箱"); for (int i = 0; i < custs.length; i++) { // System.out.println(i + 1 + "\t" + custs[i].getName() + "\t" + custs[i].getGender() + "\t" + custs[i].getAge() + "\t\t" + custs[i].getPhone() + "\t" + custs[i].getEmail()); System.out.println((i+1) + "\t" + custs[i].getDetails()); } } System.out.println("-------------------------客户列表完成-------------------------"); } public static void main(String[] args) { CustomerView view = new CustomerView(); view.enterMainMenu(); } }
"use client"; import Link from "next/link"; import MainNavigation, { NavigationMenuItem } from "../MainNavigation"; import { useState } from "react"; import { Bars3Icon, XMarkIcon } from "@heroicons/react/24/outline"; import { mainmenu } from "@/lib/mocks"; import { Dialog, DialogContent } from "@radix-ui/react-dialog"; import { Button } from "@/components/ui/button"; import LogoLink from "../LogoLink"; import { Disclosure } from "@headlessui/react"; import { ChevronDownIcon } from "lucide-react"; import { cn } from "@/lib/utils"; function Header() { const [mobileMenuOpen, setMobileMenuOpen] = useState(false); return ( <header className="fixed z-50 w-full top-0"> <nav className="bg-white border-gray-200 py-4 shadow-sm"> <div className="flex flex-wrap justify-between items-center container"> <div className="flex lg:flex-1"> <LogoLink /> </div> <MainNavigation menuItems={mainmenu} /> <div className="flex lg:hidden"> <Button variant="ghost" className="-m-2.5 inline-flex items-center justify-center p-2.5 rounded-md text-gray-400 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-blue-500" onClick={() => setMobileMenuOpen(true)} type="button" > <span className="sr-only">Open menu</span> <Bars3Icon className="h-6 w-6" aria-hidden="true" /> </Button> </div> </div> </nav> <div className="lg:hidden"> <Dialog open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}> <DialogContent className="fixed inset-y-0 right-0 z-10 w-full overflow-y-auto bg-primary sm:max-w-sm sm:ring-1 sm:ring-primary"> <div className="flex items-center justify-between p-4"> <LogoLink size={60} /> <Button type="button" variant="ghost" className="p-4 text-white hover:bg-transparent hover:text-gray-300 focus:outline-none justify-end" onClick={() => setMobileMenuOpen(false)} > <span className="sr-only">Close menu</span> <XMarkIcon className="h-6 w-6" aria-hidden="true" /> </Button> </div> <div className="mt-6 flow-root"> <div className="-my-6 divide-y-2 divide-gray-500/10"> <div className="py-6 space-y-2"> <ul> {mainmenu.map((item) => ( <li key={item.title}> {item?.subitems ? ( <Disclosure> {({ open }) => ( <> <Disclosure.Button className="flex w-full items-center justify-between px-4 py-2 text-white hover:bg-gray-800 focus:bg-gray-800 focus:outline-none"> {item.title} <ChevronDownIcon className={cn( "w-4 h-4 flex-none transition-transform", { "transform rotate-180": open, } )} aria-hidden="true" /> </Disclosure.Button> <Disclosure.Panel> <ul> {(item?.subitems ?? []).map( (subitem: NavigationMenuItem) => ( <li key={subitem.title}> <Link className="block px-4 py-2 text-white text-sm hover:bg-gray-800 focus:bg-gray-800 focus:outline-none" href={subitem.href} passHref > {subitem.title} </Link> </li> ) )} </ul> </Disclosure.Panel> </> )} </Disclosure> ) : ( <Link className="block px-4 py-2 text-white hover:bg-gray-800 focus:bg-gray-800 focus:outline-none" href={item.href} passHref > {item.title} </Link> )} </li> ))} </ul> </div> </div> </div> </DialogContent> </Dialog> </div> </header> ); } export default Header;
from copy import copy import numpy as np from .util import intersperse, plaintext2dashdots, wpm2dit_time, dashdot2char from .timings_type import * def dashdotchar2timing(dashdotchar, label=None): """Convert a '.', a '-', or a ' ' to a Timing object encoding duration and an optional label""" if dashdotchar == '.': return Timing(True, 1, DOT, label) elif dashdotchar == '-': return Timing(True, 3, DASH, label) elif dashdotchar == ' ': return Timing(False, 7, WORD_SPACE, label) else: raise Exception("Unreconized dashdot, should be . or - or space") def dashdot2timing(dashdot, label): """Convert a "dashdot" representation, such as '.--' as returned by and element of plaintext2dashdots() into a list of Timing duration objects""" r = [dashdotchar2timing(d, label) for d in dashdot] return intersperse(r, Timing(False, 1, SYM_SPACE, label)) def dashdots2timings(dashdots, labels): """Convert a "dashdotS" representation, which is a list of encoded characters such as ['.--', '.-'], into a list of lists of Timing duration objects""" return [dashdot2timing(dd, label) for dd, label in zip(dashdots, labels)] def flatten_timings(timings): """Return last flattened timings and labels""" r = [] for timing in timings: r.extend(timing) r.append(Timing(False, 3, CHAR_SPACE, timing[0].label)) # Inter-character space # Now remove inter-character space before spaces r2 = [] for i in range(len(r) - 1): if r[i].is_interchar_space() and r[i+1].is_space(): pass else: r2.append(r[i]) r2.append(r[-1]) # Now remove inter-character spaces after spaces r3 = [r2[0]] for i in range(len(r2) - 1): if r2[i+1].is_interchar_space() and r2[i].is_space(): pass else: r3.append(r2[i+1]) # Modify the labels on spaces to reflect the prior character # We actually use two-character labels, "A " prior_label = None for t in r3: if prior_label is not None and prior_label != ' ' and t.is_space(): t.label = prior_label + ' ' if not t.is_space(): prior_label = t.label else: prior_label = None # Remove labels from everything except spaces and inter-character spaces for t in r3: if not t.is_space() and not t.is_interchar_space(): t.label = INCOMPLETE return r3 def timings2training(timings): flat_timings = flatten_timings(timings) return flat_timings def plaintext2training(plaintext: str) -> List[Timing]: dd = plaintext2dashdots(plaintext) timings = dashdots2timings(dd, plaintext) flat = flatten_timings(timings) return flat def average_mark_length(timings: List[Timing]) -> float: """Return the average length of the marks (dits and dahs)""" marks = [t for t in timings if t.is_on] if len(marks) == 0: return 0 return sum([t.duration for t in marks]) / len(marks) def average_space_length(timings: List[Timing]) -> float: """Return the average length of the spaces""" spaces = [t for t in timings if not t.is_on] if len(spaces) == 0: return 0 return sum([t.duration for t in spaces]) / len(spaces) def normalize_marks(timings: List[Timing]) -> List[Timing]: """Normalize the mark lengths to the PARIS standard""" timings = copy_timings(timings) avg_mark = average_mark_length(timings) if avg_mark == 0: return timings scale = normalize_marks.paris_avg_mark / avg_mark for t in timings: if t.is_on: t.duration *= scale return timings # The average standard mark length for PARIS normalize_marks.paris_avg_mark = average_mark_length(plaintext2training("PARIS ")) def normalize_spaces(timings: List[Timing]) -> List[Timing]: """Normalize the space lengths to match the PARIS standard""" timings = copy_timings(timings) avg_space = average_space_length(timings) if avg_space == 0: return timings scale = normalize_spaces.paris_avg_space / avg_space for t in timings: if not t.is_on: t.duration *= scale return timings # The average standard mark length for PARIS normalize_spaces.paris_avg_space = average_space_length(plaintext2training("PARIS ")) def normalize_timings(timings: List[Timing]) -> List[Timing]: """Normalize the timings to match the PARIS standard (approx 1=dit, 3=dah, etc)""" timings = normalize_marks(timings) timings = normalize_spaces(timings) return timings def scale_timing(timing: Timing, wpm: float) -> Timing: """Scale the duration of a Timing object from standard (1=dit, 3=dah, etc) to the specified Words per minute equivalent and return a new Timing object with the scaled duration.""" scale = wpm2dit_time(wpm) return Timing(timing.is_on, timing.duration * scale, timing.stype, timing.label, wpm=wpm) def scale_timings(timings: List[Timing], wpm: float) -> List[Timing]: """Scale the timings to different wpm""" timings = normalize_timings(timings) return [scale_timing(t, wpm) for t in timings] def restrict_mark_space_times( timings: List[Timing], min_mark: float, max_mark: float, min_space: float, max_space: float, ) -> List[Timing]: """Restrict the durations of the symbols to the specified ranges""" timings = copy_timings(timings) for t in timings: if t.is_on: t.duration = max(min_mark, min(max_mark, t.duration)) else: t.duration = max(min_space, min(max_space, t.duration)) return timings def normalize( timings: List[Timing], num_steps: int, min_mark: float, max_mark: float, min_space: float, max_space: float, ) -> List[Timing]: """Normalize the timings to a standard duration within limits""" timings = timings[-num_steps:] timings = normalize_timings(timings) timings = restrict_mark_space_times( timings, min_mark, max_mark, min_space, max_space ) # We normalize again with the outliers reduced timings = normalize_timings(timings) return timings def timings2dashdots(timings: List[Timing]) -> Tuple[List[str], List[Timing]]: dd = [] sym = '' new_timings = [] for t in timings: new_timings.append(copy(t)) new_timings[-1].label = '~' if t.stype == DOT: sym += '.' elif t.stype == DASH: sym += '-' elif t.stype == WORD_SPACE: if len(sym) > 0: dd.append(sym) try: new_timings[-1].label = dashdot2char(sym) + ' ' except KeyError: new_timings[-1].label = ' ' dd.append(' ') elif t.stype == CHAR_SPACE: if len(sym) > 0: dd.append(sym) try: new_timings[-1].label = dashdot2char(sym) except KeyError: pass sym = '' elif t.stype == SYM_SPACE: pass else: raise ValueError(f"Unknown stype {t.stype}") return dd, new_timings def separate_durations_by_stype(timings_set: List[List[Timing]]) -> dict: """Return a dictionary of durations for each symbol type in the timings set. """ durations = {} for sym in marks_stypes + spaces_stypes: durations[sym] = np.array([t.duration for timing in timings_set for t in timing if t.stype == sym]) return durations def string2timings(text: str, wpm: float, fwpm: float) -> List[Timing]: """ Convert a string to a list of Morse Code Timing objects :param text: the string to convert :param wpm: words per minute :param fwpm: fansworth words per minute, used for characters and intra-character spaces :return: """ fdit_time = wpm2dit_time(fwpm) dit_time = wpm2dit_time(wpm) dd = plaintext2dashdots(text) timings = [] assert(len(dd) == len(text)) for char, label in zip(dd, text): for mark_or_space in char: if mark_or_space == '.': timings.append(Timing(True, fdit_time, DOT, wpm=fwpm, label=INCOMPLETE)) timings.append(Timing(False, fdit_time, SYM_SPACE, wpm=fwpm, label=INCOMPLETE)) elif mark_or_space == '-': timings.append(Timing(True, 3 * fdit_time, DASH, wpm=fwpm, label=INCOMPLETE)) timings.append(Timing(False, fdit_time, SYM_SPACE, wpm=fwpm, label=INCOMPLETE)) elif mark_or_space == ' ': timings.append(Timing(False, 7 * dit_time, WORD_SPACE, wpm=wpm, label=INCOMPLETE)) else: raise Exception(f"Expected ., -, or space but got {mark_or_space}") if timings[-1].stype == SYM_SPACE: timings = timings[:-1] if char != ' ': timings.append(Timing(False, 3 * dit_time, CHAR_SPACE, wpm=wpm, label=INCOMPLETE)) if len(timings) > 1: timings[-1].label = label # this will always be a WORD_SPACE or CHAR_SPACE # Remove trailing char or sym spaces while len(timings) > 0 and timings[-1].stype in [SYM_SPACE, CHAR_SPACE]: timings = timings[:-1] # Remove leading char or sym spaces while len(timings) > 0 and timings[0].stype in [SYM_SPACE, CHAR_SPACE]: timings = timings[1:] # Now remove extra spaces timings2 = [] for i, timing in enumerate(timings): if timing.stype not in [SYM_SPACE, CHAR_SPACE]: timings2.append(timing) else: word_space_before = i > 0 and timings[i - 1].stype == WORD_SPACE word_space_after = i < len(timings) - 1 and timings[i + 1].stype == WORD_SPACE if (not word_space_before) and (not word_space_after): timings2.append(timing) return timings2
var express = require('express'); var router = express.Router(); const models = require('../models'); var jwt = require('jsonwebtoken'); var { secretKey, Response, tokenValid } = require('../helpers/util') router.post('/auth', async function (req, res, next) { try { const { email, password } = req.body const user = await models.User.findOne({ where: { email: email } }) if (!user) return res.json(new Response('User not Found', false)) const match = await user.authenticate(password) if (!match) return res.json(new Response('Password Is Wrong', false)) var token = jwt.sign({ user: user.id }, secretKey); res.json(new Response({ email: user.email, token: token })) } catch (error) { res.json(new Response('Something Went Wrong', false)) } }); router.get('/', async function (req, res, next) { try { const page = parseInt(req.query.page) || 1; const limit = 3; const offset = (page - 1) * limit; const { count, rows: users } = await models.User.findAndCountAll({ include: [ { model: models.Todo } ], order: [['id', 'asc']], limit, offset }) res.json({ count, users, page }) } catch (error) { res.json({ error }) } }); router.post('/', async function (req, res, next) { try { const user = await models.User.create({ email: req.body.email, password: req.body.password }) res.json(user) } catch (error) { res.json(new Response('Something Went Wrong', false)) } }); module.exports = router;
from flask import Flask, render_template, request, send_file from qrcode import constants import qrcode from io import BytesIO app = Flask(__name__, template_folder='templates') @app.route('/') def index(): return render_template('index.html') @app.route('/generate_qr', methods=['POST']) def generate_qr(): # Get user input from the form data = request.form['data'] # Create a QRCode instance q = qrcode.QRCode( version=1, error_correction=constants.ERROR_CORRECT_H, box_size=10, border=4, ) q.add_data(data) q.make(fit=True) # Create a BytesIO object to store the image img_stream = BytesIO() img = q.make_image(fill_color="orange", back_color="white") img.save(img_stream) img_stream.seek(0) # Return the image as a response return send_file(img_stream, mimetype='image/png')
import { useState } from "react"; import reactLogo from "./assets/react.svg"; import viteLogo from "/vite.svg"; import "./App.css"; import Header from "./components/Header"; import { Route, Routes } from "react-router-dom"; import Home from "./pages/Home"; import Chats from "./components/Chats"; import Signup from "./components/Signup"; import Login from "./components/Login"; import NotFound from "./components/NotFound"; function App() { const [count, setCount] = useState(0); return ( <main> <Header /> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/signup" element={<Signup />} /> <Route path="/chat" element={<Chats />} /> <Route path="*" element={<NotFound />} /> </Routes> </main> ); } export default App;
<?php /** * @file * Allows administrators to customize the site's navigation menus. * * A menu (in this context) is a hierarchical collection of links, generally * used for navigation. */ use Drupal\Core\Url; use Drupal\Core\Breadcrumb\Breadcrumb; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Block\BlockPluginInterface; use Drupal\Core\Link; use Drupal\Core\Menu\MenuLinkInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\menu_link_content\Entity\MenuLinkContent; use Drupal\node\NodeTypeInterface; use Drupal\system\Entity\Menu; use Drupal\node\NodeInterface; use Drupal\system\MenuInterface; /** * Implements hook_help(). */ function menu_ui_help($route_name, RouteMatchInterface $route_match) { switch ($route_name) { case 'help.page.menu_ui': $output = ''; $output .= '<h3>' . t('About') . '</h3>'; $output .= '<p>' . t('The Menu UI module provides an interface for managing menus. A menu is a hierarchical collection of links, which can be within or external to the site, generally used for navigation. For more information, see the <a href=":menu">online documentation for the Menu UI module</a>.', [':menu' => 'https://www.drupal.org/documentation/modules/menu/']) . '</p>'; $output .= '<h3>' . t('Uses') . '</h3>'; $output .= '<dl>'; $output .= '<dt>' . t('Managing menus') . '</dt>'; $output .= '<dd>' . t('Users with the <em>Administer menus and menu links</em> permission can add, edit, and delete custom menus on the <a href=":menu">Menus page</a>. Custom menus can be special site menus, menus of external links, or any combination of internal and external links. You may create an unlimited number of additional menus, each of which will automatically have an associated block (if you have the <a href=":block_help">Block module</a> installed). By selecting <em>Edit menu</em>, you can add, edit, or delete links for a given menu. The links listing page provides a drag-and-drop interface for controlling the order of links, and creating a hierarchy within the menu.', [':block_help' => (\Drupal::moduleHandler()->moduleExists('block')) ? Url::fromRoute('help.page', ['name' => 'block'])->toString() : '#', ':menu' => Url::fromRoute('entity.menu.collection')->toString()]) . '</dd>'; $output .= '<dt>' . t('Displaying menus') . '</dt>'; $output .= '<dd>' . t('If you have the Block module enabled, then each menu that you create is rendered in a block that you enable and position on the <a href=":blocks">Block layout page</a>. In some <a href=":themes">themes</a>, the main menu and possibly the secondary menu will be output automatically; you may be able to disable this behavior on the <a href=":themes">theme\'s settings page</a>.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? Url::fromRoute('block.admin_display')->toString() : '#', ':themes' => Url::fromRoute('system.themes_page')->toString(), ':theme_settings' => Url::fromRoute('system.theme_settings')->toString()]) . '</dd>'; $output .= '</dl>'; return $output; } if ($route_name == 'entity.menu.add_form' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) { return '<p>' . t('You can enable the newly-created block for this menu on the <a href=":blocks">Block layout page</a>.', [':blocks' => Url::fromRoute('block.admin_display')->toString()]) . '</p>'; } elseif ($route_name == 'entity.menu.collection' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) { return '<p>' . t('Each menu has a corresponding block that is managed on the <a href=":blocks">Block layout page</a>.', [':blocks' => Url::fromRoute('block.admin_display')->toString()]) . '</p>'; } } /** * Implements hook_entity_type_build(). */ function menu_ui_entity_type_build(array &$entity_types) { /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */ $entity_types['menu'] ->setFormClass('add', 'Drupal\menu_ui\MenuForm') ->setFormClass('edit', 'Drupal\menu_ui\MenuForm') ->setFormClass('delete', 'Drupal\menu_ui\Form\MenuDeleteForm') ->setListBuilderClass('Drupal\menu_ui\MenuListBuilder') ->setLinkTemplate('add-form', '/admin/structure/menu/add') ->setLinkTemplate('delete-form', '/admin/structure/menu/manage/{menu}/delete') ->setLinkTemplate('edit-form', '/admin/structure/menu/manage/{menu}') ->setLinkTemplate('add-link-form', '/admin/structure/menu/manage/{menu}/add') ->setLinkTemplate('collection', '/admin/structure/menu'); if (isset($entity_types['node'])) { $entity_types['node']->addConstraint('MenuSettings', []); } } /** * Implements hook_block_view_BASE_BLOCK_ID_alter() for 'system_menu_block'. */ function menu_ui_block_view_system_menu_block_alter(array &$build, BlockPluginInterface $block) { if ($block->getBaseId() == 'system_menu_block') { $menu_name = $block->getDerivativeId(); $build['#contextual_links']['menu'] = [ 'route_parameters' => ['menu' => $menu_name], ]; } } /** * Helper function to create or update a menu link for a node. * * @param \Drupal\node\NodeInterface $node * Node entity. * @param array $values * Values for the menu link. */ function _menu_ui_node_save(NodeInterface $node, array $values) { /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */ if (!empty($values['entity_id'])) { $entity = MenuLinkContent::load($values['entity_id']); if ($entity->isTranslatable()) { if (!$entity->hasTranslation($node->language()->getId())) { $entity = $entity->addTranslation($node->language()->getId(), $entity->toArray()); } else { $entity = $entity->getTranslation($node->language()->getId()); } } } else { // Create a new menu_link_content entity. $entity = MenuLinkContent::create([ 'link' => ['uri' => 'entity:node/' . $node->id()], 'langcode' => $node->language()->getId(), ]); $entity->enabled->value = 1; } $entity->title->value = trim($values['title']); $entity->description->value = trim($values['description']); $entity->menu_name->value = $values['menu_name']; $entity->parent->value = $values['parent']; $entity->weight->value = $values['weight'] ?? 0; $entity->isDefaultRevision($node->isDefaultRevision()); $entity->save(); } /** * Returns the definition for a menu link for the given node. * * @param \Drupal\node\NodeInterface $node * The node entity. * * @return array * An array that contains default values for the menu link form. */ function menu_ui_get_menu_link_defaults(NodeInterface $node) { // Prepare the definition for the edit form. /** @var \Drupal\node\NodeTypeInterface $node_type */ $node_type = $node->type->entity; $menu_name = strtok($node_type->getThirdPartySetting('menu_ui', 'parent', 'main:'), ':'); $defaults = FALSE; if ($node->id()) { $id = FALSE; // Give priority to the default menu $type_menus = $node_type->getThirdPartySetting('menu_ui', 'available_menus', ['main']); if (in_array($menu_name, $type_menus)) { $query = \Drupal::entityQuery('menu_link_content') ->accessCheck(TRUE) ->condition('link.uri', 'node/' . $node->id()) ->condition('menu_name', $menu_name) ->sort('id', 'ASC') ->range(0, 1); $result = $query->execute(); $id = (!empty($result)) ? reset($result) : FALSE; } // Check all allowed menus if a link does not exist in the default menu. if (!$id && !empty($type_menus)) { $query = \Drupal::entityQuery('menu_link_content') ->accessCheck(TRUE) ->condition('link.uri', 'entity:node/' . $node->id()) ->condition('menu_name', array_values($type_menus), 'IN') ->sort('id', 'ASC') ->range(0, 1); $result = $query->execute(); $id = (!empty($result)) ? reset($result) : FALSE; } if ($id) { $menu_link = MenuLinkContent::load($id); $menu_link = \Drupal::service('entity.repository')->getTranslationFromContext($menu_link); $defaults = [ 'entity_id' => $menu_link->id(), 'id' => $menu_link->getPluginId(), 'title' => $menu_link->getTitle(), 'title_max_length' => $menu_link->getFieldDefinitions()['title']->getSetting('max_length'), 'description' => $menu_link->getDescription(), 'description_max_length' => $menu_link->getFieldDefinitions()['description']->getSetting('max_length'), 'menu_name' => $menu_link->getMenuName(), 'parent' => $menu_link->getParentId(), 'weight' => $menu_link->getWeight(), ]; } } if (!$defaults) { // Get the default max_length of a menu link title from the base field // definition. $field_definitions = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('menu_link_content'); $max_length = $field_definitions['title']->getSetting('max_length'); $description_max_length = $field_definitions['description']->getSetting('max_length'); $defaults = [ 'entity_id' => 0, 'id' => '', 'title' => '', 'title_max_length' => $max_length, 'description' => '', 'description_max_length' => $description_max_length, 'menu_name' => $menu_name, 'parent' => '', 'weight' => 0, ]; } return $defaults; } /** * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm. * * Adds menu item fields to the node form. * * @see menu_ui_form_node_form_submit() */ function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) { // Generate a list of possible parents (not including this link or descendants). // @todo This must be handled in a #process handler. $node = $form_state->getFormObject()->getEntity(); $defaults = menu_ui_get_menu_link_defaults($node); /** @var \Drupal\node\NodeTypeInterface $node_type */ $node_type = $node->type->entity; /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */ $menu_parent_selector = \Drupal::service('menu.parent_form_selector'); $type_menus_ids = $node_type->getThirdPartySetting('menu_ui', 'available_menus', ['main']); if (empty($type_menus_ids)) { return; } /** @var \Drupal\system\MenuInterface[] $type_menus */ $type_menus = Menu::loadMultiple($type_menus_ids); $available_menus = []; foreach ($type_menus as $menu) { $available_menus[$menu->id()] = $menu->label(); } if ($defaults['id']) { $default = $defaults['menu_name'] . ':' . $defaults['parent']; } else { $default = $node_type->getThirdPartySetting('menu_ui', 'parent', 'main:'); } $parent_element = $menu_parent_selector->parentSelectElement($default, $defaults['id'], $available_menus); // If no possible parent menu items were found, there is nothing to display. if (empty($parent_element)) { return; } $form['menu'] = [ '#type' => 'details', '#title' => t('Menu settings'), '#access' => \Drupal::currentUser()->hasPermission('administer menu'), '#open' => (bool) $defaults['id'], '#group' => 'advanced', '#attached' => [ 'library' => ['menu_ui/drupal.menu_ui'], ], '#tree' => TRUE, '#weight' => -2, '#attributes' => ['class' => ['menu-link-form']], ]; $form['menu']['enabled'] = [ '#type' => 'checkbox', '#title' => t('Provide a menu link'), '#default_value' => (int) (bool) $defaults['id'], ]; $form['menu']['link'] = [ '#type' => 'container', '#parents' => ['menu'], '#states' => [ 'invisible' => [ 'input[name="menu[enabled]"]' => ['checked' => FALSE], ], ], ]; // Populate the element with the link data. foreach (['id', 'entity_id'] as $key) { $form['menu']['link'][$key] = ['#type' => 'value', '#value' => $defaults[$key]]; } $form['menu']['link']['title'] = [ '#type' => 'textfield', '#title' => t('Menu link title'), '#default_value' => $defaults['title'], '#maxlength' => $defaults['title_max_length'], ]; $form['menu']['link']['description'] = [ '#type' => 'textfield', '#title' => t('Description'), '#default_value' => $defaults['description'], '#description' => t('Shown when hovering over the menu link.'), '#maxlength' => $defaults['description_max_length'], ]; $form['menu']['link']['menu_parent'] = $parent_element; $form['menu']['link']['menu_parent']['#title'] = t('Parent link'); $form['menu']['link']['menu_parent']['#attributes']['class'][] = 'menu-parent-select'; $form['menu']['link']['weight'] = [ '#type' => 'number', '#title' => t('Weight'), '#default_value' => $defaults['weight'], '#description' => t('Menu links with lower weights are displayed before links with higher weights.'), ]; foreach (array_keys($form['actions']) as $action) { if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') { $form['actions'][$action]['#submit'][] = 'menu_ui_form_node_form_submit'; } } $form['#entity_builders'][] = 'menu_ui_node_builder'; } /** * Entity form builder to add the menu information to the node. */ function menu_ui_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) { $entity->menu = $form_state->getValue('menu'); } /** * Form submission handler for menu item field on the node form. * * @see menu_ui_form_node_form_alter() */ function menu_ui_form_node_form_submit($form, FormStateInterface $form_state) { $node = $form_state->getFormObject()->getEntity(); if (!$form_state->isValueEmpty('menu')) { $values = $form_state->getValue('menu'); if (empty($values['enabled'])) { if ($values['entity_id']) { $entity = MenuLinkContent::load($values['entity_id']); $entity->delete(); } } elseif (trim($values['title'])) { // Decompose the selected menu parent option into 'menu_name' and 'parent', // if the form used the default parent selection widget. if (!empty($values['menu_parent'])) { [$menu_name, $parent] = explode(':', $values['menu_parent'], 2); $values['menu_name'] = $menu_name; $values['parent'] = $parent; } _menu_ui_node_save($node, $values); } } } /** * Implements hook_form_FORM_ID_alter() for \Drupal\node\NodeTypeForm. * * Adds menu options to the node type form. * * @see NodeTypeForm::form() * @see menu_ui_form_node_type_form_builder() */ function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) { /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */ $menu_parent_selector = \Drupal::service('menu.parent_form_selector'); $menu_options = array_map(function (MenuInterface $menu) { return $menu->label(); }, Menu::loadMultiple()); asort($menu_options); /** @var \Drupal\node\NodeTypeInterface $type */ $type = $form_state->getFormObject()->getEntity(); $form['menu'] = [ '#type' => 'details', '#title' => t('Menu settings'), '#attached' => [ 'library' => ['menu_ui/drupal.menu_ui.admin'], ], '#group' => 'additional_settings', ]; $form['menu']['menu_options'] = [ '#type' => 'checkboxes', '#title' => t('Available menus'), '#default_value' => $type->getThirdPartySetting('menu_ui', 'available_menus', ['main']), '#options' => $menu_options, '#description' => t('The menus available to place links in for this content type.'), ]; // @todo See if we can avoid pre-loading all options by changing the form or // using a #process callback. https://www.drupal.org/node/2310319 // To avoid an 'illegal option' error after saving the form we have to load // all available menu parents. Otherwise, it is not possible to dynamically // add options to the list using ajax. $options_cacheability = new CacheableMetadata(); $options = $menu_parent_selector->getParentSelectOptions('', NULL, $options_cacheability); $form['menu']['menu_parent'] = [ '#type' => 'select', '#title' => t('Default parent link'), '#default_value' => $type->getThirdPartySetting('menu_ui', 'parent', 'main:'), '#options' => $options, '#description' => t('Choose the menu link to be the default parent for a new link in the content authoring form.'), '#attributes' => ['class' => ['menu-title-select']], ]; $options_cacheability->applyTo($form['menu']['menu_parent']); $form['#validate'][] = 'menu_ui_form_node_type_form_validate'; $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder'; } /** * Validate handler for forms with menu options. * * @see menu_ui_form_node_type_form_alter() */ function menu_ui_form_node_type_form_validate(&$form, FormStateInterface $form_state) { $available_menus = array_filter($form_state->getValue('menu_options')); // If there is at least one menu allowed, the selected item should be in // one of them. if (count($available_menus)) { $menu_item_id_parts = explode(':', $form_state->getValue('menu_parent')); if (!in_array($menu_item_id_parts[0], $available_menus)) { $form_state->setErrorByName('menu_parent', t('The selected menu link is not under one of the selected menus.')); } } else { $form_state->setValue('menu_parent', ''); } } /** * Entity builder for the node type form with menu options. * * @see menu_ui_form_node_type_form_alter() */ function menu_ui_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) { $type->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options')))); $type->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent')); } /** * Return an associative array of the custom menus names. * * @param bool $all * (optional) If FALSE return only user-added menus, or if TRUE also include * the menus defined by the system. Defaults to TRUE. * * @return array * An array with the machine-readable names as the keys, and human-readable * titles as the values. * * @deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. Use * \Drupal\system\Entity\Menu::loadMultiple() instead. * * @see https://www.drupal.org/node/3027453 */ function menu_ui_get_menus($all = TRUE) { @trigger_error(__FUNCTION__ . '() is deprecated in drupal:9.3.0 and is removed from drupal:10.0.0. Use \Drupal\system\Entity\Menu::loadMultiple() instead. See https://www.drupal.org/node/3027453', E_USER_DEPRECATED); if ($custom_menus = Menu::loadMultiple()) { if (!$all) { $custom_menus = array_diff_key($custom_menus, menu_list_system_menus()); } foreach ($custom_menus as $menu_name => $menu) { $custom_menus[$menu_name] = $menu->label(); } asort($custom_menus); } return $custom_menus; } /** * Implements hook_preprocess_HOOK() for block templates. */ function menu_ui_preprocess_block(&$variables) { if ($variables['configuration']['provider'] == 'menu_ui') { $variables['attributes']['role'] = 'navigation'; } } /** * Implements hook_system_breadcrumb_alter(). */ function menu_ui_system_breadcrumb_alter(Breadcrumb $breadcrumb, RouteMatchInterface $route_match, array $context) { // Custom breadcrumb behavior for editing menu links, we append a link to // the menu in which the link is found. if (($route_match->getRouteName() == 'menu_ui.link_edit') && $menu_link = $route_match->getParameter('menu_link_plugin')) { if (($menu_link instanceof MenuLinkInterface)) { // Add a link to the menu admin screen. $menu = Menu::load($menu_link->getMenuName()); $breadcrumb->addLink(Link::createFromRoute($menu->label(), 'entity.menu.edit_form', ['menu' => $menu->id()])); } } }
from datetime import timedelta from django.shortcuts import render from django import forms from django.forms import ValidationError from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.utils import timezone from django.db.models import Q from django.utils.translation import gettext_lazy as _ class UserCacheMixin: user_cache = None class SignIn(UserCacheMixin, forms.Form): password = forms.CharField(label=_('کلمه عبور'), strip=False, widget=forms.PasswordInput(attrs={'id': 'myInput', 'type': 'password'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if settings.USE_REMEMBER_ME: self.fields['remember_me'] = forms.BooleanField(label=_('مرا بخاطر بسپار'), required=False) def clean_password(self): password = self.cleaned_data['password'] if not self.user_cache: return password if not self.user_cache.check_password(password): raise ValidationError(_('شما کلمه عبور نامعتبر را وارد کردید.')) return password class SignInViaUsernameForm(SignIn): username = forms.CharField(label=_('نام کاربري')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['username', 'password', 'remember_me'] return ['username', 'password'] def clean_username(self): username = self.cleaned_data['username'] user = User.objects.filter(username=username).first() if not user: raise ValidationError(_('شما نام کاربری نامعتبر را وارد کردید.')) if not user.is_active: raise ValidationError(_('این حساب فعال نیست.')) self.user_cache = user return username class SignInViaEmailForm(SignIn): email = forms.EmailField(label=_('ایمیل')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['email', 'password', 'remember_me'] return ['email', 'password'] def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('شما آدرس ایمیل نامعتبر را وارد کردید.')) if not user.is_active: raise ValidationError(_('این حساب فعال نیست.')) self.user_cache = user return email class SignInViaEmailOrUsernameForm(SignIn): email_or_username = forms.CharField(label=_('ایمیل با نام کاربری')) @property def field_order(self): if settings.USE_REMEMBER_ME: return ['email_or_username', 'password', 'remember_me'] return ['email_or_username', 'password'] def clean_email_or_username(self): email_or_username = self.cleaned_data['email_or_username'] user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first() if not user: raise ValidationError(_('شما آدرس ایمیل یا نام کاربری نامعتبر را وارد کردید.')) if not user.is_active: raise ValidationError(_('این حساب فعال نیست.')) self.user_cache = user return email_or_username class SignUpForm(UserCreationForm): class Meta: model = User fields = settings.SIGN_UP_FIELDS email = forms.EmailField(label=_('ایمیل'), help_text=_('اجباری. آدرس ایمیلی را که ازقبل وجود دارد را وارد کنید.')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).exists() if user: raise ValidationError(_('شما نمیتوانید از این آدرس ایمیل استفاده کنید.')) return email class ResendActivationCodeForm(UserCacheMixin, forms.Form): email_or_username = forms.CharField(label=_('ایمیل یا نام کاربری')) def clean_email_or_username(self): email_or_username = self.cleaned_data['email_or_username'] user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first() if not user: raise ValidationError(_('شما آدرس ایمیل یا نام کاربری نامعتبر را وارد کردید.')) if user.is_active: raise ValidationError(_('این حساب در حال حاضر فعال است.')) activation = user.activation_set.first() if not activation: raise ValidationError(_('کد فعال سازی پیدا نشد.')) now_with_shift = timezone.now() - timedelta(hours=24) if activation.created_at > now_with_shift: raise ValidationError(_('کد فعال سازی ارسال شد. شما میتوانید در 24 ساعت آینده کد جدید را دوباره دزخواست کنید.')) self.user_cache = user return email_or_username class ResendActivationCodeViaEmailForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('ایمیل')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('شما آدرس ایمیل نامعتبر را وارد کردید.')) if user.is_active: raise ValidationError(_('این حساب در حال حاضر فعال است.')) activation = user.activation_set.first() if not activation: raise ValidationError(_('کد فعال سازی پیدا نشد.')) now_with_shift = timezone.now() - timedelta(hours=24) if activation.created_at > now_with_shift: raise ValidationError(_('کد فعال سازی ارسال شد. شما میتوانید در 24 ساعت آینده کد جدید را دوباره دزخواست کنید.')) self.user_cache = user return email class RestorePasswordForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('ايميل')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('شما آدرس ایمیل نامعتبر را وارد کردید.')) if not user.is_active: raise ValidationError(_('این حساب فعال نیست.')) self.user_cache = user return email class RestorePasswordViaEmailOrUsernameForm(UserCacheMixin, forms.Form): email_or_username = forms.CharField(label=_('ایمیل یا نام کاربری')) def clean_email_or_username(self): email_or_username = self.cleaned_data['email_or_username'] user = User.objects.filter(Q(username=email_or_username) | Q(email__iexact=email_or_username)).first() if not user: raise ValidationError(_('شما آدرس ایمیل یا نام کاربری نامعتبر را وارد کردید.')) if not user.is_active: raise ValidationError(_('این حساب فعال نیست.')) self.user_cache = user return email_or_username def phone_valid(value): if len(value) >= 12: raise ValidationError(f'حداکثر عدد وارد شده باید 11 رقم باشد.({len(value)}عدد وارد شده)') elif len(value) <= 10: raise ValidationError(f'حداقل عدد وارد شده باید 11 رقم باشد.({len(value)}عدد وارد شده)') elif '-' in value: raise ValidationError(f'فرمت تلفن همراه وارد شده اشتباه است.') class ChangeProfileForm(forms.Form): first_name = forms.CharField(label=_('نام'), max_length=30, required=False) last_name = forms.CharField(label=_('نام خانوادگي'), max_length=150, required=False) phone_number = forms.CharField(label=_('تلفن همراه'),widget=forms.NumberInput,validators=[phone_valid]) class ChangeEmailForm(forms.Form): email = forms.EmailField(label=_('ایمیل')) def __init__(self, user, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) def clean_email(self): email = self.cleaned_data['email'] if email == self.user.email: raise ValidationError(_('لطفا ایمیل دیگری را وارد نمایید.')) user = User.objects.filter(Q(email__iexact=email) & ~Q(id=self.user.id)).exists() if user: raise ValidationError(_('شما نمیتوانید از این ایمیل استفاده کنید.')) return email class RemindUsernameForm(UserCacheMixin, forms.Form): email = forms.EmailField(label=_('ایمیل')) def clean_email(self): email = self.cleaned_data['email'] user = User.objects.filter(email__iexact=email).first() if not user: raise ValidationError(_('شما آدرس ایمیل نامعتبر را وارد کردید.')) if not user.is_active: raise ValidationError(_('این حساب فعال نیست.')) self.user_cache = user return email
import { HttpException, HttpStatus, Inject, Injectable, NotFoundException, } from '@nestjs/common'; // import { User } from './entities/user.entity'; import { CreateUserDto } from './dto/create-user.dto'; import { PG_CONNECTION } from 'src/constants'; import { User } from './entities/user.entity'; import { UpdateUserDto } from './dto/update-user.dto'; import { encodePassword } from 'src/utils/bcyrpt'; @Injectable() export class UsersService { constructor(@Inject(PG_CONNECTION) private conn: any) {} async getUsers() { try { const result = await this.conn.query( 'SELECT id, username, password FROM public."user"', ); return { data: result.rows, }; } catch (error) { throw new NotFoundException(); } } async getUsersLeaderboard() { try { const result = await this.conn.query(` SELECT public."user".id AS user_id, public."user".username, COUNT(public."exercise".id) AS exercise_count FROM public."user" LEFT JOIN public."exercise" ON public."user".id = public."exercise".user_id WHERE public."exercise".completed_at >= CURRENT_DATE - INTERVAL '7 days' OR public."exercise".completed_at IS NULL GROUP BY public."user".id, public."user".username ORDER BY exercise_count DESC; `); return { data: result.rows, }; } catch (error) { throw new NotFoundException(); } } async getUsersByLatestExercise() { try { const result = await this.conn.query(` SELECT public."user".id AS user_id, public."user".username AS user_username, public."exercise".id AS exercise_id, public."exercise"."type" AS exercise_type, public."exercise".duration AS exercise_duration, public."exercise".score AS exercise_score, public."exercise".completed_at AS latest_completed_at FROM public."user" LEFT JOIN public."exercise" ON public."user".id = public."exercise".user_id WHERE public."exercise".completed_at = ( SELECT MAX(completed_at) FROM public."exercise" WHERE user_id = public."user".id ) ORDER BY latest_completed_at DESC; `); return { data: result.rows, }; } catch (error) { throw new NotFoundException(); } } async getOne(id: string) { try { const result = await this.conn.query( ` SELECT id, username, age, height, weight, sex FROM public."user" WHERE id='${id}' `, ); return { data: result.rows[0], }; } catch (error) { throw new NotFoundException(); } } async getOneByUsername(username: string): Promise<User> { try { const result = await this.conn.query( `SELECT id, username, password, age, height, weight, sex FROM public."user" WHERE username='${username}'`, ); return result.rows[0]; } catch (error) { throw new NotFoundException(); } } async createUser(userData: CreateUserDto) { const payload = { username: userData.username, password: encodePassword(userData.password), }; try { await this.conn.query( `INSERT INTO public."user" (username, "password") VALUES('${payload.username}', '${payload.password}');`, ); return { message: `Successfully registered ${payload.username}`, }; } catch (error) { throw new HttpException(error, HttpStatus.BAD_REQUEST); } } async updateProfile(id: string, payload: UpdateUserDto) { try { await this.conn.query( `UPDATE public."user" SET height = ${payload.height}, weight = ${payload.weight}, sex = '${payload.sex}', age = ${payload.age} WHERE id = '${id}';`, ); return { message: 'Update profile successful.', data: payload, }; } catch (error) { throw new NotFoundException(); } } }
use ::bitflags::bitflags; use ::deferred_future::LocalDeferredFuture; use ::futures::FutureExt; use ::nwg::{self as nwg, ControlHandle, Event as NwgEvent, Frame, FrameBuilder, FrameFlags, NwgError}; use ::webview2::{Controller, Environment, EnvironmentBuilder, Result as WvResult}; use ::std::{cell::RefCell, path::Path, mem, rc::Rc, sync::atomic::{AtomicUsize, Ordering}}; use ::winapi::{shared::windef::{HWND, RECT}, um::winuser::{GetClientRect, SC_RESTORE, WM_SYSCOMMAND, WS_BORDER, WS_DISABLED, WS_VISIBLE}}; use super::{NwgResult, WebviewContainer}; static HANDLE_ID: AtomicUsize = AtomicUsize::new(0xffff + 1); bitflags! { #[derive(PartialEq, Eq)] pub struct WebviewContainerFlags: u32 { const NONE = 0; const VISIBLE = WS_VISIBLE; const DISABLED = WS_DISABLED; const BORDER = WS_BORDER; } } pub struct WebviewContainerBuilder<'a> { window: Option<ControlHandle>, webview_env: Option<Environment>, webview_env_builder: EnvironmentBuilder<'a>, frame_builder: FrameBuilder } impl<'a> Default for WebviewContainerBuilder<'a> { fn default() -> Self { Self { window: None, webview_env: None, webview_env_builder: Environment::builder(), frame_builder: Frame::builder() } } } impl<'a> WebviewContainerBuilder<'a> { /// nwg::FrameBuilder 的配置项 pub fn flags(mut self, flags: WebviewContainerFlags) -> WebviewContainerBuilder<'a> { let mut frame_flags = FrameFlags::NONE; if flags.contains(WebviewContainerFlags::BORDER) { frame_flags = frame_flags | FrameFlags::BORDER; } if flags.contains(WebviewContainerFlags::DISABLED) { frame_flags = frame_flags | FrameFlags::DISABLED; } if flags.contains(WebviewContainerFlags::VISIBLE) { frame_flags = frame_flags | FrameFlags::VISIBLE; } self.frame_builder = self.frame_builder.flags(frame_flags); self } /// nwg::FrameBuilder 的配置项 pub fn size(mut self, size: (i32, i32)) -> WebviewContainerBuilder<'a> { self.frame_builder = self.frame_builder.size(size); self } /// nwg::FrameBuilder 的配置项 pub fn position(mut self, pos: (i32, i32)) -> WebviewContainerBuilder<'a> { self.frame_builder = self.frame_builder.position(pos); self } /// nwg::FrameBuilder 的配置项 pub fn enabled(mut self, e: bool) -> WebviewContainerBuilder<'a> { self.frame_builder = self.frame_builder.enabled(e); self } /// nwg::FrameBuilder 的配置项 pub fn parent<C: Into<ControlHandle>>(mut self, p: C) -> WebviewContainerBuilder<'a> { self.frame_builder = self.frame_builder.parent(p); self } /// webview2::EnvironmentBuilder 的配置项 pub fn browser_executable_folder(mut self, browser_executable_folder: &'a Path) -> Self { self.webview_env_builder = self.webview_env_builder.with_browser_executable_folder(browser_executable_folder); self } /// webview2::EnvironmentBuilder 的配置项 pub fn user_data_folder(mut self, user_data_folder: &'a Path) -> Self { self.webview_env_builder = self.webview_env_builder.with_user_data_folder(user_data_folder); self } /// webview2::EnvironmentBuilder 的配置项 pub fn additional_browser_arguments(mut self, additional_browser_arguments: &'a str) -> Self { self.webview_env_builder = self.webview_env_builder.with_additional_browser_arguments(additional_browser_arguments); self } /// webview2::EnvironmentBuilder 的配置项 pub fn language(mut self, language: &'a str) -> Self { self.webview_env_builder = self.webview_env_builder.with_language(language); self } /// webview2::EnvironmentBuilder 的配置项 pub fn target_compatible_browser_version(mut self, target_compatible_browser_version: &'a str) -> Self { self.webview_env_builder = self.webview_env_builder.with_target_compatible_browser_version(target_compatible_browser_version); self } /// webview2::EnvironmentBuilder 的配置项 pub fn allow_single_sign_on_using_osprimary_account(mut self, allow_single_sign_on_using_osprimary_account: bool) -> Self { self.webview_env_builder = self.webview_env_builder.with_allow_single_sign_on_using_osprimary_account(allow_single_sign_on_using_osprimary_account); self } /// webview2::EnvironmentBuilder 的配置项。 /// 获取当前浏览器实例版本字符串 pub fn get_available_browser_version_string(&self) -> WvResult<String> { self.webview_env_builder.get_available_browser_version_string() } // 其它 pub fn window<C: Into<ControlHandle>>(mut self, window: C) -> WebviewContainerBuilder<'a> { self.window = Some(window.into()); self } pub fn webview_env<E: Into<Environment>>(mut self, webview_env: E) -> WebviewContainerBuilder<'a> { self.webview_env = Some(webview_env.into()); self } /// 1. 在多 TAB 应用程序场景下,重用`webview2::Environment(i.e. CoreWebView2Environment)`实例。 /// 于是,由相同`CoreWebView2Environment`实例构造的多`webview`将共用相同的 /// 1. 浏览器进程 /// 2. 渲染进程 /// 3. 缓存目录 /// 2. 需要深度定制 CoreWebView2Environment 实例。比如, /// 1. 默认语言 /// 2. 缓存目录 /// 3. 浏览器启动参数 /// 4. 浏览器版本号 /// 5. 浏览器安装目录 /// 6. 是否允许单点登录 pub fn build(self, webview_container: &mut WebviewContainer) -> NwgResult<()> { // 主窗体 let window_handle = self.window.ok_or(NwgError::initialization("window 配置项代表了主窗体。它是必填项"))?; let window_hwnd = window_handle.hwnd().ok_or(NwgError::control_create("主窗体不是有效的 Win32 COM 控件"))?; // webview 容器 self.frame_builder.build(&mut webview_container.frame.borrow_mut())?; let frame_hwnd = webview_container.frame.borrow().handle.hwnd().ok_or(NwgError::control_create("Webview 容器控件 Frame 初始化失败"))?; macro_rules! unpack { ($variable: ident, $return: expr) => { match $variable.upgrade() { Some(variable) => variable, None => return $return } }; } // webview 组件构造异步锁 webview_container.ready_fut.replace({ let webview_ctrl = Rc::clone(&webview_container.webview_ctrl); let webview_ready_future = LocalDeferredFuture::default(); let defer = webview_ready_future.defer(); let frame = Rc::clone(&webview_container.frame); let build = move |env: Environment| env.clone().create_controller(frame_hwnd, move |webview_ctrl_core| { let webview_ctrl_core = webview_ctrl_core?; let webview = webview_ctrl_core.get_webview()?; align_webview_2_container(&webview_ctrl_core, frame, frame_hwnd)?; #[cfg(debug_assertions)] println!("[WebviewContainerBuilder][build]Webview 实例化成功"); webview_ctrl.borrow_mut().replace(webview_ctrl_core.clone()); defer.borrow_mut().complete((env, webview_ctrl_core, webview)); Ok(()) }); if let Some(webview_env) = self.webview_env { build(webview_env) } else { self.webview_env_builder.build(move |env| build(env?)) }.map(|_| webview_ready_future.shared()).map_err(|err|NwgError::control_create(err.to_string())) }?); webview_container.event_handle.replace({ // 因为【主窗体】直接就是 webview 的父组件,所以传递主窗体的事件给 webview 组件。 let webview_ctrl = Rc::downgrade(&webview_container.webview_ctrl); let is_closing = Rc::downgrade(&webview_container.is_closing); let frame = Rc::downgrade(&webview_container.frame); nwg::full_bind_event_handler(&window_handle, move |event, _data, handle| { let is_closing = unpack!(is_closing, ()); if *is_closing.borrow() { return; } if let ControlHandle::Hwnd(hwnd) = handle { if window_hwnd == hwnd { // 事件源是主窗体 let webview_ctrl = unpack!(webview_ctrl, ()); match event { // 当主窗体被最小化时,关闭 webview 组件,以减小空耗。 NwgEvent::OnWindowMinimize => webview_ctrl.borrow().as_ref().and_then(|controller| { #[cfg(debug_assertions)] println!("[WebviewContainer][OnWindowMinimize]Webview 被挂起了"); controller.put_is_visible(false).map_err(|err| eprintln!("[OnWindowMinimize]{err}")).ok() }), // 当主窗体被移动时,徒手传递位移事件给 webview 组件。 NwgEvent::OnMove => webview_ctrl.borrow().as_ref().and_then(|controller| controller.notify_parent_window_position_changed().map_err(|err| eprintln!("[OnMove]{err}")).ok() ), _ => Some(()) }; } else if frame_hwnd == hwnd { // 事件源是 webview 容器 Frame let webview_ctrl = unpack!(webview_ctrl, ()); match event { NwgEvent::OnResize => { // 当主窗体被调整大小时,徒手传递尺寸调整事件给 webview 组件。 let frame = unpack!(frame, ()); webview_ctrl.borrow().as_ref().and_then(move |controller| { align_webview_2_container(controller, frame, frame_hwnd).map_err(|err| eprintln!("[OnResize|OnWindowMaximize]{err}")).ok() }) }, NwgEvent::OnMove => webview_ctrl.borrow().as_ref().and_then(|controller| controller.notify_parent_window_position_changed().map_err(|err| eprintln!("[OnMove]{err}")).ok() ), _ => Some(()) }; } } }) }); webview_container.raw_event_handle.replace({ // nwg 封闭里漏掉了【主窗体】的 restore 事件,所以这里直接经由 winapi crate 的原始接口挂事件处理函数了。 let handle_id = loop { let handle_id = HANDLE_ID.fetch_add(1, Ordering::Relaxed); if !nwg::has_raw_handler(&window_handle, handle_id) { break handle_id; } }; let webview_ctrl = Rc::downgrade(&webview_container.webview_ctrl); let is_closing = Rc::downgrade(&webview_container.is_closing); nwg::bind_raw_event_handler(&window_handle, handle_id, move |_, msg, w, _| { let webview_ctrl = unpack!(webview_ctrl, None); let is_closing = unpack!(is_closing, None); if !*is_closing.borrow() && (WM_SYSCOMMAND, SC_RESTORE) == (msg, w as usize) { #[cfg(debug_assertions)] println!("[WebviewContainer][OnWindowMinimize]Webview 被恢复了"); webview_ctrl.borrow().as_ref().and_then(|controller| // 当主窗体被还原时,打开 webview 组件。 controller.put_is_visible(true).map_err(|err| eprintln!("[OnWindowRestore]{err}")).ok() ); } None })? }); #[cfg(debug_assertions)] println!("[WebviewContainerBuilder][build]同步执行结束"); Ok(()) } } /// 调整 webview 控件的大小·至·包含该 webview 控件的容器元素的最新大小 fn align_webview_2_container(webview_ctrl: &Controller, frame: Rc<RefCell<Frame>>, frame_hwnd: HWND) -> WvResult<()> { let (successful, mut rect) = unsafe { let mut rect = mem::zeroed(); let successful = GetClientRect(frame_hwnd, &mut rect); (successful, rect) }; if successful == 0 { let position = frame.borrow().position(); let size = frame.borrow().size(); rect = RECT { top: position.1, left: position.0, right: size.0 as i32, bottom: size.1 as i32 } } println!("rect={{top: {}, left: {}, width: {}, height: {} }}", rect.top, rect.left, rect.right, rect.bottom); return webview_ctrl.put_bounds(rect); }
import from { "engine", "components", "renderers", "random", "thread", "console", "math" }; class runtime { application@ self; int64 clip_now = 0; usize clip_count = 0; runtime(application_desc&in init) { @self = application(init); self.set_on_initialize(initialize_callback(this.initialize)); self.set_on_dispatch(dispatch_callback(this.dispatch)); self.set_on_publish(publish_callback(this.publish)); self.set_on_window_event(window_event_callback(this.window_event)); } void initialize() { base_processor@ load_model = self.content.get_processor(component_id("skin_model")); base_processor@ load_texture = self.content.get_processor(component_id("texture_2d")); base_processor@ load_animation = self.content.get_processor(component_id("skin_animation")); @self.scene = scene_graph(scene_graph_desc::get(self)); scene_entity@ camera = self.scene.get_camera_entity(); camera.add_component(free_look_component(camera)); camera.add_component(fly_component(camera)); render_system@ system = self.scene.get_renderer(); system.add_renderer(skin_renderer(system)); scene_entity@ wolf = self.scene.add_entity(); wolf.get_transform().set_rotation(vector3(270 * deg2radf(), 0, 0)); material@ body_material = self.scene.add_material(); material@ eyes_material = self.scene.add_material(); material@ fur_material = self.scene.add_material(); material@ teeth_material = self.scene.add_material(); material@ claws_material = self.scene.add_material(); body_material.set_diffuse_map(cast<texture_2d@>(self.content.load(load_texture, "body.jpg"))); fur_material.set_diffuse_map(cast<texture_2d@>(self.content.load(load_texture, "fur.png"))); eyes_material.set_diffuse_map(cast<texture_2d@>(self.content.load(load_texture, "eyes.jpg"))); teeth_material.surface.diffuse = vector3(0.226f, 0.232f, 0.188f); claws_material.surface.diffuse = vector3(0.141f, 0.141f, 0.141f); skin_component@ drawable = cast<skin_component@>(wolf.add_component(skin_component(wolf))); drawable.set_drawable(cast<skin_model@>(self.content.load(load_model, "wolf.fbx"))); drawable.set_material_for("Wolf1_Material__wolf_col_tga_0", body_material); drawable.set_material_for("Wolf2_fur__fella3_jpg_001_0.001", fur_material); drawable.set_material_for("Wolf3_eyes_0", eyes_material); drawable.set_material_for("Wolf3_teeth__nor2_tga_0", teeth_material); drawable.set_material_for("Wolf3_claws_0", claws_material); skin_animator_component@ animator = cast<skin_animator_component@>(wolf.add_component(skin_animator_component(wolf))); animator.set_animation(cast<skin_animation@>(self.content.load(load_animation, "wolf.fbx"))); animator.state.looped = true; clip_count = animator.get_clips_count(); } void dispatch(clock_timer@ time) { bool go_to_left = self.window.is_key_down_hit(key_code::q); bool go_to_right = self.window.is_key_down_hit(key_code::e); if (self.window.is_key_down_hit(key_code::space)) { skin_animator_component@ animation = cast<skin_animator_component@>(self.scene.get_component(component_id("skin_animator_component"), 0)); if (animation !is null) { if (!animation.state.is_playing()) animation.play(clip_now); else animation.pause(); } } else if (go_to_left || go_to_right) { if (go_to_left && --clip_now < 0) clip_now = int64(clip_count) - 1; else if (go_to_right && ++clip_now > int64(clip_count)) clip_now = 0; skin_animator_component@ animation = cast<skin_animator_component@>(self.scene.get_component(component_id("skin_animator_component"), 0)); if (animation !is null) animation.play(clip_now); } self.scene.dispatch(time); } void publish(clock_timer@ time) { self.scene.publish_and_submit(time, 0, 0, 0, false); } void window_event(window_state state, int x, int y) { switch (state) { case window_state::resize: self.renderer.resize_buffers(x, y); if (self.scene !is null) self.scene.resize_buffers(); break; case window_state::close: self.stop(); break; } } } int main() { application_desc init; init.graphics.vsync_mode = vsync::off; init.window.maximized = true; init.environment = "assets"; runtime app(init); return app.self.start(); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = ensureAuthenticated; var _AppError = require("../errors/AppError"); var jwt = _interopRequireWildcard(require("jsonwebtoken")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function ensureAuthenticated(req, res, next) { const authHeader = req.headers.authorization; if (!authHeader) { throw new _AppError.AppError("Unauthorized", 401); } const [scheme, token] = authHeader.split(" "); if (!/^Bearer$/i.test(scheme)) { throw new _AppError.AppError("Unauthorized", 401); } jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => { if (err) { if (err.message === "jwt expired") { throw new _AppError.AppError("Expired Token", 401); } else { throw new _AppError.AppError("Invalid Token", 401); } } req.user = decoded.id; return next(); }); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app1"> <ol> <todo-item v-for="item in groceryList" :todo="item" :key="item.id"></todo-item> </ol> </div> </body> <script> Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>' }) </script> <script> var app1 = new Vue({ el: '#app1', data: { groceryList: [{ id: 0, text: '蔬菜' }, { id: 1, text: '奶酪' }, { id: 2, text: '随便其它什么人吃的东西' } ] } }) </script> </html>
#include <iostream> //using namespace std; since we are using std::cout, cin we do not have to use this now. int main() { int num{}; std::cout <<"Enter a number: ";//character out std::cin >>num;//character in std::cout <<'\n'; std::cout << "\nYou have entered " << num <<".\n"<< std::endl; //using 2 inputs at the same time now; int x{}; int y{};//best practice we declare all the variables in separate lines; std::cout <<"Enter any two number: "; std::cin >> x >>y; std::cout <<"\nThe you have entered " <<x <<" and " <<y <<".\n"; /*endl is end line, it takes cursor to a new line, but, its drawback is that is *it flushes buffer every time it is used, along with going to a new line so *\n' is a preferred way *it using only '\n', we can have to use single inverted comma(') *but, we can use inside the double inverted comma("); along with outputting text. */ //note: << is an insertion operator, but, >> is an extraction operator return 0;//it doesn't matter even if you use return 1 or put any value instead of 0; }
<script setup> import { PerfectScrollbar } from 'vue3-perfect-scrollbar' import axios from 'axios'; import {location} from '@/helpers/helper' import {URL, token} from '@/helpers/token' import { emailValidator, requiredValidator, } from '@validators' const props = defineProps({ isDrawerOpen: { type: Boolean, required: true, }, }) const emit = defineEmits([ 'update:isDrawerOpen', 'userData', ]) const isFormValid = ref(false) const refForm = ref() const host_name = ref('') const ip_address = ref('') const reader_name = ref('') const hardware_address = ref('') const port = ref('') const serial_number = ref('') const description = ref('') const selectedlocation = ref('') const locationList=location() const subsystem_id = ref(2) //const session = ref() // const plan = ref() // const status = ref() // ?? drawer close const closeNavigationDrawer = () => { emit('update:isDrawerOpen', false) nextTick(() => { refForm.value?.reset() refForm.value?.resetValidation() }) } const onSubmit = () => { refForm.value?.validate().then(({ valid }) => { if (valid) { axios .post( URL() + `/devices/reader`, { requestType: "create", reader_data: { host_name: host_name.value, port: port.value, ip_address: ip_address.value, reader_name: reader_name.value, serial_number: serial_number.value, description: description.value, hardware_address: hardware_address.value, location: selectedlocation.value, }, subsystem_id: subsystem_id.value, }, { headers: { Authorization: token() } } ) .then((response) => { console.log(response.data); emit("userData", { status: "success", data: { id: 0, host_name: host_name.value, port: port.value, ip_address: ip_address.value, reader_name: reader_name.value, serial_number: serial_number.value, description: description.value, hardware_address: hardware_address.value, location: selectedlocation.value, }, subsystem_id: subsystem_id.value, message: "Controller Successfully Created", }); }) .catch((error) => { console.log(error); emit("userData", { status: "failed", data: { id: 0, host_name: host_name.value, port: port.value, ip_address: ip_address.value, reader_name: reader_name.value, serial_number: serial_number.value, description: description.value, hardware_address: hardware_address.value, location: selectedlocation.value, }, subsystem_id: subsystem_id.value, message: error, }); }) emit('update:isDrawerOpen', false) // nextTick(() => { // refForm.value?.reset() // refForm.value?.resetValidation() // }) } }) } const handleDrawerModelValueUpdate = val => { emit('update:isDrawerOpen', val) } </script> <template> <VNavigationDrawer temporary :width="400" location="end" class="scrollable-content" :model-value="props.isDrawerOpen" @update:model-value="handleDrawerModelValueUpdate" > <!-- ?? Title --> <div class="d-flex align-center pa-6 pb-1"> <h3 class="title-header"> {{$t('Reader - Create')}}</h3> <VSpacer /> <!-- ?? Close btn --> <VBtn variant="tonal" color="default" icon size="32" class="rounded" @click="closeNavigationDrawer" > <VIcon size="18" icon="tabler-x" /> </VBTn> </div> <PerfectScrollbar :options="{ wheelPropagation: false }"> <VCard flat> <VCardText> <!-- ?? Form --> <VForm ref="refForm" v-model="isFormValid" @submit.prevent="onSubmit" > <VRow> <!-- ?? Full name --> <VCol cols="12"> <VTextField v-model="host_name" :rules="[requiredValidator]" label="Host Name" /> </VCol> <VCol cols="12"> <VTextField v-model="description" :rules="[requiredValidator]" label="Description" /> </VCol> <VCol cols="12"> <VTextField v-model="ip_address" :rules="[requiredValidator]" label="IP Address" /> </VCol> <!-- ?? Email --> <VCol cols="12"> <VTextField v-model="port" :rules="[requiredValidator]" label="Port Number" /> </VCol> <!-- ?? company --> <VCol cols="12"> <VTextField v-model="reader_name" :rules="[requiredValidator]" label="Reader Name" /> </VCol> <!-- ?? company --> <VCol cols="12"> <VTextField v-model="hardware_address" :rules="[requiredValidator]" label="Hardware Address" /> </VCol> <!-- ?? company --> <VCol cols="12"> <VTextField v-model="serial_number" :rules="[requiredValidator]" label="Serial Number" /> </VCol> <VCol cols="12"> <VSelect v-model="selectedlocation" label="Select Location" :rules="[requiredValidator]" :items="locationList" /> </VCol> <VCol cols="12"> <VTextField v-model="subsystem_id" label="SubSystem ID" :rules="[requiredValidator]" /> </VCol> <!-- ?? Submit and Cancel --> <VCol cols="12"> <VBtn type="submit" class="me-3" > Create </VBtn> <VBtn type="reset" variant="tonal" color="secondary" @click="closeNavigationDrawer" > Cancel </VBtn> </VCol> </VRow> </VForm> </VCardText> </VCard> </PerfectScrollbar> </VNavigationDrawer> </template>
function Get-PowerPlan { <# .SYNOPSIS Returns Windows power plans. .DESCRIPTION Returns all Windows power plans or just the active power plan. .PARAMETER ID Optional GUID for a specific power plan (default is to return all power plans) .PARAMETER ComputerName Optional name of a remote computer. Default is local computer. .PARAMETER IsActive Optional. Return only the active power plan .EXAMPLE Get-PowerPlan Returns all power plans defined on the local computer .EXAMPLE Get-PowerPlan -IsActive Returns the current power plan for the local computer .EXAMPLE Get-PowerPlan -IsActive -ComputerName WS123 Returns the current power plan for computer WS123 .LINK https://github.com/Skatterbrainz/psPowerPlan/blob/master/docs/Get-PowerPlan.md #> [CmdletBinding()] param ( [parameter()][string]$ID = "", [parameter()][string]$ComputerName = "", [parameter()][switch]$IsActive ) if ([string]::IsNullOrWhiteSpace($ID)) { $params = @{ Class = "Win32_PowerPlan" Namespace = "root\cimv2\power" } if (![string]::IsNullOrWhiteSpace($ComputerName)) { $params.Add("ComputerName", $ComputerName) } $plans = @(Get-WmiObject @params) if ($IsActive) { $plans = @($plans | Where-Object {$_.IsActive -eq $True}) } foreach ($plan in $plans) { $id = $plan.InstanceID.Split('\')[1].Substring(1,36) [pscustomobject]@{ Name = $plan.ElementName Description = $plan.Description Caption = $plan.Caption ID = $id IsActive = $plan.IsActive } } } else { POWERCFG -QUERY $($ID).Trim() } } function Set-PowerPlan { <# .SYNOPSIS Set Active Power Plan .DESCRIPTION Set Active Power Plan from a list of standard names .PARAMETER ID GUID of power plan to set active .PARAMETER Interactive If ID is not provided, and Interactive is requested, the available Power plans are displayed in a GridView to select one to set active. .EXAMPLE Set-PowerPlan -ID 381b4222-f694-41f0-9685-ff5bb260df2e .LINK https://github.com/Skatterbrainz/psPowerPlan/blob/master/docs/Set-PowerPlan.md #> [CmdletBinding()] param ( [parameter()][string]$ID, [parameter()][switch]$Interactive ) try { $plans = Get-PowerPlan $activeplan = $plans | Where-Object {$_.IsActive -eq $true} Write-Host "Active power plan is: $($activeplan.Name) - $($activeplan.ID)" if (![string]::IsNullOrWhiteSpace($ID)) { if ($ID -in ($plans.ID)) { if ($ID -eq $($plans | Where-Object {$_.IsActive -eq $True} | Select-Object -ExpandProperty ID)) { Write-Warning "*** $ID is already active" } else { POWERCFG /SETACTIVE $ID Write-Host "$ID is now active" } } } elseif ($Interactive) { $plan = $plans | Out-GridView -Title "Select Power Plan to set Active" -OutputMode Single if ($plan) { POWERCFG /SETACTIVE $plan.ID Write-Host "$($plan.ID) is now active" } } } catch { Write-Error $_.Exception.Message } } Set-PowerPlan -Interactive
import { render, waitFor, screen } from '@testing-library/react'; import { QueryClient, QueryClientProvider } from 'react-query'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import Products from './Products'; const server = setupServer( rest.get('https://mks-frontend-challenge-04811e8151e6.herokuapp.com/api/v1/products', (req, res, ctx) => { return res( ctx.json({ products: [ { id: 1, name: 'Product 1' }, { id: 2, name: 'Product 2' }, ], }) ); }) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); const queryClient = new QueryClient({ defaultOptions: { queries: { }, }, }); test('renders Products component with data', async () => { render( <QueryClientProvider client={queryClient}> <Products /> </QueryClientProvider> ); await waitFor(() => { expect(screen.getByText('Product 1')).toBeInTheDocument(); expect(screen.getByText('Product 2')).toBeInTheDocument(); }); }); test('renders Products component with loading state', async () => { render( <QueryClientProvider client={queryClient}> <Products /> </QueryClientProvider> ); expect(screen.getByText('loading...')).toBeInTheDocument(); await waitFor(() => { expect(screen.queryByText('loading...')).toBeNull(); }); }); test('renders Products component with error state', async () => { server.use( rest.get('https://mks-frontend-challenge-04811e8151e6.herokuapp.com/api/v1/products', (req, res, ctx) => { }) ); render( <QueryClientProvider client={queryClient}> <Products /> </QueryClientProvider> ); await waitFor(() => { expect(screen.getByText('failed to load')).toBeInTheDocument(); }); });
require_relative 'casilla' module Civitas class Tablero def initialize (indiceCarcel) if indiceCarcel>=1 @numCasillaCarcel=indiceCarcel else @numCasillaCarcel=1 end @casillas = Array.new salida = Casilla.new("Salida") @casillas.push(salida) @porSalida=0 @tieneJuez = false end def correcto resultado=false resultado=true if (@casillas.length() > @numCasillaCarcel && @tieneJuez == true) return resultado end def correcto2(numCasilla) resultad=false if correcto() == true && numCasilla < @casillas.length() resultad=true end return resultad end def get_por_salida resultado=@porSalida if(@porSalida>0) @porSalida=@porSalida-1 end return resultado end def aniade_casilla(casilla) if @casillas.length== @numCasillaCarcel carcel=Casilla.new("Carcel") @casillas.push(carcel) end if casilla.instance_of? Casilla_juez aniade_juez() else @casillas.push(casilla) end if @casillas.length== @numCasillaCarcel carcel=Casilla.new("Carcel") @casillas.push(carcel) end end def aniade_juez if @tieneJuez==false juez = Casilla_juez.new(numCasillaCarcel, "Juez") @casillas.push(juez) @tieneJuez=true end end def get_casilla(numCasilla) return @casillas.at(numCasilla) end def nueva_posicion(actual, tirada) if correcto()==false resultado=-1 else resultado=actual+tirada if correcto2(resultado)==false aux=resultado- @casillas.length resultado=aux end end if resultado != actual+tirada @porSalida=@porSalida+1 end return resultado end def calcular_tirada(origen, destino) resultado=destino-origen if resultado<0 resultado=resultado [email protected] end return resultado end attr_accessor :casillas, :salida, :numCasillaCarcel, :porSalida private :correcto end end
/* * The MIT License * * Copyright 2022 Alexandru Tabacaru. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package searchaibenchmark; /** * If you find a serious bug in my program please send me an email: [email protected] * * * This program was developed during my research study at BGU university. * The program was developed over 1.5 years during the course of my study. * The primary purpose of the program is to visualize search algorithms (2D), * and help the student understand step-by-step, and develop new algorithms/heuristics. * The secondary purpose of this program is to allow student run these algorithms * in marathon mode for collecting statistical data of the performance (run-time/expansions). * * * This program consist of additional feature that is part of my research, * the feature is to allow research on the new define problem called MATB. * The MATB is best described in my, and my mentors: Dr. Dor Azmon, Prof. Ariel Felner. * The paper was published on SOCS-2022 conference. * Paper Title: Meeting at the border of two separate domains. * The additional feature is connecting two maps/graphs with border nodes connecting them. * And my research main purpose was to develop new heuristic that make use of the border nodes * to improve heuristic search algorithms on these MATB problems. * * * With this program I provide implementations for some of the known algorithms: * A*, MM, fMM, A*+BMPX, with the heuristic FE and added my own heuristics from my research: * FBE, E-FBE. * My research is still ongoing to develop a improvement to these new 2 heuristics. * Users may test them, and develop their own. * Plan to add additional search algorithms: BS*, NBS. * * * The program was built with focus on object-oriented methodology. * This allows to run exactly the algorithm class file on 2D and 3D. * Also, able to provide the heuristic object to the algorithm and so, * making different combinations of algorithms & heuristics. * * * ----------------------------------------------------------- * * This is main function to start the project. * The purpose of this package is to allow user experiment with different search * algorithms that are implemented within this package. * The user may add his own algorithms & heuristics, and easily learn the characteristics. * The program also allows to run search algorithms in animation mode, or to see step by step, * the animation is for 2D maps only (no visualization for 3D maps). * * There are two options for maps, either selecting single map, or selecting dual maps. * For dual map mode, the selected maps are concatenated along the X-axis, for both 2D/3D. * In dual mode, there will be a wall between the two maps, and it is needed to solder the maps * which means to connected the maps as one creating open passages through the wall. * There are two types of creating passages, either simple terrain, or border node. * The border node, is for experimenting with specific problem of two maps/graphs which * have a border between them and the user could use those border nodes to research for new * algorithms/heuristics. * * * @author Alexandru Tabacaru */ public class SearchAIBenchMark { public static void main(String[] args) throws Exception { // prevents bug for Comparator/Sorter/Merger System.setProperty("java.util.Arrays.useLegacyMergeSort", "true"); System.out.println("Starting grid map benchmark."); MapSelection mapFiles = new MapSelection(); try { mapFiles.getMap(); } catch(Exception e){ System.out.println("Exception try to get map."); } mapFiles.setSize(800, 700); mapFiles.setLocationRelativeTo(null); mapFiles.setVisible(true); } }
import { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import MainEmpty from '../main-empty/main-empty'; import Sorting from '../sorting/sorting'; import LocationList from '../location-list/location-list'; import OfferList from '../offer-list/offer-list'; import Map from '../map/map'; import Header from '../header/header'; import LoadingScreen from '../loading-screen/loading-screen'; import { selectLocation } from '../../store/app-state/selectors'; import { selectDataLoadedStatus, selectOffers } from '../../store/main-data/selectors'; import { fetchOffersAction } from '../../store/api-actions'; import cn from 'classnames'; function Main(): JSX.Element { const city = useSelector(selectLocation); const offers = useSelector(selectOffers(city.name)); const isDataLoaded = useSelector(selectDataLoadedStatus); const [activeCardId, setActiveCardId] = useState(Infinity); const dispatch = useDispatch(); useEffect(() => { dispatch(fetchOffersAction()); }, [dispatch]); if (!isDataLoaded) { return <LoadingScreen />; } return ( <div className="page page--gray page--main"> <Header /> <main className={cn('page__main', 'page__main--index', { 'page__main--index-empty': !offers })}> <h1 className="visually-hidden">Cities</h1> <div className="tabs"> <section className="locations container"> <LocationList /> </section> </div> <div className="cities"> {offers && ( <div className="cities__places-container container"> <section className="cities__places places"> <h2 className="visually-hidden">Places</h2> <b className="places__found"> {offers ? offers.length : 0} places to stay in {city.name} </b> <Sorting /> <OfferList offers={offers} setActiveCardId={setActiveCardId} /> </section> <div className="cities__right-section"> <Map offers={offers} selectedPoint={activeCardId} /> </div> </div> )} {!offers && <MainEmpty />} </div> </main> </div> ); } export default Main;
The ``3-say_my_name`` module Tests for the function ``say_my_name`` :: >>> say_my_name = __import__("3-say_my_name").say_my_name Expected inputs --------------- :: >>> first = "Chee-zaram" >>> last = "Okeke" >>> say_my_name(first, last) My name is Chee-zaram Okeke >>> say_my_name("Ovy", "Evbodi") My name is Ovy Evbodi Empty string(s) --------------- :: >>> say_my_name("Ovy", "") My name is Ovy >>> say_my_name("", "Okeke") My name is Okeke >>> say_my_name("", "") My name is Optional argument ----------------- :: >>> say_my_name("Chee-zaram") My name is Chee-zaram TypeError --------- :: >>> say_my_name(2, "Okeke") Traceback (most recent call last): ... TypeError: first_name must be a string >>> say_my_name("Ovy", ['one']) Traceback (most recent call last): ... TypeError: last_name must be a string None ---- :: >>> print(say_my_name(None, "Okeke")) Traceback (most recent call last): ... TypeError: first_name must be a string >>> print(say_my_name("Chee", None)) Traceback (most recent call last): ... TypeError: last_name must be a string >>> print(say_my_name(None, None)) Traceback (most recent call last): ... TypeError: first_name must be a string Missing arguments ----------------- :: >>> print(say_my_name()) Traceback (most recent call last): ... TypeError: say_my_name() missing 1 required positional argument: 'first_name'
# Minesweeper Python Implementation Documentation ## Table of Contents 1. [Introduction](#introduction) 2. [Cell Class](#cell-class) 3. [Board Class](#board-class) 4. [Game Class](#game-class) 5. [UserInterface Class](#userinterface-class) 6. [Usage](#usage) 7. [Pygame Integration](#pygame-integration) 8. [Conclusion](#conclusion) ## 1. Introduction <a name="introduction"></a> This Minesweeper Python implementation provides a comprehesive and modular approach to creating both a text-based and graphical version of the Minesweeper game. TheMinesweeper is a classic single-player puzzle game where the player's objective is to uncover all cells on the game board that do not contain mines. This documentation covers the key components of the codebase, including: - classes, - methods, and their - functionalities. ## 2. Cell Class <a name="cell-class"></a> The `Cell` class represents individual cells on the Minesweeper board. Each cell has the following attributes: - `is_mine`: Indicates whether the cell contains a mine. - `is_flagged`: Indicates whether the cell has been flagged by the player. - `is_revealed`: Indicates whether the cell has been revealed. - `adjacent_mines`: Number of adjacent cells containing mines. ### Methods: - `reveal()`: Reveals the content of the cell. - `toggle_flag()`: Toggles the flagged state of the cell. - `set_adjacent_mines(counter)`: Calculates and sets the number of adjacent mines. ## 3. Board Class <a name="board-class"></a> The `Board` class represents the game board in Minesweeper. - It initializes the board with empty cells, - randomly places mines, and - sets the number of adjacent mines for each cell. ### Key Attributes: - `num_rows`: Number of rows on the board. - `num_cols`: Number of columns on the board. - `num_mines`: Number of mines on the board. - `cells`: A 2D list of `Cell` objects representing the game grid. ### Methods: - `initialize_board()`: Initializes the board with empty cells, places mines, and sets adjacent mines. - `place_mines()`: Randomly places mines on the board. - `set_adjacent_mines(row, col)`: Calculates and sets the number of adjacent mines for a given cell. - `reveal_adjacent_cells(row, col)`: Reveals adjacent cells when an empty cell is revealed. - `reveal_cell(row, col)`: Reveals a cell, handles adjacent empty cells, and checks for mines or game over. - `flag_cell(row, col)`: Flags or unflags a cell. - `display_board()`: Displays the current state of the board to the player. - `is_game_over()`: Checks if the game is over, either by win or loss. ## 4. Game Class <a name="game-class"></a> The `Game` class manages the gameplay. - It tracks the game state, including whether the game is over or if the player has won. ### Key Attributes: - `board`: An instance of the `Board` class representing the game board. - `game_over`: Indicates whether the game is over. - `win`: Indicates whether the player has won. ### Methods: - `start_game()`: Initializes the game by creating the board and placing mines. - `play()`: Handles player moves, updates the board, and checks for game status, including flagging cells and revealing cells. - `check_win()`: Checks if the player has won by revealing all non-mine cells. - `end_game()`: Ends the game by revealing all cells and displaying the result. ## 5. UserInterface Class <a name="userinterface-class"></a> The `UserInterface` class handles user input and display. It contains static methods for getting user input and displaying the board. ### Key Methods: - `get_user_input(board)`: Gets valid user input for row and column within the board's dimensions. - `display_board(board)`: Displays the current state of the board to the player. ## 6. Usage <a name="usage"></a> To use the Minesweeper game, create instances of the `Board` and `Game` classes, and then call the relevant methods to play the game. You can use the `UserInterface` class to handle user input and display the board. ## 7. Pygame Integration <a name="pygame-integration"></a> The code also includes integration with the Pygame library to create a graphical interface for the Minesweeper game (This part is still undrr intergration). It utilizes Pygame to display the game board, cells, and interactions within a graphical window. Key Pygame-related code elements include initializing Pygame, creating a Pygame window, and updating the window based on the game state within the game loop. ## 8. Conclusion <a name="conclusion"></a> No conclusion yet
# ezsam (easy segment anything model) A command line and gui tool to segment images and video via text prompts. Input images and videos, describe the subjects or objects you want to keep, and output new images and videos with the background removed. ## Why? Meta's [Segment Anything](https://github.com/facebookresearch/segment-anything) is a powerful tool for separating parts of images, but requires coordinate prompts&mdash;either bounding boxes or points. And manual prompt generation is tedious for large collections of still images or video. In contrast, text-based prompts describing the object(s) in the foreground to segment can be constant. Inspired by [Grounded-Segment-Anything](https://github.com/IDEA-Research/Grounded-Segment-Anything), this project tries to package a simpler to use tool. If you're not interested in text-based prompts with Segment Anything, check out [rembg](https://github.com/danielgatis/rembg). ## How does it work? The foreground is selected using text prompts to [GroundingDINO](https://github.com/IDEA-Research/GroundingDINO) to detect objects. Image segments are generated using [Segment Anything](https://github.com/facebookresearch/segment-anything) or [Segment Anything HQ (SAM-HQ)](https://github.com/SysCV/SAM-HQ). ##### [Get started](install.md){ .md-button .md-button--primary .float-right } [Learn more](usage.md){ .md-button .float-right .mr-2 } ###
package com.home.keycloak.proxy import java.util import scala.jdk.CollectionConverters.* import io.circe.Json import io.circe.syntax.* import org.keycloak.events.admin.{ AdminEvent, AuthDetails } import org.keycloak.events.{ Event, EventListenerProvider } import zio.* import zio.kafka.producer.Producer import zio.kafka.serde.Serde class KeycloakToKafkaEventListenerProvider( eventTopic: String, adminEventTopic: String, producer: Producer, runtime: Runtime[Any] ) extends EventListenerProvider: private implicit val unsafe: Unsafe = Unsafe.unsafe(identity) override def onEvent(event: Event): Unit = val encodedEvent = Json .obj( "id" -> Option(event.getId).asJson, "time" -> Option(event.getTime).asJson, "type" -> Option(event.getType).map(_.toString).asJson, "realm_id" -> Option(event.getRealmId).asJson, "client_id" -> Option(event.getClientId).asJson, "user_id" -> Option(event.getUserId).asJson, "session_id" -> Option(event.getSessionId).asJson, "ip_address" -> Option(event.getIpAddress).asJson, "error" -> Option(event.getError).asJson, "details" -> Option(event.getDetails).getOrElse(new util.HashMap()).asScala.toMap.asJson ) .noSpaces runtime.unsafe.run: producer.produce(eventTopic, event.getUserId, encodedEvent, Serde.string, Serde.string) override def onEvent(event: AdminEvent, includeRepresentation: Boolean): Unit = val encodedEvent = Json .obj( "id" -> Option(event.getId).asJson, "time" -> Option(event.getTime).asJson, "realm_id" -> Option(event.getRealmId).asJson, "auth_details" -> Option(event.getAuthDetails).map(authDetailsAsJson).asJson, "resource_type" -> Option(event.getResourceTypeAsString).asJson, "operation_type" -> Option(event.getOperationType).map(_.toString).asJson, "resource_path" -> Option(event.getResourcePath).asJson, "representation" -> Option(event.getRepresentation).asJson, "error" -> Option(event.getError).asJson ) .noSpaces runtime.unsafe.run: producer.produce(adminEventTopic, event.getAuthDetails.getUserId, encodedEvent, Serde.string, Serde.string) private def authDetailsAsJson(authDetails: AuthDetails): Json = Json.obj( "realm_id" -> authDetails.getRealmId.asJson, "client_id" -> authDetails.getClientId.asJson, "user_id" -> authDetails.getUserId.asJson, "ip_address" -> authDetails.getIpAddress.asJson ) override def close(): Unit = runtime.unsafe.run(ZIO.logInfo("Closing the event listener provider"))
package concurrent; import org.junit.runner.Description; import org.junit.runner.notification.RunNotifier; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Group; import org.openjdk.jmh.annotations.GroupThreads; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.profile.StackProfiler; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.Options; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; // 度量批次为10次 @Measurement(iterations = 10) // 预热批次为10次 @Warmup(iterations = 10) // 采用平均响应时间作为度量方式 @BenchmarkMode(Mode.AverageTime) // 时间单位为微秒 @OutputTimeUnit(TimeUnit.MICROSECONDS) public class SynchronizedVsLockVsAtomicInteger { @State(Scope.Group) public static class IntMonitor { private int x; private final Lock lock = new ReentrantLock(); // 使用显式锁Lock进行共享资源同步 public void lockInc() { lock.lock(); try { x++; } finally { lock.unlock(); } } // 使用synchronized关键字进行共享资源同步 public void synInc() { synchronized (this) { x++; } } } // 直接采用AtomicInteger @State(Scope.Group) public static class AtomicIntegerMonitor { private AtomicInteger x = new AtomicInteger(); public void inc() { x.incrementAndGet(); } } // 基准测试方法 @GroupThreads(10) @Group("sync") @Benchmark public void syncInc(IntMonitor monitor) { monitor.synInc(); } // 基准测试方法 @GroupThreads(10) @Group("lock") @Benchmark public void lockInc(IntMonitor monitor) { monitor.lockInc(); } // 基准测试方法 @GroupThreads(10) @Group("atomic") @Benchmark public void atomicIntegerInc(AtomicIntegerMonitor monitor) { monitor.inc(); } public static void main(String[] args) throws RunnerException { Options opts = new OptionsBuilder() .include(SynchronizedVsLockVsAtomicInteger.class.getSimpleName()) .forks(1) .timeout(TimeValue.seconds(10)) .addProfiler(StackProfiler.class) .build(); new Runner(opts) { }.run(); } }
// 6-3장 import { useState, useEffect } from "react"; function Effects() { const [counter, setValue] = useState(0); const [keyword, setKeyword] = useState(""); const onClick = () => setValue((prev) => prev + 1); const onChange = (event) => setKeyword(event.target.value); console.log("i run all the time"); useEffect(() => { console.log("i run only once."); }, []); // 단 한번만 실행됨 useEffect(() => { console.log("i run whe 'keyword' changes"); //keyword의 길이가 6자 이상이면서 공란이 아닐경우에 실행 }, [keyword]); // keyword가 변화할때만 실행되게끔 함. useEffect(() => { console.log("i run whe 'counter' changes"); //keyword의 길이가 6자 이상이면서 공란이 아닐경우에 실행 }, [counter]); // counter가 변화할때만 실행되게끔 함. useEffect(() => { console.log("i run when keyword & counter chages"); }, [keyword,counter]); //keyword나 counter가 변화할때 실행되게끔함 return ( <div> <input onChange={onChange} type="text" placeholder="Search here..." /> <h1>{counter}</h1> <button onClick={onClick}>click me</button> </div> ) } export default Effects;
WCSLIB 4.8 - an implementation of the FITS WCS standard. Copyright (C) 1995-2011, Mark Calabretta This file is part of WCSLIB. WCSLIB is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. WCSLIB is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with WCSLIB. If not, see <http://www.gnu.org/licenses/>. Correspondence concerning WCSLIB may be directed to: Internet email: [email protected] Postal address: Dr. Mark Calabretta Australia Telescope National Facility, CSIRO PO Box 76 Epping NSW 1710 AUSTRALIA Author: Mark Calabretta, Australia Telescope National Facility http://www.atnf.csiro.au/~mcalabre/index.html $Id: wcsprintf.h,v 4.8.1.1 2011/08/15 08:07:06 cal103 Exp cal103 $ * * WCSLIB 4.8 - C routines that implement the FITS World Coordinate System * (WCS) standard. * * Summary of the wcsprintf routines * --------------------------------- * These routines allow diagnostic output from celprt(), linprt(), prjprt(), * spcprt(), tabprt(), wcsprt(), and wcserr_prt() to be redirected to a file or * captured in a string buffer. Those routines all use wcsprintf() for output. * * * wcsprintf() - Print function used by WCSLIB diagnostic routines * --------------------------------------------------------------- * wcsprintf() is used by the celprt(), linprt(), prjprt(), spcprt(), tabprt(), * wcsprt(), and wcserr_prt() routines. Its output may be redirected to a file * or string buffer via wcsprintf_set(). By default output goes to stdout. * * Given: * format char* Format string, passed to one of the printf(3) family * of stdio library functions. * * ... mixed Argument list matching format, as per printf(3). * * Function return value: * int Number of bytes written. * * * wcsprintf_set() - Set output disposition for wcsprintf() * -------------------------------------------------------- * wcsprintf_set() sets the output disposition for wcsprintf() which is used by * the celprt(), linprt(), prjprt(), spcprt(), tabprt(), wcsprt(), and * wcserr_prt() routines. * * Output goes to stdout by default if wcsprintf_set() has not been called. * * Given: * wcsout FILE* Pointer to an output stream that has been opened for * writing, e.g. by the fopen() stdio library function, * or one of the predefined stdio output streams - stdout * and stderr. If zero (NULL), output is written to an * internally-allocated string buffer, the address of * which may be obtained by wcsprintf_buf(). * * Function return value: * int Status return value: * 0: Success. * * * wcsprintf_buf() - Get the address of the internal string buffer * --------------------------------------------------------------- * wcsprintf_buf() returns the address of the internal string buffer created * when wcsprintf_set() is invoked with its FILE* argument set to zero. * * Function return value: * const char * * Address of the internal string buffer. The user may * free this buffer by calling wcsprintf_set() with a * valid FILE*, e.g. stdout. The free() stdlib library * function must NOT be invoked on this const pointer. * * * WCSPRINTF_PTR() macro - Print addresses in a consistent way * ----------------------------------------------------------- * WCSPRINTF_PTR() is a preprocessor macro used to print addresses in a * consistent way. * * On some systems the "%p" format descriptor renders a NULL pointer as the * string "0x0". On others, however, it produces "0" or even "(nil)". On * some systems a non-zero address is prefixed with "0x", on others, not. * * The WCSPRINTF_PTR() macro ensures that a NULL pointer is always rendered as * "0x0" and that non-zero addresses are prefixed with "0x" thus providing * consistency, for example, for comparing the output of test programs. * #ifndef WCSLIB_WCSPRINTF #define WCSLIB_WCSPRINTF #ifdef __cplusplus extern "C" { #endif #define WCSPRINTF_PTR(str1, ptr, str2) \ if (ptr) { \ wcsprintf("%s%#lx%s", (str1), (unsigned long)(ptr), (str2)); \ } else { \ wcsprintf("%s0x0%s", (str1), (str2)); \ } int wcsprintf_set(FILE *wcsout); int wcsprintf(const char *format, ...); const char *wcsprintf_buf(void); #ifdef __cplusplus } #endif #endif /* WCSLIB_WCSPRINTF */
// // SettingView.swift // wordpop // // Created by AhmetVural on 5.05.2022. // import SwiftUI struct SettingView: View { @EnvironmentObject var settings: ASettings @Environment(\.dismiss) var dismiss var body: some View { ZStack{ Color("background") .ignoresSafeArea() VStack{ ZStack{ HStack{ Button{ dismiss() }label:{ Image(systemName: "arrowshape.backward.fill") .font(.title) .foregroundColor(.cyan) } .padding() Spacer() } Text(LocalizedStringKey("Settings")) .font(.title) .bold() .foregroundColor(Color("dark")) .padding(.vertical) } VStack{ Text(LocalizedStringKey("Language")) .font(.title.bold()) .foregroundColor(Color("dark")) .padding(.vertical, 10 * sizeScreenIphone()) HStack{ VStack { HStack{ Text(LocalizedStringKey("Native")) .font(.system(size: 20 * sizeScreenIphone(), weight: .medium)) .foregroundColor(Color("dark")) } Picker(selection: $settings.native, label: Text("Native"), content: { Text("English 🇺🇸").tag(Language.english) Text("Turkish 🇹🇷").tag(Language.turkish) Text("Spanish 🇪🇸").tag(Language.spanish) Text("French 🇫🇷").tag(Language.french) Text("German 🇩🇪").tag(Language.german) } ) //.pickerStyle(WheelPickerStyle()) .accentColor((Color("dark"))) .frame(height: 100 * sizeScreenIphone()) } VStack { HStack { Text(LocalizedStringKey("Learning")) .font(.system(size: 20 * sizeScreenIphone(), weight: .medium)) .foregroundColor(Color("dark")) } Picker(selection: $settings.learning, label: Text("Learning"), content: { Text("English 🇺🇸").tag(Language.english) Text("Turkish 🇹🇷").tag(Language.turkish) Text("Spanish 🇪🇸").tag(Language.spanish) Text("French 🇫🇷").tag(Language.french) Text("German 🇩🇪").tag(Language.german) }) // .pickerStyle(WheelPickerStyle()) .accentColor((Color("dark"))) .frame(height: 100 * sizeScreenIphone()) } } Spacer() } .padding() .frame(width: 370 * sizeScreenIphone(), height: 280 * sizeScreenIphone()) .background(Color("yellow").opacity(0.5)) .cornerRadius(20 * sizeScreenIphone()) VStack{ Text(LocalizedStringKey("Level")) .font(.title.bold()) .foregroundColor(Color("dark")) .padding(.vertical, 10 * sizeScreenIphone()) VStack{ Text(LocalizedStringKey("Beginner")) .bold() .foregroundColor(.white) .frame(width: 200 * sizeScreenIphone(), height: 50 * sizeScreenIphone()) .background(Color("dark"),in:RoundedRectangle(cornerRadius:15 * sizeScreenIphone())) ZStack{ Text(LocalizedStringKey("Intermediate")) .bold() .blur(radius: 5) .foregroundColor(.white) Image(systemName: "lock") } .frame(width: 200 * sizeScreenIphone(), height: 50 * sizeScreenIphone()) .background(Color("gray"),in:RoundedRectangle(cornerRadius:15 * sizeScreenIphone())) ZStack{ Text(LocalizedStringKey("Pro")) .bold() .blur(radius: 5) .foregroundColor(.white) Image(systemName: "lock") } .frame(width: 200 * sizeScreenIphone(), height: 50 * sizeScreenIphone()) .background(Color("gray"),in:RoundedRectangle(cornerRadius:15 * sizeScreenIphone())) } Spacer() } .padding() .frame(width: 370 * sizeScreenIphone(), height: 280 * sizeScreenIphone()) .background(Color("yellow").opacity(0.5)) .cornerRadius(20 * sizeScreenIphone()) .padding(.vertical, 30 * sizeScreenIphone()) Spacer() } } .navigationBarBackButtonHidden(true) } } struct SettingView_Previews: PreviewProvider { static var previews: some View { SettingView().environmentObject(ASettings()) } }
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; public class MulticastChat { private static final int MAX_MESSAGE_LENGTH = 20; private static final int BUFLEN = 100; private static boolean working = true; private static int port; private static InetAddress groupAddress; private static MulticastSocket socket; public static void main(String[] args) { if (args.length != 3 || args[2].length() > 6) { System.out.println("Uzycie: java -jar zad3_chat.jar " + "<IP> <PORT> <NICK - maks 6 znakow>"); return; } initialize(args); // inicjalizuje socket, adres, potrzebne wartosci pol DatagramPacket sending; System.out.println("Przygotowany do nadawania..."); while (working) { String message = System.console().readLine(); // pobierz wiadomosc if (message.length() > MAX_MESSAGE_LENGTH) { System.err .println("Zbyt dluga wiadomosc - maksymalna dlugosc to 20"); continue; } String preparedMessage = Messager.prepareMessage(message); // przygotuj do wyslania w odpowiednim kodowaniu try { // na odpowiedni serwer sending = new DatagramPacket(preparedMessage.getBytes("ASCII"), preparedMessage.length(), groupAddress, port); } catch (UnsupportedEncodingException e) { System.err .println("SYSTEM: Problem z kodowaniem, uzycie defaultowego"); sending = new DatagramPacket(preparedMessage.getBytes(), preparedMessage.length(), groupAddress, port); } try { socket.send(sending); // wyslij, jesli nieudane to koniec } catch (IOException e) { e.printStackTrace(); working = false; } } finalizeSocket(); } private static void initialize(String[] args) { String nick = args[2]; Messager.setNick(nick); try { port = Integer.parseInt(args[1]); // pobierz numer portu } catch (NumberFormatException e) { e.printStackTrace(); return; } Runtime.getRuntime().addShutdownHook(new Thread() { // koniec pracy CTRL+C @Override public void run() { working = false; finalizeSocket(); } }); try { groupAddress = InetAddress.getByName(args[0]); // pobierz adres grupowy i sprawdz czy odpowiedni if (!groupAddress.isMulticastAddress()) { throw new Exception( "Podany adres nie jest adresem multicastowym"); } } catch (Exception e) { e.printStackTrace(); return; } try { // przygotuj socket komunikacyjny socket = new MulticastSocket(port); socket.joinGroup(groupAddress); } catch (IOException e) { e.printStackTrace(); if (socket != null) { socket.close(); } return; } // przygotuj program do odbierania wiadomosci w osobnym watku startReceivingThread(); } private static void startReceivingThread() { Thread receiver = new Thread() { @Override public void run() { byte[] buffer; DatagramPacket received; System.out.println("Przygotowany do odbierania..."); while (working) { try { buffer = new byte[BUFLEN]; received = new DatagramPacket(buffer, BUFLEN); socket.receive(received); // jesli dane w odpowiednim formacie to sparsuj i ladnie wypisz Messager.checkAndPrintMessage(received.getData()); } catch (IOException e) { e.printStackTrace(); working = false; } } } }; receiver.start(); } private static void finalizeSocket() { // zakoncz komunikacje if (socket != null) { try { socket.leaveGroup(groupAddress); } catch (IOException e) { e.printStackTrace(); } socket.close(); } } }
import React, { useState } from "react"; import RecipeCard from "../../pages/home/RecipeCard"; import axios from "axios"; import { Input, Button, Options, Select, FormDiv } from "./Header.styled"; const Form = () => { const [query, setQuery] = useState(""); const [meal, setMeal] = useState(""); const [data, setData] = useState([]); // console.log("query:", query); // console.log("meal:", meal); const getFoods = async () => { const url = `https://api.edamam.com/search?q=${query}&app_id=29e1b965&app_key=d36f57f6f46ee8cfaffc07daa4a40dad&mealType=${meal}`; const { data } = await axios(url); setData(data.hits); }; // console.log("data", data); // getFoods(); const search = () => { if (query && meal) { return getFoods(); } else { alert("Please Enter a keys."); } }; return ( <FormDiv> <Input type="text" value={query} onChange={(e) => setQuery(e.target.value)} /> <Button onClick={search}>SEARCH</Button> <Select name="aa" id="" value={meal} onChange={(e) => setMeal(e.target.value)} > <Options value="" defaultChecked disabled> Select </Options> <Options value="breakfast">Breakfast</Options> <Options value="lunch">Lunch</Options> <Options value="dinner">Dinner</Options> <Options value="snack">Snack</Options> <Options value="teatime">Teatime</Options> </Select> {data && <RecipeCard data={data} />} </FormDiv> ); }; export default Form;
import { useState } from 'react'; import Layout from '@/components/layout'; import stylesGuitarra from '../../styles/guitarras.module.css'; const GuitarraUrl = ({ guitarraSeleccionada, carrito, setCarrito }) => { const { name, description, price, image } = guitarraSeleccionada[0].attributes; const [cantidad, setCantidad] = useState(0); const selectedImage = image.data.attributes.url; const agregarAlCarrito = (e) => { e.preventDefault(); const itemObj = { name, price, selectedImage, cantidad, id: guitarraSeleccionada[0].id, }; if (carrito.some((item) => item.id === itemObj.id)) { const carritoActualizado = carrito.map((item) => { if (item.id === itemObj.id) { item.cantidad = itemObj.cantidad; } return item; }); setCarrito(carritoActualizado); alert('Cantidad Actualizada'); return; } setCarrito((carrito) => [...carrito, itemObj]); alert('Articulo Añadido'); }; return ( <Layout title={name} description={`Información de la Guitarra ${name}`}> <div className="contenedor"> <div className={stylesGuitarra.guitarra}> <img src={selectedImage} alt={`Fotografia de la guitarra ${name}`} /> <div className={stylesGuitarra.contenido}> <h3>{name} </h3> <p className={stylesGuitarra.descripcion}>{description} </p> <p> Precio: $<span className={stylesGuitarra.precio}>{price}</span> </p> <form className={stylesGuitarra.formulario}> <label htmlFor="cantidad-guitarra">Cantidad</label> <select name="cantidad-guitarra" id="cantidad-guitarra" value={cantidad} onChange={(e) => setCantidad(+e.target.value)} > <option value="">-- Elija La Cantidad --</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <button onClick={agregarAlCarrito} className={stylesGuitarra.enlace} > Añadir al Carrito </button> </form> </div> </div> </div> </Layout> ); }; export async function getStaticPaths() { const respuesta = await fetch(`${process.env.API_URL}/guitarras`); const { data: guitarras } = await respuesta.json(); const paths = guitarras.map((item) => { const obj = { params: { url: item.attributes.url, }, }; return obj; }); return { paths, fallback: false, }; } export async function getStaticProps({ params: { url } }) { const urlApi = `${process.env.API_URL}/guitarras?filters[url]=${url}&populate=image`; const respuesta = await fetch(urlApi); const { data: guitarraSeleccionada } = await respuesta.json(); return { props: { guitarraSeleccionada, }, }; } export default GuitarraUrl;
import json import os import re import time from urllib.parse import quote import requests import urllib3 urllib3.disable_warnings() class LCSpider: graph_url = 'https://leetcode-cn.com/graphql' user_agent = ( 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/77.0.3865.120 Safari/537.36' ) lc_en_cookie = '' lc_cn_cookie = '' def __init__(self): self.session = requests.session() # ['0000-0099', '0100-0199', ..., '9900-9999'] self.sub_folders = [ str(i * 100).zfill(4) + '-' + str(i * 100 + 99).zfill(4) for i in range(100) ] self.difficulty_mapper = dict(Easy='简单', Medium='中等', Hard='困难') self.result = [] def get_question_detail(self, question_title_slug): """fetch question detail from lc's api""" form_data = { 'operationName': 'globalData', 'query': 'query globalData {\n feature {\n questionTranslation\n subscription\n signUp\n ' 'discuss\n mockInterview\n contest\n store\n book\n chinaProblemDiscuss\n ' 'socialProviders\n studentFooter\n cnJobs\n enableLsp\n enableWs\n ' 'enableDebugger\n enableDebuggerAdmin\n enableDarkMode\n tasks\n ' 'leetbook\n __typename\n }\n userStatus {\n isSignedIn\n isAdmin\n ' 'isStaff\n isSuperuser\n isTranslator\n isPremium\n isVerified\n ' 'isPhoneVerified\n isWechatVerified\n checkedInToday\n username\n ' 'realName\n userSlug\n groups\n avatar\n optedIn\n ' 'requestRegion\n region\n activeSessionId\n permissions\n notificationStatus {\n ' 'lastModified\n numUnread\n __typename\n }\n completedFeatureGuides\n ' 'useTranslation\n accountStatus {\n isFrozen\n inactiveAfter\n __typename\n ' '}\n __typename\n }\n siteRegion\n chinaHost\n websocketUrl\n userBannedInfo {\n ' 'bannedData {\n endAt\n bannedType\n __typename\n }\n __typename\n }\n}\n', 'variables': {}, } headers = { 'User-Agent': LCSpider.user_agent, 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Referer': 'https://leetcode-cn.com/problems/' + question_title_slug, # lc-cn cookie here 'cookie': LCSpider.lc_cn_cookie, } self.session.post( url=LCSpider.graph_url, data=json.dumps(form_data), headers=headers, timeout=10, verify=False, ) form_data = { 'operationName': 'questionData', 'variables': {'titleSlug': question_title_slug}, 'query': 'query questionData($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n ' 'questionId\n questionFrontendId\n categoryTitle\n boundTopicId\n title\n ' 'titleSlug\n content\n translatedTitle\n translatedContent\n isPaidOnly\n ' 'difficulty\n likes\n dislikes\n isLiked\n similarQuestions\n ' 'contributors {\n username\n profileUrl\n avatarUrl\n __typename\n ' '}\n langToValidPlayground\n topicTags {\n name\n slug\n ' 'translatedName\n __typename\n }\n companyTagStats\n codeSnippets {\n ' 'lang\n langSlug\n code\n __typename\n }\n stats\n hints\n ' 'solution {\n id\n canSeeDetail\n __typename\n }\n status\n ' 'sampleTestCase\n metaData\n judgerAvailable\n judgeType\n mysqlSchemas\n ' 'enableRunCode\n envInfo\n book {\n id\n bookName\n pressName\n ' 'source\n shortDescription\n fullDescription\n bookImgUrl\n ' 'pressImgUrl\n productUrl\n __typename\n }\n isSubscribed\n ' 'isDailyQuestion\n dailyRecordStatus\n editorType\n ugcQuestionId\n style\n ' 'exampleTestcases\n __typename\n }\n}\n', } # get question detail resp = self.session.post( url=LCSpider.graph_url, data=json.dumps(form_data).encode('utf-8'), headers=headers, timeout=10, verify=False, ) res = resp.json() return res['data']['question'] def get_all_questions(self): """fetch all question from lc's api""" headers = { 'accept': 'application/json, text/javascript, */*; q=0.01', 'content-type': 'application/json', 'user-agent': LCSpider.user_agent, 'x-requested-with': 'XMLHttpRequest', # lc cookie here 'cookie': LCSpider.lc_en_cookie, } resp = self.session.get( url='https://leetcode.com/api/problems/all/', headers=headers, allow_redirects=False, timeout=10, verify=False, ) questions = resp.json()['stat_status_pairs'] for question in questions: time.sleep(0.5) question_title_slug = question['stat']['question__title_slug'] success = False question_detail = None for _ in range(5): try: question_detail = self.get_question_detail(question_title_slug) if question_detail: success = True break except Exception as e: print(f'error:{str(e)}') time.sleep(1) frontend_question_id = str(question['stat']['frontend_question_id']).zfill( 4 ) no = int(frontend_question_id) // 100 question_title_en = question['stat']['question__title'] question_title_en = re.sub(r'[\\/:*?"<>|]', '', question_title_en).strip() if not success or not question_detail: print(f'skip {frontend_question_id}. {question_title_en}') continue url_cn = f'https://leetcode-cn.com/problems/{question_title_slug}' url_en = f'https://leetcode.com/problems/{question_title_slug}' path_cn = f'/solution/{self.sub_folders[no]}/{frontend_question_id}.{quote(question_title_en)}/README.md' path_en = f'/solution/{self.sub_folders[no]}/{frontend_question_id}.{quote(question_title_en)}/README_EN.md' print(f'{frontend_question_id}. {question_title_en}') topic_tags = question_detail.get('topicTags') item = { 'question_id': str(question['stat']['question_id']).zfill(4), 'frontend_question_id': frontend_question_id, 'paid_only': question['paid_only'], 'paid_only_cn': question_detail.get('isPaidOnly'), # Shell Database Algorithms Concurrency 'category': question_detail.get('categoryTitle'), 'url_cn': url_cn, 'url_en': url_en, 'relative_path_cn': path_cn, 'relative_path_en': path_en, 'title_cn': question_detail.get('translatedTitle') or question_title_en or '', 'title_en': question_title_en or '', 'question_title_slug': question_title_slug, 'content_en': question_detail.get('content'), 'content_cn': question_detail.get('translatedContent') or question_detail.get('content'), 'tags_en': [e['name'] for e in topic_tags if e['name']] or [], 'tags_cn': [ e['translatedName'] for e in topic_tags if e['translatedName'] ] or [], 'difficulty_en': question_detail.get('difficulty'), 'difficulty_cn': self.difficulty_mapper.get( question_detail.get('difficulty') ), 'code_snippets': question_detail.get('codeSnippets') or [], } col1_cn = f'[{frontend_question_id}]({url_cn})' col2_cn = ( f'[{item["title_cn"]}]({path_cn})' if item["title_cn"] else f'[{item["title_en"]}]({path_en})' ) col3_cn = ','.join([f'`{tag}`' for tag in item['tags_cn']]) col3_cn = '' if (col3_cn == 'None' or not col3_cn) else col3_cn col4_cn = item['difficulty_cn'] col5_cn = '🔒' if item['paid_only_cn'] else '' col1_en = f'[{frontend_question_id}]({url_en})' col2_en = f'[{item["title_en"]}]({path_en})' col3_en = ','.join([f'`{tag}`' for tag in item['tags_en']]) col3_en = '' if (col3_en == 'None' or not col3_en) else col3_en col4_en = item['difficulty_en'] col5_en = '🔒' if item['paid_only'] else '' item['md_table_row_cn'] = [col1_cn, col2_cn, col3_cn, col4_cn, col5_cn] item['md_table_row_en'] = [col1_en, col2_en, col3_en, col4_en, col5_en] self.result.append(item) def save_result(self): with open('result.json', 'w', encoding='utf-8') as f: f.write(json.dumps(self.result)) @staticmethod def generate_readme(): """generate readme files""" with open('./result.json', 'r', encoding='utf-8') as f: result = f.read() result = json.loads(result) md_table_cn = [item['md_table_row_cn'] for item in result] md_table_en = [item['md_table_row_en'] for item in result] # generate README.md items = [] table_cn = ( '\n| 题号 | 题解 | 标签 | 难度 | 备注 |\n| --- | --- | --- | --- | --- |' ) for item in sorted(md_table_cn, key=lambda x: x[0]): items.append( f'\n| {item[0]} | {item[1]} | {item[2]} | {item[3]} | {item[4]} |' ) table_cn += ''.join(items) with open('./readme_template.md', 'r', encoding='utf-8') as f: readme_cn = f.read() with open('./README.md', 'w', encoding='utf-8') as f: f.write(readme_cn.format(table_cn)) # generate README_EN.md items = [] table_en = '\n| # | Solution | Tags | Difficulty | Remark |\n| --- | --- | --- | --- | --- |' for item in sorted(md_table_en, key=lambda x: x[0]): items.append( f'\n| {item[0]} | {item[1]} | {item[2]} | {item[3]} | {item[4]} |' ) table_en += ''.join(items) with open('./readme_template_en.md', 'r', encoding='utf-8') as f: readme_en = f.read() with open('./README_EN.md', 'w', encoding='utf-8') as f: f.write(readme_en.format(table_en)) def generate_question_readme(self): with open('./problem_readme_template.md', 'r', encoding='utf-8') as f: readme_cn = f.read() with open('./problem_readme_template_en.md', 'r', encoding='utf-8') as f: readme_en = f.read() with open('./sql_problem_readme_template.md', 'r', encoding='utf-8') as f: sql_readme_cn = f.read() with open('./sql_problem_readme_template_en.md', 'r', encoding='utf-8') as f: sql_readme_en = f.read() with open('./bash_problem_readme_template.md', 'r', encoding='utf-8') as f: bash_readme_cn = f.read() with open('./bash_problem_readme_template_en.md', 'r', encoding='utf-8') as f: bash_readme_en = f.read() with open('./result.json', 'r', encoding='utf-8') as f: result = f.read() result = json.loads(result) for item in result: if not item['content_cn'] and not item['content_en']: continue no = int(item['frontend_question_id']) // 100 path = f'./{self.sub_folders[no]}/{item["frontend_question_id"]}.{item["title_en"]}' path = path.replace(":", " ") if os.path.isdir(path): continue os.makedirs(path) # choose the readme template category = item['category'] if category == 'Shell': readme_template_cn = bash_readme_cn readme_template_en = bash_readme_en elif category == 'Database': readme_template_cn = sql_readme_cn readme_template_en = sql_readme_en else: readme_template_cn = readme_cn readme_template_en = readme_en # generate lc-cn problem readme with open(f'{path}/README.md', 'w', encoding='utf-8') as f1: f1.write( readme_template_cn.format( int(item['frontend_question_id']), item["title_cn"], item['url_cn'], item['relative_path_en'], item['content_cn'], ) ) # generate lc-en problem readme with open(f'{path}/README_EN.md', 'w', encoding='utf-8') as f2: f2.write( readme_template_en.format( int(item['frontend_question_id']), item["title_en"], item['url_en'], item['relative_path_cn'], item['content_en'], ) ) @staticmethod def generate_summary(): """generate summary files""" summary_cn = '' summary_en = '' for file in os.listdir('./'): if os.path.isdir("./" + file) and file != '__pycache__': summary_cn += f'\n- {file}\n' summary_en += f'\n- {file}\n' for sub in os.listdir('./' + file): sub = sub.replace('`', ' ') enc = quote(sub) summary_cn += f' - [{sub}](/solution/{file}/{enc}/README.md)\n' summary_en += f' - [{sub}](/solution/{file}/{enc}/README_EN.md)\n' # generate summary.md with open('./summary.md', 'w', encoding='utf-8') as f: f.write(summary_cn) # generate summary_en.md with open('./summary_en.md', 'w', encoding='utf-8') as f: f.write(summary_en) if __name__ == '__main__': spider = LCSpider() spider.get_all_questions() spider.save_result() spider.generate_readme() spider.generate_question_readme() spider.generate_summary()
// // FullStockData.swift // StockScanner // // Created by Colstin Donaldson on 10/19/23. // import Foundation struct FullStockData { let symbol: String let companyName: String let price: Double let volume: Int let changesPercentage: Double let change: Double var formattedPrice: String { return String(format: "%.2f", price) } var formattedChangesPercentage: String { return String(format: "%.1f", changesPercentage) } var formattedVolume: String { if volume >= 1_000_000_000 { return String(format: "%.2fB", Double(volume) / 1_000_000_000.0 ) } else if volume >= 100_000_000 { return String(format: "%.0fM", Double(volume) / 1_000_000.0 ) } else if volume >= 10_000_000 { return String(format: "%.1fM", Double(volume) / 1_000_000.0 ) } else if volume >= 1_000_000 { return String(format: "%.2fM", Double(volume) / 1_000_000.0 ) } else { return "\(volume / 1_000)K" } } }
/** * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ package com.liferay.frontend.data.set.sample.web.internal.provider; import com.liferay.frontend.data.set.provider.FDSDataProvider; import com.liferay.frontend.data.set.provider.search.FDSKeywords; import com.liferay.frontend.data.set.provider.search.FDSPagination; import com.liferay.frontend.data.set.sample.web.internal.constants.FDSSampleFDSNames; import com.liferay.frontend.data.set.sample.web.internal.model.UserEntry; import com.liferay.petra.function.transform.TransformUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.search.Sort; import com.liferay.portal.kernel.service.UserLocalService; import com.liferay.portal.kernel.theme.ThemeDisplay; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.liferay.portlet.usersadmin.util.UsersAdminUtil; import java.util.LinkedHashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; /** * @author Marko Cikos */ @Component( property = "fds.data.provider.key=" + FDSSampleFDSNames.CLASSIC, service = FDSDataProvider.class ) public class ClassicFDSDataProvider implements FDSDataProvider<UserEntry> { @Override public List<UserEntry> getItems( FDSKeywords fdsKeywords, FDSPagination fdsPagination, HttpServletRequest httpServletRequest, Sort sort) throws PortalException { ThemeDisplay themeDisplay = (ThemeDisplay)httpServletRequest.getAttribute( WebKeys.THEME_DISPLAY); return TransformUtil.transform( UsersAdminUtil.getUsers( _userLocalService.search( themeDisplay.getCompanyId(), fdsKeywords.getKeywords(), WorkflowConstants.STATUS_APPROVED, new LinkedHashMap<String, Object>(), fdsPagination.getStartPosition(), fdsPagination.getEndPosition(), sort)), user -> new UserEntry( user.getEmailAddress(), user.getFirstName(), user.getUserId(), user.getLastName())); } @Override public int getItemsCount( FDSKeywords fdsKeywords, HttpServletRequest httpServletRequest) throws PortalException { ThemeDisplay themeDisplay = (ThemeDisplay)httpServletRequest.getAttribute( WebKeys.THEME_DISPLAY); return _userLocalService.searchCount( themeDisplay.getCompanyId(), fdsKeywords.getKeywords(), WorkflowConstants.STATUS_APPROVED, null); } @Reference private UserLocalService _userLocalService; }
import React from 'react' import { colors } from '../Assets/theme' import Header from './Header' import Footer from './Footer' import { Helmet } from 'react-helmet' export default function Privacy() { const data = [ { question: "Introduction", answer: ` Welcome to the app (the “App”) of Homeatz (“Homeatz,” “we,” “us,” or “our”). Homeatz provides an online marketplace in which personal chefs, caterers and other individuals can list, offer, sell and deliver food items and meal orders to the general public, and customers can browse and purchase Meals. Your privacy is extremely important to us. This Privacy Policy explains what Personal Data (defined below) we collect, how we use and share that data, and your choices concerning our data practices. Before using the Service or submitting any Personal Data to Homeatz, please review this Privacy Policy carefully and contact us via details available in the side menu of the app, if you have any questions. By using the Service, you agree to the practices described in this Privacy Policy. If you do not agree to this Privacy Policy, please do not access the Site or otherwise use the Service. ` }, { question: "1. PERSONAL DATA WE COLLECT", answer:` We collect information that alone or in combination with other information in our possession could be used to identify you (“Personal Data”) as follows: Personal Data You Provide: We collect Personal Data that you provide to Homeatz by (i) filling out required and optional profile information when signing up for the Service, or (ii) contacting us by e-mail. The Personal Data collected during these interactions may vary based on what you choose to share with us, but it will generally include name, e-mail address, telephone number, location and the financial information necessary to ensure payments can be processed by our payment processor Stripe, Inc. (“Stripe”). Accordingly, in addition to this Privacy Policy and our Terms of Service, information related to your purchases is also processed according to Stripe's services agreement and privacy policy. Personal Data We Collect Through Our Social Media Pages: We have pages on social media sites like Instagram, Twitter, LinkedIn, and Facebook (“Social Media Pages”). When you interact with our Social Media Pages, we will collect Personal Data that you elect to provide to us, such as your contact details. In addition, the companies that host our Social Media Pages may provide us with aggregate information and analytics regarding the use of our Social Media Pages. Personal Data We Receive Automatically From Your Use of the Service: When you visit, use and interact with the Service, we may receive certain information about your visit, use or interactions. For example, we may monitor the number of people that visit the Service, peak hours of visits, which page(s) you visit, which links you click, what text you enter, how your mouse moves around the Service, the domains you come from (e.g., google.com, facebook.com, etc.), broad geographical information, and navigation patterns. In particular, the following information is created and automatically logged in our systems: • Device information: Includes name of the device, operating system. Information collected may depend on the type of device you use and its settings. • Usage Information: We collect information about how you use our Service, such as the types of content that you view or engage with, the features you use, the actions you take, and the time, frequency and duration of your activities. Analytics: We use Google Analytics, a web analytics service provided by Google, Inc. (“Google”). Google Analytics help us analyze how users use the Site and enhance your experience when you use the Site. For more information on how Google uses this data, go to www.google.com/policies/privacy/partners/. Our third party service providers, including Facebook, may use cookies, pixels or other tracking technologies to collect information about your browsing activities over time and across different websites following your use of the App [and use that information to send targeted advertisements]. Our App currently does not respond to “Do Not Track” (“DNT”) signals and operates as described in this Privacy Policy whether or not a DNT signal is received. If we do respond to DNT signals in the future, we will update this Privacy Policy to describe how we do so. ` }, { question: "2. HOW WE USE PERSONAL DATA", answer:` We may use Personal Data for the following purposes: • To provide the Service, including the online marketplace in which individuals can sell food items and meal orders to customers; • To respond to your inquiries, comments, feedback or questions; • To send administrative information to you, for example, information regarding the Service, requests for feedback, and changes to our terms, conditions, and policies; • To analyze how you interact with our Service; • To maintain and improve the content and functionality of the Service; • To develop new products and services; • To prevent fraud, criminal activity, or misuses of our Service, and to ensure the security of our IT systems, architecture and networks; and • To comply with legal obligations and legal process and to protect our rights, privacy, safety or property, and/or that of our affiliates, you or other third parties. Aggregated Information. We may aggregate Personal Data and use the aggregated information in an anonymized form to analyze the effectiveness of our Service, to improve and add features to our Service, and for other similar purposes. In addition, from time to time, we may analyze the general behavior and characteristics of users of our Services and share aggregated and anonymized information like general user statistics with prospective business partners. We may collect aggregated information through the Service and through other means described in this Privacy Policy. Marketing. We may use your Personal Data to contact you to tell you about products or services we believe may be of interest to you. If at any time you do not wish to receive future marketing communications, you may contact us via ‘Contact Us’ section on the app. If you unsubscribe from our marketing lists, you will no longer receive marketing communications but we may still contact you regarding management of your account, other administrative matters, and to respond to your requests. ` }, { question: "3. SHARING AND DISCLOSURE OF PERSONAL DATA", answer:` In certain limited circumstances set forth below we may share your Personal Data with third parties without further notice to you, unless required by the law, as set forth below: • Vendors and Service Providers: To assist us in meeting business operations needs and to perform certain services and functions, we may share Personal Data with vendors and service providers, including providers of hosting services, cloud services and other information technology services providers, email communication software and email newsletter services, advertising and marketing services, payment processors, customer relationship management and customer support services, and analytics services. Pursuant to our instructions, these parties will access, process or store Personal Data in the course of performing their duties to us. We take commercially reasonable steps to ensure our service providers adhere to the "Security Standards" we apply to your Personal Data (as detailed below). • Business Transfers: If we are involved in a merger, acquisition, financing due diligence, reorganization, bankruptcy, receivership, sale of all or a portion of our assets, or transition of service to another provider, your Personal Data and other information may be shared in the diligence process with counterparties and others assisting with the transaction and transferred to a successor or affiliate as part of that transaction along with other assets. • Legal Requirements: If required to do so by law or in the good faith belief that such action is necessary to (i) comply with a legal obligation, including to meet national security or law enforcement requirements, (ii) protect and defend our rights or property, (iii) prevent fraud, (iv) act in urgent circumstances to protect the personal safety of users of the Services, or the public, or (v) protect against legal liability. • Affiliates: We may share Personal Data with our affiliates, meaning an entity that controls, is controlled by, or is under common control with Homeatz. Our affiliates may use the Personal Data we share in a manner consistent with this Privacy Policy. ` }, { question: "4. DATA RETENTION", answer: "We keep Personal Data for as long as reasonably necessary for the purposes described in this Privacy Policy, while we have a business need to do so, or as required by law (e.g. for tax, legal, accounting or other purposes), whichever is the longer." }, { question: "5. UPDATE YOUR INFORMATION", answer: "Please log in to your account or ‘Contact Us’ if you need to change or correct your Personal Data." }, { question: "6. LINKS TO OTHER WEBSITES", answer: "The Service may contain links to other websites not operated or controlled by Homeatz, including social media services (“Third Party Sites”). The information that you share with Third Party Sites will be governed by the specific privacy policies and terms of service of the Third Party Sites and not by this Privacy Policy. By providing these links we do not imply that we endorse or have reviewed these sites. Please contact the Third Party Sites directly for information on their privacy practices and policies." }, { question: "7. SECURITY", answer: "You use the Service at your own risk. We implement commercially reasonable technical, administrative, and organizational measures to protect Personal Data both online and offline from loss, misuse, and unauthorized access, disclosure, alteration or destruction. However, no Internet or e-mail transmission is ever fully secure or error free. Therefore, you should take special care in deciding what information you send to us via the Service or e-mail. Please keep this in mind when disclosing any Personal Data to Homeatz via the Internet. In addition, we are not responsible for circumvention of any privacy settings or security measures contained on the Service, or third party websites." }, { question: "8. YOUR CHOICES", answer: "In certain circumstances providing Personal Data is optional. However, if you choose not to provide Personal Data that is needed to use some features of our Services, you may be unable to use those features." }, { question: "9. CHANGES TO THE PRIVACY POLICY", answer: "The Service, and our business may change from time to time. As a result we may change this Privacy Policy at any time. When we do we will post an updated version on this page, unless another type of notice is required by the applicable law. By continuing to use our Service or providing us with Personal Data after we have posted an updated Privacy Policy, or notified you by other means if applicable, you consent to the revised Privacy Policy and practices described in it." }, { question: "10. CONTACT US", answer: "If you have any questions about our Privacy Policy or information practices, please feel free to contact us via the options available in the side menu of the app" }, { question: "Date of Last Revision: June 15, 2021" }, ] React.useEffect(() => { window.scrollTo({ top: 0, behavior: "smooth" }) }, []) return ( <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', }}> <Helmet> <meta charSet="utf-8" /> <title>Homeatz Privacy Policy</title> <meta name="description" content="At Homeatz, we value your privacy. This Privacy Policy outlines how we collect, use, and protect your personal information when you use our platform." /> </Helmet> <Header/> <div style={{ display: "flex", flexDirection: "column", backgroundColor: colors.lightPink, width: "100vw", height: 250, justifyContent: "center", alignItems: "center" }}> <p style={{ marginBlock: 0, color: colors.logoPink, fontSize: 40, textAlign: 'center', fontFamily: "BalsamiqSans-Bold", }}> HOMEATZ App Privacy Policy </p> <p style={{ marginBlock: 0, color: colors.logoPink, fontSize: 20, textAlign: 'center', fontFamily: "BalsamiqSans-Bold", }}> Last updated: 15/06/2021 </p> </div> <div style={{ display: "flex", flexDirection: "column", width: "90vw", justifyContent: "space-evenly", alignItems: "center", alignSelf: "center", marginTop: 50, }}> { data.map((item, index) => { return ( <div key={index} style={{ display: "flex", flexDirection: "column", boxShadow: "5px 5px 10px #88888850", padding: 25, borderRadius: 8, width: "80vw", // height: "18vh", justifyContent: "space-evenly", marginBottom: 20, }}> <p style={{ textDecoration: 'none', marginBlock: 0, color: colors.black, fontSize: 20, fontWeight: 'bold', textAlign: 'left', fontFamily: "LEMONMILK-Bold", cursor: 'pointer', }}> {item?.question} </p> <p style={{ textDecoration: 'none', marginBlock: 0, color: colors.black, fontSize: 16, textAlign: 'left', fontFamily: "BalsamiqSans-Regular", }}> {item?.answer?.split('\n').map(function (value, key) { return ( <span key={key}> {value} <br /> </span> ) }) } </p> </div> ) }) } </div> <div style={{ marginTop: "30vh", }}> <Footer /> </div> </div> ) }
<template> <div class="editor-page"> <div class="container page"> <div class="row"> <div class="col-md-10 offset-md-1 col-xs-12"> <ul class="error-messages"> <template v-for="(messages, field) in errors"> <li v-for="(msg, index) in messages" :key="index"> {{ field }} {{ msg }} </li> </template> </ul> <form @submit.prevent="onSubmit"> <fieldset> <fieldset class="form-group"> <input type="text" class="form-control form-control-lg" placeholder="Article Title" v-model="article.title" /> </fieldset> <fieldset class="form-group"> <input type="text" class="form-control" placeholder="What's this article about?" v-model="article.description" /> </fieldset> <fieldset class="form-group"> <textarea class="form-control" rows="8" placeholder="Write your article (in markdown)" v-model="article.body" ></textarea> </fieldset> <fieldset class="form-group"> <input type="text" class="form-control" placeholder="Enter tags" v-model="article.tags" /> <div class="tag-list"></div> </fieldset> <button class="btn btn-lg pull-xs-right btn-primary" > Publish Article </button> </fieldset> </form> </div> </div> </div> </div> </template> <script> import { createArticle } from '@/api/article' export default { middleware: 'authenticated', name: 'EditorIndex', async asyncData() { return { article: {}, errors: {}, } }, methods: { async onSubmit () { try { const { data } = await createArticle({ article: { title: this.article.title, description: this.article.description, body: this.article.body, tagList: [], }, }); this.$router.push(`/article/${data.article.slug}`); } catch (error) { this.errors = error.response.data.errors; } } } }; </script> <style> </style>
import { useEffect, useState } from "react"; type Data = { id: string; name: string; category: string; }; const url: Data[] = [ { id: "sign-up-form", name: "Sign-Up Form", category: "HTML", }, { id: "javascript-circles", name: "javascript Circles", category: "JavaScript", }, { id: "javascript-sqares", name: "javascript Squares", category: "JavaScript", }, { id: "rainbow-circles", name: "Rainbow Circles", category: "CSS", }, ]; const Test = () => { const [HTMLData, setHTMLData] = useState<Data[]>([]); const [CSSData, setCSSData] = useState<Data[]>([]); const [JavaScriptData, setJavaScriptData] = useState<Data[]>([]); useEffect(() => { url.map((data) => { if (data.category === "HTML") setHTMLData((prevState) => { return [...prevState, data]; }); else if (data.category === "CSS") setCSSData((prevState) => { return [...prevState, data]; }); else if (data.category === "JavaScript") setJavaScriptData((prevState) => { return [...prevState, data]; }); }); }, []); const displayData = (data: Data) => { return ( <div key={data.id}> <h3>{data.name}</h3> </div> ); }; return ( <> <div> <h2>HTML</h2> {HTMLData.length && HTMLData.map((data) => { return displayData(data); })} </div> <div> <h2>CSS</h2> {CSSData.length && CSSData.map((data) => { return displayData(data); })} </div> <div> <h2>JavaScript</h2> {JavaScriptData.length && JavaScriptData.map((data) => { return displayData(data); })} </div> </> ); }; export default Test;
const dotenv = require('dotenv'); // Init env so files can use it dotenv.config(); const express = require('express'); const cors = require('cors'); const morgan = require('morgan'); const mongoose = require('mongoose'); const cookieParser = require('cookie-parser'); const { LIMIT_UPLOAD, MONGO_URI } = require('./constants'); const connectToRoutes = require('./routes'); const app = express(); const PORT = process.env.PORT || 5000; // Init configs app.use(express.json({ limit: LIMIT_UPLOAD, extended: true })); app.use(express.urlencoded({ limit: LIMIT_UPLOAD, extended: true })); app.use(cookieParser()); app.use( cors({ origin: true, credentials: true, }) ); // Connect to routes connectToRoutes(app); app.get('/', (req, res) => { res.send('Welcome to fire land app 👋'); }); // HTTP logger app.use(morgan('dev')); // Connect to db const connectToDb = () => { try { mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('Connected to DB 🍕'); app.listen(PORT, () => { console.log(`Server started on port ${PORT} 🍔`); }); } catch (error) { console.log(`Server got an error 👉 ${error}`); } }; // Call db connectToDb();
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Models\Indicador; use Illuminate\Http\Request; class IndicadorController extends Controller { public function __construct() { $this->middleware('can:admin.indicadores.index')->only('index'); $this->middleware('can:admin.indicadores.create')->only('create', 'store'); $this->middleware('can:admin.indicadores.edit')->only('edit', 'update', 'show'); $this->middleware('can:admin.indicadores.destroy')->only('destroy'); } public function index() { $indicadores = Indicador::all(); return view('admin.indicadores.index', compact("indicadores")); } public function create() { return view('admin.indicadores.create'); } public function store(request $request) { // $indicador = new Indicador(); // $indicador->name = $request->name; // $indicador->description = $request->description; // $indicador->enabled = true; // $indicador->save(); $indicador = Indicador::create($request->all()); return redirect()->route('admin.indicadores.index', $indicador)->with('info', 'El Indicador se creo con exito'); } public function edit(Indicador $indicador) { return view('admin.indicadores.edit',compact("indicador")); } public function update(Request $request, Indicador $indicador) { $request->validate([ //si no se usa este tiene que ser StoreIndicador (request) 'name'=>'required', 'description'=>'required', 'enabled'=>'required' ]); // $indicador->name= $request->name; // $indicador->description= $request->description; // $indicador->save(); $indicador->update($request->all()); return redirect()->route('admin.indicadores.index', $indicador)->with('info', 'El Indicador se actualizo con exito'); } public function getindicadorcount() { $cantidad = Indicador::all()->count(); return response()->json(['msg' => $cantidad]); } public function show(Indicador $indicador) { return view('admin.indicadores.show',compact('indicador')); } }
import { StyleSheet ,View,Button,TextInput, Modal,Image} from "react-native"; import { useState } from "react"; function GoalInput(props) { const [enterredGoalText,setEnteredGoalText] = useState(''); function goalInputHandler(eneterdText){ setEnteredGoalText(eneterdText); }; function addGoalHandler(){ props.onAddGoal(enterredGoalText); setEnteredGoalText(''); } return ( <Modal visible={props.visible} animationType="slide" > <View style={styles.inputContainer}> <Image style={styles.image} source={require('../assets/images/goal.jpg')} /> <TextInput placeholder='Your course goal' onChangeText={goalInputHandler} style={styles.textInput} value={enterredGoalText} /> <View style={styles.buttonContainer}> <View style={styles.button}> <Button title='Add Goal'onPress={addGoalHandler} color='#5e0acc'/> </View> <View style={styles.button}> <Button title='Cancel'onPress={props.onCancel} color='#f31282'/> </View> </View> </View> </Modal> ) } export default GoalInput const styles = StyleSheet.create({ inputContainer : { flex : 1, justifyContent : 'center', alignItems : 'center', padding : 16, backgroundColor : '#311b6b' }, textInput : { borderWidth : 1, borderColor : '#e4d0ff', backgroundColor : '#e4d0ff', color : '#120438', borderRadius : 6, width : '90%', marginRight : 8, padding : 16, }, buttonContainer : { flexDirection : 'row', marginTop : 60, }, button : { width : '30%', marginHorizontal : 8, }, image: { width : 100, height : 100, margin : 20, } })
import { sortedLastIndexOf } from "lodash" import { detach, getRoot, types } from "mobx-state-tree" import { api_create_drama, api_update_drama } from "../../queries/drama" import Asset from "../models/Asset" const PublishDramaStore = types .model('PublishDramaStore', { video: types.optional( Asset, {} ), dramaId: types.maybeNull(types.number), frame: types.maybeNull(types.boolean), hashId: types.maybeNull(types.string), description: types.optional(types.string, ''), tags: types.optional(types.array(types.string), []), loading: false, uploadingError: false }) .views(self => ({ get token() { return getRoot(self).authStore.token }, get publishing() { return self.loading || self.video.loading }, get uploadingVideo() { return self.video.loading }, get dramasFactory() { return getRoot(self).dramasFactory }, get homeStore() { return getRoot(self).homeStore }, get validPublish() { return !self.uploadingVideo && self.description } })) .actions(self => ({ async createDrama(challengeId) { try { const res = await api_create_drama(self.token, { challengeId }) if (res.error) throw res self.set('hashId', res.data.hashId) self.set('dramaId', res.data.id) return res.data } catch (err) { return err } }, async upload(file, challengeId) { try { self.set('loading', true) self.set('uploadingError', false) const data = await self.createDrama(challengeId) if (data.error) throw data const dramaId = data.id const hashId = data.hashId const video = Asset.create({}) self.set('video', video) const res = await video.upload(dramaId, hashId, self.token, file) self.set('loading', false) if (res.error) throw res } catch (err) { self.set('uploadingError', true) self.set('loading', false) return err } }, async updateDrama() { try { self.set('loading', true) const res = await api_update_drama(self.token, { drama: { id: self.dramaId, frame: self.frame, description: self.description, tags: self.tags } }) let data = { ...res.data, video: { ...res.data.video, localUrl: self.video?.localUrl } } self.dramasFactory.addUpdateDrama(data) self.set('loading', false) self.clearData() return res.data } catch (err) { self.set('loading', false) return err } }, clearData() { self.removeVideo(), self.clear() }, removeVideo() { if (self.video) detach(self.video) }, clear() { self.set('dramaId', null) self.set('hashId', null) self.set('frame', false) self.set('description', '') self.set('tags', []) }, set(key, value) { self[key] = value } })) export default PublishDramaStore
------------------------------------------------------ CHAPTER 06 - DATA LOADING AND STORAGE ------------------------------------------------------ - Parsing Functions in pandas Function Description -------------------------------------------------------------------------------------- read_csv Load delimited data from a file, URL, or file-like object; use comma as default delimiter read_table Load delimited data from a file, URL, or file-like object; use tab ('\t') as default delimiter read_fwf Read data in fixed-width column format (i.e., no delimiters) read_clipboard Version of read_table that reads data from the clipboard; useful for converting tables from web pages read_excel Read tabular data from an Excel XLS or XLSX file read_hdf Read HDF5 files written by pandas read_html Read all tables found in the given HTML document read_json Read data from a JSON (JavaScript Object Notation) string representation read_msgpack Read pandas data encoded using the MessagePack binary format read_pickle Read an arbitrary object stored in Python pickle format read_sas Read a SAS dataset stored in one of the SAS system’s custom storage formats read_sql Read the results of a SQL query (using SQLAlchemy) as a pandas DataFrame read_stata Read a dataset from Stata file format read_feather Read the Feather binary file format - Reading from CSV # Here we have a sample csv >>> !cat examples/ex1.csv a,b,c,d,message 1,2,3,4,hello 5,6,7,8,world 9,10,11,12,foo # Here we read the csv into a DataFrame >>> df = pd.read_csv('examples/ex1.csv') >>> df a b c d message 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo # Or, we can use 'read_table' and specify the delimiter, which will give # us the same DataFrame >>> pd.read_table('examples/ex1.csv', sep=',') # Sometimes files don't have a header row >>> !cat examples/ex2.csv 1,2,3,4,hello 5,6,7,8,world 9,10,11,12,foo # In this case, you can either let pandas assign default column names >>> pd.read_csv('examples/ex2.csv', header=None) 0 1 2 3 4 0 1 2 3 4 hello 1 5 6 7 8 world 2 9 10 11 12 foo # Or you can specify the column names yourself >>> pd.read_csv('examples/ex2.csv', names=['a', 'b', 'c', 'd', 'message']) - Specifying Index and Columns # You can specify that one of the columns should be the index >>> names = ['a', 'b', 'c', 'd', 'e'] >>> pd.read_csv('examples/ex2.csv', names=names, index_col='message') a b c d message hello 1 2 3 4 world 5 6 7 8 foo 9 10 11 12 # A list of column names can be passed to form a hierarchical index of multiple columns >>> !cat examples/csv_mindex.csv key1,key2,value1,value2 one,a,1,2 one,b,3,4 one,c,5,6 one,d,7,8 two,a,9,10 two,b,11,12 two,c,13,14 two,d,15,16 >>> parsed = pd.read_csv('examples/csv_mindex.csv', index_col=['key1', 'key2']) >>> parsed value1 value2 key1 key2 one a 1 2 b 3 4 c 5 6 d 7 8 two a 9 10 b 11 12 c 13 14 d 15 16 - Parsing Input # In some cases, a table may not have a fixed delimiter, for instance using a # variable amount of whitespace to separate fields. Regex's can be used # in this case. >>> result = pd.read_table('examples/ex3.txt', sep='\s+') # The 'skiprows' option can be used to skip rows without data >>> pd.read_csv('examples/ex4.csv', skiprows=[0, 2, 3]) - Handling Missing Values Missing data is usually either not present (just an empty string) or marked by some kind of sentinel value (like 'NA' or 'NULL'). >>> !cat examples/ex5.csv something,a,b,c,d,message one,1,2,3,4,NA two,5,6,,8,world three,9,10,11,12,foo >>> result = pd.read_csv('examples/ex5.csv') >>> result something a b c d message 0 one 1 2 3.0 4 NaN 1 two 5 6 NaN 8 world 2 three 9 10 11.0 12 foo >>> pd.is_null(result) something a b c d message 0 False False False False False True 1 False False False True False False 2 False False False False False False # The 'na_values' option can take either a list or set of strings to consider # missing values. (NaN will be inserted in those cells.) >>> result = pd.read_csv('examples/ex5.csv', na_values=['NULL']) # Different 'na_values' can be specified for each column also >>> sentinels = {'message': ['foo', 'NA'], 'something': ['two']} >>> pd.read_csv('examples/ex5.csv', na_values=sentinels) - List of 'read_csv' and 'read_table' Arguments Argument Description --------------------------------------------------------------------------------------------- path String indicating filesystem location, URL, or file-like object sep or delimiter Character sequence or regular expression to use to split fields in each row header Row number to use as column names; defaults to 0 (first row), but should be None if there is no header row index_col Column numbers or names to use as the row index in the result; can be a single name/number or a list of them for a hierarchical index names List of column names for result, combine with header=None skiprows Number of rows at beginning of file to ignore or list of row numbers (starting from 0) to skip. na_values Sequence of values to replace with NA. comment Character(s) to split comments off the end of lines. parse_dates Attempt to parse data to datetime; False by default. If True, will attempt to parse all columns. Otherwise can specify a list of column numbers or name to parse. If element of list is tuple or list, will combine multiple columns together and parse to date (e.g., if date/time split across two columns). keep_date_col If joining columns to parse date, keep the joined columns; False by default. converters Dict containing column number of name mapping to functions (e.g., {'foo': f} would apply the function f to all values in the 'foo' column). dayfirst When parsing potentially ambiguous dates, treat as international format (e.g., 7/6/2012 -> June 7, 2012); False by default. date_parser Function to use to parse dates. nrows Number of rows to read from beginning of file. iterator Return a TextParser object for reading file piecemeal. chunksize For iteration, size of file chunks. skip_footer Number of lines to ignore at end of file. verbose Print various parser output information, like the number of missing values placed in non-numeric columns. encoding Text encoding for Unicode (e.g., 'utf-8' for UTF-8 encoded text). squeeze If the parsed data only contains one column, return a Series. thousands Separator for thousands (e.g., ',' or '.'). - Reading Text Files in Pieces When processing very large files, you may want to only read a small part of the file, or to iterate through chunks of the file. # We can change the pandas display setting when looking at large files >>> pd.options.display.max_rows = 10 # If we want to read only a small number of rows from the file, we can use 'nrows' >>> pd.read_csv('examples/ex6.csv', nrows=5) # To read a file in pieces, specify a 'chunksize' as a number of rows >>> chunker = pd.read_csv('examples/ex6.csv', chunksize=1000) >>> tot = pd.Series([]) >>> for piece in chunker: tot = tot.add(piece[key].value_counts(), fill_value=0) >>> tot = tot.sort_values(ascending=False) - Writing Data to Text Format # Read a csv file >>> data = pd.read_csv('examples/ex5.csv') >>> data # Write the DataFrame to a csv >>> data.to_csv('examples/out.csv') # Different outputs and separators can be used >>> data.to_csv(sys.stdout, sep='|') # The value that can be inserted for missing values is set with 'na_rep' >>> data.to_csv(sys.stdout, na_rep='NULL') # Both row and column labels are written by default, but both can be disabled >>> data.to_csv(sys.stdout, index=False, header=False) # Just a subset of columns can be written >>> data.to_csv(sys.stdout, index=False, columns=['a', 'b', 'c') # A Series object can also be written to csv >>> dates = pd.date_range('1/1/2000', periods=7) >>> ts = pd.Series(np.arange(7), index=dates) >>> ts.to_csv('examples/tseries.csv') >>> !cat examples/tseries.csv 2000-01-01,0 2000-01-02,1 2000-01-03,2 2000-01-04,3 2000-01-05,4 2000-01-06,5 2000-01-07,6 - Working With Delimited Formats Sometimes, a file will contain malformed lines that trip up the pandas data reader. In these cases, it's often easier to iterate through the file by hand using Python's built-in 'csv' module. # Simple example >>> import csv >>> f = open('examples/ex7.csv') >>> reader = csv.reader(f) >>> for line in reader: print(line) ['a', 'b', 'c'] ['1', '2', '3'] ['1', '2', '3'] # An example where more wrangling is required >>> with open('examples/ex7.csv') as f: lines = list(csv.reader(f)) >>> header, values = lines[0], lines[1:] >>> data_dict = {h: v for h, v in zip(header, zip(*values))} # To define a custom csv parsing format with a different delimeter, string-quoting # convention, and line terminator, we can define a subclass of 'csv.Dialect'. >>> class MyDialect(csv.Dialect): lineterminator = '\n' delimiter = ';' quotechar = '"' quoting = csv.QUOTE_MINIMAL >>> reader = csv.reader(f, dialect=MyDialect) # The 'csv.writer' can be used to write files, and can also use a dialect >>> with open('mydata.csv', 'w') as f: writer = csv.writer(f, dialect=my_dialect) writer.writerow(('one', 'two', 'three')) writer.writerow(('1', '2', '3')) writer.writerow(('4', '5', '6')) writer.writerow(('7', '8', '9')) - List of CSV Dialect Options Argument Description ------------------------------------------------------------------------------------ delimiter One-character string to separate fields; defaults to ','. lineterminator Line terminator for writing; defaults to '\r\n'. Reader ignores this and recognizes cross-platform line terminators. quotechar Quote character for fields with special characters (like a delimiter); default is '"'. quoting Quoting convention. Options include csv.QUOTE_ALL (quote all fields), csv.QUOTE_MINIMAL (only fields with special characters like the delimiter), csv.QUOTE_NONNUMERIC, and csv.QUOTE_NONE (no quoting). See Python’s documentation for full details. Defaults to QUOTE_MINIMAL. skipinitialspace Ignore whitespace after each delimiter; default is False. doublequote How to handle quoting character inside a field; if True, it is doubled (see online documentation for full detail and behavior). escapechar String to escape the delimiter if quoting is set to csv.QUOTE_NONE; disabled by default. - JSON Data # Create a JSON string >>> """ {"name": "Wes", "places_lived": ["United States", "Spain", "Germany"], "pet": null, "siblings": [{"name": "Scott", "age": 30, "pets": ["Zeus", "Zuko"]}, {"name": "Katie", "age": 38, "pets": ["Sixes", "Stache", "Cisco"]}] } """ # Load the JSON string into Python >>> import json >>> result = json.loads(obj) >>> result {'name': 'Wes', 'pet': None, 'places_lived': ['United States', 'Spain', 'Germany'], 'siblings': [{'age': 30, 'name': 'Scott', 'pets': ['Zeus', 'Zuko']}, {'age': 38, 'name': 'Katie', 'pets': ['Sixes', 'Stache', 'Cisco']}]} # 'json.dumps' converts a Python string back to JSON >>> asjson = json.dumps(result) # Series and DataFrame objects can automatically read JSON >>> !cat examples/example.json [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}, {"a": 7, "b": 8, "c": 9}] >>> data = pd.read_json('examples/example.json') >>> data a b c 0 1 2 3 1 4 5 6 2 7 8 9 # Series and DataFrame can export to JSON also >>> print(data.to_json()) {"a":{"0":1,"1":4,"2":7},"b":{"0":2,"1":5,"2":8},"c":{"0":3,"1":6,"2":9}} >>> print(data.to_json(orient='records')) [{"a":1,"b":2,"c":3},{"a":4,"b":5,"c":6},{"a":7,"b":8,"c":9}] - XML and HTML Scraping Python has many libraries for reading and writing data in XML and HTML. Popular ones include 'lxml' (fast) and 'Beautiful Soup' and 'html5lib' (better at handling malformed data). pandas does have a 'read_html' function, which uses either lxml or Beautiful Soup under the hood. # By default, 'read_html' searches for and tries to parse anything inside of # <table> tags >>> tables = pd.read_html('examples/fdic_failed_bank_list.html') >>> len(tables) 1 >>> failures = tables[0] >>> failures.head() Bank Name City ST CERT \ 0 Allied Bank Mulberry AR 91 1 The Woodbury Banking Company Woodbury GA 11297 2 First CornerStone Bank King of Prussia PA 35312 3 Trust Company Bank Memphis TN 9956 4 North Milwaukee State Bank Milwaukee WI 20364 Acquiring Institution Closing Date Updated Date 0 Today's Bank September 23, 2016 November 17, 2016 1 United Bank August 19, 2016 November 17, 2016 2 First-Citizens Bank & Trust Company May 6, 2016 September 6, 2016 3 The Bank of Fayette County April 29, 2016 September 6, 2016 4 First-Citizens Bank & Trust Company March 11, 2016 June 16, 2016 # Now, we'll compute the number of bank failures by year >>> close_timestamps = pd.to_datetime(failures['Closing Date']) >>> close_timestamps.dt.year.value_counts() 2010 157 2009 140 2011 92 2012 51 2008 25 ... 2004 4 2001 4 2007 3 2003 3 2000 2 Name: Closing Date, Length: 15, dtype: int64 - Parsing XML With LXML.Objectify # Here we use 'lxml.objectify' to parse an xml file and get a reference to the # root node >>> from lxml import objectify >>> path = 'datasets/mta_perf/Performance_MNR.xml' >>> parsed = objectify.parse(open(path)) >>> root = parsed.getroot() # Now, we can populate a dict of tag names to data values >>> data = [] >>> skip_fields = ['PARENT_SEQ', 'INDICATOR_SEQ', 'DESIRED_CHANGE', 'DECIMAL_PLACES'] # root.INDICATOR is a generator that returns each <INCICATOR> xml element >>> for elt in root.INDICATOR el_data = {} for child in elt.getchildren(): if child in skip_fields: continue el_data[child.tag] = child.pyval data.append(ed_data) # Then, we can convert the list of dicts into a DataFrame >>> perf = pd.DataFrame(data) # 'lxml.objectify' can also parse XML Metadata using the StringIO module >>> from io import StringIO >>> tag = '<a href="http://www.google.com">Google</a>' >>> root = objectify.parse(StringIO(tag)).getroot() >>> root.get('href') 'http://www.google.com' >>> root.text 'Google' - Binary Data Formats pandas objects have a 'to_pickle' method that can be used to serialize objects to disk. Note that pickle is recommended only as a short-term storage format. This is because it's not really possible to guarantee that pickle will be stable over time. # Pickle an object >>> frame = pd.read_csv('examples/ex1.csv') >>> frame.to_pickle('examples/frame_pickle') # Unpickle an object >>> frame = pd.read_pickle('examples/frame_pickle') Other binary formats that can be used to store pandas objects: 1. bcolz = compressable column-oriented binary format based on the Blosc compression library 2. Feather = cross-language column-oriented file format, uses Apache Arrow columnar memory format - HDF5 HDF5 ('Hierarchical Data Format') is a well-regarded file format intended for storing large quantities of scientific array data. It is available as a C library, and has interfaces for many other languages. Each HDF5 file can store multiple datasets and supporting metadata. It supports on-the-fly compression with a variety of compression modes. It is a good choice for working with very large datasets that don't fit into memory, since you can read and write small sections of much larger arrays. Since many data science problems are IO-bound (not CPU-bound), using something like HDF5 can massively accelerate your applications. Note that HDF5 is not a database. It is best suited for write-once, read-many datasets. Concurrent writes can corrupt a file. Python has the 'PyTables' and 'h5py' libraries for working with HDF5 files directly, and pandas provides a high-level interface that simplifies storing pandas objects. # The HDFStore class works like a dict >>> frame = pd.DataFrame({'a': np.random.randn(100)}) >>> store = pd.HDFStore('mydata.h5') # Add the entire DataFrame or just a column to the store >>> store['obj1'] = frame >>> store['obj1_col'] = frame['a'] # To retrive an object from the store >>> frame = store['obj1'] # The HDFStore supports 2 storage schemas, 'fixed' and 'table' # 'table' is slower, but it supports query operations >>> store.put('obj2', frame, format='table') >>> store.select('obj2', where=['index >= 10 and index <= 15']) a 10 1.007189 11 -1.296221 12 0.274992 13 0.228913 14 1.352917 15 0.886429 >>> store.close() # The pandas 'read_hdf' and 'to_hdr' functions give you shortcuts to these tools >>> frame.to_hdf('mydata.h5', 'obj3', format='table') >>> pd.read_hdf('mydata.h5', 'obj3', where=['index < 5']) - Reading Excel Files pandas supports reading from Excel files (2003+) using the 'ExcelFile' class or the built-in 'read_excel' function. These tools use the 'xlrd' and 'openpyxl' libraries under the hood. # Read an excel file >>> xlsx = pd.ExcelFile('examples/ex1.xslx') >>> df = pd.read_excel(xslx, 'Sheet1') # Write to an excel file >>> writer = pd.ExcelWriter('examples/ex2.xslx') >>> frame.to_excel(writer, 'Sheet1') >>> writer.save() # More concise write syntax >>> frame.to_excel('examples/ex2.xslx') - Interacting With Web APIs There are a number of ways to interact with web APIs from Python. One of the most common is the 'requests' package. # Get the last 30 issues for pandas on GitHub >>> import requests >>> url = 'https://api.github.com/repos/pandas-dev/pandas/issues' >>> resp = requests.get(url) >>> resp <Response [200]> # Get the json returned in the response >>> data = resp.json() >>> data[0]['title'] 'BUG: rank with +-inf, #6945' # Convert the json dictionary to a DataFrame >>> issues = pd.DataFrame(data, columns=['number', 'title', 'labels', 'state']) - Interacting With Databases # Create a sqlite db >>> import sqlite3 >>> query = """ .....: CREATE TABLE test .....: (a VARCHAR(20), b VARCHAR(20), .....: c REAL, d INTEGER .....: );""" >>> con = sqlite3.connect('mydata.sqlite') >>> con.execute(query) >>> con.commit() # Insert some data >>> data = [('Atlanta', 'Georgia', 1.25, 6), .....: ('Tallahassee', 'Florida', 2.6, 3), .....: ('Sacramento', 'California', 1.7, 5)] >>> stmt = "INSERT INTO test VALUES(?, ?, ?, ?)" >>> con.executemany(stmt, data) >>> con.commit() # Most Python SQL drivers return a list of tuples when selecting from a table >>> cursor = conn.execute('select * from test') >>> rows = cursor.fetchall() >>> rows [('Atlanta', 'Georgia', 1.25, 6), ('Tallahassee', 'Florida', 2.6, 3), ('Sacramento', 'California', 1.7, 5)] # The tuples in 'rows' can be passed to the DataFrame constructor, but you also # need the column names, which are contained in the cursor's 'description' # attribute. >>> pd.DataFrame(rows, columns=[x[0] for x in cursor.description]) - Using SQLAlchemy The 'SQLAlchemy' toolkit abstracts away many of the common differences between SQL databases, and using it with pandas can greatly simplify you database code. >>> import sqlalchemy as sqla >>> db = sqla.create_engine('sqlite:///mydata.sqlite') >>> pd.read_sql('select * from test', db)
import { createContext, useEffect, useState } from "react"; import axios from "axios"; import React from "react"; interface User { username: string; } interface UserInfo { username: string; password: string; } interface AuthContextType { user: User | null; login: (UserInfo: UserInfo) => void; logout: () => void; authUser: () => void; } export const AuthContext = createContext<AuthContextType>({ user: null, login: async () => {}, logout: async () => {}, authUser: async () => {}, }); export const AuthContextProvider = ({ children, }: { children: React.ReactNode; }) => { const [user, setUser] = useState<User | null>(null); const login = async (userInfo: UserInfo): Promise<void> => { await axios.post("http://localhost:8080/auth/login", userInfo, { withCredentials: true, }); authUser(); }; const logout = async () => { await axios.post("http://localhost:8080/auth/logout", null, { withCredentials: true, }); setUser(null); }; const authUser = async () => { try { const res = await axios.get("http://localhost:8080/user/getUsername", { withCredentials: true, }); const username: string = res.data; setUser({ username }); } catch (err) { console.log(err); } }; useEffect(() => { authUser(); }, []); return ( <AuthContext.Provider value={{ user, login, logout, authUser }}> {children} </AuthContext.Provider> ); };
import { useState, useEffect } from "react"; import { fetchProductById } from "../api/products"; import { addLineItem } from "../api/lineItems"; import { useNavigate, useParams } from "react-router-dom"; import useAuth from "./Auth/hooks/useAuth"; import "../components/components css/ProductItem.css"; export function ProductItem() { const [singleProduct, setSingleProduct] = useState(null); const [quantity, setQuantity] = useState(0); const { id } = useParams(); const { user } = useAuth(); const navigate = useNavigate(); useEffect(() => { async function getProduct() { const product = await fetchProductById(id); setSingleProduct(product.productById); } getProduct(); }, [id]); async function handleAddToCart() { try { // Set the singleProduct.id, a quantity to our endpoint await addLineItem(singleProduct.id); navigate(`/my-cart/${singleProduct.id}`); } catch (err) { console.error(err); } } return ( <div className="product-item-container"> {singleProduct && ( <> <div className="product-image-container"> {singleProduct.image && ( <img src={singleProduct.image} alt={singleProduct.name} /> )} </div> <div className="product-details"> <p>{singleProduct.name}</p> <p>{singleProduct.description}</p> <p>${singleProduct.price}</p> <button onClick={handleAddToCart}>Add to Cart</button> </div> </> )} </div> ); }
<?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; use App\Http\Controllers\UserController; use App\Http\Controllers\ContactController; use App\Http\Controllers\ProfileController; use App\Http\Controllers\Auth\LoginController; use App\Http\Controllers\Auth\RegisterController; use App\Http\Controllers\auth\VerificationController; use App\Http\Controllers\Auth\ResetPasswordController; use App\Http\Controllers\Auth\ForgotPasswordController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ // Route::get('/', 'index')->name('home'); // Route::get('/', [HomeController::class, 'index']); // Route::get('/', function () { // return redirect('/dashboard'); // })->middleware('auth'); // Route::get('/dashboard', function () { // return view('dashboard'); // })->name('dashboard')->middleware('auth'); Route::get('/contacts', [ContactController::class, 'index'])->name('contacts')->middleware('auth'); Route::post('/contacts/add', [ContactController::class, 'add'])->name('contact-add')->middleware('auth'); Route::get('/contacts-delete/{id}', [ContactController::class, 'destroy'])->name('contact-delete')->middleware('auth'); Route::get('/contacts-edit/{id}', [ContactController::class, 'edit'])->name('contact-edit')->middleware('auth'); Route::put('/contacts-update/{id}', [ContactController::class, 'update'])->name('contact-update')->middleware('auth'); Route::get('/wallet', function () { return view('wallet'); })->name('wallet')->middleware('auth'); Route::get('/RTL', function () { return view('RTL'); })->name('RTL')->middleware('auth'); Route::get('/profile', function () { return view('account-pages.profile'); })->name('profile')->middleware('auth'); Route::get('/signin', function () { return view('account-pages.signin'); })->name('signin'); Route::get('/signup', function () { return view('account-pages.signup'); })->name('signup')->middleware('guest'); Route::get('/sign-up', [RegisterController::class, 'create']) ->middleware('guest') ->name('sign-up'); Route::post('/sign-up', [RegisterController::class, 'store']) ->middleware('guest'); Route::get('/sign-in', [LoginController::class, 'create']) ->middleware('guest') ->name('sign-in'); Route::post('/sign-in', [LoginController::class, 'store']) ->middleware('guest'); Route::post('/logout', [LoginController::class, 'destroy']) ->middleware('auth') ->name('logout'); Route::get('/forgot-password', [ForgotPasswordController::class, 'create']) ->middleware('guest') ->name('password.request'); Route::post('/forgot-password', [ForgotPasswordController::class, 'store']) ->middleware('guest') ->name('password.email'); Route::get('/reset-password/{token}', [ResetPasswordController::class, 'create']) ->middleware('guest') ->name('password.reset'); Route::post('/reset-password', [ResetPasswordController::class, 'store']) ->middleware('guest'); Route::get('/management/user-profile', [ProfileController::class, 'index'])->name('users.profile')->middleware('auth'); Route::put('/management/user-profile/update', [ProfileController::class, 'update'])->name('users.update')->middleware('auth'); Route::get('/management/users-management', [UserController::class, 'index'])->name('users-management')->middleware('auth'); Route::post('/management/users-add', [UserController::class, 'add'])->name('users-add')->middleware('auth'); Route::get('/management/users-delete/{id}', [UserController::class, 'destroy'])->name('users-delete')->middleware('auth'); Route::get('/users-edit/{id}', [UserController::class, 'edit'])->name('users-edit')->middleware('auth'); Route::put('/users-edit/update/{id}', [UserController::class, 'update'])->name('users-update')->middleware('auth'); Route::get('/', function () { return view('index'); }); Route::get('/email/verify/{id}/{hash}', [VerificationController::class, 'verify'])->name('verification.verify'); Route::get('/check-email', [VerificationController::class, 'show'])->name('verification-notice'); Route::get('/dashboard', function () { if(Auth::user()->email_verified_at==null) return redirect('/email/verify'); return view('dashboard'); })->middleware(['auth', 'verified'])->name('dashboard'); Route::get('/email/verify', function () { return view('auth.verification-email'); })->name('verification.done');
/* * Copyright (C) 2022 Vaticle * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use std::{ collections::HashMap, sync::{Arc, RwLock}, time::Duration, }; use crossbeam::atomic::AtomicCell; use futures::{Stream, StreamExt, TryStreamExt}; use log::error; use prost::Message; use tokio::{ select, sync::{ mpsc::{error::SendError, unbounded_channel as unbounded_async, UnboundedReceiver, UnboundedSender}, oneshot::channel as oneshot_async, }, time::{sleep_until, Instant}, }; use tokio_stream::wrappers::UnboundedReceiverStream; use tonic::Streaming; use typedb_protocol::transaction::{self, server::Server, stream::State}; use super::response_sink::ResponseSink; use crate::{ common::{error::ConnectionError, RequestID, Result}, connection::{ message::{TransactionRequest, TransactionResponse}, network::proto::{IntoProto, TryFromProto}, runtime::BackgroundRuntime, }, }; pub(in crate::connection) struct TransactionTransmitter { request_sink: UnboundedSender<(TransactionRequest, Option<ResponseSink<TransactionResponse>>)>, is_open: Arc<AtomicCell<bool>>, shutdown_sink: UnboundedSender<()>, } impl Drop for TransactionTransmitter { fn drop(&mut self) { self.is_open.store(false); self.shutdown_sink.send(()).ok(); } } impl TransactionTransmitter { pub(in crate::connection) fn new( background_runtime: &BackgroundRuntime, request_sink: UnboundedSender<transaction::Client>, response_source: Streaming<transaction::Server>, ) -> Self { let (buffer_sink, buffer_source) = unbounded_async(); let (shutdown_sink, shutdown_source) = unbounded_async(); let is_open = Arc::new(AtomicCell::new(true)); background_runtime.spawn(Self::start_workers( buffer_sink.clone(), buffer_source, request_sink, response_source, is_open.clone(), shutdown_source, )); Self { request_sink: buffer_sink, is_open, shutdown_sink } } pub(in crate::connection) fn is_open(&self) -> bool { self.is_open.load() } pub(in crate::connection) async fn single(&self, req: TransactionRequest) -> Result<TransactionResponse> { if !self.is_open() { return Err(ConnectionError::SessionIsClosed().into()); } let (res_sink, recv) = oneshot_async(); self.request_sink.send((req, Some(ResponseSink::AsyncOneShot(res_sink))))?; recv.await?.map(Into::into) } pub(in crate::connection) fn stream( &self, req: TransactionRequest, ) -> Result<impl Stream<Item = Result<TransactionResponse>>> { if !self.is_open() { return Err(ConnectionError::SessionIsClosed().into()); } let (res_part_sink, recv) = unbounded_async(); self.request_sink.send((req, Some(ResponseSink::Streamed(res_part_sink))))?; Ok(UnboundedReceiverStream::new(recv).map_ok(Into::into)) } async fn start_workers( queue_sink: UnboundedSender<(TransactionRequest, Option<ResponseSink<TransactionResponse>>)>, queue_source: UnboundedReceiver<(TransactionRequest, Option<ResponseSink<TransactionResponse>>)>, request_sink: UnboundedSender<transaction::Client>, response_source: Streaming<transaction::Server>, is_open: Arc<AtomicCell<bool>>, shutdown_signal: UnboundedReceiver<()>, ) { let collector = ResponseCollector { request_sink: queue_sink, callbacks: Default::default(), is_open }; tokio::spawn(Self::dispatch_loop(queue_source, request_sink, collector.clone(), shutdown_signal)); tokio::spawn(Self::listen_loop(response_source, collector)); } async fn dispatch_loop( mut request_source: UnboundedReceiver<(TransactionRequest, Option<ResponseSink<TransactionResponse>>)>, request_sink: UnboundedSender<transaction::Client>, mut collector: ResponseCollector, mut shutdown_signal: UnboundedReceiver<()>, ) { const MAX_GRPC_MESSAGE_LEN: usize = 1_000_000; const DISPATCH_INTERVAL: Duration = Duration::from_millis(3); let mut request_buffer = TransactionRequestBuffer::default(); let mut next_dispatch = Instant::now() + DISPATCH_INTERVAL; loop { select! { biased; _ = shutdown_signal.recv() => { if !request_buffer.is_empty() { request_sink.send(request_buffer.take()).unwrap(); } break; } _ = sleep_until(next_dispatch) => { if !request_buffer.is_empty() { request_sink.send(request_buffer.take()).unwrap(); } next_dispatch = Instant::now() + DISPATCH_INTERVAL; } recv = request_source.recv() => { if let Some((request, callback)) = recv { let request = request.into_proto(); if let Some(callback) = callback { collector.register(request.req_id.clone().into(), callback); } if request_buffer.len() + request.encoded_len() > MAX_GRPC_MESSAGE_LEN { request_sink.send(request_buffer.take()).unwrap(); } request_buffer.push(request); } else { break; } } } } } async fn listen_loop(mut grpc_source: Streaming<transaction::Server>, collector: ResponseCollector) { loop { match grpc_source.next().await { Some(Ok(message)) => collector.collect(message).await, Some(Err(err)) => { break collector.close(ConnectionError::TransactionIsClosedWithErrors(err.to_string())).await } None => break collector.close(ConnectionError::TransactionIsClosed()).await, } } } } #[derive(Default)] struct TransactionRequestBuffer { reqs: Vec<transaction::Req>, len: usize, } impl TransactionRequestBuffer { fn is_empty(&self) -> bool { self.reqs.is_empty() } fn len(&self) -> usize { self.len } fn push(&mut self, request: transaction::Req) { self.len += request.encoded_len(); self.reqs.push(request); } fn take(&mut self) -> transaction::Client { self.len = 0; transaction::Client { reqs: std::mem::take(&mut self.reqs) } } } #[derive(Clone)] struct ResponseCollector { request_sink: UnboundedSender<(TransactionRequest, Option<ResponseSink<TransactionResponse>>)>, callbacks: Arc<RwLock<HashMap<RequestID, ResponseSink<TransactionResponse>>>>, is_open: Arc<AtomicCell<bool>>, } impl ResponseCollector { fn register(&mut self, request_id: RequestID, callback: ResponseSink<TransactionResponse>) { self.callbacks.write().unwrap().insert(request_id, callback); } async fn collect(&self, message: transaction::Server) { match message.server { Some(Server::Res(res)) => self.collect_res(res), Some(Server::ResPart(res_part)) => self.collect_res_part(res_part).await, None => error!("{}", ConnectionError::MissingResponseField("server")), } } fn collect_res(&self, res: transaction::Res) { if matches!(res.res, Some(transaction::res::Res::OpenRes(_))) { // Transaction::Open responses don't need to be collected. return; } let req_id = res.req_id.clone().into(); match self.callbacks.write().unwrap().remove(&req_id) { Some(sink) => sink.finish(TransactionResponse::try_from_proto(res)), _ => error!("{}", ConnectionError::UnknownRequestId(req_id)), } } async fn collect_res_part(&self, res_part: transaction::ResPart) { let request_id = res_part.req_id.clone().into(); match res_part.res { Some(transaction::res_part::Res::StreamResPart(stream_res_part)) => { match State::from_i32(stream_res_part.state).expect("enum out of range") { State::Done => { self.callbacks.write().unwrap().remove(&request_id); } State::Continue => { match self.request_sink.send((TransactionRequest::Stream { request_id }, None)) { Err(SendError((TransactionRequest::Stream { request_id }, None))) => { let callback = self.callbacks.write().unwrap().remove(&request_id).unwrap(); callback.error(ConnectionError::TransactionIsClosed()); } _ => (), } } } } Some(_) => match self.callbacks.read().unwrap().get(&request_id) { Some(sink) => sink.send(TransactionResponse::try_from_proto(res_part)), _ => error!("{}", ConnectionError::UnknownRequestId(request_id)), }, None => error!("{}", ConnectionError::MissingResponseField("res_part.res")), } } async fn close(self, error: ConnectionError) { self.is_open.store(false); let mut listeners = std::mem::take(&mut *self.callbacks.write().unwrap()); for (_, listener) in listeners.drain() { listener.error(error.clone()); } } }
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:iscapp/controllers/eventsProvider.dart'; import 'package:iscapp/models/eventClass.dart'; import 'package:iscapp/views/screens/events/eventsList.dart'; import 'package:iscapp/views/widgets/homeWidgets/topicGridWidget.dart'; import 'package:iscapp/views/widgets/homeWidgets/topicWidget.dart'; import 'package:iscapp/views/widgets/homeWidgets/mainEventWidget.dart'; import "package:iscapp/models/colorsClass.dart"; import 'package:provider/provider.dart'; class homeScreen extends StatefulWidget { const homeScreen({super.key}); @override State<homeScreen> createState() => _homeScreenState(); } class _homeScreenState extends State<homeScreen> with AutomaticKeepAliveClientMixin<homeScreen> { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); context.read<EventsProvider>().generateList(); Event mainEvent = context.read<EventsProvider>().mainEvent; return SingleChildScrollView( child: Padding( padding: EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width * 0.05, vertical: 20), child: Column( children: [ SizedBox( height: MediaQuery.of(context).size.width * 0.10, ), InkWell( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => EventListScreen())); }, child: mainEventWidget(mainEvent.title, mainEvent.date.toString(), mainEvent.time, mainEvent.image, context), ), SizedBox( height: 30.h, ), Align( alignment: Alignment.centerLeft, child: Text( "Topics", style: TextStyle( fontSize: 16.sp, fontWeight: FontWeight.bold, shadows: [ Shadow(color: myColors.primaryColor, offset: Offset(0, -10)) ], color: Colors.transparent, decoration: TextDecoration.underline, decorationColor: myColors.primaryColor, decorationThickness: 4, ), ), ), SizedBox( height: 30.h, ), topicGridWidget( [ topicWidget("assets/images/icons/labIcon.png", "Projects"), topicWidget("assets/images/icons/Workshhop.png", "Courses"), topicWidget("assets/images/icons/workshopidea.png", "Lab"), topicWidget("assets/images/icons/calender.png", "Events"), ], ) ], ), ), ); } }
package sy.jin.springrestdocsdsl import org.springframework.web.bind.annotation.* import org.springframework.web.multipart.MultipartFile @RestController @RequestMapping("/test") class TestController { @PostMapping("/{id}") fun test(@RequestBody req: TestDTO, @PathVariable id: Long, param1: String, param2: Int) { println("req = ${req}") println("id = ${id}") println("param1 = ${param1}") println("param2 = ${param2}") } @PostMapping("/form/{id}") fun formTest( @RequestPart("req", name = "req") req: TestDTO, @RequestPart("doc") doc: MultipartFile, @RequestPart("file") file: MultipartFile, @RequestParam("param") param: String, @PathVariable id: Long ) { println("req = ${req}") println("doc.name = ${doc.name}") println("file.name = ${file.name}") println("param1 = ${param}") println("id = ${id}") } data class TestDTO( val name: String, val email: String, val age: Int ) }
import datetime import os import requests from telethon.tl import types from telethon.tl.types import PeerUser from youtube_search import YoutubeSearch import yt_dlp import eyed3.id3 import eyed3 from telethon import Button, events from message import DOWNLOADING, UPLOADING, PROCESSING, ALREADY_IN_DB, NOT_IN_DB, SONG_NOT_FOUND from dbsessions import session, User, SongRequest from handlers import SPOTIFY, GENIUS from utils import DB_CHANNEL_ID, CLIENT, BOT_ID if not os.path.exists('covers'): os.makedirs('covers') class Song: def __init__(self, link): self.spotify = SPOTIFY.track(link) self.id = self.spotify['id'] self.spotify_link = self.spotify['external_urls']['handlers'] self.track_name = self.spotify['name'] self.artists_list = self.spotify['artists'] self.artist_name = self.artists_list[0]['name'] self.artists = self.spotify['artists'] self.track_number = self.spotify['track_number'] self.album = self.spotify['album'] self.album_id = self.album['id'] self.album_name = self.album['name'] self.release_date = int(self.spotify['album']['release_date'][:4]) self.duration = int(self.spotify['duration_ms']) self.duration_to_seconds = int(self.duration / 1000) self.album_cover = self.spotify['album']['images'][0]['url'] self.path = f'songs' self.file = f'{self.path}/{self.id}.mp3' self.uri = self.spotify['uri'] def features(self): if len(self.artists) > 1: features = "(Ft." for artistPlace in range(0, len(self.artists)): try: if artistPlace < len(self.artists) - 2: artistft = self.artists[artistPlace + 1]['name'] + ", " else: artistft = self.artists[artistPlace + 1]['name'] + ")" features += artistft except: pass else: features = "" return features def convert_time_duration(self): target_datetime_ms = self.duration base_datetime = datetime.datetime(1900, 1, 1) delta = datetime.timedelta(0, 0, 0, target_datetime_ms) return base_datetime + delta def download_song_cover(self): response = requests.get(self.album_cover) image_file_name = f'covers/{self.id}.png' image = open(image_file_name, "wb") image.write(response.content) image.close() return image_file_name def yt_link(self): results = list(YoutubeSearch(str(self.track_name + " " + self.artist_name)).to_dict()) time_duration = self.convert_time_duration() yt_url = None for yt in results: yt_time = yt["duration"] yt_time = datetime.datetime.strptime(yt_time, '%M:%S') difference = abs((yt_time - time_duration).total_seconds()) if difference <= 3: yt_url = yt['url_suffix'] break if yt_url is None: return None yt_link = str("https://www.youtube.com/" + yt_url) return yt_link def yt_download(self, yt_link=None): options = { # PERMANENT options 'format': 'bestaudio/best', 'keepvideo': True, 'outtmpl': f'{self.path}/{self.id}', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '320' }], } if yt_link is None: yt_link = self.yt_link() with yt_dlp.YoutubeDL(options) as mp3: mp3.download([yt_link]) def lyrics(self): try: return GENIUS.search_song(self.track_name, self.artist_name).lyrics except: return None def song_meta_data(self): mp3 = eyed3.load(self.file) mp3.tag.artist_name = self.artist_name mp3.tag.album_name = self.album_name mp3.tag.album_artist = self.artist_name mp3.tag.title = self.track_name + self.features() mp3.tag.track_num = self.track_number mp3.tag.year = self.track_number lyrics = self.lyrics() if lyrics is not None: mp3.tag.lyrics.set(lyrics) mp3.tag.images.set(3, open(self.download_song_cover(), 'rb').read(), 'image/png') mp3.tag.save() def download(self, yt_link=None): if os.path.exists(self.file): print(f'[SPOTIFY] Song Already Downloaded: {self.track_name} by {self.artist_name}') return self.file print(f'[YOUTUBE] Downloading {self.track_name} by {self.artist_name}...') self.yt_download(yt_link=yt_link) print(f'[SPOTIFY] Song Metadata: {self.track_name} by {self.artist_name}') self.song_meta_data() print(f'[SPOTIFY] Song Downloaded: {self.track_name} by {self.artist_name}') return self.file async def song_telethon_template(self): message = f''' 🎧 Название :`{self.track_name}` 🎤 Артист : `{self.artist_name}{self.features()}` 💿 Альбом : `{self.album_name}` 📅 Дата релиза : `{self.release_date}` [Скачать обложку]({self.album_cover}) [ID]({self.uri}) ''' buttons = [[Button.inline(f'📩 Скачать трек', data=f"download_song:{self.id}")], [Button.inline(f'🖼️ Скачать обложку', data=f"download_song_image:{self.id}")], [Button.inline(f'👀 Альбом', data=f"album:{self.album_id}")], [Button.inline(f'🧑‍🎨 Авторы альбома', data=f"track_artist:{self.id}")], [Button.inline(f'📃 Текст песни', data=f"track_lyrics:{self.id}")], [Button.url(f'🎵 Слушать в Spotify', self.spotify_link)], ] return message, self.album_cover, buttons async def artist_buttons_telethon_templates(self): message = f"{self.track_name} track Artist's" buttons = [[Button.inline(artist['name'], data=f"artist:{artist['id']}")] for artist in self.artists_list] return message, buttons def save_db(self, user_id: int, song_id_in_group: int): user = session.query(User).filter_by(telegram_id=user_id).first() if not user: user = User(telegram_id=user_id) session.add(user) session.commit() session.add(SongRequest( spotify_id=self.id, user_id=user.id, song_id_in_group=song_id_in_group, group_id=DB_CHANNEL_ID )) session.commit() @staticmethod async def progress_callback(processing, sent_bytes, total): percentage = sent_bytes / total * 100 await processing.edit(f"Uploading: {percentage:.2f}%") @staticmethod async def upload_on_telegram(event: events.CallbackQuery.Event, song_id): processing = await event.respond(PROCESSING) # first check if the song is already in the database song_db = session.query(SongRequest).filter_by(spotify_id=song_id).first() if song_db: db_message = await processing.edit(ALREADY_IN_DB) message_id = song_db.song_id_in_group else: # if not, create a new message in the database song = Song(song_id) db_message = await event.respond(NOT_IN_DB) # update processing message await processing.edit(DOWNLOADING) # see if the song is on yt yt_link = song.yt_link() if yt_link is None: print(f'[YOUTUBE] song not found: {song.uri}') await processing.delete() await event.respond(f"{song.track_name}\n{SONG_NOT_FOUND}") return file_path = song.download(yt_link=yt_link) await processing.edit(UPLOADING) upload_file = await CLIENT.upload_file(file_path) new_message = await CLIENT.send_file( DB_CHANNEL_ID, caption=BOT_ID, file=upload_file, supports_streaming=True, attributes=( types.DocumentAttributeAudio(title=song.track_name, duration=song.duration_to_seconds, performer=song.artist_name),), ) await processing.delete() song.save_db(event.sender_id, new_message.id) message_id = new_message.id # forward the message await CLIENT.forward_messages( entity=event.chat_id, # Destination chat ID messages=message_id, # Message ID to forward from_peer=PeerUser(int(DB_CHANNEL_ID)) # ID of the chat/channel where the message is from ) await db_message.delete()
THE FREEZE SCRIPT What is Freeze? --------------- Freeze make it possible to ship arbitrary Python programs to people who don't have Python. The shipped file (called a "frozen" version of your Python program) is an executable, so this only works if your platform is compatible with that on the receiving end (this is usually a matter of having the same major operating system revision and CPU type). The shipped file contains a Python interpreter and large portions of the Python run-time. Some measures have been taken to avoid linking unneeded modules, but the resulting binary is usually not small. The Python source code of your program (and of the library modules written in Python that it uses) is not included in the binary -- instead, the compiled byte-code (the instruction stream used internally by the interpreter) is incorporated. This gives some protection of your Python source code, though not much -- a disassembler for Python byte-code is available in the standard Python library. At least someone running "strings" on your binary won't see the source. How does Freeze know which modules to include? ---------------------------------------------- Freeze uses a pretty simple-minded algorithm to find the modules that your program uses: given a file containing Python source code, it scans for lines beginning with the word "import" or "from" (possibly preceded by whitespace) and then it knows where to find the module name(s) in those lines. It then recursively scans the source for those modules (if found, and not already processed) in the same way. Freeze will not see import statements hidden behind another statement, like this: if some_test: import M # M not seen or like this: import A; import B; import C # B and C not seen nor will it see import statements constructed using string operations and passed to 'exec', like this: exec "import %s" % "M" # M not seen On the other hand, Freeze will think you are importing a module even if the import statement it sees will never be executed, like this: if 0: import M # M is seen One tricky issue: Freeze assumes that the Python interpreter and environment you're using to run Freeze is the same one that would be used to run your program, which should also be the same whose sources and installed files you will learn about in the next section. In particular, your PYTHONPATH setting should be the same as for running your program locally. (Tip: if the program doesn't run when you type "python hello.py" there's little chance of getting the frozen version to run.) How do I use Freeze? -------------------- Normally, you should be able to use it as follows: python freeze.py hello.py where hello.py is your program and freeze.py is the main file of Freeze (in actuality, you'll probably specify an absolute pathname such as /usr/joe/python/Tools/freeze/freeze.py). (With Python 1.4, freeze is much more likely to work "out of the box" than before, provided Python has been installed properly.) What do I do next? ------------------ Freeze creates three files: frozen.c, config.c and Makefile. To produce the frozen version of your program, you can simply type "make". This should produce a binary file. If the filename argument to Freeze was "hello.py", the binary will be called "hello". Note: you can use the -o option to freeze to specify an alternative directory where these files are created. This makes it easier to clean up after you've shipped the frozen binary. Troubleshooting --------------- If you have trouble using Freeze for a large program, it's probably best to start playing with a really simple program first (like the file hello.py). If you can't get that to work there's something fundamentally wrong -- perhaps you haven't installed Python. To do a proper install, you should do "make install" in the Python root directory. --Guido van Rossum (home page: http://www.python.org/~guido/)
@functions { private string IsActive(string page) => Url.ActionContext.ActionDescriptor.DisplayName! == page ? "active" : ""; } <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Header - Домашняя Работа</title> <link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css"> <link rel="shortcut icon" href="~/favicon.png" type="image/x-icon"/> </head> <body> @*хедер*@ <header class="container-fluid"> <div class="row text-light align-items-center h-100-px"> <h1 class="ms-4">@ViewBag.Header</h1> </div> </header> <div class="container-fluid"> <div class="row"> @*навигационное меню*@ <div class="col-2 pt-4 ps-3 text-primary"> <nav class="d-grid gap-2"> <a asp-page="/Index" class="btn btn-lg btn-outline-primary text-start @IsActive("/Index")" title="Перейти на страницу"> Главная </a> <a asp-page="/Products" class="btn btn-lg btn-outline-primary text-start @IsActive("/Products")" title="Перейти на страницу"> Бытовая техника </a> <a asp-page="/Figures" class="btn btn-lg btn-outline-primary text-start @IsActive("/Figures")" title="Перейти на страницу"> Фигуры </a> </nav> @await RenderSectionAsync("Controls", false) </div> @*контент*@ <div class="col-10 p-5 pt-4"> <main> @RenderBody() </main> </div> </div> </div> @*футер*@ <footer class="container-fluid"> <div class="row align-items-center bg-light" style="height: 4rem"> <h6 class="text-center">&copy;2022, Масленников Виталий, г. Донецк, КА «ШАГ», ПД011.</h6> </div> </footer> @*<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>*@ </body> </html>
import React from 'react'; export default class FlavorForm extends React.Component { constructor(prop) { super(prop); this.state = { value: 'coconut' }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange({ target: { value } }) { this.setState({ value }); } handleSubmit(event) { alert('Flavor ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> Flavor: <label> <select value={this.state.value} onChange={this.handleChange}> <option value='coconut'>Coconut</option> <option value='grapefruit'>Grapefruit</option> <option value='lime'>Lime</option> <option value='mango'>Mango</option> </select> </label> <input type='submit' value='submit' /> </form> ); } }
#use wml::debian::ddp title="Manuais do DDP para usuários" #include "$(ENGLISHDIR)/doc/manuals.defs" #include "$(ENGLISHDIR)/doc/user-manuals.defs" #use wml::debian::translation-check translation="1.127" maintainer="Felipe Augusto van de Wiel (faw)" # To translator: If I'm right, only Cartão de Referência do Debian GNU/Linux # needs to be updated in order to be in sync with 1.137 -- Regards, taffit <document "FAQ do Debian GNU/Linux" "faq"> <div class="centerblock"> <p> Perguntas Feitas Freqüentemente por Usuários. <doctable> <authors "Susan G. Kleinmann, Sven Rudolph, Santiago Vila, Josip Rodin, Javier Fernández-Sanguino Peña"> <maintainer "Javier Fernández-Sanguino Peña"> <status> pronto </status> <availability> <inpackage "debian-faq"><br> <inddpsvn-debian-faq> </availability> </doctable> </div> <hr> <document "Guia de Instalação Debian" "install"> <div class="centerblock"> <p> Instruções de instalação para a distribuição Debian GNU/Linux. O manual descreve o processo de instalação usando o Debian Installer, o sistema de instalação para o Debian que foi lançado inicialmente com o <a href="$(HOME)/releases/sarge/">Sarge</A> (Debian GNU/Linux 3.1).<br> Informações adicionais sobre a instalação podem ser encontradas no <a href="https://wiki.debian.org/DebianInstaller/FAQ">FAQ do Instalador Debian</a> e nas <a href="https://wiki.debian.org/DebianInstaller">páginas wiki do Instalador Debian</a>. <doctable> <authors "Equipe do Debian Installer"> <maintainer "Equipe do Debian Installer"> <status> O manual ainda não está perfeito. Está sendo feito um trabalho ativo para a versão atual e futuras versões do Debian. Ajuda é bem-vinda, especialmente sobre a instalação e traduções não-x86. Contate <a href="mailto:[email protected]?subject=Install%20Manual">\ [email protected]</a> para mais informações. </status> <availability> <insrcpackage "installation-guide"> <br><br> <a href="$(HOME)/releases/stable/installmanual">Versão publicada para a distribuição estável</a> <br> Disponível nos <a href="$(HOME)/CD/">CDs e DVDs oficiais completos</a> no diretório <tt>/doc/manual/</tt>. <br><br> <a href="https://d-i.alioth.debian.org/manual/">Versão em desenvolvimento</a> <br> Cópia de trabalho disponível nos fontes SVN: <ul> <li>Checkout anônimo: <br> # TODO: We need a tag for SVN access (<insvn??>) <tt>svn co svn://anonscm.debian.org/svn/d-i/trunk/manual</tt> <li><a href="http://anonscm.debian.org/viewvc/d-i/trunk/manual/">Interface web</A> </ul> # <br> # <a href="$(HOME)/releases/testing/installmanual">Versão sendo preparada # para a próxima distribuição estável (atualmente, testing)</a> </availability> </doctable> <p> Versões do guia de instalação para distribuições anteriores (e possivelmente o próximo lançamento) do Debian estão listadas a partir da <a href="$(HOME)/releases/">página dos lançamentos</a> para estas versões. </div> <hr> <document "Notas de Lançamento Debian" "relnotes"> <div class="centerblock"> <p> Este documento contém informações sobre o que há de novo na distribuição atual do Debian GNU/Linux e informações completas sobre como atualizar para usuários de versões antigas do Debian. <doctable> <authors "Adam Di Carlo, Bob Hilliard, Josip Rodin, Anne Bezemer, Rob Bradford, Frans Pop, Andreas Barth, Javier Fernández-Sanguino Peña, Steve Langasek"> <status> Ativamente trabalhado para os lançamentos Debian. Contate <a href="mailto:[email protected]?subject=Release%20Notes">[email protected]</a> para mais informações. Problemas e patches devem ser relatados como <a href="https://bugs.debian.org/release-notes">bugs contra o pseudo-pacote release-notes</a>. </status> <availability> <a href="$(HOME)/releases/stable/releasenotes">Versão lançada</a> <br> Disponível nos <a href="$(HOME)/CD/">CDs e DVDs oficiais completos</a> no diretório <tt>/doc/release-notes/</tt>. # <br> # Also available at <a href="$(HOME)/mirror/list">ftp.debian.org and all mirrors</a> # in the <tt>/debian/doc/release-notes/</tt> directory. # <br> # <a href="$(HOME)/releases/testing/releasenotes">Versão sendo preparada # para a próxima distribuição estável (em teste)</a> <inddpsvn-release-notes> </availability> </doctable> </div> <hr> <document "Referência Debian" "quick-reference"> <div class="centerblock"> <p> Esta referência ao Debian GNU/Linux cobre muitos aspectos da administração do sistema através de exemplos em comandos do shell. Tutoriais básicos, dicas e outras informações são fornecidas para tópicos que incluem a instalação do sistema, o gerenciamento de pacotes Debian, o kernel Linux no Debian, configuração do sistema, construção de um gateway, editores de texto, CVS, programação e GnuPG. <p>Conhecido anteriormente como "Referência Rápida". <doctable> <authors "Osamu Aoki (&#38738;&#26408; &#20462;)"> <maintainer "Osamu Aoki (&#38738;&#26408; &#20462;)"> <status> Manual de usuário mais compreensivo do DDP até o momento. Aceitando críticas construtivas. </status> <availability> <inpackage "debian-reference"><br> <inddpsvn-debian-reference> </availability> </doctable> </div> <hr> <document "Cartão de Referência do Debian GNU/Linux" "refcard"> <div class="centerblock"> <p> A idéia deste cartão de referência é disponibilizar os comandos mais importantes do Debian GNU/Linux aos usuários novatos. Conhecimentos básicos (ou mais) de computadores, arquivos, diretórios e linha de comando são necessários. <doctable> <authors "W. Martin Borgert"> <maintainer "W. Martin Borgert"> <status> publicado; em desenvolvimento ativo </status> <availability> <inpackage "debian-refcard"><br> <inddpsvn-refcard> </availability> </doctable> </div> <hr> <document "FAQ do Debian GNU/Linux e Java" "java-faq"> <div class="centerblock"> <p> O propósito desse FAQ é ser um lugar para procurar por todo tipo de perguntas que um desenvolvedor ou usuário pode ter sobre o Java em relação ao Debian, ele inclui problemas de licenças, pacotes de desenvolvimento disponíveis e programas relacionados com a construção de um ambiente Java feito de Software Livre. <doctable> <authors "Javier Fernández-Sanguino Peña"> <status> Desenvolvimento parado, um novo mantenedor é necessário para o documento, e parte de seu conteúdo pode não estar atualizado. </status> <availability> <inpackage "java-common"><br> <inddpsvn-debian-java-faq> </availability> </doctable> </div> <hr> <document "Manual de Segurança Debian" "securing"> <div class="centerblock"> <p> Este manual descreve a segurança do sistema operacional Debian GNU/Linux e interna do projeto Debian. Ele começa com o processo de assegurar e fortalecer a instalação Debian GNU/Linux padrão (tanto manual quanto automaticamente), cobre algumas das tarefas envolvidas em configurar um usuário seguro e ambiente de rede, dá informações sobre as ferramentas de segurança disponíveis, passos a serem tomados antes e depois de um comprometimento e também descreve como a segurança é reforçada no Debian pela equipe de segurança. O documento inclui um guia de fortalecimento passo-a-passo e nos apêndices há informações detalhadas sobre como configurar um sistema de detecção de intrusões e uma bridge firewall com o Debian GNU/Linux. <doctable> <authors "Alexander Reelsen, Javier Fernández-Sanguino Peña"> <maintainer "Javier Fernández-Sanguino Peña"> <status> Publicado; em desenvolvimento com poucas mudanças. Parte do seu conteúdo pode não estar totalmente atualizado. </status> <availability> <inpackage "harden-doc"><br> <inddpsvn-securing-debian-howto> </availability> </doctable> </div>
--- title: "Encoding vs. Decoding" description: "Visualization techniques encode data into visual shapes and colors. We assume that what the user of a visualization does is decode those values, but things aren’t that simple." date: 2017-02-20 21:25:18 tags: attention featuredImage: https://media.eagereyes.org/wp-content/uploads/2017/02/vispipeline-teaser.png --- <p align="center"><img src="https://media.eagereyes.org/wp-content/uploads/2017/02/vispipeline-teaser.png" alt="" width="720" height="500" /></p> # Encoding vs. Decoding Visualization techniques encode data into visual shapes and colors. We assume that what the user of a visualization does is decode those values, but things aren’t that simple. ## Encoding When a program draws a bar chart, it calculates the length of the bars from the numbers it’s supposed to represent. When it draws a pie chart, it calculates angles. When it draws a scatterplot, it looks at two numbers for each data point and turns those into coordinates to draw a shape. We understand the encoding part very well. There’s nothing mysterious about how a chart comes about, it’s a mechanical process. This is also where we have much of the theory of visualization, such as it is. Bertin’s retinal variables, despite their name, are all about encoding. Likewise, Wilkinson’s Grammar of Graphics has a formalism for many different ways of encoding numbers. Data properties, like whether a data field or column is numerical vs. categorical, whether there’s a meaningful zero, etc., are all about encoding. This is the stuff that lives inside the machine, and that we can formalize very easily. ## Decoding When it comes to decoding, things get a lot messier. What do we decode? We like to assume that decoding just reverses the encoding: we read the values from the visualization. But not only don’t we do that, we do many other things that are surprisingly poorly understood. In a bar chart, we rarely look at individual bars. Instead, we compare them to each other. We also look at the shape of the plot. Which is why being able to sort a chart is incredibly important (charts are from <a href="/blog/2016/all-those-misleading-election-maps">this posting on problems with election maps</a>). <p align="center"><img class="aligncenter size-full wp-image-9772" src="https://media.eagereyes.org/wp-content/uploads/2016/11/states-alpha.png" alt="" width="596" height="363" /></p> <p align="center"><img class="aligncenter size-full wp-image-9773" src="https://media.eagereyes.org/wp-content/uploads/2016/11/states-sorted.png" alt="" width="596" height="363" /></p> In a pie chart, we presumably compare a slice to the whole. Except we also compare slices to each other, of course. And that thing about the angle? Well, we’re apparently <a href="/blog/2016/an-illustrated-tour-of-the-pie-chart-study-results">not actually reading it that way</a>. It gets even more interesting when we look at complex charts like scatterplots, parallel coordinates, etc. In a scatterplot, nobody compares two data points along two axes. Instead, we look at the overall shape. That gives us an idea of correlation (which we’re surprisingly good at estimating), clusters and density, and outliers. Those are much more interesting than merely looking at data values. ## The Value of Visualization If visualization were about decoding values from charts, things like aspect ratio would not matter; the number of bars between the two you’re comparing would not matter; the orientation of slices in a pie chart would not matter. If it were about decoding values, we would not be getting anywhere as much out of visualization as we do. We would not be getting correlation or clusters or outliers from a scatterplot. There would be little point in drawing pictures from data at all. What makes visualization powerful is our ability to go beyond the mere decoding of values from a chart. That makes it interesting, but it also makes it complicated. So far, we have focused our understanding largely on the encoding side of visualization. We need to learn much more about the complex and powerful decoding side. <PostedBy /> <aside class="comments"> --- ## Comments Bilal says… > Very good point, thank you Robert <a href="http://twitter.com/rybesh" rel="nofollow noopener" target="_blank">Ryan Shaw (@rybesh)</a> says… > One good way to start understanding the value of visualization better might be to choose a new metaphor: https://goo.gl/zhZKgh <a href="/about" rel="nofollow noopener" target="_blank">Robert Kosara</a> says… > Ryan, that link doesn't appear to be working. I'm just getting an Access Denied error. <a href="http://glasbrint.com" rel="nofollow noopener" target="_blank">Alex Cookson</a> says… > I had the same issue. Here's a working link: > > http://www.academia.edu/6290150/The_Conduit_Metaphor_A_Case_of_Frame_Conflict_in_Our_Language_about_Languag <a href="http://glasbrint.com" rel="nofollow noopener" target="_blank">Alex Cookson</a> says… > I'll also follow up with a link to the Wikipedia article. As a layman, I found the article difficult to follow. > > https://en.wikipedia.org/wiki/Conduit_metaphor <a href="http://www.culturerover.com" rel="nofollow noopener" target="_blank">Michael Kramer</a> says… > This brought to mind the famous essay by Stuart Hall, https://faculty.georgetown.edu/irvinem/theory/SH-Encoding-Decoding.pdf > https://en.wikipedia.org/wiki/Encoding/decoding_model_of_communication Stephen Hampshire says… > Excellent blog post, and an excellent article too. I particularly like "Human communication will almost always go astray unless real energy is expended" p. 295 </aside>
.. _amazon_s3: Amazon S3 This document covers configuration specific to the Amazon Web Services S3 (Simple Storage Service). See also the base S3 configuration in :ref:`s3_storages`. .. code-block:: none plugin { # Basic configuration (v2.3.10+): obox_fs = aws-s3:https://BUCKETNAME.s3.REGION.amazonaws.com/?auth_role=s3access&region=REGION&parameters # Basic configuration (old versions): #obox_fs = s3:https://ACCESSKEY:[email protected]/?region=REGION&parameters } +-------------------------+----------------------------------------------------+ | Parameter | Description | | See :ref:`s3_storages` for all S3 parameters. | +-------------------------+----------------------------------------------------+ IAM authentication ------------------ .. dovecotadded:: 2.3.10 Dovecot supports AWS Identity and Access Management (IAM) for authenticating requests to AWS S3 using the AWS EC2 Instance Metadata Service (IMDS), solely version 2 of IMDS (IMDSv2) is supported. Using IAM allows running Dovecot with S3 Storage while not keeping the credentials in the configuration. A requirement for using IMDSv2 is that Dovecot is running on an AWS EC2 instance, otherwise the IMDS will not be reachable. Additionally an IAM role must be configured which allows trusted entities, EC2 in this case, to assume that role. The role (for example ``s3access``) that will be assumed must have the ``AmazonS3FullAccess`` policy attached. The ``auth_role`` can be configured as a URL parameter which specifies the IAM role to be assumed. If no ``auth_role`` is configured, no IAM lookup will be done. .. code-block:: none plugin { obox_fs = aws-s3:https://bucket-name.s3.region.amazonaws.com/?auth_role=s3access&region=region } When using IAM you must ensure that the ``fs-auth`` service has proper permissions/owner. Configure the user for the fs-auth listener to be the same as for :dovecot_core:ref:`mail_uid`. .. code-block:: none mail_uid = vmail service fs-auth { unix_listener fs-auth { user = vmail } } For more information about IAM roles for EC2 please refer to: `IAM roles for Amazon EC2 <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_ For general information about IAM: `IAM UserGuide <https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html>`_ Manual authentication --------------------- Get ACCESSKEY and SECRET from `www.aws.amazon.com <https://aws.amazon.com/>`_ -> My account -> Security credentials -> Access credentials. Create the ``BUCKETNAME`` from AWS Management Console -> S3 -> Create Bucket. If the ``ACCESSKEY`` or ``SECRET`` contains any special characters, they can be %hex-encoded. .. Note:: ``dovecot.conf`` handles %variable expansion internally as well, so % needs to be escaped as %% and ':' needs to be escaped as %%3A. For example if the SECRET is "foo:bar" this would be encoded as ``https://ACCESSKEY:foo%%3Abar:s3.example.com/``. This double-%% escaping is needed only when the string is read from ``dovecot.conf`` - it doesn't apply for example if the string comes from a userdb lookup. Dispersion prefix ----------------- .. code-block:: none mail_location = obox:%8Mu/%u:INDEX=~/:CONTROL=~/ As also explained in :ref:`s3_storages`, AWS can internally shard data much more efficiently by including a dispersion prefix in all S3 paths. Without this the S3 bucket may not scale above a certain limit in the number of S3 requests/second. We recommend implementing the dispersion prefix by using the first 8 characters of the hex representation of the MD5 hash of the username at the beginning of each object path. When a S3 bucket is created, AWS creates a single shared partition for the bucket with a default limit of 3,500 requests/second for PUTs/DELETEs/POSTs and 5500 requests/second for GETs (see `Best Practices Design Patterns: Optimizing Amazon S3 Performance <https://docs.aws.amazon.com/AmazonS3/latest/dev/optimizing-performance.html>`_). This 3,500 TPS limit is generally too small and quickly surpassed by Dovecot which results in a spike of ``503: Slow Down`` log events. It is strongly recommended to contact AWS to request they manually set up at least 1 layer of hex partitioning (``0-9a-f``), to create 16 dedicated partitions for your bucket. This "1 hex" layer of partitioning means a theoretical capacity of 56,000 PUTs/DELETEs/POSTs and 88,000 GETs per second. Per AWS, you can go pretty deep in the number of layers, but most customers do not need more than 2 layers of partitioning, (2 layers = 16x16 = 256 partitions = this would theoretically provide you up to ~896,000 PUT/DELETE/POST TPS and 1,408,000 GET TPS if requests are distributed evenly across the partitions). DNS --- AWS instances are known to react badly when high packets per second network traffic is generated by e.g. DNS lookups. Please see :ref:`os_configuration_dns_lookups`. AWS Signature version --------------------- S3 driver uses the AWS signature version 2 method by default, but version 4 can be used by adding the region parameter to the S3 URL: .. code-block:: none plugin { obox_index_fs = https://ACCESSKEY:[email protected]/?region=eu-central-1 } aws-s3 scheme ------------- .. dovecotadded:: 2.3.10 Using the ``aws-s3`` scheme is a simpler way to configure the S3 driver for AWS. Currently it's the same as using the ``s3`` scheme with the following URL parameters (see :ref:`http_storages`): * ``addhdrvar=x-amz-security-token:%{auth:token}`` - Enable using security token if returned by IAM lookup. * ``loghdr=x-amz-request-id`` and ``loghdr=x-amz-id-2`` - Include the these headers' values in all log messages related to the request. This additional information helps when Troubleshooting Amazon S3 See https://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html Example debug log message, which shows how the x-amz-\* headers are included: .. code-block:: none Debug: http-client: conn 1.2.3.4:443 [1]: Got 200 response for request [Req1: GET https://test-mails.s3-service.com/?prefix=user%2Fidx%2F]: OK (x-amz-request-id:AABBCC22BB7798869, x-amz-id-2:DeadBeefanXBapRucWGAD1+aWwYMfwmXydlI0mHSuh4ic/j8Ji7gicTsP7xpMQz1IR9eydzeVI=) (took 63 ms + 140 ms in queue) Example configuration --------------------- With IAM: .. code-block:: none mail_location = obox:%8Mu/%u:INDEX=~/:CONTROL=~/ plugin { obox_fs = fscache:512M:/var/cache/mails/%4Nu:compress:zstd:3:aws-s3:https://bucket-name.s3.region.amazonaws.com/?region=region&auth_role=s3access obox_index_fs = compress:zstd:3:aws-s3:https://bucket-name.s3.region.amazonaws.com/?region=region&auth_role=s3access fts_dovecot_fs = fts-cache:fscache:512M:/var/cache/fts/%4Nu:compress:zstd:3:aws-s3:https://bucket-name.s3.region.amazonaws.com/%8Mu/%u/fts/?region=region&auth_role=s3access obox_max_parallel_deletes = 1000 } mail_uid = vmail service fs-auth { unix_listener fs-auth { user = vmail } } Without IAM: .. code-block:: none mail_location = obox:%8Mu/%u:INDEX=~/:CONTROL=~/ plugin { obox_fs = fscache:512M:/var/cache/mails/%4Nu:compress:zstd:3:aws-s3:https://ACCESSKEY:[email protected]/?region=region&auth_role=s3access obox_index_fs = compress:zstd:3:aws-s3:https://ACCESSKEY:[email protected]/?region=region&auth_role=s3access fts_dovecot_fs = fts-cache:fscache:512M:/var/cache/fts/%4Nu:compress:zstd:3:aws-s3:https://ACCESSKEY:[email protected]/%8Mu/%u/fts/?region=region&auth_role=s3access obox_max_parallel_deletes = 1000 }
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <head> <meta charset="ISO-8859-1"> <title>Lista De Tarefas</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> <style> a{ color: white; } a:hover { color: white; text-decoration: none; } </style> </head> <body> <div class="container"> <h1 class="p-3"> Lista de Tarefas: Itens</h1> <form:form> <table class="table table-bordered"> <tr> <th>Id</th> <th>Titulo</th> <th>Data</th> <th>Status</th> <th>Marcar Concluida</th> <th>Editar</th> <th>Deletar</th> </tr> <c:forEach var="todo" items="${list}"> <tr> <td>${todo.id}</td> <td>${todo.title}</td> <td>${todo.date}</td> <td>${todo.status}</td> <td> <button type="button" class="btn btn-success" onclick="window.location.href='/updateToDoStatus/${todo.id}'">Marcar Concluida</button> </td> <td> <button type="button" class="btn btn-primary" onclick="window.location.href='/editToDoItem/${todo.id}'">Editar</button> </td> <td> <button type="button" class="btn btn-danger" onclick="window.location.href='/deleteToDoItem/${todo.id}'">Deletar</button> </td> </tr> </c:forEach> </table> </form:form> <button type="button" class="btn btn-primary btn-block" onclick="window.location.href='/addToDoItem'"> Adicionar Novo Item </button> </div> <script th:inline="javascript"> window.onload = function() { var msg = "${message}"; if (msg == "Sucesso ao salvar") { Command: toastr["success"]("Item adicionado com sucesso!!") } else if (msg == "Sucesso ao deletar") { Command: toastr["success"]("Item deletado com sucesso!!") } else if (msg == "Erro ao deletar") { Command: toastr["error"]("Algum erro ocorreu, não foi possível deletar item.") } else if (msg == "Sucesso ao editar") { Command: toastr["success"]("Item atualizado com sucesso!!") } toastr.options = { "closeButton": true, "debug": false, "newestOnTop": false, "progressBar": true, "positionClass": "toast-top-right", "preventDuplicates": false, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" } } </script> </body> </html>
package com.qx.gulimall.ware.controller; import java.util.Arrays; import java.util.List; import java.util.Map; import com.qx.common.dto.StockVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.qx.gulimall.ware.entity.WareSkuEntity; import com.qx.gulimall.ware.service.WareSkuService; import com.qx.common.utils.PageUtils; import com.qx.common.utils.R; /** * 商品库存 * * @author qx * @email [email protected] * @date 2020-07-06 20:10:59 */ @RestController @RequestMapping("ware/waresku") public class WareSkuController { @Autowired private WareSkuService wareSkuService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("ware:waresku:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = wareSkuService.queryPage(params); return R.ok().put("page", page); } /** * 是否还有库存 */ @GetMapping("has-stoke/{skuId}") public R hasStock(@PathVariable Long skuId){ boolean flag = wareSkuService.hasStock(skuId); return R.ok().put("data",flag); } /** * 是否还有库存 */ @PostMapping("/has-stoke") public R hasStockBySkuIds(@RequestBody List<Long> skuIdList){ List<StockVo> stockVoList = wareSkuService.hasStockBySkuIds(skuIdList); R ok = R.ok(); R r = ok.setData(stockVoList); return r; } /** * 信息 */ @RequestMapping("/info/{id}") //@RequiresPermissions("ware:waresku:info") public R info(@PathVariable("id") Long id){ WareSkuEntity wareSku = wareSkuService.getById(id); return R.ok().put("wareSku", wareSku); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("ware:waresku:save") public R save(@RequestBody WareSkuEntity wareSku){ wareSkuService.save(wareSku); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("ware:waresku:update") public R update(@RequestBody WareSkuEntity wareSku){ wareSkuService.updateById(wareSku); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("ware:waresku:delete") public R delete(@RequestBody Long[] ids){ wareSkuService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
// @TODO: YOUR CODE HERE! var svgWidth = 960; var svgHeight = 700; var margin = { top: 20, right: 40, bottom: 60, left: 100 }; var width = svgWidth - margin.left - margin.right; var height = svgHeight - margin.top - margin.bottom; // Create an SVG wrapper, append an SVG group that will hold our chart, and shift the latter by left and top margins. var svg = d3.select("#scatter") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight); var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); d3.csv("assets/data/data.csv").then(function (state_data) { console.log(state_data); //Data state_data.forEach(function (data) { data.income = +data.income; data.obesity = +data.obesity; }); //Scale var xLinearScale = d3.scaleLinear() .domain([0, d3.max(state_data, d => d.income)]) .range([0, width]); var yLinearScale = d3.scaleLinear() .domain([0, d3.max(state_data, d => d.obesity)]) .range([height, 0]); //Axis var bottomAxis = d3.axisBottom(xLinearScale); var leftAxis = d3.axisLeft(yLinearScale); chartGroup.append("g") .attr("transform", `translate(0, ${height})`) .call(bottomAxis); chartGroup.append("g") .call(leftAxis); //Marks var circlesGroup = chartGroup.selectAll("circle") .data(state_data) .enter() .append("circle") .attr("cx", d => xLinearScale(d.income)) .attr("cy", d => yLinearScale(d.obesity)) .attr("r", "12") .attr("fill", "purple") .attr("opacity", ".7"); //Popup var toolTip = d3.tip() .attr("class", "tooltip") .offset([80, -60]) .html(function (d) { return (`${d.state}<br>Income: ${d.income}<br>Obesity: ${d.obesity}`); }); chartGroup.call(toolTip); circlesGroup.on("click", function (data) { toolTip.show(data, this); }) .on("mouseout", function (data, index) { toolTip.hide(data); }); //Labels chartGroup.append("text") .attr("transform", "rotate(-90)") .attr("y", 0 - margin.left + 40) .attr("x", 0 - (height / 2)) .attr("dy", "1em") .attr("class", "axisText") .style("fill", "black") .style("font-weight", "bold") .text("Obeisty(%)"); chartGroup.append("text") .attr("transform", `translate(${width / 2}, ${height + margin.top + 30})`) .attr("class", "axisText") .style("font-weight", "bold") .text("Income"); }).catch(function (error) { console.log(error); });
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ // // Please run in othervm mode. SunJSSE does not support dynamic system // properties, no way to re-use system properties in samevm/agentvm mode. // /* * @test * @bug 8148421 8193683 * @summary Transport Layer Security (TLS) Session Hash and Extended * Master Secret Extension * @summary Increase the number of clones in the CloneableDigest * @library /javax/net/ssl/templates * @compile DigestBase.java * @run main/othervm HandshakeHashCloneExhaustion * TLSv1.2 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * @run main/othervm HandshakeHashCloneExhaustion * TLSv1.1 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA */ import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.Security; import javax.net.ssl.SSLSocket; public class HandshakeHashCloneExhaustion extends SSLSocketTemplate { private static String[] protocol; private static String[] ciphersuite; private static String[] mds = { "SHA", "MD5", "SHA-256" }; /* * Run the test case. */ public static void main(String[] args) throws Exception { // Add in a non-cloneable MD5/SHA1/SHA-256 implementation Security.insertProviderAt(new MyProvider(), 1); // make sure our provider is functioning for (String s : mds) { MessageDigest md = MessageDigest.getInstance(s); String p = md.getProvider().getName(); if (!p.equals("MyProvider")) { throw new RuntimeException("Unexpected provider: " + p); } } if (args.length != 2) { throw new Exception( "Usage: HandshakeHashCloneExhaustion protocol ciphersuite"); } System.out.println("Testing: " + args[0] + " " + args[1]); protocol = new String [] { args[0] }; ciphersuite = new String[] { args[1] }; (new HandshakeHashCloneExhaustion()).run(); } @Override protected void runServerApplication(SSLSocket socket) throws Exception { socket.setNeedClientAuth(true); socket.setEnabledProtocols(protocol); socket.setEnabledCipherSuites(ciphersuite); // here comes the test logic InputStream sslIS = socket.getInputStream(); OutputStream sslOS = socket.getOutputStream(); sslIS.read(); sslOS.write(85); sslOS.flush(); } @Override protected void runClientApplication(SSLSocket socket) throws Exception { InputStream sslIS = socket.getInputStream(); OutputStream sslOS = socket.getOutputStream(); sslOS.write(280); sslOS.flush(); sslIS.read(); } }
import os import tensorflow as tf import tensorflow_addons as tfa from tensorflow.keras import layers, Model os.environ['CPP_TF_MIN_LOG_LEVEL'] = '2' print(tf.__version__) class MLP(layers.Layer): def __init__(self, name, hidden_features, out_features, drop_rate=0): super(MLP, self).__init__() self.fc1 = layers.Dense(hidden_features, name=f'{name}_MLP_DENSE1') self.act = tfa.layers.GELU() self.fc2 = layers.Dense(out_features, name=f'{name}_MLP_DENSE2') self.drop = layers.Dropout(drop_rate, name=f'{name}_MLP_DROP') def call(self, inputs, training=None): x = self.fc1(inputs) x = self.act(x) x = self.fc2(x) if training: x = self.drop(x) return x class Attention(layers.Layer): def __init__(self, name, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., sr_ratio=1): super(Attention, self).__init__() assert dim % num_heads == 0, f"dim {dim} should be divided by num_heads {num_heads}." self.dim = dim self.num_heads = num_heads self.head_dim = dim // num_heads # dimension for each head self.scale = qk_scale or self.head_dim ** -.5 self.q = layers.Dense(dim, use_bias=qkv_bias, name=f'{name}_Q') self.kv = layers.Dense(2 * dim, use_bias=qkv_bias, name=f'{name}_KV') self.attention_drop = layers.Dropout(attn_drop, name=f'{name}_ATTEN_DROP') self.proj = layers.Dense(dim, name=f'{name}_PROJ_DENSE') self.proj_drop = layers.Dropout(proj_drop, name=f'{name}_PROJ_DROP') self.sr_ratio = sr_ratio if sr_ratio > 1: self.sr = layers.Conv2D(dim, kernel_size=sr_ratio, strides=sr_ratio, name=f'{name}_SR_CONV2D') self.norm = layers.LayerNormalization() def call(self, inputs, H, W): # (b, 196, 768) -> (b, 196, num_heads, head_dim) q = layers.Reshape((-1, self.num_heads, self.head_dim))(self.q(inputs)) # (b, 196, num_heads, head_dim)-> (b, num_heads, 196, head_dim) q = tf.transpose(q, [0, 2, 1, 3]) if self.sr_ratio > 1: # (b, 196, 768) -> (b, 14, 14, 768) x_ = tf.reshape(inputs, [-1, H, W, self.dim]) # (b, 14, 14, 768) -> (b, 7, 7, 768) x_ = self.sr(x_) # (b, 7, 7, 768) -> (b, 49, 768) x_ = tf.reshape(x_, [-1, H//self.sr_ratio * W//self.sr_ratio, self.dim]) # (b, 49, 768) x_ = self.norm(x_) # (b, 49, 768) -> # (b, 49, 768 *2) kv = self.kv(x_) # (b, 49, 768 *2) -> (b, 49, 2, num_heads, head_dim) kv = tf.reshape(kv, [-1, H//self.sr_ratio * W//self.sr_ratio, 2, self.num_heads, self.head_dim]) # (b, 49, 2, num_heads, head_dim) -> (2, b, num_heads, 49, head_dim) kv = tf.transpose(kv, [2, 0, 3, 1, 4]) else: # (b, 196, 768) -> # (b, 49, 768 *2) kv = self.kv(inputs) # (b, 196, 768 *2) -> (b, 196, 2, num_heads, head_dim) kv = layers.Reshape((-1, 2, self.num_heads, self.head_dim))(kv) # (b, 49, 2, num_heads, head_dim) -> (2, b, num_heads, 49, head_dim) kv = tf.transpose(kv, [2, 0, 3, 1, 4]) k, v = kv[0], kv[1] # calc attention # (b, num_heads, 196, 96) * (b, num_heads, 96, 196) -> (b, num_heads, 196, 196) attention = tf.matmul(q, tf.transpose(k, [0,1,3,2])) * self.scale # (b, num_heads, 196, 196) attention = tf.nn.softmax(attention, axis=-1) attention = self.attention_drop(attention) # (b, num_heads, 196, 196) * # (b, num_heads, 196, 96) -> (b, num_heads, 196, 96) x = tf.matmul(attention, v) # (b, num_heads, 196, 96) -> (b, 196, num_heads, 96) x = tf.transpose(x, [0, 2, 1, 3]) # (b, 196, num_heads, 96) -> (b, 196, num_heads * 96) x = layers.Reshape((-1, self.num_heads * self.head_dim))(x) # (b, N, C) -> (b, N, proj_dim) x = self.proj(x) x = self.proj_drop(x) return x class Block(layers.Layer): def __init__(self, name, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., proj_drop=0., sr_ratio=1): super(Block, self).__init__() self.norm1 = layers.LayerNormalization() self.attention = Attention(name, dim, num_heads, qkv_bias, qk_scale, attn_drop, proj_drop, sr_ratio) self.norm2 = layers.LayerNormalization() self.mlp = MLP(name, hidden_features=int(dim * mlp_ratio), out_features=dim, drop_rate=drop) def call(self, inputs, H, W): x = self.norm1(inputs) x = self.attention(x, H, W) x = inputs + x y = self.norm2(x) y = self.mlp(y) return x + y class PatchEmbedding(layers.Layer): def __init__(self, name, img_size=224, patch_size=16, embedding_dim=768): super(PatchEmbedding, self).__init__() self.img_size = img_size self.patch_size = patch_size self.embedding_dim = embedding_dim assert img_size % patch_size == 0, f"img_size {img_size} should be divided by patch_size {patch_size}." self.H, self.W = img_size // patch_size, img_size // patch_size self.num_patches = self.H * self.W self.project = layers.Conv2D(embedding_dim, kernel_size=patch_size, strides=patch_size, name=f'{name}_PATCH_CONV2D') self.norm = layers.LayerNormalization() def call(self, inputs): # (b, 224, 224, 3) -> (b, 14, 14, 768) x = self.project(inputs) # (b, 14, 14, 768) -> (b, 196, 768) x = tf.reshape(x, [-1, self.num_patches, self.embedding_dim]) # (b, 196, 768) x = self.norm(x) return x, (self.H, self.W) class PyramidVisionTransformer(Model): def __init__(self, img_size=224, patch_size=4, batch_size=64, num_classes=1000, embed_dims=[64, 128, 256, 512], num_heads=[1, 2, 4, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=False, qk_scale=None, drop_rate=0., attn_drop_rate=0., depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1]): """ initialize function for PVC :param img_size: image size default value 224 :param patch_size: patch size default value 4 :param num_classes: number of classes default value 1000 :param embed_dims: embedding dimension from stage 1 to 4 :param num_heads: number of attention heads from stage 1 to 4 :param mlp_ratios: MLP layer hidden layer ratio from stage 1 to 4 :param qkv_bias: qkv using bias or not :param qk_scale: qkv scale or not :param drop_rate: drop rate for MLP layer :param attn_drop_rate: attention drop rate :param depths: number of attention modules from stage 1 to 4 :param sr_ratios: spatial reduction attention ratios from stage 1 to 4 """ super(PyramidVisionTransformer, self).__init__() self.num_classes = num_classes self.depths = depths self.batch_size = batch_size self.embed_dims = embed_dims # patch_embed self.patch_embed1 = PatchEmbedding(name='patch_embed1', img_size=img_size, patch_size=patch_size, embedding_dim=embed_dims[0]) self.patch_embed2 = PatchEmbedding(name='patch_embed2', img_size=img_size // 4, patch_size=2, embedding_dim=embed_dims[1]) self.patch_embed3 = PatchEmbedding(name='patch_embed3', img_size=img_size // 8, patch_size=2, embedding_dim=embed_dims[2]) self.patch_embed4 = PatchEmbedding(name='patch_embed4', img_size=img_size // 16, patch_size=2, embedding_dim=embed_dims[3]) # position embedding self.weight_initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=.02) self.pos_embed1 = None self.pos_embed2 = None self.pos_embed3 = None self.pos_embed4 = None self.pos_drop1 = layers.Dropout(drop_rate) self.pos_drop2 = layers.Dropout(drop_rate) self.pos_drop3 = layers.Dropout(drop_rate) self.pos_drop4 = layers.Dropout(drop_rate) # Blocks self.block1 = [Block(name=f'BLOCK1_{i}', dim=embed_dims[0], num_heads=num_heads[0], mlp_ratio=mlp_ratios[0], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, sr_ratio=sr_ratios[0]) for i in range(depths[0])] self.block2 = [Block(name=f'BLOCK2_{i}', dim=embed_dims[1], num_heads=num_heads[1], mlp_ratio=mlp_ratios[1], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, sr_ratio=sr_ratios[1]) for i in range(depths[1])] self.block3 = [Block(name=f'BLOCK3_{i}', dim=embed_dims[2], num_heads=num_heads[2], mlp_ratio=mlp_ratios[2], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, sr_ratio=sr_ratios[2]) for i in range(depths[2])] self.block4 = [Block(name=f'BLOCK4_{i}', dim=embed_dims[3], num_heads=num_heads[3], mlp_ratio=mlp_ratios[3], qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, sr_ratio=sr_ratios[3]) for i in range(depths[3])] self.norm = layers.LayerNormalization() # class token self.cls_token = None # dense layer for prediction self.dense = layers.Dense(num_classes, name='CLASSIFICATION_DENSE') def get_config(self): config = { 'weight_initializer' : self.weight_initializer } base_config = super(PyramidVisionTransformer, self).get_config() return dict(list(base_config.items()) + list(config.items())) def build(self, input_shape): self.pos_embed1 = self.add_weight(shape=[1, self.patch_embed1.num_patches, self.embed_dims[0]], initializer=self.weight_initializer, name='pos_embed1') self.pos_embed2 = self.add_weight(shape=[1, self.patch_embed2.num_patches, self.embed_dims[1]], initializer=self.weight_initializer, name='pos_embed2') self.pos_embed3 = self.add_weight(shape=[1, self.patch_embed3.num_patches, self.embed_dims[2]], initializer=self.weight_initializer, name='pos_embed3') self.pos_embed4 = self.add_weight(shape=[1, self.patch_embed4.num_patches + 1, self.embed_dims[3]], initializer=self.weight_initializer, name='pos_embed4') self.cls_token = self.add_weight(shape=[1, 1, self.embed_dims[3]], initializer=self.weight_initializer, name='cls_token') super(PyramidVisionTransformer, self).build(input_shape) def call(self, inputs): # stage 1, patch image (b, 224, 224, 3) -> (b, 56, 56, 64) -> (b, 3136, 64) x, (H, W) = self.patch_embed1(inputs) # adding position embedding x = x + self.pos_embed1 # dropout x = self.pos_drop1(x) # transformer encoder for blk in self.block1: x = blk(x, H, W) # (b, 3136, 64) # (b, 3136, 64) -> (b, 56, 56, 64) x = tf.reshape(x, [-1, H, W, self.embed_dims[0]]) # stage 2 patch image (b, 56, 56, 64) -> (b, 28, 28, 64) -> (b, 784, 128) x, (H, W) = self.patch_embed2(x) # adding position embedding x = x + self.pos_embed2 # dropout x = self.pos_drop2(x) # transformer encoder for blk in self.block2: x = blk(x, H, W) # (b, 784, 128) # (b, 784, 128) -> (b, 28, 28, 128) x = tf.reshape(x, [-1, H, W, self.embed_dims[1]]) # stage 3 patch image (b, 28, 28, 128) -> (b, 14, 14, 256) -> (b, 196, 256) x, (H, W) = self.patch_embed3(x) # adding position embedding x = x + self.pos_embed3 # dropout x = self.pos_drop3(x) # transformer encoder for blk in self.block3: x = blk(x, H, W) # (b, 196, 256) # (b, 196, 256) -> (b, 14, 14, 256) x = tf.reshape(x, [-1, H, W, self.embed_dims[2]]) # stage 4 patch image (b, 14, 14, 256) -> (b, 7, 7, 512) -> (b, 49, 512) x, (H, W) = self.patch_embed4(x) # concat with cls token (b, 49, 512) -> (b, 50, 512) cls_token = tf.broadcast_to(self.cls_token, [self.batch_size, 1, self.embed_dims[3]]) x = layers.concatenate([cls_token, x], axis=1) # adding position embedding x = x + self.pos_embed4 # dropout x = self.pos_drop4(x) # transformer encoder for blk in self.block4: x = blk(x, H, W) # (b, 50, 512) # layer normalization x = self.norm(x) # extract cls token cls_token = x[:, 0] # dense layer to make prediction predictions = self.dense(cls_token) return predictions def pvt_tiny(**kwargs): return PyramidVisionTransformer(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], **kwargs) def pvt_small(**kwargs): return PyramidVisionTransformer(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, depths=[3, 4, 6, 3], sr_ratios=[8, 4, 2, 1], **kwargs) def pvt_medium(**kwargs): return PyramidVisionTransformer(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, depths=[3, 4, 18, 3], sr_ratios=[8, 4, 2, 1], **kwargs) def pvt_large(**kwargs): return PyramidVisionTransformer(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, depths=[3, 8, 27, 3], sr_ratios=[8, 4, 2, 1], **kwargs) def pvt_huge_v2(**kwargs): return PyramidVisionTransformer(patch_size=4, embed_dims=[128, 256, 512, 768], num_heads=[2, 4, 8, 12], mlp_ratios=[8, 8, 4, 4], qkv_bias=True, depths=[3, 10, 60, 3], sr_ratios=[8, 4, 2, 1], **kwargs) if __name__ == '__main__': inputs = tf.random.normal([4, 32, 32, 3]) pvt = pvt_tiny(batch_size=4, img_size=32, num_classes=10) outputs = pvt(inputs) print(outputs.shape)
# Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers The developers at Mystique Unicorn [process files as soon as they arrive][5]. They want to switch to an event-driven architecture. They were looking for a custom trigger, whether it be payload-based or time-based, to process files efficiently. They heard about Azure's capabilities for event processing. Can you help them implement this event processing at Mystique Unicorn? ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_001.png) ## 🎯 Solution Our solution enables seamless event processing on Azure Blob Storage through the use of Azure Functions and [HTTP triggers][1]. With a simple HTTP payload containing the `blob_name`, the function can retrieve the corresponding blob using an [input binding][2] and process it accordingly. Our solution also includes an [output binding][3] to persist the processed event back to Blob Storage. By leveraging the power of Bicep, all necessary resources can be easily provisioned and managed with minimal effort. Our solution uses Python for efficient event processing, allowing for quick and easy deployment of sophisticated event processing pipelines. 1. ## 🧰 Prerequisites This demo, instructions, scripts and bicep template is designed to be run in `westeurope`. With few or no modifications you can try it out in other regions as well(_Not covered here_). - 🛠 Azure CLI Installed & Configured - [Get help here](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) - 🛠 Bicep Installed & Configured - [Get help here](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install) - 🛠 VS Code & Bicep Extenstions - [Get help here](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install#vs-code-and-bicep-extension) 1. ## ⚙️ Setting up the environment - Get the application code ```bash https://github.com/miztiik/azure-blob-input-binding-to-function cd azure-blob-input-binding-to-function ``` 1. ## 🚀 Prepare the environment Let check you have Azure Cli working with ```bash # You should have azure cli preinstalled az account show ``` You should see an output like this, ```json { "environmentName": "AzureCloud", "homeTenantId": "16b30820b6d3", "id": "1ac6fdbff37cd9e3", "isDefault": true, "managedByTenants": [], "name": "YOUR-SUBS-NAME", "state": "Enabled", "tenantId": "16b30820b6d3", "user": { "name": "miztiik@", "type": "user" } } ``` 1. ## 🚀 Deploying the application - **Stack: Main Bicep** This will create the following resoureces - General purpose Storage Account with blob container - This will be used by Azure functions to store the function code - Storage Account with blob container - - This will be used to store the events - Python Azure Function - Input, Trigger, Output Binding to the blob container for events ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_002.png) ```bash # make deploy sh deployment_scripts/deploy.sh ``` After successfully deploying the stack, Check the `Resource Groups/Deployments` section for the resources. 1. ## 🔬 Testing the solution - **Upload file(s) to blob** Get the storage account and container name from the output of the deployment. Upload a file to the container and check the logs of the function app to see the event processing in action. Sample bash script to upload files to blob container. You can also upload manually from the portal, ```bash FILE_NAME_PREFIX=$(openssl rand -hex 4) FILE_NAME="${RANDOM}_$(date +'%Y-%m-%d')_event.json" SA_NAME="warehouseg2hpj3003" CONTAINER_NAME="store-events-blob-003" echo -n "{\"message\": \"hello world on $(date +'%Y-%m-%d')\"}" > ${FILE_NAME} az storage blob upload \ --account-name ${SA_NAME} \ --container-name ${CONTAINER_NAME} \ --name ${FILE_NAME} \ --file ${FILE_NAME} \ --auth-mode login ``` Trigger the function with the following payload. You can also trigger the function from the portal, ```json { "blob_name": "29050_2023-05-05_event" } ``` ```bash # Create JSON file echo -n "{\"name\": $RANDOM, \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\"}" > "${BLOB_NAME}" # Upload file to Azure Blob container az storage blob upload --account-name "${STORAGE_ACCOUNT}" \ --container-name "${CONTAINER}" \ --name "${BLOB_NAME}" \ --file "${BLOB_NAME}" \ --auth-mode login ``` ```bash JSON_DATA='{"blob_name":"29050_2023-05-05_event"}' URL="https://store-backend-fnapp-003.azurewebsites.net/api/store-events-consumer-fn-003" curl -X POST \ -H "Content-Type: application/json" \ -d "${JSON_DATA}" \ "${URL}" ``` You should see an output like this, >Blob 29050_2023-05-05_event.json processed ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_002_1.png) 1. ## 🔬 Observations This solution has also bootstrapped the function with applicaiton insights. This gives us a lot of insights on how the input/output bindings works. For example, when we look at the application map, we can see the calls made to the blob storage and also the percentage of success/failure. If we drill down the errors we can see the error code and the error message. ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_005.png) ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_006.png) ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_007.png) We can observe that the output binding triggers a `HEAD` call to the storage account to check if the blob exists. It results in error `404` as the blob does not exist, it will create a new blob with the processed data. ```bash 2023-05-04T19:12:38.0139679Z HEAD https://warehouseg2hpj3003.blob.core.windows.net/store-events-blob-003/processed/2023-05-04T19-12-37Z_e1c41b31-1867-4005-9041-4f031a8ba2b1_42ec4195_bulk.json 2023-05-04T19:12:38.0417501Z HEAD https://warehouseg2hpj3003.blob.core.windows.net/store-events-blob-003/processed/2023-05-04T19-12-37Z_e1c41b31-1867-4005-9041-4f031a8ba2b1_42ec4195_bulk.json 2023-05-04T19:12:38.0616047Z PUT https://warehouseg2hpj3003.blob.core.windows.net/store-events-blob-003/processed/2023-05-04T19-12-37Z_e1c41b31-1867-4005-9041-4f031a8ba2b1_42ec4195_bulk.json ``` ![Miztiik Automation - Azure Blob Storage Processing with Python Azure Functions with HTTP Triggers](images/miztiik_architecture_azure_blob_storage_processing_in_functions_http_trigger_004.png) _Ofcourse the screenshots and the data will be different, as they were taken during different file upload process_ 1. ## 📒 Conclusion Here we have demonstrated trigger Azure functions with http trigger and process blob files. You can extend the solution and configure the function to send the events to other services like Event Hub, Service Bus, or persist them to Cosmos etc. 1. ## 🧹 CleanUp If you want to destroy all the resources created by the stack, Execute the below command to delete the stack, or _you can delete the stack from console as well_ - Resources created during [Deploying The Application](#-deploying-the-application) - _Any other custom resources, you have created for this demo_ ```bash # Delete from resource group az group delete --name Miztiik_Enterprises_xxx --yes # Follow any on-screen prompt ``` This is not an exhaustive list, please carry out other necessary steps as maybe applicable to your needs. ## 📌 Who is using this This repository aims to show how to Bicep to new developers, Solution Architects & Ops Engineers in Azure. ### 💡 Help/Suggestions or 🐛 Bugs Thank you for your interest in contributing to our project. Whether it is a bug report, new feature, correction, or additional documentation or solutions, we greatly value feedback and contributions from our community. [Start here](/issues) ### 👋 Buy me a coffee [![ko-fi](https://www.ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Q5Q41QDGK) Buy me a [coffee ☕][900]. ### 📚 References 1. [Azure Functions HTTP Trigger][1] 1. [Azure Blob Storage Input Binding][2] 1. [Azure Blob Storage Ouput Binding][3] 1. [Azure Functions Best Practices][4] 1. [Miztiik Blog - Blob Storage Event Processing with Python Azure Functions][5] [1]: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=python-v1 [2]: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-input?tabs=python-v1 [3]: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-output?tabs=python-v1 [4]: https://learn.microsoft.com/en-us/azure/azure-functions/functions-best-practices [5]: https://github.com/miztiik/azure-blob-trigger-python-function ### 🏷️ Metadata ![miztiik-success-green](https://img.shields.io/badge/Miztiik:Automation:Level-100-green) **Level**: 100 [100]: https://www.udemy.com/course/aws-cloud-security/?referralCode=B7F1B6C78B45ADAF77A9 [101]: https://www.udemy.com/course/aws-cloud-security-proactive-way/?referralCode=71DC542AD4481309A441 [102]: https://www.udemy.com/course/aws-cloud-development-kit-from-beginner-to-professional/?referralCode=E15D7FB64E417C547579 [103]: https://www.udemy.com/course/aws-cloudformation-basics?referralCode=93AD3B1530BC871093D6 [899]: https://www.udemy.com/user/n-kumar/ [900]: https://ko-fi.com/miztiik [901]: https://ko-fi.com/Q5Q41QDGK
#ifndef MPM_MPM_EXPLICIT_H_ #define MPM_MPM_EXPLICIT_H_ #ifdef USE_GRAPH_PARTITIONING #include "graph.h" #endif #include "mpm_base.h" namespace mpm { //! MPMExplicit class //! \brief A class that implements the fully explicit one phase mpm //! \details A single-phase explicit MPM //! \tparam Tdim Dimension template <unsigned Tdim> class MPMExplicit : public MPMBase<Tdim> { public: //! Default constructor MPMExplicit(const std::shared_ptr<IO>& io); //! Solve bool solve() override; //! Compute stress strain //! \param[in] phase Phase to smooth pressure void compute_stress_strain(unsigned phase); protected: // Generate a unique id for the analysis using mpm::MPMBase<Tdim>::uuid_; //! Time step size using mpm::MPMBase<Tdim>::dt_; //! Current step using mpm::MPMBase<Tdim>::step_; //! Number of steps using mpm::MPMBase<Tdim>::nsteps_; //! Number of steps using mpm::MPMBase<Tdim>::nload_balance_steps_; //! Output steps using mpm::MPMBase<Tdim>::output_steps_; //! A unique ptr to IO object using mpm::MPMBase<Tdim>::io_; //! JSON analysis object using mpm::MPMBase<Tdim>::analysis_; //! JSON post-process object using mpm::MPMBase<Tdim>::post_process_; //! Logger using mpm::MPMBase<Tdim>::console_; //! MPM Scheme using mpm::MPMBase<Tdim>::mpm_scheme_; //! Stress update method using mpm::MPMBase<Tdim>::stress_update_; //! Interface scheme using mpm::MPMBase<Tdim>::contact_; #ifdef USE_GRAPH_PARTITIONING //! Graph using mpm::MPMBase<Tdim>::graph_; #endif //! velocity update using mpm::MPMBase<Tdim>::velocity_update_; //! Gravity using mpm::MPMBase<Tdim>::gravity_; //! Mesh object using mpm::MPMBase<Tdim>::mesh_; //! Materials using mpm::MPMBase<Tdim>::materials_; //! Node concentrated force using mpm::MPMBase<Tdim>::set_node_concentrated_force_; //! Damping type using mpm::MPMBase<Tdim>::damping_type_; //! Damping factor using mpm::MPMBase<Tdim>::damping_factor_; //! Locate particles using mpm::MPMBase<Tdim>::locate_particles_; private: //! Pressure smoothing bool pressure_smoothing_{false}; //! Interface bool interface_{false}; }; // MPMExplicit class } // namespace mpm #include "mpm_explicit.tcc" #endif // MPM_MPM_EXPLICIT_H_
import type mdIt from 'markdown-it'; import { stringRepeat } from '../helpers/string-repeat.js'; export const tabReplacePlugin: mdIt.PluginWithOptions<{tabWidth: number}> = (md, options) => { // default to being two spaces wide const tabWidth: number = options?.tabWidth ?? 2; // patch the current rule, don't replace it completely const originalRule = md.renderer.rules.fence; md.renderer.rules.fence = function(tokens, idx, options, env, self) { tokens[idx]!.content = expandTabs(tokens[idx]!.content, tabWidth); return originalRule?.call(this, tokens, idx, options, env, self) ?? tokens[idx]!.content; }; // do the tab/space replacement const expandTabs = (content: string, tabWidth: number) => { let idx = 0; // while we're not at the end of the string: // - is the character at the current position a tab? // - yes, replace with spaces and move the current position forward // - no, jump to the character after the next newline while (idx > -1 && idx < content.length) { while (content[idx] === '\t') { content = content.substring(0, idx) + stringRepeat(tabWidth, ' ') + content.substring(idx + 1); idx += tabWidth; } idx = content.indexOf('\n', idx); // if there are no `\n` characters, break if (idx === -1) break; idx += 1; } return content; }; };
# python-bs4-web-scraping ## Overview This project involves web scraping multiple websites using BeautifulSoup (bs4) to extract the most common words and their frequencies. The collected data is then processed, translated using Deepl, and analyzed to find common words among different websites. The results are presented in various CSV files, providing insights into word frequency and commonalities across different web pages. ## Setup 1. Clone the repository: ```bash git clone https://github.com/KeremDUZENLI/python-bs4-web-scraping.git ``` 2. Navigate to the project directory: ```bash cd python-bs4-web-scraping ``` 3. Install the required dependencies: ```bash pip install requests pip install beautifulsoup4 pip install nltk python -m nltk.downloader all pip install --upgrade deepl ``` 4. Set up your environment variables: Create a `.env` file with the following content: ``` DEEPL_KEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:xx ``` Replace `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:xx` with your Deepl API key. ## Usage 1. Run the main script to scrape websites, process data, and generate CSV files: ```bash python main.py ``` This will execute the entire pipeline, including web scraping, translation, and common word analysis. 2. Explore the generated CSV files in the `csv` directory for detailed information on word frequency and commonalities. ## Project Structure - `main.py`: Main script to execute the entire pipeline. - `tool/`: Directory containing utility functions for directory setup and environment variable retrieval. - `web/`: Directory containing web scraping and translation functions. - `csv/`: Directory to store the generated CSV files. - `README.md`: Project documentation. ## Dependencies - `requests`: For making HTTP requests. - `bs4` (Beautiful Soup): For parsing HTML content. - `nltk` (Natural Language Toolkit): For natural language processing tasks. - `deepl`: For translating text using Deepl API.
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <import type="android.view.View"/> <variable name="vmSignUp" type="org.android.go.sopt.present.viewModel.LoginPageViewModel" /> </data> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_title" android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="center" android:text="SIGNUP" android:textSize="32sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.1" /> <TextView android:id="@+id/tv_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="ID" android:textSize="20sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@id/et_id" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/tv_title" /> <EditText android:id="@+id/et_id" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginHorizontal="30dp" android:backgroundTint="@{!vmSignUp.signUpId.empty &amp; !vmSignUp.isValidId()? @color/red_500 : @color/black}" android:hint="아이디를 입력하세요" android:inputType="text" android:text="@={vmSignUp.signUpId}" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/tv_id" /> <TextView android:id="@+id/tv_id_warn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ID 조건: 영문, 숫자가 포함되어야 하고 6~10글자 이내" android:textColor="@color/red_500" android:textSize="8sp" visibility="@{ !vmSignUp.signUpId.empty &amp; !vmSignUp.isValidId() ? View.VISIBLE : View.GONE}" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/et_id" /> <TextView android:id="@+id/tv_password" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="비밀번호" android:textSize="20sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@id/et_password" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/et_id" /> <EditText android:id="@+id/et_password" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="비밀번호를 입력하세요" android:inputType="textPassword" android:text="@={vmSignUp.signUpPwd}" android:backgroundTint="@{!vmSignUp.signUpPwd.empty &amp; !vmSignUp.isValidPwd()? @color/red_500 : @color/black}" app:layout_constraintEnd_toEndOf="@id/et_id" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/tv_password" /> <TextView android:id="@+id/tv_pw_warn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Password 조건: 영문, 숫자, 특수문자가 포함되어야 하고 6~12글자 이내" android:textColor="@color/red_500" android:textSize="8sp" android:visibility="@{ !vmSignUp.signUpPwd.empty &amp; !vmSignUp.isValidPwd() ? View.VISIBLE : View.GONE}" app:layout_constraintStart_toStartOf="@id/et_password" app:layout_constraintTop_toBottomOf="@id/et_password" /> <TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="이름" android:textSize="20sp" android:textStyle="bold" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/et_password" /> <EditText android:id="@+id/et_name" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="이름 입력하세요" android:inputType="text" app:layout_constraintEnd_toEndOf="@id/et_id" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/tv_name" /> <TextView android:id="@+id/tv_speciality" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:text="특기" android:textSize="20sp" android:textStyle="bold" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/et_name" /> <EditText android:id="@+id/et_speciality" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="MBTI를 입력하세요" android:inputType="text" app:layout_constraintEnd_toEndOf="@id/et_id" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/tv_speciality" /> <Button android:id="@+id/btn_signup" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:enabled="@{vmSignUp.canClickSignUpBtn}" android:padding="10dp" android:text="회원가입 완료" app:layout_constraintEnd_toEndOf="@id/et_id" app:layout_constraintStart_toStartOf="@id/et_id" app:layout_constraintTop_toBottomOf="@id/et_speciality" /> </androidx.constraintlayout.widget.ConstraintLayout> </layout>
@isTest public class movimientoBatchTest { public static testmethod void habilidadTestOk() { SingleRequestMock fakeResponse = new SingleRequestMock(200, 'Complete', '{"name": "Pound",'+ '"id": 1,'+ '"accuracy": 100,'+ '"effect_chance": null,'+ '"priority": 0,'+ '"target": { "name": "selected-pokemon", "url": "https://pokeapi.co/api/v2/move-target/10/" },'+ '"effect_entries": [ { "effect": "Inflicts regular damage.", "language": { "name": "en", "url": "https://pokeapi.co/api/v2/language/9/" }, "short_effect": "Inflicts regular damage with no additional effect." } ],'+ '"power": 40,'+ '"pp": 35,'+ '"type": { "name": "normal", "url": "https://pokeapi.co/api/v2/type/1/" }}', null); Test.setMock(HttpCalloutMock.class, fakeResponse); test.startTest(); Id batchJobId = Database.executeBatch(new movimientoBatch(), 1); test.stopTest(); List<Movimiento__c> moveList = [SELECT Id, name, ExtId__c, Punteria__c, Chance_de_Efecto__c, Prioridad__c, Objetivo__c, Efecto__c, Poder__c, Pp__c, Tipo__c FROM Movimiento__c LIMIT 1]; System.assertEquals(1, moveList.size(), 'los valores no coinciden'); System.assertEquals('Pound', moveList[0].name, 'los valores no coinciden'); System.assertEquals(1, moveList[0].ExtId__c, 'los valores no coinciden'); System.assertEquals(100, moveList[0].Punteria__c, 'los valores no coinciden'); System.assertEquals(null, moveList[0].Chance_de_Efecto__c, 'los valores no coinciden'); System.assertEquals(0, moveList[0].Prioridad__c, 'los valores no coinciden'); System.assertEquals('selected-pokemon', moveList[0].Objetivo__c, 'los valores no coinciden'); System.assertEquals('Inflicts regular damage with no additional effect.', moveList[0].Efecto__c, 'los valores no coinciden'); System.assertEquals(40, moveList[0].Poder__c, 'los valores no coinciden'); System.assertEquals(35, moveList[0].Pp__c, 'los valores no coinciden'); System.assertEquals('Normal', moveList[0].Tipo__c, 'los valores no coinciden'); } public static testmethod void habilidadTestKo(){ SingleRequestMock fakeResponse = new SingleRequestMock(404, 'Incomplete', '', null); Test.setMock(HttpCalloutMock.class, fakeResponse); Test.startTest(); Id batchJobId = Database.executeBatch(new movimientoBatch(), 1); Test.stopTest(); List<Movimiento__c> moveList = [SELECT Id, Name FROM Movimiento__c]; System.assertEquals(0, moveList.size(), 'La lista tiene contenido'); } }
// // ProfileView.swift // OnlineFitnessTrainerApp // // Created by Admin on 7/6/23. // import UIKit final class ProfileView: UIView { // Const profile Imge Height private let profileIamgeHeight: CGFloat = 100 // MARK:- Create Autlets programaticaly private lazy var profileImageView: UIImageView = { let imageView = UIImageView() imageView.clipsToBounds = true imageView.isUserInteractionEnabled = true imageView.contentMode = .scaleAspectFill imageView.layer.cornerRadius = profileIamgeHeight / 2 imageView.image = Const.Icon.personIcon .withTintColor(.gray, renderingMode: .alwaysOriginal) self.addSubview(imageView) return imageView }() private lazy var eddButton: UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.layer.cornerRadius = 7 btn.backgroundColor = Const.Colors.highlightBackgroundColor btn.setImage(Const.Icon.addIcon .withTintColor(.black, renderingMode: .alwaysOriginal) .withConfiguration(UIImage.SymbolConfiguration(pointSize: 15, weight: .bold)), for: .normal ) btn.addTarget(self, action: #selector(eddButtonTapped), for: .touchUpInside) self.addSubview(btn) return btn }() private(set) lazy var fullNameTextField: UITextField = { let placeHolder = "Name" let textField = createTextFiled(with: placeHolder) return textField }() private(set) lazy var lastNameTextField: UITextField = { let placeHolder = "Last name" let textField = createTextFiled(with: placeHolder) return textField }() private(set) lazy var emailTextField: UITextField = { let placeHolder = "Email" let textField = createTextFiled(with: placeHolder) textField.addRight(image: Const.Icon.emailIcon) return textField }() private(set) lazy var phoneNumberTextField: UITextField = { let placeHolder = "Phone Number" let textField = createTextFiled(with: placeHolder) return textField }() private lazy var stackViewForTextField: UIStackView = { let stack = UIStackView() stack.axis = .vertical stack.distribution = .fillEqually stack.alignment = .fill stack.spacing = 20 stack.addArrangedSubview(fullNameTextField) stack.addArrangedSubview(lastNameTextField) stack.addArrangedSubview(emailTextField) stack.addArrangedSubview(phoneNumberTextField) self.addSubview(stack) return stack }() // MARK:- View lifeCycle override func layoutSubviews() { super.layoutSubviews() adjustConstraints() } } // MARK:- Extension extension ProfileView { // MARK:- Private Methods private func createTextFiled(with placeHolder: String) -> UITextField { let textField = UITextField() textField.addLeftPaddingPoint(15) textField.attributedPlaceholder = NSAttributedString(string: placeHolder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13) ] ) textField.backgroundColor = Const.Colors.backgroundColorLightDark textField.textColor = Const.Colors.tintColorWhite textField.font = UIFont.systemFont(ofSize: 13) textField.layer.cornerRadius = Const.Radius.cornerRadiusForButton return textField } private func adjustConstraints() { profileImageView.anchor(top: self.topAnchor, paddingTop: 10, bottom: stackViewForTextField.topAnchor, paddingBottom: 10, left: nil, paddingLeft: 0, right: nil, paddingRight: 0, width: profileIamgeHeight, height: profileIamgeHeight, centerX: self.centerXAnchor, centerY: nil ) let eddButtonConstraints = [ eddButton.topAnchor.constraint(equalTo: profileImageView.bottomAnchor, constant: -30), eddButton.heightAnchor.constraint(equalToConstant: 25), eddButton.widthAnchor.constraint(equalTo: eddButton.heightAnchor), eddButton.trailingAnchor.constraint(equalTo: profileImageView.trailingAnchor, constant: -10) ] NSLayoutConstraint.activate(eddButtonConstraints) stackViewForTextField.anchor(top: nil, paddingTop: 0, bottom: self.bottomAnchor, paddingBottom: 10, left: self.leftAnchor, paddingLeft: 0, right: nil, paddingRight: 0, width: 0, height: 0, centerX: self.centerXAnchor, centerY: nil ) } // MARK:- Post Notification To Change Profile Photo @objc private func eddButtonTapped() { NotificationCenter.default.post(name: .changeProfilePhoto, object: nil) } func updateProfile(image: UIImage) { self.profileImageView.image = image } }
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gtest/gtest.h" #include "base/log/log.h" #include "base/utils/utils.h" #include "core/components/test/unittest/flex/flex_test_utils.h" #include "core/components/test/unittest/mock/mock_render_common.h" #include "core/components/text/text_component.h" using namespace testing; using namespace testing::ext; namespace OHOS::Ace { namespace { constexpr double SMALL_BOX = 100.0; constexpr double MEDIUM_BOX = 200.0; constexpr double LARGE_BOX = 300.0; constexpr double SMALL_TEXT = 50.0; constexpr double MEDIUM_TEXT = 100.0; constexpr double LARGE_TEXT = 150.0; constexpr double SMALL_BASELINE = 30; constexpr double MEDIUM_BASELINE = 60; constexpr double RECT_WIDTH = 1080.0; constexpr double CENTER_SPACE_SIZE = 240.0; constexpr double END_SPACE_SIZE = 480.0; constexpr double BETWEEN_SPACE_SIZE = 240.0; constexpr double AROUND_FRONT_SPACE_SIZE = 80.0; constexpr double EVENLY_SPACE_SIZE = 120.0; constexpr double AROUND_SPACE_SIZE = 160.0; constexpr double CENTER_ALIGN_SIZE = 50.0; constexpr double END_ALIGN_SIZE = 100.0; constexpr double ROW_COL_CENTER_SIZE = 390.0; constexpr double ROW_COL_SMALL_CENTER_SIZE = 290.0; } // namespace class RenderRowTest : public testing::Test { public: static void SetUpTestCase() { GTEST_LOG_(INFO) << "RenderRowTest SetUpTestCase"; } static void TearDownTestCase() { GTEST_LOG_(INFO) << "RenderRowTest TearDownTestCase"; } void SetUp() {} void TearDown() {} }; /** * @tc.name: RenderFlexUpdate001 * @tc.desc: Verify the Update Interface of RenderFlex does not work for other components * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH4 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderFlexUpdate001, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderFlexUpdate001 start"; /** * @tc.steps: step1. construct Text Component and RenderFlex. */ RefPtr<TextComponent> text = AceType::MakeRefPtr<TextComponent>("Hi Ace"); RefPtr<RenderFlex> renderFlex = AceType::MakeRefPtr<RenderFlex>(); /** * @tc.steps: step2. call the Update interface of RenderFlex * @tc.expected: step2. renderFlex are not set need layout */ renderFlex->Update(text); EXPECT_TRUE(!renderFlex->NeedLayout()); } /** * @tc.name: RenderFlexUpdate002 * @tc.desc: Verify that RenderFlex works for flex component. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH4 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderFlexUpdate002, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderFlexUpdate002 start"; /** * @tc.steps: step1. construct flex component and RenderFlex. */ RefPtr<TextComponent> text = AceType::MakeRefPtr<TextComponent>("Hi Ace"); FlexAlign main = FlexAlign::FLEX_START; FlexAlign cross = FlexAlign::FLEX_START; std::list<RefPtr<Component>> child; child.emplace_back(text); RefPtr<RowComponent> row = AceType::MakeRefPtr<RowComponent>(main, cross, child); RefPtr<RenderFlex> renderFlex = AceType::MakeRefPtr<RenderFlex>(); /** * @tc.steps: step2. call Update interface of renderFlex * @tc.expected: step2. renderFlex are set needLayout */ renderFlex->Update(row); EXPECT_TRUE(renderFlex->NeedLayout()); } /** * @tc.name: RenderRowLayout001 * @tc.desc: Verify the row component with main(start) and cross(start) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout001, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout001 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-start. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition().IsZero()); EXPECT_TRUE(secondBox->GetPosition() == Offset(SMALL_BOX, 0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderRowLayout002 * @tc.desc: Verify the row component with main(start) and cross(center) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout002, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout002 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-center. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::CENTER); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(0, CENTER_ALIGN_SIZE + CENTER_ALIGN_SIZE)); EXPECT_TRUE(secondBox->GetPosition() == Offset(SMALL_BOX, CENTER_ALIGN_SIZE)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderRowLayout003 * @tc.desc: Verify the row component with main(start) and cross(end) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout003, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout003 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-end. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_END); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(0, END_ALIGN_SIZE + END_ALIGN_SIZE)); EXPECT_TRUE(secondBox->GetPosition() == Offset(SMALL_BOX, END_ALIGN_SIZE)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderRowLayout004 * @tc.desc: Verify the row component with main(start) and cross(stretch) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout004, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout004 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-stretch. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::STRETCH); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly, the size of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(0, 0.0)); EXPECT_TRUE(secondBox->GetPosition() == Offset(SMALL_BOX, 0.0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(SMALL_BOX + MEDIUM_BOX, 0.0)); EXPECT_TRUE(firstBox->GetLayoutSize() == Size(SMALL_BOX, LARGE_BOX)); EXPECT_TRUE(secondBox->GetLayoutSize() == Size(MEDIUM_BOX, LARGE_BOX)); EXPECT_TRUE(thirdBox->GetLayoutSize() == Size(LARGE_BOX, LARGE_BOX)); } /** * @tc.name: RenderRowLayout005 * @tc.desc: Verify the row component with main(center) and cross(start) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout005, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout005 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as center-start. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::CENTER, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(CENTER_SPACE_SIZE, 0.0)); EXPECT_TRUE(secondBox->GetPosition() == Offset(CENTER_SPACE_SIZE + SMALL_BOX, 0.0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(CENTER_SPACE_SIZE + SMALL_BOX + MEDIUM_BOX, 0.0)); } /** * @tc.name: RenderRowLayout006 * @tc.desc: Verify the row component with main(end) and cross(start) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout006, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout006 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as end-start. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_END, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(END_SPACE_SIZE, 0.0)); EXPECT_TRUE(secondBox->GetPosition() == Offset(END_SPACE_SIZE + SMALL_BOX, 0.0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(END_SPACE_SIZE + SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderRowLayout007 * @tc.desc: Verify the row component with main(space-between) and cross(start) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout007, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout007 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as space_between-start. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::SPACE_BETWEEN, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(0, 0)); EXPECT_TRUE(secondBox->GetPosition() == Offset(BETWEEN_SPACE_SIZE + SMALL_BOX, 0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(BETWEEN_SPACE_SIZE + BETWEEN_SPACE_SIZE + SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderRowLayout008 * @tc.desc: Verify the row component with main(space-around) and cross(start) works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout008, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout008 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as space_around-start. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::SPACE_AROUND, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(AROUND_FRONT_SPACE_SIZE, 0.0)); EXPECT_TRUE(secondBox->GetPosition() == Offset(AROUND_FRONT_SPACE_SIZE + AROUND_SPACE_SIZE + SMALL_BOX, 0.0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(AROUND_FRONT_SPACE_SIZE + AROUND_SPACE_SIZE + AROUND_SPACE_SIZE + SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderRowLayout009 * @tc.desc: Verify the row component with main(center) and cross(center) under row component works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout009, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout009 start"; /** * @tc.steps: step1. construct the node tree, row has a child row, child row are set as center-center. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderFlex> childRow = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::CENTER, FlexAlign::CENTER); row->AddChild(childRow); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); childRow->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); childRow->AddChild(secondBox); RefPtr<RenderFlex> secondChildRow = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::CENTER, FlexAlign::CENTER); row->AddChild(secondChildRow); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); thirdBox->Attach(mockContext); secondChildRow->AddChild(thirdBox); RefPtr<RenderBox> fourthBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); fourthBox->Attach(mockContext); secondChildRow->AddChild(fourthBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); childRow->Attach(mockContext); secondChildRow->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(childRow->GetPosition() == Offset(0.0, 0.0)); EXPECT_TRUE(secondChildRow->GetPosition() == Offset(RECT_WIDTH, 0.0)); EXPECT_TRUE(firstBox->GetPosition() == Offset(ROW_COL_CENTER_SIZE, CENTER_ALIGN_SIZE)); EXPECT_TRUE(secondBox->GetPosition() == Offset(ROW_COL_CENTER_SIZE + SMALL_BOX, 0.0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(ROW_COL_SMALL_CENTER_SIZE, CENTER_ALIGN_SIZE)); EXPECT_TRUE(fourthBox->GetPosition() == Offset(ROW_COL_SMALL_CENTER_SIZE + MEDIUM_BOX, 0.0)); } /** * @tc.name: RenderRowLayout010 * @tc.desc: Verify the row component with main(center) and cross(center) under column component works fine. * @tc.type: FUNC * @tc.require: AR000DAQTH AR000DAIH5 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout010, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderRowLayout010 start"; /** * @tc.steps: step1. construct the node tree, parent column has a child row, child column are set as center-center. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> column = FlexTestUtils::CreateRenderFlex(FlexDirection::COLUMN, FlexAlign::FLEX_START, FlexAlign::FLEX_START); root->AddChild(column); RefPtr<RenderFlex> childRow = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::CENTER, FlexAlign::CENTER); column->AddChild(childRow); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); childRow->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); childRow->AddChild(secondBox); RefPtr<RenderFlex> secondChildRow = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::CENTER, FlexAlign::CENTER); column->AddChild(secondChildRow); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); thirdBox->Attach(mockContext); secondChildRow->AddChild(thirdBox); RefPtr<RenderBox> fourthBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); fourthBox->Attach(mockContext); secondChildRow->AddChild(fourthBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); column->Attach(mockContext); childRow->Attach(mockContext); secondChildRow->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(childRow->GetPosition() == Offset(0.0, 0.0)); EXPECT_TRUE(secondChildRow->GetPosition() == Offset(0.0, MEDIUM_BOX)); EXPECT_TRUE(firstBox->GetPosition() == Offset(ROW_COL_CENTER_SIZE, CENTER_ALIGN_SIZE)); EXPECT_TRUE(secondBox->GetPosition() == Offset(ROW_COL_CENTER_SIZE + SMALL_BOX, 0.0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(ROW_COL_SMALL_CENTER_SIZE, CENTER_ALIGN_SIZE)); EXPECT_TRUE(fourthBox->GetPosition() == Offset(ROW_COL_SMALL_CENTER_SIZE + MEDIUM_BOX, 0.0)); } /** * @tc.name: RenderRowLayout011 * @tc.desc: Verify the row component with main(space-evenly) and cross(start) works fine. * @tc.type: FUNC * @tc.require: SR000F3BA7 AR000F3BA9 * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderRowLayout011, TestSize.Level1) { /** * @tc.steps: step1. construct the RenderNode tree, flex are set as space_between-start. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::SPACE_EVENLY, FlexAlign::FLEX_START); root->AddChild(row); RefPtr<RenderBox> firstBox = FlexTestUtils::CreateRenderBox(SMALL_BOX, SMALL_BOX); firstBox->Attach(mockContext); row->AddChild(firstBox); RefPtr<RenderBox> secondBox = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); secondBox->Attach(mockContext); row->AddChild(secondBox); RefPtr<RenderBox> thirdBox = FlexTestUtils::CreateRenderBox(LARGE_BOX, LARGE_BOX); thirdBox->Attach(mockContext); row->AddChild(thirdBox); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstBox->GetPosition() == Offset(EVENLY_SPACE_SIZE, 0)); EXPECT_TRUE(secondBox->GetPosition() == Offset(2 * EVENLY_SPACE_SIZE + SMALL_BOX, 0)); EXPECT_TRUE(thirdBox->GetPosition() == Offset(3 * EVENLY_SPACE_SIZE + SMALL_BOX + MEDIUM_BOX, 0)); } /** * @tc.name: RenderBaseline001 * @tc.desc: Verify the row component with main(start) and cross(baseline) works fine when all the children are text. * @tc.type: FUNC * @tc.require: AR000DAQTI * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderBaseline001, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderBaseline001 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-baseline. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::BASELINE); root->AddChild(row); RefPtr<MockRenderText> firstText = FlexTestUtils::CreateRenderText(SMALL_TEXT); row->AddChild(firstText); RefPtr<MockRenderText> secondText = FlexTestUtils::CreateRenderText(MEDIUM_TEXT); row->AddChild(secondText); RefPtr<MockRenderText> thirdText = FlexTestUtils::CreateRenderText(LARGE_TEXT); row->AddChild(thirdText); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); firstText->Attach(mockContext); secondText->Attach(mockContext); thirdText->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstText->GetPosition() == Offset(0, MEDIUM_BASELINE)); EXPECT_TRUE(secondText->GetPosition() == Offset(SMALL_TEXT, SMALL_BASELINE)); EXPECT_TRUE(thirdText->GetPosition() == Offset(SMALL_TEXT + MEDIUM_TEXT, 0)); } /** * @tc.name: RenderBaseline002 * @tc.desc: Verify the row component with main(start) and cross(baseline) works fine when not all children are text. * @tc.type: FUNC * @tc.require: AR000DAQTI * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderBaseline002, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderBaseline002 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-baseline. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::BASELINE); root->AddChild(row); RefPtr<MockRenderText> firstText = FlexTestUtils::CreateRenderText(SMALL_TEXT); row->AddChild(firstText); RefPtr<MockRenderText> secondText = FlexTestUtils::CreateRenderText(MEDIUM_TEXT); row->AddChild(secondText); RefPtr<RenderBox> box = FlexTestUtils::CreateRenderBox(MEDIUM_BOX, MEDIUM_BOX); box->Attach(mockContext); row->AddChild(box); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); firstText->Attach(mockContext); secondText->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstText->GetPosition() == Offset(0, MEDIUM_BOX - SMALL_BASELINE)); EXPECT_TRUE(secondText->GetPosition() == Offset(SMALL_TEXT, MEDIUM_BOX - MEDIUM_BASELINE)); EXPECT_TRUE(box->GetPosition() == Offset(SMALL_TEXT + MEDIUM_TEXT, 0)); } /** * @tc.name: RenderBaseline003 * @tc.desc: Verify the row component with main(start) and cross(baseline) works fine when some children are flexItem. * @tc.type: FUNC * @tc.require: AR000DAQTI * @tc.author: yangfan */ HWTEST_F(RenderRowTest, RenderBaseline003, TestSize.Level1) { GTEST_LOG_(INFO) << "RenderRowTest RenderBaseline003 start"; /** * @tc.steps: step1. construct the RenderNode tree, flex are set as start-baseline. */ auto mockContext = MockRenderCommon::GetMockContext(); RefPtr<RenderRoot> root = FlexTestUtils::CreateRenderRoot(); RefPtr<RenderFlex> row = FlexTestUtils::CreateRenderFlex(FlexDirection::ROW, FlexAlign::FLEX_START, FlexAlign::BASELINE); root->AddChild(row); RefPtr<MockRenderText> firstText = FlexTestUtils::CreateRenderText(SMALL_TEXT); row->AddChild(firstText); RefPtr<RenderFlexItem> flexItem = FlexTestUtils::CreateRenderFlexItem(0, 0, 0); row->AddChild(flexItem); RefPtr<MockRenderText> secondText = FlexTestUtils::CreateRenderText(MEDIUM_TEXT); flexItem->AddChild(secondText); /** * @tc.steps: step2. call PerformLayout interface * @tc.expected: step2. the positions of three boxes are set correctly */ root->Attach(mockContext); row->Attach(mockContext); firstText->Attach(mockContext); flexItem->Attach(mockContext); secondText->Attach(mockContext); root->PerformLayout(); EXPECT_TRUE(firstText->GetPosition() == Offset(0, SMALL_BASELINE)); EXPECT_TRUE(flexItem->GetPosition() == Offset(SMALL_TEXT, 0)); } } // namespace OHOS::Ace
/** * ProjectName * * Author: * Company: * * website */ import { StyleProp, TextStyle } from "react-native"; import { createTheme, TextProps } from "@rneui/themed"; import { moderateScale } from "react-native-size-matters"; import Colors from "./colors"; import Typography, { fontSizes } from "./typography"; const getExtendedTextStyles = (props: Partial<TextProps>) => { const extendedStyles: Array<StyleProp<TextStyle>> = [ { ...Typography.regular }, props.bold && { ...Typography.bold }, props.italic && { ...Typography.italic }, props.bold && props.italic && { ...Typography.boldItalic }, props.medium && { ...Typography.medium }, props.medium && props.italic && { ...Typography.mediumItalic }, props.strikethrough && { textDecorationLine: "line-through", textDecorationStyle: "solid" }, props.underlined && { textDecorationLine: "underline", textDecorationStyle: "solid" }, props.center && { textAlign: "center" }, props.color && { color: Colors[props.color] || props.color }, props.p1 && { ...fontSizes.p1, lineHeight: moderateScale(1.5) }, props.p2 && { ...fontSizes.p2, lineHeight: moderateScale(1.5) } ]; return extendedStyles; }; const getTextStyles = (props: Partial<TextProps>) => { const extendedStyles = getExtendedTextStyles(props); return { h1Style: [ { ...fontSizes.h1 }, extendedStyles ], h2Style: [ { ...fontSizes.h2 }, extendedStyles ], h3Style: [ { ...fontSizes.h3 }, extendedStyles ], h4Style: [ { ...fontSizes.h4 }, extendedStyles ], style: [ { ...fontSizes.p1 }, extendedStyles ] }; }; export const theme = createTheme({ lightColors: { primary: Colors.primary, secondary: Colors.secondary, tertiary: Colors.tertiary, success: Colors.success, error: Colors.danger, warning: Colors.warning, disabled: Colors.secondary, searchBg: Colors.light }, darkColors: { primary: Colors.primary, secondary: Colors.secondary, tertiary: Colors.tertiary, success: Colors.success, error: Colors.danger, warning: Colors.warning, disabled: Colors.secondary, searchBg: Colors.dark }, components: { Button: () => ({ titleStyle: { ...Typography.bold, ...fontSizes.button } }), Icon: props => ({ type: props.type || props.font }), Input: (props, currentTheme) => ({ containerStyle: { paddingHorizontal: 0 }, inputContainerStyle: { borderColor: currentTheme.colors.black }, labelStyle: { ...Typography.regular, ...fontSizes.inputLabel }, inputStyle: { ...Typography.regular, padding: 0, ...fontSizes.input }, placeholderTextColor: Colors.muted, errorStyle: { ...Typography.regular, ...fontSizes.inputError }, cursorColor: Colors.primary, leftIconContainerStyle: { marginRight: moderateScale(6), marginVertical: 0 }, rightIconContainerStyle: { marginLeft: moderateScale(6), marginVertical: 0 } }), Text: props => getTextStyles(props), ListItemTitle: props => getTextStyles(props) } });
import { zodResolver } from "@hookform/resolvers/zod"; import axios from "axios"; import React, { useState } from "react"; import { SubmitHandler, useForm } from "react-hook-form"; import { useParams } from "react-router"; import { z } from "zod"; import { useAppDispatch } from "../../reducers/hooks"; import { refreshFriendPost, refreshUserPost, } from "../../reducers/postsReducer"; import Button from "../Button/Button"; interface EditCommentModalProps { commentId: string; content: string; postId: string; } const CommentSchema = z.object({ content: z.string().min(1).max(250), }); type CommentSchemaType = z.infer<typeof CommentSchema>; const EditCommentModal = (props: EditCommentModalProps) => { const [isEdited, setIsEdited] = useState<boolean>(false); const { id } = useParams(); const dispatch = useAppDispatch(); const { handleSubmit, register, formState: { isSubmitting, isSubmitted }, } = useForm<CommentSchemaType>({ resolver: zodResolver(CommentSchema), defaultValues: { content: props.content }, }); const onSubmit: SubmitHandler<CommentSchemaType> = async (data) => { try { await axios.put(`/api/comments/${props.commentId}`, data); typeof id === "undefined" ? dispatch(refreshFriendPost(props.postId)) : dispatch(refreshUserPost(props.postId)); setIsEdited(true); } catch (error) { console.log(error); } }; return ( <form className="flex flex-col gap-2" onSubmit={handleSubmit(onSubmit)}> <p>Edytuj komentarz:</p> <textarea cols={50} rows={5} maxLength={250} className="resize-none bg-violet-50 rounded-xl p-2 focus:outline-none" spellCheck={false} disabled={isSubmitting || isSubmitted} {...register("content")} ></textarea> {isEdited && <p className="self-center">Komentarz został edytowany</p>} {!isEdited && ( <Button type="submit" lightness="200" circle={false}> Edytuj </Button> )} </form> ); }; export default EditCommentModal;
# Welcome to Remix + Vite! 📖 See the [Remix docs](https://remix.run/docs) and the [Remix Vite docs](https://remix.run/docs/en/main/future/vite) for details on supported features. ## Stack - Testing: [Vitest](https://vitest.dev) + [@remix-run/testing](https://remix.run/docs/en/main/other-api/testing) - Styling : [Tailwind](https://tailwindcss.com/) - Code quality: [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [git hooks](https://typicode.github.io/husky/) - i18n: [i18next](https://remix.run/resources/remix-i18next) - API mocking: [MSW](https://mswjs.io/) ## Development Run the Vite dev server: ```shellscript npm run dev ``` ## Deployment First, build your app for production: ```sh npm run build ``` Then run the app in production mode: ```sh npm start ``` Now you'll need to pick a host to deploy it to. ### DIY If you're familiar with deploying Node applications, the built-in Remix app server is production-ready. Make sure to deploy the output of `npm run build` - `build/server` - `build/client`
# Google Tasks Backup to Sheets Hey there! 👋 This is a neat little project that backs up your Google Tasks into a Google Sheet. Perfect for those who don't want to lose their tasks and lists, especially since Google Tasks doesn't have a recycle bin feature. ## What's This All About? This Google Apps Script automatically backs up your Google Tasks into a Google Sheet. It's a straightforward way to ensure that your tasks are safe, even if they accidentally get deleted from Google Tasks. ## Features - **Automatic Backup:** Creates a separate sheet for each of your task lists in Google Tasks and backs up your tasks neatly. - **Status Tracking:** Keeps track of tasks' statuses, identifying what's active or deleted. - **Customizable Backup Frequency:** Choose how often you want to back up your tasks - hourly, daily, or weekly. ## Getting Started 1. **Open Google Sheets:** Start with a new Google Sheet for this adventure. 2. **Open the Script Editor:** In the Sheets menu, click on `Extensions > Apps Script`. 3. **Copy-Paste the Script:** Copy the script from this repo and paste it into the script editor. 4. **Run the Script:** Click on `Run > Run function > onOpen` to create the custom menu. 5. **Authorize the Script:** Follow the prompts to authorize the script if required. 6. **Access the Custom Menu:** In your Google Sheet, you will see a new menu 'Back Up Google Tasks'. ## Using the Script - **Run Backup Now:** Click this to immediately back up your Google Tasks. - **Set Backup Frequency:** Hover over this option to set the frequency of automatic backups. Choose from hourly, daily, or weekly backups. ## Note - Remember to enable the Google Tasks API from your Google Cloud Console for the script to work. - This script runs within the Google environment, ensuring your data's privacy and security. ## Contributing Feel free to fork this repo, tweak it, and submit improvements! Got an idea or suggestion? Open an issue and let's make this script even better.
/** * Create Definition factory from provided classname which must implement {@link ComponentDefinitionsFactory}. * Factory class must extend {@link DefinitionsFactory}. * @param classname Class name of the factory to create. * @return newly created factory. * @throws DefinitionsFactoryException If an error occur while initializing factory */ protected ComponentDefinitionsFactory createFactoryInstance(String classname) throws DefinitionsFactoryException { try { Class factoryClass = RequestUtils.applicationClass(classname); Object factory = factoryClass.newInstance(); return (ComponentDefinitionsFactory) factory; } catch (ClassCastException ex) { // Bad classname throw new DefinitionsFactoryException( "Error - createDefinitionsFactory : Factory class '" + classname + " must implement 'DefinitionsFactory'.", ex); } catch (ClassNotFoundException ex) { // Bad classname throw new DefinitionsFactoryException( "Error - createDefinitionsFactory : Bad class name '" + classname + "'.", ex); } catch (InstantiationException ex) { // Bad constructor or error throw new DefinitionsFactoryException(ex); } catch (IllegalAccessException ex) { throw new DefinitionsFactoryException(ex); } }
import React,{useContext,useState,useRef} from 'react'; import gql from 'graphql-tag'; import {useQuery,useMutation} from '@apollo/react-hooks'; import { Button,Icon,Label,Image, Card, Grid,Form } from 'semantic-ui-react'; import LikeButton from '../components/LikeButton' import moment from 'moment'; import {AuthContext} from '../context/auth'; import DeleteButton from '../components/DeleteButton'; import MyPopup from '../util/MyPopup'; function SinglePost(props){ //edw bazei sto postId tin timi tou post pou yparxei stin grammi tou url const postId = props.match.params.postId; const{user} = useContext(AuthContext); const commentInputRef=useRef(null); const [comment,setComment] = useState(''); //epeidi theloume to field tou getPost dinoume sto data to alias getPost, to name getPost diladi const {data:{getPost}={}} = useQuery(FETCH_POST_QUERY,{ variables:{ postId } }) console.log(getPost); const [submitComment] = useMutation(SUBMIT_COMMENT_MUTATION,{ update(){ setComment(''); commentInputRef.current.blur(); }, variables: { postId, body: comment } }); function deletePostCallback(){ props.history.push('/'); } //let epeidi einai conditional let postMarkup; if(!getPost){ //perimenoume na fortosei, mporoume na balooume kai kyklo pou gyrnaei postMarkup = <p>Loading post.....</p> }else{ const {id,body,createdAt,username,comments,likes,likeCount,commentCount,profilePic}=getPost; console.log(getPost); postMarkup=( <Grid> <Grid.Row> <Grid.Column width={2}> {profilePic?( <Image src={profilePic} /> ):( <Image src='https://react.semantic-ui.com/images/avatar/large/matthew.png' wrapped ui={false} /> )} </Grid.Column> <Grid.Column width={10}> <Card fluid> <Card.Content> <Card.Header>{username}</Card.Header> <Card.Meta>{moment(createdAt).fromNow()}</Card.Meta> <Card.Description>{body}</Card.Description> </Card.Content> <hr/> <Card.Content extra> <LikeButton user={user} post={{id,likeCount,likes}}/> <MyPopup content="Comment on post"> <Button as="div" labelPosition="right" onClick={()=>console.log("comment on post")} > <Button basic color="blue"> <Icon name="comments"/> </Button> <Label basic color="blue" pointing="left"> {commentCount} </Label> </Button> </MyPopup> {user && user.username===username &&( <DeleteButton postId={id} callback={deletePostCallback}/> )} </Card.Content> </Card> {user && ( <Card fluid> <Card.Content> <p>Post a comment</p> <Form> <div className="ui action input fuild"> <input type="text" placeholder="Comment.." value={comment} onChange={event =>setComment(event.target.value)} ref={commentInputRef} /> <button type="submit" className="ui button teal" //ean den yparxoun comments tote tha einai disabled disabled={comment.trim()===''} onClick={submitComment} > Submit </button> </div> </Form> </Card.Content> </Card> )} {comments.map(comment=>( <Card fluid key={comment.id}> <Card.Content> {comment.profilePic?( <Image size='mini' floated='right' src={profilePic} /> ):( <Image floated='right' size='mini' src='https://react.semantic-ui.com/images/avatar/large/jenny.jpg' /> )} {user && user.username === comment.username &&( <DeleteButton postId={id} commentId={comment.id}/> )} <Card.Header>{comment.username}</Card.Header> <Card.Meta>{moment(comment.createdAt).fromNow()}</Card.Meta> <Card.Description>{comment.body}</Card.Description> </Card.Content> </Card> ))} </Grid.Column> </Grid.Row> </Grid> ) } return postMarkup; } const SUBMIT_COMMENT_MUTATION =gql` mutation($postId:ID!,$body:String!){ createComment(postId:$postId, body:$body){ id comments{ id body createdAt username profilePic } commentCount } } ` const FETCH_POST_QUERY = gql` query($postId:ID!){ getPost(postId: $postId){ id body createdAt username likeCount profilePic likes{ username } commentCount comments{ id username createdAt body profilePic } } } `; export default SinglePost
// // Created by Jelmer Bennema on 1/3/24. // #include <boost/numeric/ublas/lu.hpp> #include "Practical05/Practical05Exercises.hpp" #include "Utils/UtilityFunctions.hpp" /** MonteCarlo4 - given a grid of initial stock values (2D GBM), generates a set of possible corresponding payoffs * @param vS0 an std vector of initial factors * @param dR riskfree rate * @param dSigma1 vol of the first component * @param dSigma2 vol of the second component * @param dRho correlation of driving BM components * @param dT time to maturity * @param payoff payoff function * @return regressed value */ exercises::BVector exercises::MonteCarlo4(std::vector<BVector> vS0, double dR, double dSigma1, double dSigma2, double dRho, double dT, Function const& payoff){ BVector S(2); BVector::size_type i, n; n = vS0.size(); BVector final_payoff(n); // create vector of simulated stock prices for (i = 0; i < n; i++) { // construct brownian increments double B1 = utils::NormalDist() * sqrt(dT); double B2 = utils::NormalDist() * sqrt(dT); B2 = dRho * B1 + sqrt(1 - dRho * dRho) * B2; // Use geometric brownian motion S[0] = vS0[i][0] * exp((dR - dSigma1 * dSigma1 * 0.5)*dT + dSigma1 * B1); S[1] = vS0[i][1] * exp((dR - dSigma2 * dSigma2 * 0.5)*dT + dSigma2 * B2); //find payoff vector - and apply discount final_payoff[i] = payoff(S) * exp(-dR*dT); } return final_payoff; }
""" Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c. Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated +3: defghijklmnopqrstuvwxyzabc Example The alphabet is rotated by , matching the mapping above. The encrypted string is . Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted. Function Description Complete the caesarCipher function in the editor below. caesarCipher has the following parameter(s): string s: cleartext int k: the alphabet rotation factor Returns string: the encrypted string Input Format The first line contains the integer, , the length of the unencrypted string. The second line contains the unencrypted string, . The third line contains , the number of letters to rotate the alphabet by. Constraints is a valid ASCII string without any spaces. Sample Input 11 middle-Outz 2 Sample Output okffng-Qwvb Explanation Original alphabet: abcdefghijklmnopqrstuvwxyz Alphabet rotated +2: cdefghijklmnopqrstuvwxyzab m -> o i -> k d -> f d -> f l -> n e -> g - - O -> Q u -> w t -> v z -> b """ """ first get the letters into an alphabetical order as an array. after that the idea is that whenever we encoutner a letter we get the number representation of that letter and then apply the rotation by k numbers making the check to see if it is a captial letter or not. """ def caesarCipher(s, k): # Write your code here letters = [] for i in range(26): letters.append(chr(i+97)) output = "" iscapital = False for i in s: if i.isalpha(): if i.isupper(): iscapital = True index = (ord(i.lower())-97) curletter = letters[(index+ k) % 26] if iscapital: output+= curletter.upper() else: output+=curletter iscapital = False else: output+=i return output
<link rel="import" href="../../polymer/polymer.html"> <link rel="import" href="../px-vis-scale.html"> <link rel="import" href="../px-vis-svg.html"> <dom-module id="px-vis-scale-demo"> <link rel="import" type="css" href="../css/px-vis-demo.css"/> <template> <p id="px-vis-scale-anchor" class="epsilon demo__title">px-vis-scale</p> <div class="demo u-p+"> <div class="outline"> <!-- need for scale --> <px-vis-svg width="[[width]]" height="[[height]]" margin="[[margin]]" svg="{{svg}}"> </px-vis-svg> <px-vis-scale x-axis-type="time" y-axis-type="linear" complete-series-config="[[seriesConfig]]" chart-extents="[[chartExtents]]" width="[[width]]" height="[[height]]" margin="[[margin]]" chart-data={{chartData}} x="{{x}}" y="{{y}}" current-domain-x="{{currentDomainX}}" current-domain-y="{{currentDomainY}}" selected-domain="[[selectedDomain]]"> </px-vis-scale> <p style="text-align: center; color: rgb(150,168,178)">px-vis-scale cannot be seen</p> </div> <div class="demo__discription"> <p class="u-mt0"><strong>All charts need an interpretor component.</strong> These <strong>cannot be seen</strong> but provide the basic framework for drawing objects to be displayed.</p> <p>Interpretor components convert data into drawing space coordinates.</p> <p>The scale component creates 'x' &amp 'y' and 'currentDomainX' &amp 'currentDomainY' variables which can be passed into drawing components.</p> <p style="oblique">Note: All the subsequent charts will have this component, but they will not be shown in the code snippet.</p> </div> </div> <div> <px-demo-snippet element-properties="[[elempropScale]]" element-name="px-vis-scale" code-link="http://codepen.io/menkhakl/pen/GjOVvr"> </px-demo-snippet> </div> </template> <script> Polymer({ is: "px-vis-scale-demo", properties:{ //basics width: { type : Number, value : 500 }, height:{ type : Number, value : 100 }, margin:{ type : Object, value : { "top": 10, "right": 10, "bottom": 10, "left": 10 } }, chartData:{ type : Array, value : [{ 'x': 1397102460000, 'y': 0.56 },{ 'x': 1397139660000, 'y': 0.4 },{ 'x': 1397177400000, 'y': 0.43 },{ 'x': 1397228040000, 'y': 0.33 },{ 'x': 1397248260000, 'y': 0.47 },{ 'x': 1397291280000, 'y': 0.41 },{ 'x': 1397318100000, 'y': 0.26 },{ 'x': 1397342100000, 'y': 0.42 },{ 'x': 1397390820000, 'y': 0.27 },{ 'x': 1397408100000, 'y': 0.38 },{ 'x': 1397458800000, 'y': 0.36 },{ 'x': 1397522940000, 'y': 0.32 }] }, seriesConfig:{ type : Object, value: { 'mySeries': { "name":"My-Series", "type": "line", "x": 'x', "y": 'y', 'color': "rgb(93,165,218)" } } }, //chartExtents chartExtents:{ type : Object, value: { "x": [Infinity,-Infinity], "y": [0,-Infinity] } }, // demo snippet elempropScale:{ type : Object, value:{ "xAxisType":"time", "yAxisType":"linear", "completeSeriesConfig":"[[seriesConfig]]", "chartExtents":"[[chartExtents]]", "width":"[[width]]", "height":"[[height]]", "margin":"[[margin]]", "chartData":"{{chartData}}", "x":"{{x}}", "y":"{{y}}", "currentDomainX":"{{currentDomainX}}", "currentDomainY":"{{currentDomainY}}", "selectedDomain":"[[selectedDomain]]" } } } }); </script> </dom-module>
// Arrays in JS - Basic Functions // The Array object is used to store multiple values in a single variable: // Full list of functions here: https://www.w3schools.com/js/js_array_methods.asp let students = ["Dimitar", "Ivan", "Sarah", "Nikola", "Jesus"]; // Arrays 101 - Push & Pop // Push adds new element and returns length of the array // Pop removes the last element of the array and returns it students.push("Kiril"); console.log(students); students.pop(); console.log(students); // Arrays 101 - slice (it's non-inclusive) console.log(students.slice(1, 3)); // Arrays 101 - splice(start, end, item1, item2, itemX) // WARNING: Splice overwrites the original array students.splice(0, 3, "Bob", "Andy"); console.log(students); // Arrays 101 - shift - removes first item of array and returns it // WARNING: shift overwrites the original array const firstStudent = students.shift(); console.log(firstStudent); // Arrays 101 - unshift - adds new elements to the beginning of an array // WARNING: unshift overwrites the original array students.unshift("Apple", "Banana", "Orange"); console.log(students); // Arrays 101 - join students.join(" | "); // Arrays 101 - fill students.fill("Mandarliev", 0, students.length); console.log(students); // Arrays 101 - length console.log(students.length); // Arrays 101 - toString console.log(students.toString()); // Arrays 101 - recerse students = ["Dimitar", "Ivan", "Sarah", "Nikola", "Jesus"]; console.log(students.reverse()); // Arrays 101 - contact let moreStudents = ['Andy', 'Andrew', 'Stefani']; const allStudents = students.concat(moreStudents).concat(['Andy']) console.log(allStudents);
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pyerima <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/10/23 16:02:38 by mbartos #+# #+# */ /* Updated: 2024/01/30 11:50:49 by pyerima ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_H # define LIBFT_H # include <stddef.h> # include <stdlib.h> # include <unistd.h> # include <stdarg.h> # include <stdint.h> # include <fcntl.h> # ifndef BUFFER_SIZE # define BUFFER_SIZE 1 # endif typedef struct s_list { void *content; struct s_list *next; } t_list; int ft_atoi(const char *str); void ft_bzero(void *s, size_t n); void *ft_calloc(size_t count, size_t size); int ft_isalnum(int c); int ft_isalpha(int c); int ft_isascii(int c); int ft_isdigit(int c); int ft_isprint(int c); void *ft_memchr(const void *s, int c, size_t n); int ft_memcmp(const void *s1, const void *s2, size_t n); void *ft_memcpy(void *dest, const void *src, size_t n); void *ft_memmove(void *dest, const void *src, size_t n); void *ft_memset(void *s, int c, size_t n); char *ft_strchr(const char *s, int c); char *ft_strdup(const char *str); size_t ft_strlcpy(char *dst, const char *src, size_t size); size_t ft_strlcat(char *dest, const char *src, size_t size); size_t ft_strlen(const char *s); int ft_strncmp(const char *s1, const char *s2, size_t n); char *ft_strnstr(const char *str, const char *to_find, size_t len); char *ft_strrchr(const char *s, int c); int ft_tolower(int c); int ft_toupper(int c); char *ft_substr(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); char *ft_strtrim(char const *s1, char const *set); char **ft_split(char const *s, char c); char *ft_itoa(int n); char *ft_strmapi(char const *s, char (*f)(unsigned int, char)); void ft_striteri(char *s, void (*f)(unsigned int, char*)); void ft_putchar_fd(char c, int fd); void ft_putstr_fd(char *s, int fd); void ft_putendl_fd(char *s, int fd); void ft_putnbr_fd(int n, int fd); t_list *ft_lstnew(void *content); void ft_lstadd_front(t_list **lst, t_list *new); int ft_lstsize(t_list *lst); t_list *ft_lstlast(t_list *lst); void ft_lstadd_back(t_list **lst, t_list *new); void ft_lstdelone(t_list *lst, void (*del)(void*)); void ft_lstclear(t_list **lst, void (*del)(void*)); void ft_lstiter(t_list *lst, void (*f)(void *)); t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)); void ft_type_choose(char type, va_list args, int *ptr_sum); int ft_printf(const char *str, ...); void ft_putchar_c(char c, int *ptr_sum); void ft_putnbr_c(int n, int *ptr_sum); void ft_putunsnbr(unsigned int n, int *ptr_sum); void ft_puthexa(unsigned int n, char hex_base, int *ptr_sum); void ft_putpointer(void *ptr, int *ptr_sum); void ft_put_ptr_hexa_adress(unsigned long number, int *ptr_sum); void ft_putstr_c(char *s, int *ptr_sum); char *get_next_line(int fd); #endif
//used to show all alerts images (myalert, autoalert) for the given duration selected for each camera //each cam has its name, then images, then a limiter seperating it //"useRemoveScroll" removes scroll on page if data is absent //contains action "getDurationTime" in reducer "investigationReducer" //component reruns when "getDurationTime" action changes redux state of "investigation.durationTime" //"getDurationTime" action is called on select change in Tabs.jsx //response.data.alert has structure as //[ { cameraName: "cam801", //images: [ "image_url",... ] } ] //to be noted //e.image is absent in node.js api creation hence the code for it is useless import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; import axios from "axios"; import useRemoveScroll from "../../../hooks/useRemoveScroll"; // import "./recentAlert.scss"; import './styles/recentAlert.scss' import CameraAlertBox from "./subComponents/CameraAlertBox"; import NotFound from "../../common/notFound"; import { CircularProgress } from '@mui/material'; import Box from '@mui/material/Box'; // main component const RecentAlerts = () => { //redux state of durationTime let durationTime = useSelector( (state) => state.investigation.durationTime ); const [allRecentAlertsList, setAllRecentAlertsList] = useState([]); //data to be displayed const [loader, setLoader] = useState(false); function toDataUrl(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function () { var reader = new FileReader(); reader.onloadend = function () { callback(reader.result); }; reader.readAsDataURL(xhr.response); }; xhr.open("GET", url); xhr.responseType = "blob"; xhr.send(); } //get all alert images(myalert and autoalert) const getAllAlert = () => { setLoader(true) //shows spinner in ui when fetching data let durationTime2 = 1; //default duration time 1 hour if (durationTime) { durationTime2 = Number(durationTime); //modify duration time to new time(string) if its truthy } //url in axios.get() takes cuurent duration time(durationTime2) as '1' or '2' or '3' or '4' let react_app_base_url = `${process.env.REACT_APP_BASE_URL_PROTOCOL}://${window.location.hostname}:${process.env.REACT_APP_BASE_URL_PORT}`; axios .get(`${react_app_base_url}${process.env.REACT_APP_RECENT_ALERTS}${durationTime2}`) .then( (response) => { //used to get img from url, but not used as "e.image" is absent response.data.alert.forEach((e) => { if (e.image != null && e.image != '') { toDataUrl(e.image, async function (myBase64) { e.base_url = await myBase64; e.Results = Array.isArray(e.Results) //found "e.Results" unused anywhere ? e.Results.flat(1) // [[0, 1], [2, 3]] --> [0, 1 ,2, 3] : `${e.Results[0].x[0]} ${e.Results[0].x[1]},${e.Results[0].y[0]} ${e.Results[0].y[1]} ,${e.Results[0].w[0]} ${e.Results[0].w[1]},${e.Results[0].h[0]} ${e.Results[0].h[1]}`; }); } }); setAllRecentAlertsList(response.data.alert); //set new state on duration time change let mapData = []; //used to create and array of objects of structure [ {cameraName: 'camera_name', cameraDetail:[...] }] //found unused for (let i = 0; i < response.data.alert.length; i++) { if (response.data.alert[i].image != null && response.data.alert[i].image != '') { let filteredData = response.data.alert.filter((data) => { return response.data.alert[i].camera_name === data.camera_name; }); mapData.push({ cameraName: response.data.alert[i].camera_name, cameraDetail: filteredData, //array containing data only for current "i" camera_name }); } } //found unused //// [...["cameraName", {...}].values(), ] //if correct should return an array of objects [{}, {}, ...] let arrayUniqueByKey = [ ...new Map( mapData.map((item) => [item["cameraName"], item]) ).values(), ]; //found unused //modify array of objects by adding "isShowFlag" property to each object setTimeout(() => { arrayUniqueByKey = arrayUniqueByKey.map((data) => { data.isShowFlag = false data.cameraDetail.map((detail) => detail?.Results?.length > 0 ? data.isShowFlag = true : data.isShowFlag = false ) return data }) // setAIFrames(arrayUniqueByKey); setLoader(false) }, 1000); }, (error) => { setLoader(false) } ); }; //runs on first render only useEffect(() => { getAllAlert(); }, []); //used to remove class "hide-scrollbar" added on monitor/active & spotlight but does not work useEffect(() => { var element = document.getElementById("body-tag"); element.classList.remove("hide-scrollbar"); }, []) //reruns to fetch new data on durationTime change in select dropdown useEffect(() => { getAllAlert(); }, [durationTime]); //used to remove scroll when "allRecentAlertsList" array length is 0 useRemoveScroll(allRecentAlertsList); //jsx returned for RecentAlerts return ( <> {loader ? ( <Box position="absolute" top="50%" left="50%" transform="translate(-50%, -50%)" > <CircularProgress /> </Box> ) : ( <> <div className="recentAlert"> <div className="mt-5 mx-0" //display cameraName > {!loader && allRecentAlertsList?.length > 0 ? //if loding OR no Data --> show not found allRecentAlertsList.map((data, i) => <CameraAlertBox data = {data} key = {i} indexed = {i} />) : <div className="my_alert_not_found my-5"> <NotFound/> </div> } </div> </div> </> )} </> ) }; export default RecentAlerts;
// Copyright (C) 2020 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only import QtQuick import QtQuick3D import QtQuick.Window import "qml" Rectangle { width: 600 height: 480 color: Qt.rgba(0, 0, 0, 1) View3D { id: layer anchors.fill: parent environment: SceneEnvironment { clearColor: Qt.rgba(0, 0, 0, 1) } PerspectiveCamera { id: camera position: Qt.vector3d(0, 0, 350) clipFar: 5000 } DirectionalLight { } // Model with animated texture Model { x: -100 y: 100 eulerRotation: Qt.vector3d(20, 40, 0) source: "#Cube" DefaultMaterial { id: myMaterial diffuseMap: Texture { id: myTexture sourceItem: AnimatedItem { id: myItem } } } materials: [myMaterial] } // Model using the same material Model { x: 100 y: 100 eulerRotation: Qt.vector3d(20, 40, 0) source: "#Cube" materials: myMaterial } // Model using the same texture Model { x: -100 y: -100 eulerRotation: Qt.vector3d(20, 40, 0) source: "#Cube" materials: DefaultMaterial { diffuseMap: myTexture } } // Model using the same item Model { x: 100 y: -100 eulerRotation: Qt.vector3d(20, 40, 0) source: "#Cube" materials: DefaultMaterial { diffuseMap: Texture { // Note: Flipping the texture this time sourceItem: myItem flipV: true } } } } }