text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <x-app-layout> <x-slot name="header"> <head> <meta charset="utf-8"> <title>Blog</title> <!-- Fonts --> <link href="https://fonts.bunny.net/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet"> </head> <h2 class="font-semibold text-xl text-gray-800 leading-tight"> {{ __('Index') }} </h2> </x-slot> <body class="antialiased"> <h1>Blog Name</h1> <a href="/posts/create">[create]</a> <div class='posts'> @foreach($posts as $post) <div class='post'> <a href="/posts/{{$post->id}}"><h2 class='title'>{{ $post->title }}</h2></a> <a href="/categories/{{ $post->category->id }}">{{ $post->category->name }}</a> <p class='body'>{{ $post->body }}</p> <form action="/posts/{{$post->id}}" id="form_{{$post->id}}" method="post"> @csrf @method('DELETE') <button type="button" onclick="deletePost({{$post->id}})">delete</button> </form> </div> @endforeach <br> ログインユーザー:{{ Auth::user()->name }} </div> <div class='paginate'>{{ $posts->links()}}</div> <script> function deletePost(id){ 'use strict' if(confirm('削除すると復元できません。\n本当に削除しますか?')){ document.getElementById(`form_${id}`).submit(); } } </script> </body> </x-app-layout> </html>
const request = require('supertest') const app = require('../../src/app') const connection = require('../../src/database/connection') describe('ONG', ()=>{ beforeEach(async ()=>{ await connection.rollback() await connection.migrate.latest() }) afterAll(async ()=>{ await connection.destroy() }) it('Should be able to create a new ONG', async ()=>{ const response = await request(app) .post('/ongs') .send({ name: 'APAD', email: 'contato@hotmail.com', whatsapp: '00000000000', city: 'Rio', uf: 'SC' }) expect(response.body).toHaveProperty('id') }) })
import { ChangeEvent, FormEvent, useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import '../css/Signup.css'; import Footer from './Footer'; interface SignupProps { showAlert: (type: string, message: string) => void; } export const Signup: React.FC<SignupProps> = ({ showAlert }) => { const navigate = useNavigate(); useEffect(() => { document.title = "eNotepad - Signup"; }, []); // Empty dependency array to avoid continuous re-rendering const [formData, setFormData] = useState({ name: '', email: '', password: '', cpassword: '', }); const handleOnSubmit = async (event: FormEvent<HTMLFormElement>) => { event.preventDefault(); // Prevent page reload const { name, email, password, cpassword } = formData; if (password !== cpassword) { showAlert('danger', 'Passwords do not match!'); return; } try { const response = await fetch(`${process.env.REACT_APP_API_URL}/auth/signup`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ name, email, password }), }); if (response.ok) { const responseJson = await response.json(); localStorage.setItem('token', responseJson.data.authToken); // Store auth token navigate('/'); // Navigate to home page showAlert('success', 'Registered successfully!'); } else { const errorData = await response.json(); showAlert('danger', errorData.message); // Show error message } } catch (error) { showAlert('danger', 'An error occurred during signup.'); } }; const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => { const { name, value } = event.target; setFormData((prevFormData) => ({ ...prevFormData, [name]: value, })); }; return ( <div> <div className="signup-container"> <h2>Signup for eNotepad</h2> {/* Improved heading */} <form className="signup-form my-4" onSubmit={handleOnSubmit}> {/* Name Input */} <div className="form-group"> <label htmlFor="name" className="form-label">Name</label> <input type="text" className="form-input" id="name" name="name" value={formData.name} onChange={handleInputChange} minLength={3} required /> </div> {/* Email Input */} <div className="form-group"> <label htmlFor="email" className="form-label">Email Address</label> <input type="email" className="form-input" id="email" name="email" value={formData.email} onChange={handleInputChange} required /> </div> {/* Password Input */} <div className="form-group"> <label htmlFor="password" className="form-label">Password</label> <input type="password" className="form-input" id="password" name="password" value={formData.password} onChange={handleInputChange} minLength={6} required /> </div> {/* Confirm Password Input */} <div className="form-group"> <label htmlFor="cpassword" className="form-label">Confirm Password</label> <input type="password" className="form-input" id="cpassword" name="cpassword" value={formData.cpassword} onChange={handleInputChange} required /> </div> {/* Submit Button */} <button type="submit" className="submit-btn">Register</button> </form> </div> <Footer /> </div> ); };
module.exports = () => { const { isNumber, log, warn, isFalsy, isObject } = require('x-utils-es/umd') const config = require('../config') const { readFile, writeFile } = require('x-fs')({ dir: config.memoryPath, ext: '.json', silent: true }) const Helpers = require('./Walle.helpers')() return class Walle extends Helpers { constructor(opts, debug) { super(opts, debug) /// set commands this.initCommands() } /** * - set start position * - set commands * - if memory/state was set update current state * - do not set initial state if memory was enabled */ initCommands() { if (this.options.memory) { if (this.debug) log('walle memory/state is enabled') let availState = readFile('walle_state') || {} if (!isFalsy(availState)) { this.commands = this.schema.commands this.updateState(availState) } else this.commands = [].concat(this.startPosition, this.schema.commands || []) } else { this.commands = [].concat(this.startPosition, this.schema.commands || []) } } updateState(availState = {}) { if (isNumber(availState.x) && isNumber(availState.y) && isObject(availState.direction)) { this.x = availState.x this.y = availState.y this.directionNum = availState.direction.value this.state = availState if (this.debug) log('walle memory/state updated') } } /** * @output * - get latest walking output */ output() { return { X: this.state.x, Y: this.state.y, Direction: this.state.direction.name } } print() { let o = this.output() return `X: ${o.X} Y: ${o.Y} Direction: ${o.Direction}` } /** * - operational data for walle, * - source file `Schema.js` * @returns {commands, operators} */ get schema() { return this.options.schema } /** * @state * - keep last state of walle */ set state(v) { this._state = v } get state() { return this._state } set commands(v) { this._commands = v } /** * @commands * example: this.schema.commands >> [ { o: 'R', val: 90, inx: 1 }, // RIGHT { o: 'L', val: -90, inx: 10 } // LEFT { o: 'W', val: 5, inx: 2 }, // moving ] @returns [] */ get commands() { return this._commands } /** * @walk * wall-e walks :) * - loop thru each command */ walk() { if(this.debug) log('Walle starting to walk...') this.commands.forEach(({ o, val, inx }, i) => { // direction if (o === 'R' || o === 'L') this.directionNum = val // walking walue if (o === 'W') { if (this.direction.coordinates === 'y') { if (this.direction.pos === '+') this.y += val if (this.direction.pos === '-') this.y -= val } if (this.direction.coordinates === 'x') { if (this.direction.pos === '+') this.x += val if (this.direction.pos === '-') this.x -= val } } // set last recorded state this.state = { x: this.x, y: this.y, direction: this.direction } if (this.debug) { if (inx === -1) log('Walle walking, start position', this.output()) log('Walle walking', this.output()) } }) if (this.options.memory) writeFile('walle_state', this.state) return this } /** * map assigned directionNum to cardinals * @returns {name, value,coordinates,pos} last direction */ get direction() { let d = this.cardinals.filter(({ name, value, coordinates, pos }) => { if (this.directionNum === value) return { name, value, coordinates, pos } })[0] if (!d) { warn('invalid direction', this.directionNum) return {} } return d } } }
#include "GameOverState.h" #include <iostream> #include "Game.h" #include "MainMenuState.h" #include "GameState.h" using namespace std; // Begin GameOverState void GameOverState::Enter() { cout << "Entering GAME END..." << endl; m_vButtons.push_back(new Button("Assets/Sprites/replaySprite.png", { 0,0,440, 128 }, { 400,200,220,80 })); m_vButtons.push_back(new Button("Assets/Sprites/exit.png", { 0,0,400,100 }, { 400,512,200,50 })); m_pFont = TTF_OpenFont("Assets/Fonts/OrbitRegular.ttf", 40); } void GameOverState::Update() { // Update buttons. Allows for mouseovers. for (int i = 0; i < (int)m_vButtons.size(); i++) m_vButtons[i]->Update(); //else if exit was clicked, we need to go back to main menu if (m_vButtons[btn::restart]->Clicked()) { Game::Instance()->GetFSM()->Clean(); // Clear all states, including GameState on bottom. //start a new game Game::Instance()->GetFSM()->ChangeState(new GameState()); } //else if exit was clicked, we need to go back to main menu else if (m_vButtons[btn::exit]->Clicked()) { Game::Instance()->GetFSM()->Clean(); // Clear all states, including GameState on bottom. //go back to main menu Game::Instance()->GetFSM()->ChangeState(new MainMenuState()); } } void GameOverState::Render() { //Game::Instance()->GetFSM()->GetStates().front()->Render(); //SDL_SetRenderDrawBlendMode(Game::Instance()->GetRenderer(), SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(Game::Instance()->GetRenderer(), 0, 180, 171, 128); //draw background SDL_Rect rect = { 128, 128, 768, 512 }; SDL_RenderFillRect(Game::Instance()->GetRenderer(), &rect); //draw the buttons for (int i = 0; i < (int)m_vButtons.size(); i++) m_vButtons[i]->Render(); //draw fonts string s = "-[. CLEAR .]-"; RenderFont(true, s.c_str(), 380, 320); string s1 = "SCORES: " + to_string(highScore); RenderFont(true, s1.c_str(), 380, 400); ScreenState::Render(); } void GameOverState::Exit() { cout << "Return to main..." << endl; for (int i = 0; i < (int)m_vButtons.size(); i++) { delete m_vButtons[i]; m_vButtons[i] = nullptr; } m_vButtons.clear(); m_vButtons.shrink_to_fit(); }
import numpy as np import sympy as sy from scipy import misc """ 1. sympy 计算导函数 """ x, y = sy.symbols('x, y') f = x ** 2 * sy.sin(x) print(sy.diff(f, x, 1)) # 一阶导函数,参数(方程,自变量,阶数) print(sy.diff(f, x, 2)) # 二阶导函数 f = x + y + x*y + sy.sin(x*y) print(sy.diff(f, x, 1, y, 2)) # 偏导数,对 x 求 一阶导,对 y 求二阶导 """ 2. 计算导数值 """ """ 方法 1:利用 sympy 求出导函数,然后计算导数值 """ """ 方法 2:利用 scipy,过程如下:""" # step 1:定义函数 def f(x, a, b, c): return a * x ** 2 + b * x + c # step 2:计算一阶导数值 x = np.linspace(0, 10, 11) drv = misc.derivative(f, x, args=(1,2,3), dx=1e-6) print(drv)
"use client"; import React, { useEffect, useRef, useState } from "react"; import { Button, Col, Drawer, FloatButton, Grid, Menu, Modal, Popconfirm, Row, Tooltip, Typography } from "antd"; import { Virtuoso, VirtuosoHandle } from "react-virtuoso"; import { useBoolean } from "ahooks"; import clsx from "clsx"; import Link from "next/link"; import { range } from "lodash"; import { MenuOutlined, PlayCircleFilled, ReadOutlined } from "@ant-design/icons"; import Verse from "@/components/Verse"; import PlayForm, { PlayConfig } from "@/components/PlayForm"; import AudioBar from "@/components/AudioBar"; import lf from "@/utils/localforage"; interface Props { chapter: Chapter; leftContent: VerseText[][]; rightContent: VerseText[][]; chapters: { chapters: Chapter[] }; versesRecitations: { id: number; url: string; verse_key: string }[]; recitations: GetRecitationsResponse; playerSettings: PlaySettings; } const Chapter: React.FC<Props> = ({ chapter: currentChapter, chapters, leftContent, rightContent, versesRecitations, recitations, playerSettings, }) => { const responsive = Grid.useBreakpoint(); const chapterNumber = currentChapter.id; const [readerMode, setReaderMode] = useState<"reading" | "recitation">("reading"); const [chaptersDrawerOpen, { setTrue: openChaptersDrawer, setFalse: closeChaptersDrawer }] = useBoolean(false); const [playModalOpen, { setTrue: openPlayModal, setFalse: closePlayModal }] = useBoolean(false); const [hasRestoredProgress, setHasRestoredProgress] = useState(false); const virtualListRef = useRef<VirtuosoHandle>(null); const [faves, setFaves] = useState<string[]>([]); const [playbackConfig, setPlaybackConfig] = useState<PlayConfig>({ ...playerSettings, start: 1, end: currentChapter.verses_count, }); const [isPlayingVerses, setIsPlayingVerses] = useState(false); const [playingVerseNumber, setPlayingVerseNumber] = useState<number>(); const [muted, setMuted] = useState(false); const [volume, setVolume] = useState(1); React.useEffect(() => { lf.ready().then(() => { lf.getItem("faves-quran").then((favesData) => { if (typeof (favesData as string[])?.length === "number") { const surahFaves = (favesData as string[]).filter((f) => f.startsWith(`${chapterNumber}:`)); setFaves(surahFaves); } }); // sync localforage across tabs lf.configObservables({ crossTabNotification: true, crossTabChangeDetection: true, }); const ob = lf.newObservable({ key: "faves-quran", crossTabNotification: true, }); ob.subscribe({ next: (args) => { const surahFaves = args.newValue.filter((f: any) => f.startsWith(`${chapterNumber}:`)); setFaves(surahFaves); }, }); }); }, [chapterNumber]); // exit recitation mode if chapter changes useEffect(() => { setReaderMode("reading"); }, [chapterNumber]); // restore progress React.useEffect(() => { if (hasRestoredProgress || !virtualListRef.current) { return; } const key = `progress-surah-${chapterNumber}`; lf.ready().then(() => { lf.getItem(key).then((progress) => { // validation if (typeof progress === "number" && progress > 0 && progress <= currentChapter.verses_count) { virtualListRef.current?.scrollToIndex({ index: progress - 1, align: "start", behavior: "smooth", }); } }); }); setHasRestoredProgress(true); }, [virtualListRef.current]); const verseList: { left: VerseText[]; right: VerseText[] }[] = []; range(currentChapter.verses_count).forEach((i) => { const l = leftContent.map((c) => c?.[i]); const r = rightContent.map((c) => c?.[i]); // if (![...l, ...r].includes(undefined)) { verseList.push({ left: l as VerseText[], right: r as VerseText[] }); // } }); return ( <> <FloatButton.BackTop /> <Drawer placement="left" closable={false} bodyStyle={{ padding: 0 }} onClose={closeChaptersDrawer} open={chaptersDrawerOpen} > <Menu theme="dark" selectedKeys={[`${currentChapter.id}`]} mode="inline"> {chapters?.chapters.map((chapter) => ( <Menu.Item key={chapter.id} className="text-left" onClick={closeChaptersDrawer}> <Link href={`/chapters/${chapter.id}`}> <Tooltip overlayClassName="capitalize" title={chapter.translated_name.name} placement="right"> <Typography.Text className="capitalize"> <span className="mr-3">{chapter.id}</span> {chapter.name_simple} </Typography.Text> </Tooltip> </Link> </Menu.Item> ))} </Menu> </Drawer> <Modal destroyOnClose title="Play Options" onCancel={closePlayModal} open={playModalOpen} footer={null}> <PlayForm recitations={recitations} verseCount={currentChapter.verses_count} playSettings={playerSettings} onSubmit={(playerSettingsData) => { setReaderMode("recitation"); closePlayModal(); setPlaybackConfig(playerSettingsData); setIsPlayingVerses(true); }} /> </Modal> <div className="fixed top-16 shadow-md bg-444 w-full z-10"> <div className="flex items-stretch"> <div> <Button className={clsx("h-full border-none rounded-none", { "px-3": !responsive.md, })} onClick={openChaptersDrawer} > <MenuOutlined className="text-xl" /> {responsive.md && "Chapters"} </Button> </div> <div className="flex-grow p-3 text-center"> <Typography.Text ellipsis={{ tooltip: `${currentChapter.name_simple} - ${currentChapter.translated_name.name}`, }} className="capitalize text-lg" strong={responsive.md} > {currentChapter.name_simple} - {currentChapter.translated_name.name} </Typography.Text> </div> {readerMode === "reading" ? ( <div> <Button className={clsx("h-full border-none rounded-none", { "px-3": !responsive.md, })} onClick={openPlayModal} type="primary" > <PlayCircleFilled className="text-xl" /> {responsive.md && " Recite"} </Button> </div> ) : ( <div> <Popconfirm title="Stop recitation?" onConfirm={() => setReaderMode("reading")} okText="Yes" cancelText="No" placement="bottomRight" > <Button className={clsx("h-full border-none rounded-none", { "px-3": !responsive.md, })} type="primary" > <ReadOutlined className="text-xl" /> {responsive.md && " Read"} </Button> </Popconfirm> </div> )} </div> </div> <Row className="mt-13 py-6 flex-grow" justify="center"> <Col span={24}> <Virtuoso data={verseList} useWindowScroll ref={virtualListRef} // eslint-disable-next-line react/no-unstable-nested-components itemContent={(i) => { const item = verseList[i]; return ( <div key={i}> <Row justify="center"> <Col span={22} className="py-3" style={{ borderBottom: i === verseList.length - 1 ? undefined : "1px solid #666", }} > <Verse verseNumber={i + 1} chapterNumber={chapterNumber} faved={faves.includes(`${chapterNumber}:${i + 1}`)} totalVerses={currentChapter.verses_count} left={item.left} right={item.right} hideTafsirs={readerMode === "recitation" && playerSettings.hideTafsirs} audioUrl={versesRecitations?.find((a) => a.verse_key === `${chapterNumber}:${i + 1}`)?.url} onPlay={() => { setPlayingVerseNumber(i + 1); setIsPlayingVerses(false); }} onEnded={() => setPlayingVerseNumber(-1)} isPlaying={playingVerseNumber === i + 1} muted={muted} // setMuted={setMuted} volume={volume} // setVolume={setVolume} /> </Col> </Row> </div> ); }} /> </Col> </Row> <Drawer placement="bottom" open={readerMode === "recitation"} mask={false} height={48} headerStyle={{ display: "none" }} closeIcon={false} bodyStyle={{ padding: 0 }} > {readerMode === "recitation" && ( <AudioBar audioUrls={versesRecitations.slice(playbackConfig.start - 1, playbackConfig.end).map((a) => a.url)} start={playbackConfig.start} isPlaying={isPlayingVerses} setIsPlaying={setIsPlayingVerses} onOpenSettings={openPlayModal} muted={muted} setMuted={setMuted} volume={volume} setVolume={setVolume} virtualListRef={virtualListRef} /> )} </Drawer> </> ); }; export default Chapter;
# Optimizing DFS on Large Graphs using Bloom Filters & False +ve Caching ## Set Membership Problem in Computer Science Although we all know the various ways to represent a set, like the Roster Form or the Set Builder Form we studied in the field of Discrete Mathematics, storing sets in the computer's memory, in a way that its elements can be both inserted and accessed efficiently has proved to be very challenging due to the fundamental nature of tradeoffs between Space/Time Complexity. But the another often neglected factor while weighing such tradeoffs is Accuracy. We will introduce you to a Probabilistic Data Structure called a Bloom Filter and see the Discrete Math behind tuning their Accuracy and compare how they improve upon traditional non probabilistic, discrete Algorithms like Depth First Search on very large graphs. Towards the end we will draw some insights from the mathematical analysis to discuss optimization using caching. ## Representing a Set in the Computer's Memory To perform membership test on a set in the computer's memory, it's necessary to understand how a set is represented in the computer's memory in the first place. Based on which we can think of ways to perform the Set Membership test in an optimal way. The drawbacks of these approaches become clearer as the cardinality of the set grows and tends to a very large number\*. So we ask you to assume that we are dealing with sets of such large cardinalities for the sake of explanation and analysing worst case scenarios and bottlenecks. \*Not ∞ as we are dealing with finite memory, ≅ 2^64 -1 which is the maximum value an unsigned long long int can hold on 64 bit CPUs. ## Representing a Set as a Linear Array The naivest and least optimal way to represent a set in a computer's memory is by using an array because in the worst case we cannot conclude if an element belongs to a set till we reach and read the last element of the array. So the time taken by the Set Membership Test on a set represented as an array depends linearly on the cardinality of the set(N), leading to a O(N) Time and Space Complexity. - Insertion is an O(N) Operation too as we need to perform a set membership test prior to insertion to avoid inserting duplicate members in the set! At the end we can either be 0% or 100% sure if the element exists in the set. ## Representing a Set as a Balanced Binary Tree A more optimal way to represent a set in a computer's memory is by using a balanced binary tree because in the worst case we can conclude that an element doesn't belongs to a set if a node containing the same value doesn't exists in the tree in O(log N) Time.\* Insertion is an O(log n) operation too as maintaining the balanced binary tree invariant and performing set membership test to inserting duplicate members in the set takes O(log n) time. At the end we can either be 0% or 100% sure if the element exists in the set. Although O(log n) is relatively small even for large numbers, the devil lies in the inefficiencies of storing Trees in a computer's memory which is exacerbated when the entire set needs to be loaded into the RAM. Assuming that a the node of the balanced binary tree contains left and right pointers on a 64-Bit CPU Architecture, we can say that the smallest and the largest possible memory address will be 64 bit(8 bytes) long. So to store a 4 byte integer, we will have to spare 8+8=16 bytes for pointers to child nodes. - For a large set, the metadata will be 4 times the size of the data itself, which is unacceptable. - So we are trading space compactness to improve the Time Complexity from O(N) to O(log N). - Although we can represent the tree in an array, it will implicitly set an upper bound to the set's cardinality, hence leading to Amortized O(log N) Time Complexity.\* \*Inductive Proof: _[https://www\.cs\.cornell\.edu/courses/cs211/2006sp/Lectures/L06\-Induction/binary_search\.html](https://www.cs.cornell.edu/courses/cs211/2006sp/Lectures/L06-Induction/binary_search.html)_ \*As once in a while an insertion will be O(N) instead of O(log N) due to overhead of copying all existing elements into the larger array. ## Understanding Google's Bottleneck There are around 2 Billion Gmail IDs created till date, with a conservative estimate of each ID being 10 characters long where each character occupies a single byte in the computer's memory, to store all 2 billion email ids using a set implemented using a tree will require 20 Billion Bytes of data and 80 Billion Bytes of metadata even though there is no useful relationship between different gmail IDs(nodes). If a user wants to create a new ID, then Google verifies if the ID is already taken after every single keystroke! For such large datasets under such severe time constraints logarithmic time complexity can still fall short of expectation when it comes to testing for set membership of the user input in the gmail database(set of all IDs created till date, N=2 Billion) after every keystroke in a blink of an eye. ## Hashing: Optimizing Time at the cost of Space A hash function allows us to generate a mapping between a larger domain set and a smaller range set by bounding its result using the modulus operator % Suppose the domain is the set of all alphabets from A-Z and we want to create a set of alphabets that can store it's subset(range set). So we create an array of size 26+1 and use a hash function h(x) to generate a mapping between the domain and range such that: h(x) = 1 if x='A', 2 if x='B', 3 if x='C', 24 if x='X', 25 if x='Y', 26 if x='Z' ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM30.png) Now, to check the membership of any alphabet stored in variable char x, we again use the same hash function h(x) which tells us which index of the array needs to be checked, if the character stored at that index is same as x then we can conclude that x is a member of the set instead of having to read each element of the underlying linear array sequentially. The drawback to this approach is the wastage of space in the provisioned array, as the array should have a size equal to the cardinality N of the domain set regardless of the cardinality of the range set. So we get a O(1) time lookup a the cost of O(N) Space Complexity. A good hash function should ensure uniform distribution throughout the array. Still if the cardinality of the domain set is ∞(i.e. an infinite set) and the cardinality of the set to be stored is N such that N<<<∞, thenBy pigeon hole principle, number of pigeons=∞ but number of pigeonholes=N. So there must be more than one elements from domain set that can be mapped to the same index by h(x). - Such a situation is also called a Collision. In the previous example the domain set was a set of all alphabets so the cardinality of the domain was constant = 26. Hence we were able to avoid collisions due to a bijective hash function. - Now let's assume h(x) accepts a string and returns the (length of x)%10 that allows us to store the string x in the array of size 10 at that index - To insert the CAT in the null set, we store it in the 3rd index of the array of size 10 - Now h(x) will map any 3 letter word like DOG, RAT, etc. to the same 3rd index. - In fact all lengths with the digit 3 in the units place will be mapped to the 3rd index! - If CAT is stored at the 3rd index and we are asked if DOG is a member of the set then we can read the 3rd index and say that it doesn't store the word DOG inside it so DOG isn't a member of the set if DOG was never inserted after inserting CAT. - Inserting words like DOG, RAT would lead to collision and require resolution methods. - At the end we can either be 0% or 100% sure if the element exists in the set. - We can use collision resolution methods and multiple hash functions to reduce the number of collisions but cannot entirely avoid it for infinite domain sets. - But we will still require to store the entire object in the indices of the array. - This is the reason behind the atomic nature of the accuracy(assuming no collisions). - Bloom filters don't store the entire object in the indices of their underlying array, which drops the atomic nature of the accuracy, making the data structure probabilistic instead of deterministic thereby providing exceptional space complexity and compactness without coming at the cost of time complexity. - This also exposes several variables that can be tuned to set the expected accuracy of the bloom filter. ## Bloom Filters: Optimizing Space at the cost of Accuracy So what exactly are we storing in the bloom filter if not the elements themselves? Well the bloom filter is a very large array of bits(0s & 1s) where a bit is set to 1 acts as a beacon to mark the probable existence of an element. While the 0s mark the guaranteed absence of an element from the set. It's cheaper to create such a large sized array of bits as each index can either store a 0 or a 1 which is 1 bit long, compared to an array of integers where every index is 32 bits(4 bytes) long. The size of a fundamental block that can be wasted is reduced from 32 bits to 1 bit. The accuracy can be improved by using multiple hash functions. ## Working of Bloom Filters ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM31.png) ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM32.png) If h1(z) or h2(z) point to an index storing 0, then surely z isn't a member of the set. Hence there are no False -ve and only True -ve. ## Tunable parameters of Bloom Filters The load factor of a bloom filter = number of 1s/size of bloom filter When the load factor is 1, all bits are set to 1 so the False Positivity Rate is 100% If the load factor is > 0.5, we should increase the size of bloom filter and rehash all the elements. Hence we will require another copy of all the data. A Bloom filter has two main components: A bit array A[0..m-1] with all slots initially set to 0, k hash functions h1,h2,…,hk, each mapping keys onto a range [0, m −1] A Bloom filter has two tunable parameters: n: max items in the bloom filter at any given time, p: your acceptable false positive rate {0..1} (e.g. 0.01 → 1%) The number of bits needed in the bloom filter: m = -n \* ln(p) / (ln(2)^2) The number of hash functions we should apply: k = m/n \* ln(2) _[https://www\.di\-mgt\.com\.au/bloom\-calculator\.html](https://www.di-mgt.com.au/bloom-calculator.html)_ , _[https://hur\.st/bloomfilter/](https://hur.st/bloomfilter/)_ ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM33.png) ## False +ve Caching of Bloom Filters We can find the lower limit to the number of false positives = np So we can store False +ve results in a linked list, and whenever the bloom filter returns TRUE we can check if we are dealing with a false +ve or not, if we are then we return FALSE and move the node in cache to head so that it can be queried faster next time, thereby implicitly moving the least frequently queried cached items towards the tail. If a False +ve is found even after checking the cache then it gets cached by inserting itself at the head. The limitation of the approach is that if new data is to be inserted in the bloom filter we need to make sure that it is not cached as a False +ve, if it is we need to remove it from the cache. Hence it's preferable to have False +ve caching for fixed sized sets(CDNs). ## Application Of Bloom Filters For any company dealing with huge datasets, if they want to check if something doesn't exists in their database without reading the entire database can use bloom filters. They will significantly reduce the unnecessary reads on the database as the database will only be read if there is a high probability that the query exists in the database. It can be used to detect weak passwords while creating a new password. A bloom filter of malware signatures can detect similar malware. Google Chrome uses Bloom Filter to check if an URL is a threat or not. If Bloom Filter says that it is a threat, then it goes to another round of testing before alerting the user. ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM34.png) ## Designing a graph for demonstration We initially build a graph that is represented as an Adjacency List where each node stores a number and points directly to all its factors. - This simple yet powerful model allows to to easily scale up the cardinality. Then we create a bloom filter for every row in the adjacency list by inserting all factors of the node in the bloom filter for the corresponding node. Then we compress the adjacency list by removing redundancies.\*\* - Example earlier 8 would point to both 4 and 2 while 4 would also point to 2. - After compressing, 8 will only point to 4 while 4 will point to 2. ## Checking if 3 is a factor of 24 using DFS - We start at node 24 and find out that it points to node 8 & 12. - We go to node 8 which points to node 4 and the node 4 points to the node 2. - Node 2 is a leaf node as it's a prime number, so backtrack. - Backtracking from 2, 4 & 8 we reach 24, node 12 on its right points to 4 and 6. - We go to node 4 which points to the node 2. - Node 2 is a leaf node as it's a prime number, so backtrack. - Backtracking from 2, 4 we reach 12, node 6 on its right points to 2 and 3. - Node 2 is a leaf node as it's a prime number, so backtrack. - So we backtrack to 6 and explore its right node 3. - We found 3 by doing a DFS from 24, so 3 must be a factor of 24! ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM35.png) ## Checking if 3 is a factor of 24 using Bloom Filters & False +ve Caching - We ask the bloom filter stored inside node 24 if 3 is its member. - If it says False, means that 3 is definitely not a factor of 24. - If it says True, it's a probable true and could be a false +ve. - If the 3, 24 is a cached false +ve then 3 is definitely not a factor of 24. - We move the node in the cache holding 3, 24 to the head of the list. - Else we perform a DFS - If the DFS from 24 finds 3 then we can say 3 is a factor of 24. - Else we found a false +ve that is not in cache. - So we create a new node containing 3, 24 and insert it at head. - And we can say that 3 is not a factor of 24. - So over a period of time, if the bloom filters doesn't change, we will be able to cache all possible False +ves and the DFS will run only when it's almost certain that the queried element is a member of the set, so if some associated details are also stored for that member they can be returned efficiently with quicker misses. ## Measuring Improvements from Bloom Filters & False +ve Caching ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM36.png) ![](assets/Copy%20of%20DM_DSA%20PPT%20SEM37.png) Link to code: <span style="color:#0000FF"> _https://github\.com/JayaswalPrateek/DFSusingBloomFilter_ </span> ## References _[https://en\.wikipedia\.org/wiki/Bloom_filter](https://en.wikipedia.org/wiki/Bloom_filter)_ _[https://llimllib\.github\.io/bloomfilter\-tutorial/](https://llimllib.github.io/bloomfilter-tutorial/)_ _[https://www\.youtube\.com/watch?v=RSwjdlTp10](https://www.youtube.com/watch?v=RSwjdlTp108)_ _[8](https://www.youtube.com/watch?v=RSwjdlTp108)_ _[https://www\.youtube\.com/watch?v=kfFacplFY4Y](https://www.youtube.com/watch?v=kfFacplFY4Y)_ _[https://www\.youtube\.com/watch?v=mItewjU\-YG8](https://www.youtube.com/watch?v=mItewjU-YG8)_ _[https://stackoverflow\.com/questions/658439/how\-many\-hash\-functions\-does\-my\-bloom\-filter\-need](https://stackoverflow.com/questions/658439/how-many-hash-functions-does-my-bloom-filter-need)_ _[https://hackernoon\.com/probabilistic\-data\-structures\-bloom\-filter\-5374112a7832](https://hackernoon.com/probabilistic-data-structures-bloom-filter-5374112a7832)_ _[https://freecontent\.manning\.com/all\-about\-bloom\-filters/](https://freecontent.manning.com/all-about-bloom-filters/)_ _[https://systemdesign\.one/bloom\-filters\-explained/](https://systemdesign.one/bloom-filters-explained/)_ _[https://www\.enjoyalgorithms\.com/blog/bloom\-filter](https://www.enjoyalgorithms.com/blog/bloom-filter)_ _[https://redis\.io/docs/data\-types/probabilistic/bloom\-filter/](https://redis.io/docs/data-types/probabilistic/bloom-filter/)_ _[https://www\.spiceworks\.com/tech/big\-data/articles/what\-is\-a\-bloom\-filter/](https://www.spiceworks.com/tech/big-data/articles/what-is-a-bloom-filter/)_
import { useState } from "react"; import axios from 'axios' import { unauthRedirect } from "../../middlewares/authRedirect"; import Router from "next/router"; const PostTambah = ({token}) => { const [judul,setJudul] = useState('') const [isi,setIsi] = useState('') const handleSubmit = async (e) => { e.preventDefault() const {data: {data}} = await axios.post('/api/post',{title : judul,content : isi},{ headers : { "Authorization" : `Bearer ${token}` } }) setJudul('') setIsi('') Router.push('/post') } return ( <form onSubmit={handleSubmit}> <label htmlFor="judul">judul</label> <input type="text" id="judul" onChange={e => setJudul(e.target.value)} placeholder='judul' value={judul}/><br /> <textarea id="" cols="30" rows="10" placeholder="Isi" onChange={e => setIsi(e.target.value)} value={isi}></textarea> <button type="submit">Tambah</button> </form> ); } export default PostTambah; export async function getServerSideProps(context){ const {token} = unauthRedirect(context) return {props : {token}} } /* oke jadi kita check dulu ya seperti biasa apa dia sudah login atau belum kalo sudah kita kirimkan tokennya ke componentnya ya lalu kita lakukan post pada component client setelah ditambah kita bisa tambahkan redirect kehalaman post oke jadi seperti itu ya logic yang sederhana untuk membuat halaman post mudah mudahan kalian paham */
using System; using EasyAbp.PaymentService.Payments; using Volo.Abp.ObjectExtending; using Volo.Abp.Threading; namespace EasyAbp.PaymentService.Prepayment.ObjectExtending { public static class PaymentServicePrepaymentDomainObjectExtensions { private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner(); public static void Configure() { OneTimeRunner.Run(() => { /* You can configure extension properties to entities or other object types * defined in the depended modules. * * If you are using EF Core and want to map the entity extension properties to new * table fields in the database, then configure them in the PaymentServiceSampleEfCoreEntityExtensionMappings * * Example: * * ObjectExtensionManager.Instance * .AddOrUpdateProperty<IdentityRole, string>("Title"); * * See the documentation for more: * https://docs.abp.io/en/abp/latest/Object-Extensions */ ObjectExtensionManager.Instance .AddOrUpdate(new[] { typeof(Payment) }, config => { config.AddOrUpdateProperty<Guid?>(PrepaymentConsts.PaymentAccountIdPropertyName); }); }); } } }
class Ability include CanCan::Ability def initialize(user) user ||= User.new # guest user (not logged in) if user.has_role? :admin can :manage, :all else can :read, :all can :new, :all can :create, :all can :manage, Content, user_id: user.id end # Define abilities for the passed in user here. For example: # # user ||= User.new # guest user (not logged in) # if user.admin? # can :manage, :all # else # can :read, :all # end # # The first argument to `can` is the action you are giving the user # permission to do. # If you pass :manage it will apply to every action. Other common actions # here are :read, :create, :update and :destroy. # # The second argument is the resource the user can perform the action on. # If you pass :all it will apply to every resource. Otherwise pass a Ruby # class of the resource. # # The third argument is an optional hash of conditions to further filter the # objects. # For example, here the user can only update published articles. # # can :update, Article, :published => true # # See the wiki for details: # https://github.com/CanCanCommunity/cancancan/wiki/Defining-Abilities end end
import NavBar from "../components/NavBar/NavBar"; import ItemListContainer from "../containers/ItemListContainer"; import CartView from "../components/CartView/CartView" import Order from "../components/Order/Order"; import{ BrowserRouter, Routes, Route } from 'react-router-dom' import ItemDetailContainer from "../components/ItemDetailContainer/ItemDetailContainer"; import { useCartContext } from "../components/CartContext/CartContext"; import Form from "../components/Form/Form" export default function Router (){ const { cartItemCount } = useCartContext() return( <BrowserRouter> <NavBar cartItemCount={cartItemCount} /> <Routes> <Route path='/' element={<ItemListContainer/>} /> <Route path='/category/:id' element={<ItemListContainer greeting="Products"/>} /> <Route path="/item/:itemId" element={<ItemDetailContainer />} /> <Route path="/cartview" element={<CartView />} /> <Route path="/order" element={<Order/>} /> <Route path="/form" element={<Form/>}/> </Routes> </BrowserRouter> ) }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { CombatComponent } from './combat/combat.component'; import { FicheComponent } from './fiche/fiche.component'; import { HomeComponent } from './home/home.component'; const routes: Routes = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'fiche/:id', component: FicheComponent }, { path: 'combat', component: CombatComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
# frozen_string_literal: true module Queries class Product::ProductSearch < Queries::BaseQuery argument :page, Integer, required: false argument :per_page, Integer, required: false argument :query, String, required: true type Types::Models::Product::PaginationType, null: false def resolve(**params) page = params[:page].present? ? params[:page] : 1 per_page = params[:per_page].present? ? params[:per_page] : 25 products = ::Product.search("#{params[:query]}").page(page).per(per_page) { products: products, total_pages: products.length / per_page, count: products.length } end end end
import { SObjectChildRelationship } from "."; import { Utils } from "../utils/utils"; import { RecordType } from "./recordType"; import { SObjectField } from "./sObjectField"; /** * Class to represent a SObject */ export class SObject { name: string; label: string; labelPlural?: string; keyPrefix?: string; custom: boolean; queryable: boolean; customSetting: boolean; namespace?: string; childRelationships: SObjectChildRelationship[]; fields: { [key: string]: SObjectField }; recordTypes: { [key: string]: RecordType }; description: string; /** * Create a SObject instance * @param {string | { [key: string]: any }} nameOrObject SObject API Name or SObject instance * @param {string} [label] SObject label * @param {string} [labelPlural] SObject plural label * @param {string} [keyPrefix] SObject key prefix * @param {boolean} [custom] True to set SObject as custom */ constructor(nameOrObject?: string | { [key: string]: any }, label?: string, labelPlural?: string, keyPrefix?: string, custom?: boolean) { if (nameOrObject && typeof nameOrObject !== 'string') { this.name = nameOrObject.name; this.label = nameOrObject.label; this.labelPlural = nameOrObject.labelPlural; this.keyPrefix = nameOrObject.keyPrefix; this.custom = (nameOrObject.custom !== undefined) ? nameOrObject.custom : false; this.queryable = (nameOrObject.queryable !== undefined) ? nameOrObject.queryable : true; this.customSetting = (nameOrObject.customSetting !== undefined) ? nameOrObject.customSetting : false; this.namespace = nameOrObject.namespace; this.fields = serializeFields(nameOrObject.fields); this.recordTypes = serializeRecordTypes(nameOrObject.recordTypes); this.childRelationships = serializeChildRelationships(nameOrObject.childRelationships); this.description = nameOrObject.description; } else { this.namespace = undefined; this.name = nameOrObject || ''; if (this.name) { let splits = this.name.split('__'); if (splits.length > 2) { this.namespace = splits[0].trim(); } } this.label = label || this.name; this.labelPlural = labelPlural; this.keyPrefix = keyPrefix; this.custom = (custom !== undefined) ? custom : false; this.queryable = true; this.customSetting = false; this.fields = {}; this.recordTypes = {}; this.childRelationships = []; this.description = ''; } } /** * Method to set SObject API Name * @param {string} name SObject API Name * * @returns {SObject} Return SObject instance */ setName(name: string): SObject { let splits = name.split('__'); let namespace = undefined; if (splits.length > 2) { namespace = splits[0].trim(); } if (namespace) { this.namespace = namespace; } this.name = name; return this; } /** * Method to set SObject label * @param {string} label SObject label * * @returns {SObject} Return SObject instance */ setLabel(label: string): SObject { this.label = label; return this; } /** * Method to set SObject plural label * @param {string} labelPlural SObject plural label * * @returns {SObject} Return SObject instance */ setLabelPlural(labelPlural: string): SObject { this.labelPlural = labelPlural; return this; } /** * Method to set SObject key preffix * @param {string} keyPrefix SObject key preffix * * @returns {SObject} Return SObject instance */ setKeyPrefix(keyPrefix: string): SObject { this.keyPrefix = keyPrefix; return this; } /** * Method to set SObject as queriable * @param {boolean} queryable true to set SObject as queriable * * @returns {SObject} Return SObject instance */ setQueryable(queryable: boolean): SObject { this.queryable = queryable; return this; } /** * Method to set SObject as custom * @param {boolean} custom true to set SObject as custom * * @returns {SObject} Return SObject instance */ setCustom(custom: boolean): SObject { this.customSetting = (custom !== undefined) ? custom : false; return this; } /** * Method to set SObject as custom * @param {string} customSetting true to set SObject as custom * * @returns {SObject} Return SObject instance */ setCustomSetting(customSetting: boolean): SObject { this.customSetting = (customSetting !== undefined) ? customSetting : false; return this; } /** * Method to set SObject namespace * @param {string} namespace true to set SObject as custom * * @returns {SObject} Return SObject instance */ setNamespace(namespace: string): SObject { this.namespace = namespace; return this; } /** * Method to add SObjectField to the SObject * @param {string} name SObject field API Name * @param {SObjectField} field SObject Field to add * * @returns {SObject} Return SObject instance */ addField(name: string, field: SObjectField): SObject { if (this.name) { if (field.type && field.type.toLowerCase() === 'hierarchy') { if (!field.referenceTo.includes(this.name)) { field.referenceTo.push(this.name); } field.type = 'Lookup'; } else if (field.type && (field.type.toLowerCase() === 'lookup' || field.type.toLowerCase() === 'reference') && field.name === 'ParentId') { field.type = 'Lookup'; field.referenceTo.push(this.name); } else if (field.type && (field.type.toLowerCase() === 'lookup' || field.type.toLowerCase() === 'reference') && field.name === 'OwnerId') { field.type = 'Lookup'; if (!field.referenceTo.includes('User')) { field.referenceTo.push('User'); } } else if (field.type && (field.type.toLowerCase() === 'number' || field.type.toLowerCase() === 'currency' || field.type.toLowerCase() === 'percent')) { field.type = 'Decimal'; } else if (field.type && (field.type.toLowerCase() === 'checkbox' || field.type.toLowerCase() === 'boolean')) { field.type = 'Boolean'; } else if (field.type && field.type.toLowerCase() === 'datetime') { field.type = 'DateTime'; } else if (field.type && field.type.toLowerCase() === 'location') { field.type = 'Location'; } else if (field.type && field.type.toLowerCase() === 'date') { field.type = 'Date'; } else if (field.type && (field.type.toLowerCase() === 'lookup' || field.type.toLowerCase() === 'reference')) { field.type = 'Lookup'; if (field.name.endsWith('Id')) { let obj = field.name.substring(0, field.name.length - 2); if (!field.referenceTo.includes(obj)) { field.referenceTo.push(obj); } } } else if (field.type && field.type.toLowerCase() === 'id') { field.type = 'Id'; } else if (field.type && field.type.toLowerCase() === 'double') { field.type = 'Double'; } else if (field.type && field.type.toLowerCase() === 'int') { field.type = 'Integer'; } else { field.type = 'String'; } } this.fields[name.toLowerCase()] = field; return this; } /** * Method get a SObjectField from SObject * @param {string} name SObject field API Name * * @returns {SObjectField | undefined} Return the selected SObjectField or undefined if not exists */ getField(name: string): SObjectField | undefined { if (!this.fields[name.toLowerCase()]) { return undefined; } return this.fields[name.toLowerCase()]; } /** * Method to add RecordType to the SObject * @param {string} devName RecordType Developer Name * @param {RecordType} recordType RecordType to add * * @returns {SObject} Return SObject instance */ addRecordType(devName: string, recordType: RecordType): SObject { this.recordTypes[devName.toLowerCase()] = recordType; return this; } /** * Method get a RecordType from SObject * @param {string} devName RecordType developer name * * @returns {SObjectField | undefined} Return the selected SObjectField or undefined if not exists */ getRecordType(devName: string): RecordType | undefined { if (!this.recordTypes[devName.toLowerCase()]) { return undefined; } return this.recordTypes[devName.toLowerCase()]; } /** * Method to add all system fields */ addSystemFields(): void { addSystemFieldsToSObject(this); } /** * Method to fix all field datatypes */ fixFieldTypes(): void { if (this.fields && Utils.hasKeys(this.fields)) { for (const fieldKey of Object.keys(this.fields)) { const field = this.fields[fieldKey]; if (field.type && field.type.toLowerCase() === 'hierarchy') { if (!field.referenceTo.includes(this.name)) { field.referenceTo.push(this.name); } this.fields[fieldKey].type = 'Lookup'; } else if (field.type && (field.type.toLowerCase() === 'lookup' || field.type.toLowerCase() === 'reference') && field.name === 'ParentId') { this.fields[fieldKey].type = 'Lookup'; this.fields[fieldKey].referenceTo.push(this.name); } else if (field.type && (field.type.toLowerCase() === 'lookup' || field.type.toLowerCase() === 'reference') && field.name === 'OwnerId') { this.fields[fieldKey].type = 'Lookup'; if (!field.referenceTo.includes('User')) { this.fields[fieldKey].referenceTo.push('User'); } } else if (field.type && (field.type.toLowerCase() === 'number' || field.type.toLowerCase() === 'currency' || field.type.toLowerCase() === 'percent')) { this.fields[fieldKey].type = 'Decimal'; } else if (field.type && (field.type.toLowerCase() === 'checkbox' || field.type.toLowerCase() === 'boolean')) { this.fields[fieldKey].type = 'Boolean'; } else if (field.type && field.type.toLowerCase() === 'datetime') { this.fields[fieldKey].type = 'DateTime'; } else if (field.type && field.type.toLowerCase() === 'location') { this.fields[fieldKey].type = 'Location'; } else if (field.type && field.type.toLowerCase() === 'date') { this.fields[fieldKey].type = 'Date'; } else if (field.type && (field.type.toLowerCase() === 'lookup' || field.type.toLowerCase() === 'reference')) { field.type = 'Lookup'; if (field.name.endsWith('Id')) { let obj = field.name.substring(0, field.name.length - 2); if (!field.referenceTo.includes(obj)) { this.fields[fieldKey].referenceTo.push(obj); } } } else if (field.type && field.type.toLowerCase() === 'id') { this.fields[fieldKey].type = 'Id'; } else if (field.type && field.type.toLowerCase() === 'double') { this.fields[fieldKey].type = 'Double'; } else if (field.type && field.type.toLowerCase() === 'int') { this.fields[fieldKey].type = 'Integer'; } else { this.fields[fieldKey].type = 'String'; } } } } } function addSystemFieldsToSObject(sObject: SObject): void { if (!sObject.fields['id']) { sObject.fields['id'] = new SObjectField('Id'); sObject.fields['id'].label = sObject.name + ' Id'; sObject.fields['id'].custom = false; sObject.fields['id'].length = 18; sObject.fields['id'].nillable = true; sObject.fields['id'].type = 'Id'; } if (!sObject.fields['isdeleted']) { sObject.fields['isdeleted'] = new SObjectField('IsDeleted'); sObject.fields['isdeleted'].label = 'Is Deleted'; sObject.fields['isdeleted'].custom = false; sObject.fields['isdeleted'].type = 'Boolean'; } if (!sObject.fields['createdbyid']) { sObject.fields['createdbyid'] = new SObjectField('CreatedById'); sObject.fields['createdbyid'].label = 'Created By'; sObject.fields['createdbyid'].custom = false; sObject.fields['createdbyid'].referenceTo = ['User']; sObject.fields['createdbyid'].type = 'Lookup'; } if (!sObject.fields['createddate']) { sObject.fields['createddate'] = new SObjectField('CreatedDate'); sObject.fields['createddate'].label = 'Created Date'; sObject.fields['createddate'].custom = false; sObject.fields['createddate'].type = 'DateTime'; } if (!sObject.fields['lastmodifiedbyid']) { sObject.fields['lastmodifiedbyid'] = new SObjectField('LastModifiedById'); sObject.fields['lastmodifiedbyid'].label = 'Last Modified By'; sObject.fields['lastmodifiedbyid'].custom = false; sObject.fields['lastmodifiedbyid'].nillable = true; sObject.fields['lastmodifiedbyid'].referenceTo = ['User']; sObject.fields['lastmodifiedbyid'].type = 'Lookup'; } if (!sObject.fields['lastmodifieddate']) { sObject.fields['lastmodifieddate'] = new SObjectField('LastModifiedDate'); sObject.fields['lastmodifieddate'].label = 'Last Modified Date'; sObject.fields['lastmodifieddate'].custom = false; sObject.fields['lastmodifieddate'].type = 'DateTime'; } if (!sObject.fields['systemmodstamp']) { sObject.fields['systemmodstamp'] = new SObjectField('SystemModStamp'); sObject.fields['systemmodstamp'].label = 'System Mod Stamp'; sObject.fields['systemmodstamp'].custom = false; sObject.fields['systemmodstamp'].type = 'DateTime'; } if (!sObject.fields['recordtypeid']) { sObject.fields['recordtypeid'] = new SObjectField('RecordTypeId'); sObject.fields['recordtypeid'].label = 'Record Type'; sObject.fields['recordtypeid'].custom = false; sObject.fields['recordtypeid'].type = 'Lookup'; sObject.fields['recordtypeid'].referenceTo = ['RecordType']; sObject.fields['recordtypeid'].nillable = false; } if (!sObject.fields['ownerid']) { sObject.fields['ownerid'] = new SObjectField('OwnerId'); sObject.fields['ownerid'].label = 'Owner'; sObject.fields['ownerid'].custom = false; sObject.fields['ownerid'].nillable = false; sObject.fields['ownerid'].referenceTo = ['User']; sObject.fields['ownerid'].type = 'Lookup'; } } function serializeFields(objects: any): { [key: string]: SObjectField } { const result: { [key: string]: SObjectField } = {}; if (objects) { if (Utils.isObject(objects)) { for (const objKey of Object.keys(objects)) { const item = new SObjectField(objects[objKey]); result[item.name.toLowerCase()] = item; } } else if (Utils.isArray(objects)) { for (const obj of objects) { const item = new SObjectField(obj); result[item.name.toLowerCase()] = item; } } } return result; } function serializeRecordTypes(objects: any): { [key: string]: RecordType } { const result: { [key: string]: RecordType } = {}; if (objects) { if (Utils.isObject(objects)) { for (const objKey of Object.keys(objects)) { const item = new RecordType(objects[objKey]); result[item.developerName.toLowerCase()] = item; } } else if (Utils.isArray(objects)) { for (const obj of objects) { const item = new RecordType(obj); result[item.developerName.toLowerCase()] = item; } } } return result; } function serializeChildRelationships(objects: any): SObjectChildRelationship[] { const result: SObjectChildRelationship[] = []; if (objects) { for (const obj of objects) { const item = new SObjectChildRelationship(obj); result.push(item); } } return result; }
import { NextRequest, NextResponse } from "next/server"; import connects from "@/app/database/db"; import bcrypt from "bcryptjs"; import { generateAccessToken, generateRefreshToken, } from "../tokens/generateTokens"; import { setCache } from "../redis/redisFunctions"; interface UserLogin { email: string | null; password: string | null; } export const POST = async (req: NextRequest, res: NextResponse) => { const body = await req.json(); try { if (body === null) { return NextResponse.json({ error: "Body is null" }); } let { email, password }: UserLogin = body; if (email == null || password == null || email == "" || password == "") { return NextResponse.json({ error: "Required all the fields i.e, email and password", }); } const con = await connects(); const db = con.db("url-shortner"); const users = db.collection("users"); //creating a index so that can get data for db fastly const indexExists = await users.indexExists("email_1"); if (!indexExists) { users .createIndex({ email: 1 }) .then() .catch((error) => { console.log("error: ", error); }); } const userExists = await users.findOne({ email: email }); if (!userExists) { return NextResponse.json({ error: "Authentication failed" }); } const passwordMatch = await bcrypt.compare(password, userExists.password); if (!passwordMatch) { return NextResponse.json({ error: "Authentication failed" }); } console.log(process.env.JWT_SECRET_KEY); const accessToken = generateAccessToken(userExists._id.toString()); const refreshToken = generateRefreshToken(userExists._id.toString()); setCache(accessToken, accessToken, 3480) .then() .catch((error) => { console.log(error); }); return NextResponse.json({ name: userExists.name, accessToken: accessToken, refreshToken: refreshToken, }); } catch (err) { console.log(err); return NextResponse.json({ error: "Internal Server Error" }); } };
import React from "react"; import useAppContext from "../hooks/useAppContext"; import { Box, Grid } from "@mui/material"; import Legend from "./Legend"; import Layout from "./Layout"; /** * Summary component to display information. * @returns {React.ReactNode} - Rendered summary component. */ const Summary = () => { const { step, formData } = useAppContext(); console.clear(); console.log(formData); return ( <Layout> <Box sx={{ p: 3 }} className="form"> <Legend step={step} title={"Information"} description="Your Data" /> <Grid container> <pre className="text-info">{JSON.stringify(formData, null, 2)}</pre> </Grid> </Box> </Layout> ); }; Summary.propTypes = {}; export default Summary;
# Sorted Squares Exercise ## **sorted_squares**(arr: StaticArray) -> StaticArray: Write a function that receives a StaticArray where the elements are in sorted order, and returns a new StaticArray with squares of the values from the original array, sorted in non-descending order. The original array must not be modified. You may assume that the input array will have at least one element, will contain only integers in the range [-10^9, 10^9], and that elements of the input array are already in non-descending order. You do not need to write checks for these conditions. Implement a FAST solution that can process at least 5,000,000 elements in a reasonable amount of time (under a minute). Note that using a traditional sorting algorithm (even a fast sorting algorithm like merge sort or shell sort) will not pass the largest test case of 5,000,000 elements. Also, a solution using count_sort() as a helper method will also not work here, due to the wide range of values in the input array. For full credit, the function must be implemented with **O(N)** complexity. **Example #1:** ```python test_cases = ( [1, 2, 3, 4, 5], [-5, -4, -3, -2, -1, 0], [-3, -2, -2, 0, 1, 2, 3], ) for case in test_cases: arr = StaticArray(len(case)) for i, value in enumerate(sorted(case)): arr[i] = value print(arr) result = sorted_squares(arr) print(result) ``` **Output:** > STAT_ARR Size: 5 [1, 2, 3, 4, 5] > STAT_ARR Size: 5 [1, 4, 9, 16, 25] > STAT_ARR Size: 6 [-5, -4, -3, -2, -1, 0] > STAT_ARR Size: 6 [0, 1, 4, 9, 16, 25] > STAT_ARR Size: 7 [-3, -2, -2, 0, 1, 2, 3] > STAT_ARR Size: 7 [0, 1, 4, 4, 4, 9, 9] **Example #2:** ```python array_size = 5_000_000 case = [random.randint(-10**9, 10**9) for _ in range(array_size)] arr = StaticArray(len(case)) for i, value in enumerate(sorted(case)): arr[i] = value print(f'Started sorting large array of {array_size} elements') result = sorted_squares(arr) print(f'Finished sorting large array of {array_size} elements') ``` **Output:** > Started sorting large array of 5000000 elements > Finished sorting large array of 5000000 elements
package com.thesis.projectopportunities.service; import java.io.IOException; import java.net.URI; import java.util.concurrent.atomic.AtomicBoolean; import com.thesis.projectopportunities.model.User; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @Service @RequiredArgsConstructor public class KeycloakService { private static final String SERVER = "http://keycloak:8090/"; private static final String REALM = "project-opportunities"; private static final String ADMIN_CLIENT = """ [ { "id": "c86f7d3d-6d66-4baa-bddf-6a6bcc06f225", "name": "ADMIN_CLIENT", "description": "", "composite": false, "clientRole": true, "containerId": "0273e652-3dfc-4a3e-bc00-8a1f53686397", "attributes": {} } ] """; private static final String ADMIN = """ [ { "id": "31891c38-1d76-4e20-8b16-26af0976a2e6", "name": "ADMIN", "description": "", "composite": false, "clientRole": false, "containerId": "c393aee6-e5af-4664-bac4-1f0986b0ba2a", "attributes": {} } ] """; private static final String PREFIX = "admin/realms/"; private static final String USER_ENDPOINT = "/users/"; private String accessToken; @Setter(onMethod_ = @Autowired) private RestTemplate restTemplate; public boolean isAdmin(User user) throws IOException { accessToken = authAdmin(); HttpHeaders headers = setupHeaders(); HttpEntity<Object> httpEntity = new HttpEntity<>("body", headers); String userId = getUserId(user.getUsername()); String clientId = getClientId(); ResponseEntity<String> responseEntity = restTemplate.exchange(SERVER + PREFIX + REALM + USER_ENDPOINT + userId + "/role-mappings/clients/" + clientId, HttpMethod.GET, httpEntity, String.class); JsonNode jsonNode = new ObjectMapper().readTree(responseEntity.getBody()); AtomicBoolean isAdmin = new AtomicBoolean(false); jsonNode.forEach(role -> { if (role.get("name").asText().equals("ADMIN_CLIENT")) { isAdmin.set(true); } }); return isAdmin.get(); } public void addAdminRole(User user) throws IOException { accessToken = authAdmin(); HttpHeaders headers = setupHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Object> httpEntity = new HttpEntity<>(ADMIN_CLIENT, headers); String userId = getUserId(user.getUsername()); String clientId = getClientId(); restTemplate.postForEntity(SERVER + PREFIX + REALM + USER_ENDPOINT + userId + "/role-mappings/clients/" + clientId, httpEntity, String.class); httpEntity = new HttpEntity<>(ADMIN, headers); restTemplate.postForEntity(SERVER + PREFIX + REALM + USER_ENDPOINT + userId + "/role-mappings/realm", httpEntity, String.class); } private String getClientId() throws IOException { HttpHeaders headers = setupHeaders(); HttpEntity<Object> httpEntity = new HttpEntity<>("body", headers); ResponseEntity<String> responseEntity = restTemplate.exchange(SERVER + PREFIX + REALM + "/clients?clientId=project-opportunities", HttpMethod.GET, httpEntity, String.class); JsonNode jsonNode = new ObjectMapper().readTree(responseEntity.getBody()); return jsonNode.get(0).get("id").asText(); } private String getUserId(String username) throws IOException, HttpClientErrorException { HttpHeaders headers = setupHeaders(); HttpEntity<Object> httpEntity = new HttpEntity<>("body", headers); ResponseEntity<String> responseEntity = restTemplate.exchange(SERVER + PREFIX + REALM + "/users?username=" + username, HttpMethod.GET, httpEntity, String.class); JsonNode jsonNode = new ObjectMapper().readTree(responseEntity.getBody()); return jsonNode.get(0).get("id").asText(); } public String authAdmin() throws IOException { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); builder.uri(URI.create(SERVER)); builder.path("realms/master/protocol/openid-connect/token"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> body = new LinkedMultiValueMap<>(); body.set("username", "user"); body.set("password", "admin"); body.set("client_id", "admin-cli"); body.set("grant_type", "password"); HttpEntity<Object> httpEntity = new HttpEntity<>(body, headers); ResponseEntity<String> responseEntity = restTemplate.postForEntity(builder.toUriString(), httpEntity, String.class); JsonNode jsonNode = new ObjectMapper().readTree(responseEntity.getBody()); return jsonNode.get("access_token").asText(); } private HttpHeaders setupHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); return headers; } }
using BackEnd.Models; using DAL.Implementations; using DAL.Interfaces; using Entities.Entities; using Microsoft.AspNetCore.Mvc; namespace BackEnd.Controllers { [Route("api/[controller]")] [ApiController] public class SeatController : ControllerBase { private ISeatDAL seatDAL; public SeatController() { seatDAL = new SeatDALImpl(new AccountingSoftDBContext()); } TblSeat Convert(SeatModel entity) { return new TblSeat { ID = entity.ID, DATE_SEAT = entity.DATE_SEAT, CURRENCY = entity.CURRENCY, EXCHANGE_RATE = entity.EXCHANGE_RATE, REFERENCE = entity.REFERENCE, CUSTOMER_ID = entity.CUSTOMER_ID, STATUS = entity.STATUS }; } SeatModel Convert(TblSeat entity) { return new SeatModel { ID = entity.ID, DATE_SEAT = entity.DATE_SEAT, CURRENCY = entity.CURRENCY, EXCHANGE_RATE = entity.EXCHANGE_RATE, REFERENCE = entity.REFERENCE, CUSTOMER_ID = entity.CUSTOMER_ID, STATUS = entity.STATUS }; } #region Metodos para Asientos [HttpGet] public JsonResult Get() { List<TblSeat> seats = new List<TblSeat>(); seats = seatDAL.GetAll().Where(a => a.STATUS).ToList(); List<SeatModel> result = new List<SeatModel>(); foreach (TblSeat seat in seats) { result.Add(Convert(seat)); } return new JsonResult(result); } [HttpGet("{id}")] public JsonResult Get(int id) { TblSeat seat = seatDAL.Get(id); return new JsonResult(Convert(seat)); } [HttpPost] public JsonResult Post([FromBody] SeatModel seat) { TblSeat entity = Convert(seat); entity.ID = null; seatDAL.Add(entity); return new JsonResult(Convert(entity)); } [HttpPut] public JsonResult Put([FromBody] SeatModel seat) { TblSeat entity = Convert(seat); seatDAL.Update(entity); return new JsonResult(Convert(entity)); } [HttpDelete("{id}")] public JsonResult Delete(int id) { var success = seatDAL.Delete(id); return new JsonResult(success); } [HttpPost("Post/{id}")] public JsonResult Postear(int id) { var success = seatDAL.Post(id); return new JsonResult(success); } #endregion } }
import { Column } from "primereact/column"; import { DataTable } from "primereact/datatable"; import { FilterMatchMode, FilterOperator } from "primereact/api"; import { useEffect, useState } from "react"; import GlobalFilter from "../../custom/GlobalFilter/GlobalFIlter"; import ActionIconButton, { getButtonSectionWidth, } from "../../custom/ActionIconButton/ActionIconButton"; import AttributeTypeTemplate from "../../custom/AttributeTypeTemplate/AttributeTypeTemplate"; import AttributeTypeDropdown from "../../custom/AttributeTypeDropdown/AttributeTypeDropdown"; import DependencyService from "../../../services/dependency/DependencyService"; import MenuButton from "../../custom/MenuButton/MenuButton"; import EmptyTableMessage from "../../custom/EmptyTableMessage/EmptyTableMessage"; const FactTable = (props) => { const [completeFacts, setCompleteFacts] = useState([]); const [filters, setFilters] = useState({ global: { value: null, matchMode: FilterMatchMode.CONTAINS }, type: { value: null, matchMode: FilterMatchMode.CONTAINS }, attributeName: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.CONTAINS }], }, value: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.CONTAINS }], }, }); useEffect(() => { setCompleteFacts(DependencyService.getCompleteFacts(props.facts)); }, [props.facts]); const renderHeader = () => { return ( <div className="space-between" style={{ fontSize: "17px" }}> <div style={{ margin: "auto" }}>Lista Faktów</div> <div className="flex"> <GlobalFilter value={filters.global.value} changeValue={(e) => setFilters((prev) => ({ ...prev, global: { ...prev.global, value: e }, })) } /> {props.menuItems.length > 0 && ( <MenuButton menuItems={props.menuItems} tooltipPosition={"left"} /> )} </div> </div> ); }; const buttonsTemplates = (fact) => { let buttonsSection = props.buttons.map((b, i) => ( <ActionIconButton key={`attribute-button-${i}`} icon={b.icon} className={b.className} tooltip={b.tooltip} tooltipPosition={b.tooltipPosition} action={() => b.action(fact)} /> )); return ( <div className="start-from-right" start-from-right> {buttonsSection} </div> ); }; const getAttributeTemplate = (fact) => { return <div className="pl-1 w-full text-right">{fact.attributeName}</div>; }; const typeFilter = (options) => { return ( <AttributeTypeDropdown placeholder="Wybierz typ" selected={options.value} changeType={(e) => options.filterCallback(e)} /> ); }; return ( <DataTable className={`row-padding ${props.className}`} paginator={props.facts.length > 0} rows={25} value={completeFacts} header={renderHeader()} filters={filters} scrollable scrollHeight="calc(100vh - 170px)" selectionMode={props.selection && "checkbox"} dataKey="id" selection={props.selection} onSelectionChange={(e) => { let tempFact = { ...e }; delete tempFact.attributeName; props.onSelect(tempFact); }} emptyMessage={<EmptyTableMessage value="Faktów" />} > {props.selection && ( <Column selectionMode="multiple" bodyClassName="fact-view-select-column" headerClassName="fact-view-select-column" /> )} <Column bodyClassName="fact-view-type-column" headerClassName="fact-view-type-column" field="type" header="Typ" filter filterElement={typeFilter} showFilterMatchModes={false} body={(a) => ( <AttributeTypeTemplate option={a.type} short={props.shortType} /> )} /> <Column bodyClassName="fact-view-attribute- cursor-default" headerClassName="fact-view-attribute-column" field="attributeName" header={() => <div className="w-full text-right">Atrybut</div>} filter body={(e) => getAttributeTemplate(e)} /> <Column bodyClassName="fact-view-operator-column cursor-default" headerClassName="fact-view-operator-column" field="operator" header="Operator" body={(e) => <div className="mx-auto">{e.operator}</div>} /> <Column bodyClassName="fact-view-value-column cursor-default" headerClassName="fact-view-value-column" field="value" header="Wartość" filter /> <Column bodyClassName="fact-view-value-column" headerClassName="fact-view-value-column" bodyStyle={{ flex: `0 0 ${getButtonSectionWidth(props.buttons)}` }} headerStyle={{ flex: `0 0 ${getButtonSectionWidth(props.buttons)}` }} body={(f) => buttonsTemplates(f)} /> </DataTable> ); }; FactTable.defaultProps = { shortType: false, facts: [], buttons: [], menuItems: [], selection: null, onSelect: null, }; export default FactTable;
// // HomeViewModel.swift // MeMo // // Created by Irham Naufal on 08/10/23. // import SwiftUI import SwiftData extension HomeView { /// The `HomeViewModel` class is a view model for the `HomeView` view. It is responsible for managing the state of the `HomeView` and providing data to the view. @Observable final class HomeViewModel { /// A ModelContext for accessing and managing data models. var modelContext: ModelContext /// The search text entered by the user. var searchText = "" /// A list of recent notes. var recentNotes: [NoteFileResponse] = [] /// A list of all notes. var allNotes: [NoteFileResponse] = [] /// A list of folders. var folders: [FolderResponse] = [] /// A list of theme colors. var themes: [ThemeColor] = [.red, .orange, .green, .blue, .purple, .pink] /// The currently selected theme color. @ObservationIgnored @AppStorage("current_theme") var currentTheme: String = ThemeColor.purple.rawValue /// Whether or not the note sheet is displayed. var isShowSheet = false /// Initializes a new HomeViewModel object. init(modelContext: ModelContext) { self.modelContext = modelContext self.modelContext.autosaveEnabled = true } /// Counts the number of notes in a folder. func countNotes(from folder: FolderResponse) -> Int { folder.notes.count } /// Returns a description of a list of notes. func description(from notes: [NoteResponse]) -> String { return notes.compactMap({ note in note.text }).joined(separator: " ") } /// Returns a Color object for a given theme color. func bgColor(from color: String) -> Color { switch color { case ThemeColor.blue.rawValue: return .blue3 case ThemeColor.green.rawValue: return .green3 case ThemeColor.orange.rawValue: return .orange3 case ThemeColor.pink.rawValue: return .pink3 case ThemeColor.purple.rawValue: return .purple3 case ThemeColor.red.rawValue: return .red3 default: return .gray2 } } /// Returns the secondary color for the given theme color. /// The secondary color is a lighter version of the theme color. func secondaryColor(from color: String) -> Color { switch color { case ThemeColor.blue.rawValue: return .blue2 case ThemeColor.green.rawValue: return .green2 case ThemeColor.orange.rawValue: return .orange2 case ThemeColor.pink.rawValue: return .pink2 case ThemeColor.purple.rawValue: return .purple2 case ThemeColor.red.rawValue: return .red2 default: return .gray2 } } /// Returns the accent color for the given theme color. func accentColor(from color: String) -> Color { switch color { case ThemeColor.blue.rawValue: return .blue1 case ThemeColor.green.rawValue: return .green1 case ThemeColor.orange.rawValue: return .orange1 case ThemeColor.pink.rawValue: return .pink1 case ThemeColor.purple.rawValue: return .purple1 case ThemeColor.red.rawValue: return .red1 default: return .gray2 } } /// Returns the app icon for the given theme color. func appIcon(from color: String) -> Image { switch color { case ThemeColor.blue.rawValue: return .logoBlue case ThemeColor.green.rawValue: return .logoGreen case ThemeColor.orange.rawValue: return .logoOrange case ThemeColor.pink.rawValue: return .logoPink case ThemeColor.purple.rawValue: return .logoPurple default: return .logoRed } } /// Selects the specified theme. func selectTheme(_ theme: String) { currentTheme = theme // Sets the alternate icon for the app to the specified theme. UIApplication.shared.setAlternateIconName(theme) { _ in // Hides the note sheet. self.isShowSheet = false } } /// Creates a new note with the specified theme. func createNewNote() -> NoteView.NoteViewModel { let note: NoteFileResponse = .init( title: "", notes: [NoteResponse(type: .init(content: .text), text: "")], theme: self.currentTheme, createdAt: .now, modifiedAt: .now ) // Inserts the new note into the data model. modelContext.insert(note) // Returns a NoteView.NoteViewModel object for the new note. return .init(modelContext: modelContext, data: note, isNewNote: true) } /// Creates a new folder with the specified theme. func createNewFolder() -> FolderView.FolderViewModel { let folder: FolderResponse = .init( title: "", icon: "💌", theme: currentTheme, notes: [], createdAt: .now, modifiedAt: .now ) // Inserts the new folder into the data model. modelContext.insert(folder) // Returns a FolderView.FolderViewModel object for the new folder. return .init(modelContext: modelContext, data: folder) } /// Navigates to the global view with the specified search state./ func navigateToGlobal(state: SearchState) -> GlobalView.GlobalViewModel { return .init(modelContext: modelContext, data: allNotes, state: state, theme: currentTheme) } /// Opens the specified recent note./ func openRecentNote(_ note: NoteFileResponse) -> NoteView.NoteViewModel { return .init(modelContext: modelContext, data: note) } /// Opens the specified folder./ func openFolder(_ folder: FolderResponse) -> FolderView.FolderViewModel { return .init(modelContext: modelContext, data: folder) } /// Fetches all notes from the data model and updates the recent notes and folders lists./ func getAllNotes() { do { let descriptor = FetchDescriptor<NoteFileResponse>( sortBy: [SortDescriptor(\.modifiedAt, order: .reverse)] ) allNotes = try modelContext.fetch(descriptor) recentNotes = Array(allNotes.prefix(5)) for note in allNotes { guard let folder = note.folder, !folders.contains(where: { $0.id == folder.id }) else { continue } folders.append(folder) } } catch(let error) { print("Fetch recent notes failed: \(error)") } } /// Saves the changes made to the data model./ func saveChanges() { do { try modelContext.save() } catch(let error) { print(error) } } } }
// user-registration.use-case.ts import { Injectable, InternalServerErrorException } from '@nestjs/common'; import { CommandBus } from '@nestjs/cqrs'; import { DeletePermissionCommand } from '@/modules/auth/components/permission/command/delete-permission/delete-permission.command'; import { DeletePermissionInput, DeletePermissionOutput, } from '@/modules/auth/components/permission/dto/delete-permission.dto'; import { PermissionHelepr } from '@/modules/auth/components/permission/helper/permission-helper'; @Injectable() export class DeletePermissionUseCase { constructor( private readonly commandBus: CommandBus, private readonly permissionHelepr: PermissionHelepr, ) {} async deletePermission( input: DeletePermissionInput, ): Promise<DeletePermissionOutput> { try { await this.permissionHelepr.validatePermissionId(input.permissionId); await this.commandBus.execute(new DeletePermissionCommand(input)); return { success: true }; } catch (err) { throw new InternalServerErrorException(err); } } }
using Microsoft.Extensions.DependencyInjection; using ProductImporter.Model; using ProductImporter.Logic.Shared; using ProductImporter.Logic.Transformations; using ProductImporter.Transformations; namespace ProductImporter.Logic.Transformation; public class ProductTransformer : IProductTransformer { private readonly IServiceScopeFactory _serviceScopeFactory; private readonly IImportStatistics _importStatistics; public ProductTransformer(IServiceScopeFactory serviceScopeFactory, IImportStatistics importStatistics) { _serviceScopeFactory = serviceScopeFactory; _importStatistics = importStatistics; } public Product ApplyTransformations(Product product) { using var scope = _serviceScopeFactory.CreateScope(); var transformationContext = scope.ServiceProvider.GetRequiredService<IProductTransformationContext>(); transformationContext.SetProduct(product); //Remove this //var nameCapitalizer = scope.ServiceProvider.GetRequiredService<INameDecapitaliser>(); //var currencyNormalizer = scope.ServiceProvider.GetRequiredService<ICurrencyNormalizer>(); //var referenceAdder = scope.ServiceProvider.GetRequiredService<IReferenceAdder>(); //Newly added interface var productTranformers = scope.ServiceProvider.GetRequiredService<IEnumerable<IProductTransformation>>(); Thread.Sleep(2000); //Demonstrates Polymorphism foreach(var productTranformer in productTranformers) { productTranformer.Execute(); } //nameCapitalizer.Execute(); //currencyNormalizer.Execute(); //referenceAdder.Execute(); if (transformationContext.IsProductChanged()) { _importStatistics.IncrementTransformationCount(); } return transformationContext.GetProduct(); } }
/* * Copyright (c) 2015 Nathaniel Wallace * * 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. */ using KeyRingBuddy.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace KeyRingBuddy.Windows { /// <summary> /// Interaction logic for ItemListControl.xaml /// </summary> public partial class ItemListControl : UserControl { #region Constructors /// <summary> /// Constructor. /// </summary> public ItemListControl() { InitializeComponent(); } #endregion #region Properties /// <summary> /// The caption displayed. /// </summary> public string Caption { get { return textBlockCaption.Text; } set { textBlockCaption.Text = value; } } /// <summary> /// The currently selected item or null if there isn't one. /// </summary> public Item SelectedItem { get { foreach (ToggleButton button in stackPanel.Children) if (button.IsChecked.HasValue && button.IsChecked.Value) return button.Tag as Item; return null; } set { foreach (ToggleButton button in stackPanel.Children) { if (Object.Equals(value, button.Tag)) { button.IsChecked = true; break; } } } } #endregion #region Methods /// <summary> /// Clear out items. /// </summary> public void ClearItems() { bool isSelectedItem = (SelectedItem != null); stackPanel.Children.Clear(); if (isSelectedItem) OnSelectedItemChanged(EventArgs.Empty); } /// <summary> /// Add an item to the view. /// </summary> /// <param name="item">The item to add.</param> public void AddItem(Item item) { if (item == null) throw new ArgumentNullException("item"); int index = 0; for (; index < stackPanel.Children.Count; index++) { ToggleButton b = stackPanel.Children[index] as ToggleButton; Item c = b.Tag as Item; int order = String.Compare(item.Name, c.Name); if (order <= 0) break; } ToggleButton button = new ToggleButton(); button.Style = FindResource("ChromeListButtonStyle") as Style; button.HorizontalContentAlignment = HorizontalAlignment.Stretch; button.HorizontalAlignment = HorizontalAlignment.Stretch; button.Tag = item; if (item.Icon == null) { button.Content = item.Name; } else { DockPanel dp = new DockPanel(); dp.LastChildFill = true; Image img = new Image(); img.Height = 16; img.Width = 16; img.VerticalAlignment = VerticalAlignment.Center; img.Source = item.Icon; DockPanel.SetDock(img, Dock.Left); dp.Children.Add(img); TextBlock tb = new TextBlock(); tb.Text = item.Name; tb.Margin = new Thickness(10, 0, 10, 0); tb.VerticalAlignment = VerticalAlignment.Center; dp.Children.Add(tb); button.Content = dp; } if (index == stackPanel.Children.Count) stackPanel.Children.Add(button); else stackPanel.Children.Insert(index, button); } /// <summary> /// Remove the given item from the list. /// </summary> /// <param name="item">Object that raised the event.</param> public void RemoveItem(Item item) { if (item == null) throw new ArgumentNullException("item"); for (int i = 0; i < stackPanel.Children.Count; i++) { if (Object.Equals(item, (stackPanel.Children[i] as ToggleButton).Tag)) { bool isSelected = SelectedItem != null; stackPanel.Children.RemoveAt(i); if (isSelected && SelectedItem == null) OnSelectedItemChanged(EventArgs.Empty); break; } } } /// <summary> /// Raises the SelectedItemChanged event. /// </summary> /// <param name="e">Arguments to pass with the event.</param> protected virtual void OnSelectedItemChanged(EventArgs e) { if (SelectedItemChanged != null) SelectedItemChanged(this, e); } #endregion #region Event Handlers /// <summary> /// Mark the newly selected category. /// </summary> /// <param name="sender">Object that raised the event.</param> /// <param name="e">Event arguments.</param> private void stackPanel_Checked(object sender, RoutedEventArgs e) { foreach (ToggleButton button in stackPanel.Children) { if (button != e.Source) { button.IsChecked = false; button.IsEnabled = true; } else { button.IsEnabled = false; } } OnSelectedItemChanged(EventArgs.Empty); (e.Source as ToggleButton).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); } #endregion #region Events /// <summary> /// Raised when the SelectedItem is changed. /// </summary> public event EventHandler SelectedItemChanged; #endregion } }
package net.lepidodendron.entity; import com.google.common.base.Predicate; import net.ilexiconn.llibrary.client.model.tools.ChainBuffer; import net.ilexiconn.llibrary.server.animation.AnimationHandler; import net.lepidodendron.LepidodendronConfig; import net.lepidodendron.LepidodendronMod; import net.lepidodendron.entity.ai.*; import net.lepidodendron.entity.base.EntityPrehistoricFloraAgeableBase; import net.lepidodendron.entity.base.EntityPrehistoricFloraAgeableFishBase; import net.lepidodendron.entity.base.EntityPrehistoricFloraFishBase; import net.lepidodendron.entity.base.EntityPrehistoricFloraSwimmingAmphibianBase; import net.lepidodendron.item.entities.ItemBucketMesosaurus; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureAttribute; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.EntityAILookIdle; import net.minecraft.entity.ai.EntityAIWatchClosest; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.init.SoundEvents; import net.minecraft.item.ItemStack; import net.minecraft.util.*; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.oredict.OreDictionary; import javax.annotation.Nullable; public class EntityPrehistoricFloraMesosaurus extends EntityPrehistoricFloraSwimmingAmphibianBase { public BlockPos currentTarget; @SideOnly(Side.CLIENT) public ChainBuffer chainBuffer; public EntityPrehistoricFloraMesosaurus(World world) { super(world); setSize(0.6F, 0.35F); experienceValue = 0; this.isImmuneToFire = false; setNoAI(!true); enablePersistence(); //minSize = 0.3F; //maxSize = 1.0F; minWidth = 0.1F; maxWidth = 0.4F; maxHeight = 0.35F; maxHealthAgeable = 16.0D; } public static String getPeriod() { return "Permian"; } public static String getHabitat() { return "Amphibious"; } @Override public boolean breathesAir() { return true; } @Override public boolean dropsEggs() { return false; } @Override public boolean laysEggs() { return false; } protected float getAISpeedSwimmingAmphibian() { float calcSpeed = 0.11F; if (this.isReallyInWater()) { calcSpeed = 0.28f; } if (this.getTicks() < 0) { return 0.0F; //Is laying eggs } return Math.min(1F, (this.getAgeScale() * 2F)) * calcSpeed; } @Override public int getAdultAge() { return 36000; } @Override public int WaterDist() { int i = (int) LepidodendronConfig.waterMesosaurus; if (i > 16) { i = 16; } if (i < 1) { i = 1; } return i; } public AxisAlignedBB getAttackBoundingBox() { float size = this.getRenderSizeModifier() * 0.25F; return this.getEntityBoundingBox().grow(0.0F + size, 0.0F + size, 0.0F + size); } protected void initEntityAI() { tasks.addTask(0, new EntityMateAI(this, 1)); tasks.addTask(1, new EntityTemptAI(this, 1, false, true, 0)); tasks.addTask(2, new AttackAI(this, 1.0D, false, this.getAttackLength())); tasks.addTask(3, new AmphibianWander(this, NO_ANIMATION, 0.93, 80)); tasks.addTask(4, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); tasks.addTask(4, new EntityAIWatchClosest(this, EntityPrehistoricFloraFishBase.class, 8.0F)); tasks.addTask(4, new EntityAIWatchClosest(this, EntityPrehistoricFloraAgeableBase.class, 8.0F)); tasks.addTask(5, new EntityAILookIdle(this)); this.targetTasks.addTask(0, new EatFishItemsAI(this)); this.targetTasks.addTask(1, new EntityHurtByTargetSmallerThanMeAI(this, false)); this.targetTasks.addTask(3, new HuntAI(this, EntityPrehistoricFloraFishBase.class, true, (Predicate<Entity>) entity -> entity instanceof EntityLivingBase)); this.targetTasks.addTask(3, new HuntSmallerThanMeAIAgeable(this, EntityPrehistoricFloraAgeableFishBase.class, true, (Predicate<Entity>) entity -> entity instanceof EntityLivingBase, 0)); this.targetTasks.addTask(4, new HuntAI(this, EntitySquid.class, true, (Predicate<Entity>) entity -> entity instanceof EntityLivingBase)); } @Override public boolean isAIDisabled() { return false; } @Override public EnumCreatureAttribute getCreatureAttribute() { return EnumCreatureAttribute.UNDEFINED; } @Override protected boolean canDespawn() { return false; } @Override protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getAttributeMap().registerAttribute(SharedMonsterAttributes.ATTACK_DAMAGE); this.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(2.0D); this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.25D); } @Override protected boolean canTriggerWalking() { return true; } @Override public SoundEvent getAmbientSound() { return (SoundEvent) SoundEvent.REGISTRY .getObject(new ResourceLocation("lepidodendron:mesosaurus_idle")); } @Override public SoundEvent getHurtSound(DamageSource ds) { return (SoundEvent) SoundEvent.REGISTRY .getObject(new ResourceLocation("lepidodendron:mesosaurus_hurt")); } //@Override //public SoundEvent getHurtSound(DamageSource ds) { // return (SoundEvent) SoundEvent.REGISTRY.getObject(new ResourceLocation("entity.generic.hurt")); //} @Override public SoundEvent getDeathSound() { return (SoundEvent) SoundEvent.REGISTRY .getObject(new ResourceLocation("lepidodendron:mesosaurus_death")); } //@Override //public SoundEvent getDeathSound() { // return (SoundEvent) SoundEvent.REGISTRY.getObject(new ResourceLocation("entity.generic.death")); //} @Override protected float getSoundVolume() { return 1.0F; } @Override public boolean canBreatheUnderwater() { return true; } @Override public boolean getCanSpawnHere() { return this.posY < (double) this.world.getSeaLevel() && this.isInWater(); } public boolean isNotColliding() { return this.world.checkNoEntityCollision(this.getEntityBoundingBox(), this); } @Override protected int getExperiencePoints(EntityPlayer player) { return 2 + this.world.rand.nextInt(3); } @Override public boolean isOnLadder() { return false; } @Override public void onLivingUpdate() { super.onLivingUpdate(); this.renderYawOffset = this.rotationYaw; if (this.getAnimation() == ATTACK_ANIMATION && this.getAnimationTick() == 5 && this.getAttackTarget() != null) { launchAttack(); if (this.getOneHit()) { this.setAttackTarget(null); this.setRevengeTarget(null); } } AnimationHandler.INSTANCE.updateAnimations(this); } @Override public void onEntityUpdate() { super.onEntityUpdate(); } @Override public boolean attackEntityAsMob(Entity entity) { if (this.getAnimation() == NO_ANIMATION) { this.setAnimation(ATTACK_ANIMATION); //System.err.println("set attack"); } return false; } public boolean isDirectPathBetweenPoints(Vec3d vec1, Vec3d vec2) { RayTraceResult movingobjectposition = this.world.rayTraceBlocks(vec1, new Vec3d(vec2.x, vec2.y, vec2.z), false, true, false); return movingobjectposition == null || movingobjectposition.typeOfHit != RayTraceResult.Type.BLOCK; } @Nullable protected ResourceLocation getLootTable() { if (!this.isPFAdult()) { return LepidodendronMod.MESOSAURUS_LOOT_YOUNG; } return LepidodendronMod.MESOSAURUS_LOOT; } @Override public boolean isBreedingItem(ItemStack stack) { return ( (OreDictionary.containsMatch(false, OreDictionary.getOres("listAllfishraw"), stack)) // || (OreDictionary.containsMatch(false, OreDictionary.getOres("listAllmeatraw"), stack)) ); } @Override public EntityPrehistoricFloraAgeableBase createPFChild(EntityPrehistoricFloraAgeableBase entity) { return new EntityPrehistoricFloraMesosaurus(this.world); } @Override public boolean processInteract(EntityPlayer player, EnumHand hand) { ItemStack itemstack = player.getHeldItem(hand); if (!itemstack.isEmpty()) { if (itemstack.getItem() == Items.WATER_BUCKET) { player.inventory.clearMatchingItems(new ItemStack(Items.WATER_BUCKET, (int) (1)).getItem(), -1, (int) 1, null); SoundEvent soundevent = SoundEvents.ITEM_BUCKET_FILL; player.getEntityWorld().playSound(player, player.getPosition(), soundevent, SoundCategory.BLOCKS, 1.0F, 1.0F); ItemStack itemstack1 = new ItemStack(ItemBucketMesosaurus.block, (int) (1)); itemstack1.setCount(1); ItemHandlerHelper.giveItemToPlayer(player, itemstack1); this.setDead(); return true; } } return super.processInteract(player, hand); } }
# MongoDB ve Express Projesi README Bu README dosyası, MongoDB ve Express kullanarak oluşturulan bir projenin temel yapılandırması ve nasıl başlatılacağı hakkında bilgi içerir. Projenin başarılı bir şekilde çalıştırılması için aşağıdaki adımları izleyebilirsiniz. ## Gereksinimler Projenin başlatılması için aşağıdaki gereksinimlere ihtiyacınız vardır: - Kubernetes Kubernetes Cluster'a erişim. - `kubectl` komut satırı aracının yüklü olması. - MongoDB ve Express ile ilgili YAML dosyalarınızın hazır olması. ## Kurulum Adımları 1. Kubernetes Cluster'a Bağlanma Kubernetes Cluster'a bağlanmak için terminalde aşağıdaki komutu kullanın: ```bash kubectl config use-context [cluster_adı] ``` 2. MongoDB ve Express Deployment'ları Oluşturma Öncelikle MongoDB ve Express Deployment'larını oluşturun: ```bash kubectl apply -f [mongodb-ve-express-deployment-yaml-dosyası] ``` 3. MongoDB ve Express Servislerini Oluşturma Servislerinizi oluşturmak için aşağıdaki komutu kullanın: ```bash kubectl apply -f [mongodb-ve-express-servis-yaml-dosyası] ``` 4. Secret ve ConfigMap Oluşturma Projenizin çalışması için gizli bilgileri ve yapılandırmaları içeren Secret ve ConfigMap'leri oluşturun: ```bash kubectl apply -f [secret-yaml-dosyası] kubectl apply -f [configmap-yaml-dosyası] ``` 5. MongoDB ve Express Uygulamalarını Başlatma MongoDB ve Express uygulamalarını başlatmak için aşağıdaki komutu kullanın: ```bash kubectl create deployment [mongodb-deployment-adı] --image=mongo kubectl create deployment [express-deployment-adı] --image=mongo-express ``` 6. Hizmetleri Erişilebilir Kılma Express servisinin erişilebilir olması için bir LoadBalancer hizmeti oluşturun: ```bash kubectl expose deployment [express-deployment-adı] --type=LoadBalancer --port=8081 ``` Bu komut, Express uygulamanızın dış IP adresine ve belirtilen port numarasına bağlanmasını sağlar. 7. Uygulamaya Erişim Projenizin çalıştığını doğrulamak için aşağıdaki URL'yi kullanabilirsiniz: ``` http://[external-ip]:8081 ``` `[external-ip]` kısmı, LoadBalancer hizmetinizin dış IP adresi olacaktır. Bu adımları izlediğinizde MongoDB ve Express uygulamanız Kubernetes üzerinde başlamalıdır. Başka herhangi bir sorunuz veya ek talimatlarınız varsa, lütfen sorunuzu belirtin.
using NUnit.Framework.Legacy; using NUnit.Framework; using OrangeHRMTests.Data; using OrangeHRMTests.PageObjects; using NUnit.Allure.Core; namespace OrangeHRMTests.Tests { [TestFixture] [AllureNUnit] public class LoginTest : BaseLoginTest { [Test] public void A_ValidLoginTest() { GenericPages.LoginPage.InputUserName(TestSettings.Username); GenericPages.LoginPage.InputPassword(TestSettings.Password); GenericPages.LoginPage.ClickLoginButton(); ClassicAssert.AreEqual(Data.TestSettings.DashboardPageUrl, GenericPages.LoginPage.GetCurrentPageUrl()); } [Test] public void B_InValidLoginTest() { GenericPages.LoginPage.InputUserName(TestSettings.InValidUsername); GenericPages.LoginPage.InputPassword(TestSettings.InValidPassword); GenericPages.LoginPage.ClickLoginButton(); ClassicAssert.AreEqual("Invalid credentials", GenericPages.LoginPage.GetInvalidMessageTextResult()); } } }
import { Navigate, useRoutes } from 'react-router-dom'; // layouts import DashboardLayout from './layouts/dashboard'; import LogoOnlyLayout from './layouts/LogoOnlyLayout'; // import Login from './pages/Login'; import Register from './pages/Register'; import DashboardApp from './pages/DashboardApp'; import Products from './pages/admin/products/products'; import Blog from './pages/Blog'; import User from './pages/User'; import Brand from './pages/productInfo/brand/brand'; import Category from './pages/productInfo/categories/category'; import Profile from './pages/productInfo/profiles/profiles'; import Vehicle from './pages/productInfo/vehicle/vehicle'; import AddProduct from './pages/admin/products/addproducts'; import Expense from './pages/admin/expenses/expenses'; import SalesMain from './pages/admin/sales/sales'; import NotFound from './pages/Page404'; import Accounts from './pages/admin/warehouse/account'; import AllPayments from './pages/admin/payments/payments'; // ---------------------------------------------------------------------- export default function Router() { return useRoutes([ { path: '/dashboard', element: <DashboardLayout />, children: [ { path: '/', element: <Navigate to="/dashboard/app" replace /> }, { path: 'app', element: <DashboardApp /> }, { path: 'user', element: <User /> }, { path: 'category', element: <Category /> }, { path: 'brand', element: <Brand /> }, { path: 'profile', element: <Profile /> }, { path: 'vehicle', element: <Vehicle /> }, { path: 'products', element: <Products /> }, { path: 'accounts', element: <Accounts /> }, { path: 'expenses', element: <Expense /> }, { path: 'sales', element: <SalesMain /> }, { path: 'addproducts', element: <AddProduct /> }, { path: 'payments', element: <AllPayments /> }, { path: 'blog', element: <Blog /> } ] }, { path: '/', element: <LogoOnlyLayout />, children: [ { path: 'login', element: <Login /> }, { path: 'register', element: <Register /> }, { path: '404', element: <NotFound /> }, { path: '/', element: <Navigate to="/dashboard" /> }, { path: '*', element: <Navigate to="/404" /> } ] }, { path: '*', element: <Navigate to="/404" replace /> } ]); }
import React from "react"; import { Input } from "../../components/ui/input/input"; import { Button } from "../../components/ui/button/button"; import { SolutionLayout } from "../../components/ui/solution-layout/solution-layout"; import Styles from './string.module.css'; import StringAnimation from "../../components/string-animation/string-animation"; import { ElementStates } from "../../types/element-states"; import { TElement } from "../../types/types"; export const StringComponent: React.FC = () => { const [inputValue, setInputValue] = React.useState<string>(''); const [inProgress, setProgress] = React.useState<boolean>(false); const [data, setData] = React.useState<TElement<string>[]>([]); const [isShow, setIsShow] = React.useState<boolean>(false); const enterText = (e: React.ChangeEvent<HTMLInputElement>) => { setInputValue(e.target.value); } const toBegin: React.FormEventHandler<HTMLFormElement> = (e) => { e.preventDefault(); // подготовка массива с буквами const forRender = Array.from(inputValue).map(item => { return { value: item, state: ElementStates.Default } }); setData(forRender); setProgress(true); setIsShow(true); } return ( <SolutionLayout title="Строка"> <form className={Styles.form} onSubmit={toBegin}> <Input maxLength={11} type='text' isLimitText={true} style={{width: '377px'}} onChange={enterText} value={inputValue} data-cy='input' /> <Button type="submit" text="Развернуть" isLoader={inProgress} disabled={inputValue.length === 0} data-cy='button' /> </form> {isShow && ( <StringAnimation data={data} setProgress={setProgress} /> )} </SolutionLayout> ); };
// std use std::io::Error as IOError; // crates.io use rustyline::error::ReadlineError; use serde::Serialize; use thiserror::Error; // this crate use crate::rpc::RpcError; /// Application error type. #[derive(Debug, Error)] pub enum AppError { /// RPC Error #[error("rpc error happens, err: {0}")] Rpc(RpcError), /// Readline Error #[error("readline error happens, err: {0}")] Readline(String), #[error("io error happens, err: {0}")] IO(IOError), /// Custom error #[error("custom error happens, err: {0}")] Custom(String), } impl Serialize for AppError { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(self.to_string().as_str()) } } impl From<ReadlineError> for AppError { fn from(err: ReadlineError) -> Self { AppError::Readline(err.to_string()) } } impl From<RpcError> for AppError { fn from(err: RpcError) -> Self { AppError::Rpc(err) } } impl From<IOError> for AppError { fn from(err: IOError) -> Self { AppError::IO(err) } }
<script> /** * Displays a Modal for starting a new game * Handles new game logic * Used by `NewGameButton` */ import { game, resetGame } from '$lib/stores/game'; import getRoll from '$lib/util/getRoll'; export let showModal; function newGame() { resetGame(); // Set up `numDice` and `players` in `$game` $game.numDice = numDice; const players = []; for (let i = 0; i < numPlayers; i++) { players.push({ name: document.getElementById('player' + i).value.trim(), dice: Array(numDice) .fill(0) .map((_) => getRoll()) }); } $game.players = players; $game.state = 'passPhone'; // Close modal showModal = false; } let numPlayers = 2; let numDice = 5; </script> <h3 class="h3">Game Setup</h3> <div class="mt-4"> <label for="num-players-select">Number of players</label> <select bind:value={numPlayers} id="num-players-select" class="input"> {#each Array(5) as _, i} <option value={i + 2}>{i + 2}</option> {/each} </select> </div> <div class="mt-4"> <label for="num-dice-select">Number of dice</label> <select bind:value={numDice} id="num-dice-select" class="input"> {#each Array(10) as _, i} <option value={i + 1}>{i + 1}</option> {/each} </select> </div> <hr /> <h3 class="h3">Player Names (optional)</h3> {#each Array(numPlayers) as _, idx} <div class="my-4"> <label for="player{idx}">Player {idx + 1}:</label> <input id="player{idx}" type="text" class="input" /> </div> {/each} <hr /> <button on:click={newGame} class="button -primary block mt-6 mb-4">Start Game</button>
import { Request, Response } from "npm:express@4.18.2"; import ClienteModel from "../db/cliente.ts"; const addDinero = async (req: Request, res: Response) => { const { dni, cantidad } = req.params; // Parámetros que se reciben de la URL // Convertimos cantidad a número y validamos que sea un número válido const cantidadNumerica = parseFloat(cantidad); // parseFloat convierte un string a número if (isNaN(cantidadNumerica)) { // isNaN devuelve true si el parámetro no es un número const error={ // Si no es un número se devuelve un error "error":"invalid_data", "mensage": "Invalid quantity. " } return res.status(400).json(error); } // Buscar el cliente por DNI const cliente = await ClienteModel.findOne({ dni }); // Se busca el cliente por DNI if (!cliente) { // Si no existe const error={ // Se devuelve un error "error":"client_not_found", "mensage": "The client was not found. " } return res.status(404).json(error); } // Sumar la cantidad al dinero actual del cliente cliente.dinero += cantidadNumerica; // Guardar el cliente actualizado await cliente.save(); res.status(200).send({ // Se devuelve el cliente con los datos: dni, nombre y dinero dni: cliente.dni, nombre: cliente.nombre, dinero: cliente.dinero, }); }; export default addDinero; // Se exporta la función
import type webpack from 'webpack'; import type { BundleAnalyzerPlugin } from '../../../compiled/webpack-bundle-analyzer'; export type ConsoleType = 'log' | 'info' | 'warn' | 'error' | 'table' | 'group'; // may extends cache options in the futures export type BuildCacheOptions = { /** Base directory for the filesystem cache. */ cacheDirectory?: string; cacheDigest?: Array<string | undefined>; }; export interface PreconnectOption { href: string; crossorigin?: boolean; } export type Preconnect = Array<string | PreconnectOption>; export interface DnsPrefetchOption { href: string; } export type DnsPrefetch = string[]; export type PreloadIncludeType = | 'async-chunks' | 'initial' | 'all-assets' | 'all-chunks'; export type Filter = Array<string | RegExp> | ((filename: string) => boolean); export interface PreloadOrPreFetchOption { type?: PreloadIncludeType; include?: Filter; exclude?: Filter; } export interface SharedPerformanceConfig { /** * Whether to remove `console.xx` in production build. */ removeConsole?: boolean | ConsoleType[]; /** * Whether to remove the locales of [moment.js](https://momentjs.com/). */ removeMomentLocale?: boolean; /** * Specifies whether to modularize the import of [lodash](https://www.npmjs.com/package/lodash) * and remove unused lodash modules to reduce the code size of lodash. */ transformLodash?: boolean; /** * Controls the Builder's caching behavior during the build process. */ buildCache?: BuildCacheOptions | boolean; /** * Whether to print the file sizes after production build. */ printFileSize?: boolean; /** * Configure the chunk splitting strategy. */ chunkSplit?: BuilderChunkSplit; /** * Analyze the size of output files. */ bundleAnalyze?: BundleAnalyzerPlugin.Options; /** * Used to control resource `Preconnect`. * * Specifies that the user agent should preemptively connect to the target resource's origin. */ preconnect?: Preconnect; /** * Used to control resource `DnsPrefetch`. * * Specifies that the user agent should preemptively perform DNS resolution for the target resource's origin. */ dnsPrefetch?: DnsPrefetch; /** * Used to control resource `Preload`. * * Specifies that the user agent must preemptively fetch and cache the target resource for current navigation. */ preload?: true | PreloadOrPreFetchOption; /** * Used to control resource `Prefetch`. * * Specifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation. */ prefetch?: true | PreloadOrPreFetchOption; /** * Whether capture timing information for each module, * same as the [profile](https://webpack.js.org/configuration/other-options/#profile) config of webpack. */ profile?: boolean; } export interface NormalizedSharedPerformanceConfig extends SharedPerformanceConfig { printFileSize: boolean; buildCache: BuildCacheOptions | boolean; chunkSplit: BuilderChunkSplit; } export type SplitChunks = webpack.Configuration extends { optimization?: { splitChunks?: infer P; }; } ? P : never; export type CacheGroup = webpack.Configuration extends { optimization?: { splitChunks?: | { cacheGroups?: infer P; } | false; }; } ? P : never; export type ForceSplitting = RegExp[] | Record<string, RegExp>; export interface BaseSplitRules { strategy: string; forceSplitting?: ForceSplitting; override?: SplitChunks; } export interface BaseChunkSplit extends BaseSplitRules { /** todo: split-by-module not support in Rspack */ strategy: | 'split-by-module' | 'split-by-experience' | 'all-in-one' | 'single-vendor'; } export interface SplitBySize extends BaseSplitRules { strategy: 'split-by-size'; minSize?: number; maxSize?: number; } export interface SplitCustom extends BaseSplitRules { strategy: 'custom'; splitChunks?: SplitChunks; } export type BuilderChunkSplit = BaseChunkSplit | SplitBySize | SplitCustom;
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Activity } from '@modules/activities/entities/activity.entity'; import { Division } from '@modules/activities/entities/division.entity'; import { Classe } from '@modules/activities/entities/classe.entity'; import * as XLSX from 'xlsx'; import { WorkSheet } from 'xlsx'; @Injectable() export class ActivitySeedService { constructor( @InjectRepository(Activity) private activityRepository: Repository<Activity>, @InjectRepository(Division) private divisionRepository: Repository<Division>, @InjectRepository(Classe) private classeRepository: Repository<Classe>, ) {} async run() { await this.seedData(); } private static toCapitalize(value: string) { if (value) { return value.charAt(0).toUpperCase() + value.slice(1).toLowerCase(); } return ''; } private async seedData() { const xlsxData = XLSX.readFile(__dirname + '/Activities.xlsx'); const sheet: WorkSheet = xlsxData.Sheets['NAF_N']; const data = XLSX.utils.sheet_to_json(sheet); const classEntities = []; let activity_id; let division_id; for (const item of data) { if (item['Level'] === 1) { const activity = this.activityRepository.create({ code: item['Code'], name: ActivitySeedService.toCapitalize(item['Activité']), }); await activity.save(); activity_id = activity.id; } if (item['Level'] === 2 && activity_id) { const division = this.divisionRepository.create({ code: item['Code'], name: item['Division'], activity: activity_id, }); await division.save(); division_id = division.id; } if (item['Level'] === 3 && division_id) { const classe = this.classeRepository.create({ code: item['Code'], name: item['Classe'], division: division_id, }); classEntities.push(classe); } } await this.classeRepository.save(classEntities); } }
"""課題1実行用ファイル""" from sklearn.linear_model import LogisticRegression, SGDClassifier from sklearn.svm import SVC, LinearSVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.ensemble import GradientBoostingClassifier # util from utils import log_setting logger = log_setting(__name__) def load_machine_learning_model(select_model_name): """モデル読込処理""" logger.info('読込モデル %s', select_model_name) print(f'読込モデル {select_model_name}') if select_model_name == 'logreg' : # ロジスティック回帰 return LogisticRegression() elif select_model_name == 'svc' : # SVM return SVC() elif select_model_name == 'linear_svc' : # 線形SVM return LinearSVC() elif select_model_name == 'decisiontree' : # 決定木 return DecisionTreeClassifier() elif select_model_name == 'randomforest' : # ランダムフォレスト return RandomForestClassifier() elif select_model_name == 'knn' : # K-近傍法 return KNeighborsClassifier() elif select_model_name == 'gaussian' : # ナイーブベイズ return GaussianNB() elif select_model_name == 'gbk' : # 勾配ブースティング return GradientBoostingClassifier() elif select_model_name == 'sgd' : # 確率的勾配降下法 return SGDClassifier() else: logger.error('正しくないモデル名が設定されています') print('正しくないモデル名が設定されています') return ''
anovaHSD <- function(Y, X1, X2){ stars <- function(p_wartosc) { s_vec <- c() for (i in 1:length(p_wartosc)) { if (p_wartosc[i] < 0.001) s_vec[i] <- '***' else if (p_wartosc[i] < 0.01) s_vec[i] <- '**' else if (p_wartosc[i] < 0.05) s_vec[i] <- '*' else if (p_wartosc[i] < 0.1) s_vec[i] <- '.' else s_vec[i] <- ' ' } return(s_vec) } tukey <- function(m, X, Se, N, df){ diff = matrix(m$x, length(unique(X)),length(unique(X))) diff_t = t(diff) macierz = abs(diff - diff_t) colnames(macierz) <- levels(X) rownames(macierz) <- levels(X) SE = sqrt(matrix(Se, length(unique(X)))/N$x) SE_mat = matrix(SE, length(unique(X)),length(unique(X))) tukey_p = (macierz / SE_mat) tukey_p = round(1 - ptukey(tukey_p, length(unique(X)), df), digits = 4) tukey_signif = matrix(stars(tukey_p), length(unique(X)),length(unique(X))) colnames(tukey_signif) <- levels(X) rownames(tukey_signif) <- levels(X) return(list(Tukey_diff = macierz, Tukey_p = tukey_p, Tukey_signif = tukey_signif)) } parameters_X1 <- function(Y, X1){ srY = mean(Y) srG = aggregate(Y, by = list(X1), FUN = "mean") Ni = aggregate(Y, by = list(X1), FUN = "length") SSt = sum((Y - srY)^2) SSb = sum(Ni$x * (srG$x-srY)^2) SSw = SSt - SSb k1 = (length(unique(X1))-1) nk = (length(X1)-length(unique(X1))) Sb = SSb/k1 Sw = SSw/nk F = Sb/Sw p_wartosc = pf(F,length(unique(X1))-1, length(X1)-length(unique(X1)), lower.tail = FALSE) # TukeyHSD One Way tukey_X1 <- tukey(srG, X1, Sw, Ni, nk) return(list(Mean_Sq = c(Sb, Sw), Sum_Sq = c(SSb, SSw), F_value = F, df = c(k1, nk), p_val = p_wartosc, Tukey_diff = list(X1 = tukey_X1$Tukey_diff), Tukey_p = list(X1 = tukey_X1$Tukey_p), Tukey_signif = list(X1 = tukey_X1$Tukey_signif))) } parameters_X2 <- function(Y, X1, X2){ srY = mean(Y) mAlpha = aggregate(Y, by = list(X1), FUN = "mean") mBeta = aggregate(Y, by = list(X2), FUN = "mean") SSt = sum((Y - srY)^2) Ni = aggregate(Y, by = list(X1), FUN = "length") Ny = aggregate(Y, by = list(X2), FUN = "length") SSa = sum((mAlpha$x - srY)^2 * Ni$x) SSb = sum((mBeta$x - srY)^2 *Ny$x) SSe = SSt - SSa - SSb df_a = length(unique(X1)) - 1 df_b = length(unique(X2)) - 1 df = length(Y) - (length(unique(X1)) - 1) - (length(unique(X2)) - 1) - 1 Sa = SSa/df_a Sb = SSb/df_b Se = SSe/df Fa = Sa / Se Fb = Sb / Se pA = pf(Fa, df_a, df, lower.tail = FALSE) pB = pf(Fb, df_b, df, lower.tail = FALSE) # TukeyHSD Two Way tukey_X1 = tukey(mAlpha, X1, Se, Ni, df) tukey_X2 = tukey(mBeta, X2, Se, Ny, df) return(list(Sum_Sq = c(SSa, SSb, SSe), Mean_Sq = c(Sa,Sb,Se), F_value = c(Fa, Fb), df = c(df_a, df_b, df), p_val = c(pA, pB), Tukey_diff = list(X1 = tukey_X1$Tukey_diff, X2 = tukey_X2$Tukey_diff), Tukey_p = list(X1 = tukey_X1$Tukey_p, X2 = tukey_X2$Tukey_p), Tukey_signif = list(X1 = tukey_X1$Tukey_signif, X2 = tukey_X2$Tukey_signif))) } create_table <- function(out, name){ df <- c(out$df) sum_sq <- c(out$Sum_Sq) Mean <- c(out$Mean_Sq) F_val <- c(signif(out$F_value, digits = 4),'') P <- c(signif(out$p_val, digits = 4), '') stars <- c(stars(out$p_val), '') table <- format(data.frame(df, sum_sq, Mean, F_val, P, stars), digits = 3) rownames(table) <- c(name, 'Residuals') colnames(table) <- c('Df', 'Sum Sq', 'Mean Sq', 'F Value', 'Pr(>F)', 'Signif.') print(table) cat('---\n') cat("Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1\n") cat('\nTukeyHSD Diff\n\n') print(out$Tukey_diff) cat('\nTukeyHSD p_value\n\n') print(out$Tukey_p) cat('\nTukeyHSD Signif.\n\n') print(out$Tukey_signif, quote = FALSE) } if (missing(X2)){ out <- parameters_X1(Y, X1) } else { out <- parameters_X2(Y, X1, X2) } name <- as.array(as.list(match.call()[-c(1,2)])) create_table(out, name) }
#!/usr/bin/env python # -*- coding: utf-8 """A program that computes metabolic enrichment across groups of genomes and metagenomes""" import sys import anvio import anvio.kegg as kegg import anvio.terminal as terminal import anvio.filesnpaths as filesnpaths from anvio.errors import ConfigError, FilesNPathsError __author__ = "Developers of anvi'o (see AUTHORS.txt)" __copyright__ = "Copyleft 2015-2018, the Meren Lab (http://merenlab.org/)" __credits__ = [] __license__ = "GPL 3.0" __version__ = anvio.__version__ __authors__ = ['ivagljiva', 'adw96'] __resources__ = [("A description of the enrichment script run by this program can be found in Shaiber et al 2020", "https://genomebiology.biomedcentral.com/articles/10.1186/s13059-020-02195-w"), ("An example of pangenome functional enrichment in the context of the Prochlorococcus metapangenome from Delmont and Eren 2018 is included in the pangenomics tutorial", "http://merenlab.org/2016/11/08/pangenomics-v2/")] __tags__ = ["metabolism"] __requires__ = ['kegg-metabolism', 'user-metabolism', 'groups-txt', 'external-genomes', 'internal-genomes', 'functions'] __provides__ = ['functional-enrichment-txt'] __description__ = ("A program that computes metabolic enrichment across groups of genomes and metagenomes") run = terminal.Run() progress = terminal.Progress() def main(args): # make sure the output file is not going to overwrite anything if filesnpaths.is_file_exists(args.output_file, dont_raise=True): raise ConfigError(f"There is already a file at '{args.output_file}' :/ Anvi'o has a thing against overwriting existing files. " f"Please remove the exiting file first, or give a different output file name to this program.") # make sure we can write to the output file filesnpaths.is_output_file_writable(args.output_file) e = kegg.KeggModuleEnrichment(args) e.run_enrichment_stats() if __name__ == '__main__': from anvio.argparse import ArgumentParser parser = ArgumentParser(description=__description__) groupB = parser.add_argument_group('CRITICAL INPUTS', "This program requires TWO INPUT FILES: (1) an output file produced by the " "program `anvi-estimate-metabolism` as input and (2) a groups file (using the `--groups-txt` " "parameter) to specify which sample is in which group.") groupB.add_argument(*anvio.A('modules-txt'), **anvio.K('modules-txt')) groupB.add_argument(*anvio.A('groups-txt'), **anvio.K('groups-txt')) groupO = parser.add_argument_group('OUTPUT OPTIONS', "What comes out the other end. (Please provide at least the output file name.)") groupO.add_argument(*anvio.A('output-file'), **anvio.K('output-file', {'required': True})) groupE = parser.add_argument_group('OPTIONAL OPTIONS', "If you want it, here it is, come and get it.") groupE.add_argument(*anvio.A('sample-header'), **anvio.K('sample-header')) groupE.add_argument(*anvio.A('module-completion-threshold'), **anvio.K('module-completion-threshold', {'help': "This threshold defines the percent completeness score at which we consider a KEGG module to be 'present'" "in a given sample. That is, if a module's completeness in a sample is less than this value, then we say " "the module is not present in that sample, and this will affect the module's enrichment score. " "By extension, if a module's completeness is less than this value in all samples, it will have " "a very very low enrichment score (ie, it will not be considered enriched at all, because it doesn't occur in " "any groups). Note that the closer this number is to 0, the more meaningless this whole enrichment analysis is... " "but hey, this is your show. This threshold CAN be different from the completeness threshold used in `anvi-estimate-metabolism` " "if you wish. The default threshold is %(default)g."})) groupE.add_argument(*anvio.A('use-stepwise-completeness'), **anvio.K('use-stepwise-completeness')) groupE.add_argument(*anvio.A('include-samples-missing-from-groups-txt'), **anvio.K('include-samples-missing-from-groups-txt')) groupE.add_argument(*anvio.A('just-do-it'), **anvio.K('just-do-it')) args = parser.get_args(parser) try: main(args) except ConfigError as e: print(e) sys.exit(-1) except FilesNPathsError as e: print(e) sys.exit(-2)
#include <stdio.h> #include <stdlib.h> #include "fonctions.h" // Fonctions pour les listes simplement chaînées Node* creerListe() { Node *head = NULL; Node *temp = NULL; Node *newNode = NULL; int valeur, i = 1; printf("=== Creation d'une LSC (-1 pour terminer la saisie) ===\n"); while (1) { printf("Merci d'indiquer le terme n°%d : ", i++); scanf("%d", &valeur); if (valeur == -1) break; newNode = (Node*)malloc(sizeof(Node)); newNode->data = valeur; newNode->next = NULL; if (head == NULL) { head = newNode; } else { temp->next = newNode; } temp = newNode; } return head; } void afficherListe(Node *head) { Node *temp = head; while (temp != NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); } int trouverMax(Node *head) { int max = head->data; Node *temp = head; while (temp != NULL) { if (temp->data > max) { max = temp->data; } temp = temp->next; } return max; } int longueurListe(Node *head) { int longueur = 0; Node *temp = head; while (temp != NULL) { longueur++; temp = temp->next; } return longueur; } int trouverElement(Node *head, int valeur) { int position = 0; Node *temp = head; while (temp != NULL) { if (temp->data == valeur) { return position; } position++; temp = temp->next; } return -1; // Si la valeur n'est pas trouvée } int estCroissante(Node *head) { if (head == NULL || head->next == NULL) { return 1; // Une liste vide ou avec un seul élément est croissante } Node *temp = head; while (temp->next != NULL) { if (temp->data >= temp->next->data) { return 0; // Si un élément est supérieur ou égal au suivant, la liste n'est pas croissante } temp = temp->next; } return 1; } Node* ajouterAIndex(Node *head, int index, int valeur) { Node *newNode = (Node*)malloc(sizeof(Node)); newNode->data = valeur; newNode->next = NULL; if (index == 0) { newNode->next = head; return newNode; } Node *temp = head; for (int i = 0; i < index - 1 && temp != NULL; i++) { temp = temp->next; } if (temp == NULL) { free(newNode); return head; } newNode->next = temp->next; temp->next = newNode; return head; } Node* supprimerAIndex(Node *head, int index) { if (head == NULL) { return NULL; } Node *temp = head; if (index == 0) { head = head->next; free(temp); return head; } for (int i = 0; i < index - 1 && temp != NULL; i++) { temp = temp->next; } if (temp == NULL || temp->next == NULL) { return head; } Node *nodeToDelete = temp->next; temp->next = nodeToDelete->next; free(nodeToDelete); return head; } // Fonctions pour les listes doublement chaînées DNode* creerListeDouble() { DNode *head = NULL; DNode *tail = NULL; DNode *newNode = NULL; int valeur, i = 0; printf("=== Creation d'une LDC (-1 pour terminer la saisie) ===\n"); while (1) { printf("Merci d'indiquer le terme d’index [%d] : ", i++); scanf("%d", &valeur); if (valeur == -1) break; newNode = (DNode*)malloc(sizeof(DNode)); newNode->data = valeur; newNode->next = NULL; newNode->prev = tail; if (tail != NULL) { tail->next = newNode; } else { head = newNode; } tail = newNode; } return head; } void afficherListeDouble(DNode *head) { DNode *temp = head; while (temp != NULL) { printf("%d <=> ", temp->data); temp = temp->next; } printf("NULL\n"); } DNode* ajouterAIndexDouble(DNode *head, int index, int valeur) { DNode *newNode = (DNode*)malloc(sizeof(DNode)); newNode->data = valeur; newNode->next = NULL; newNode->prev = NULL; if (index == 0) { newNode->next = head; if (head != NULL) { head->prev = newNode; } return newNode; } DNode *temp = head; for (int i = 0; i < index - 1 && temp != NULL; i++) { temp = temp->next; } if (temp == NULL) { free(newNode); return head; } newNode->next = temp->next; newNode->prev = temp; if (temp->next != NULL) { temp->next->prev = newNode; } temp->next = newNode; return head; } DNode* supprimerAIndexDouble(DNode *head, int index) { if (head == NULL) { return NULL; } DNode *temp = head; if (index == 0) { head = head->next; if (head != NULL) { head->prev = NULL; } free(temp); return head; } for (int i = 0; i < index && temp != NULL; i++) { temp = temp->next; } if (temp == NULL) { return head; } if (temp->prev != NULL) { temp->prev->next = temp->next; } if (temp->next != NULL) { temp->next->prev = temp->prev; } free(temp); return head; }
/** @jsxImportSource @emotion/react */ import * as React from 'react'; import {FC} from 'react'; import {css, keyframes} from '@emotion/react'; import {Property} from 'csstype'; const falling = (name: String, offsetX: number, offsetY: number) => keyframes({ "0%" : { transform: `translate3D(${offsetX}%, ${offsetY}%, 0)`, }, "100%" : { transform: `translate3D(${-offsetX}%, ${offsetY + 100}%, 0)`, } }) const fallingNearTop = falling("falling-near-top", 0, -100); const fallingNearBottom = falling("falling-near-bottom", 0, 0); const fallingMidTop = falling("falling-mid-top", -7.5, -100); const fallingMidBottom = falling("falling-mid-bottom", -7.5, 0); const fallingFarTop = falling("falling-back-top", 7.5, -100); const fallingFarBottom = falling("falling-back-bottom", 7.5, 0); const snow = (url: String, name: String, duration: Property.AnimationDuration) => css({ overflow: "hidden", position: "absolute", pointerEvents: "none", top: 0, right: 0, bottom: 0, left: 0, height: "100%", backgroundImage: `url(${url})`, backgroundSize: "150px", backgroundRepeat: "repeat", animation: `${name} linear infinite both`, animationDuration: duration, }); const snowfallCss = css({ position: "absolute", width: "100%", height: "100%", overflow: "hidden", top: "0", }); export const Snowfall: FC = () => ( <div css={snowfallCss}> <div css={snow("img/snow-large.png", fallingNearTop, "40s")}/> <div css={snow("img/snow-large.png", fallingNearBottom, "40s")}/> <div css={snow("img/snow-medium.png", fallingMidTop, "50s")}/> <div css={snow("img/snow-medium.png", fallingMidBottom, "50s")}/> <div css={snow("img/snow-small.png", fallingFarTop, "60s")}/> <div css={snow("img/snow-small.png", fallingFarBottom, "60s")}/> </div> );
import {Component, CUSTOM_ELEMENTS_SCHEMA, OnInit, ViewChild} from '@angular/core'; import {CommonModule} from '@angular/common'; import {FormsModule} from '@angular/forms'; import { IonButton, IonButtons, IonCol, IonContent, IonFooter, IonGrid, IonHeader, IonIcon, IonItem, IonLabel, IonList, IonMenuButton, IonRow, IonSpinner, IonTitle, IonToolbar, IonInput } from '@ionic/angular/standalone'; import {ChatMessage, DefaultService, OpenAPI} from "../../stgpt_api"; import {addIcons} from "ionicons"; import {micOutline, send, volumeHigh} from 'ionicons/icons'; import {MarkdownComponent} from "ngx-markdown"; import {Storage} from '@ionic/storage-angular'; import {Router} from '@angular/router'; // Import Router import { VoiceRecorder, RecordingData, } from 'capacitor-voice-recorder'; import { TextToSpeech } from '@capacitor-community/text-to-speech'; @Component({ selector: 'app-chat', templateUrl: './chat.page.html', styleUrls: ['./chat.page.scss'], standalone: true, imports: [IonContent, IonHeader, IonTitle, IonToolbar, CommonModule, FormsModule, IonButtons, IonMenuButton, IonButton, IonList, IonItem, IonLabel, IonFooter, IonInput, IonSpinner, IonIcon, IonRow, IonGrid, IonCol, MarkdownComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class ChatPage implements OnInit { messages: ChatMessage[] = []; newMessage: string = ""; sendingMessage: boolean = false; logMessage: string = ""; private _storage: Storage | null = null; @ViewChild('input') inputElement!: IonInput; constructor(private storage: Storage, private router: Router) { addIcons({send, micOutline, volumeHigh}); } async ngOnInit() { console.log('init ChatPage') this._storage = await this.storage.create(); const result = await VoiceRecorder.canDeviceVoiceRecord() console.log(result) try { const token = await this._storage?.get("token"); OpenAPI.TOKEN = token.access_token; await DefaultService.readUsersMeUsersMeGet() } catch (error) { console.error('User is not authenticated') this.router.navigate(['/login/logout']) } console.log('User is authenticated') setTimeout(() => { this.inputElement.setFocus() }, 1); } async sendMessageBasic() { const response = await fetch(OpenAPI.BASE + '/chat', { method: 'POST', body: JSON.stringify(this.messages), headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${OpenAPI.TOKEN}` } }); await this.handleResponse(response); } async sendMessage() { this.messages.push({content: this.newMessage, role: 'user'}); this.sendingMessage = true; try { await this.sendMessageBasic(); } catch (error) { this.messages.pop(); console.error(error); } finally { this.sendingMessage = false; this.newMessage = ""; await this.inputElement.setFocus() this.logMessage = ""; } } async startAudio() { const result = await VoiceRecorder.requestAudioRecordingPermission() await VoiceRecorder.startRecording() console.log("startAudio"); } async sendAudio() { const recordingData: RecordingData = await VoiceRecorder.stopRecording(); console.log(recordingData) try { const formData = new FormData(); const audioBlob = this.b64toBlob(recordingData.value.recordDataBase64, recordingData.value.mimeType); formData.append('audio', audioBlob, 'audio'); formData.append('messages', JSON.stringify(this.messages)); const response = await fetch(OpenAPI.BASE + '/chat-audio', { method: 'POST', body: formData, headers: { 'Authorization': `Bearer ${OpenAPI.TOKEN}` } }); await this.handleResponse(response); } catch (error) { this.messages.pop(); console.error(error); } finally { this.sendingMessage = false; this.newMessage = ""; await this.inputElement.setFocus() this.logMessage = ""; } console.log("sendAudio"); } private async handleResponse(response: Response) { let message_text = "" if (!response.ok && response.status === 401) { // If the status code is 401 (unauthorized), navigate the user back to the 'login/logout' route await this.router.navigate(['/login/logout']); return; } if (response.body == null) { throw new Error('Response body is null'); } const reader = response.body.getReader(); while (true) { const {done, value} = await reader.read(); if (done) { break; } message_text += new TextDecoder("utf-8").decode(value) const splitMessages = message_text.split("%%%%"); for (let i = 0; i < splitMessages.length - 1; i++) { const message = JSON.parse(splitMessages[i]); if (message.role === "log_message") { this.logMessage = message.content; continue; } else if (this.messages.length === 0) { this.messages.push(message); } else if (message.role === this.messages[this.messages.length - 1].role) { this.messages[this.messages.length - 1].content += message.content; } else { this.messages.push(message); } } message_text = splitMessages[splitMessages.length - 1]; } } b64toBlob(b64Data: any, contentType = '', sliceSize = 512) { const byteCharacters = atob(b64Data); const byteArrays = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } return new Blob(byteArrays, {type: contentType}); } clearChat() { this.messages = []; } textToSpeech(text: string) { let utter = new window.SpeechSynthesisUtterance(text); window.speechSynthesis.cancel(); window.speechSynthesis.speak(utter); } }
package cacher import ( "sync" "time" "github.com/Rajprakashkarimsetti/apica-project/models" ) type Cache struct { Capacity int Cache map[string]*models.CacheData Head *models.CacheData Tail *models.CacheData Mutex sync.Mutex } // NewCache creates a new cache with the specified capacity. // It initializes the cache and starts a goroutine to periodically check for expired cache entries. func NewCache(capacity int) *Cache { cache := &Cache{ Capacity: capacity, Cache: make(map[string]*models.CacheData), } go cache.startExpirationCheck() return cache } // startExpirationCheck periodically checks for expired cache entries and removes them. func (c *Cache) startExpirationCheck() { ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for range ticker.C { c.Mutex.Lock() curr := c.Head for curr != nil { next := curr.Next expirationTime := time.Duration(curr.Expiration) * time.Second if time.Since(curr.TimeStamp) > expirationTime { delete(c.Cache, curr.Key) c.RemoveTail() } curr = next } c.Mutex.Unlock() } } func (c *Cache) MoveToFront(entry *models.CacheData) { if entry == c.Head { return } if entry == c.Tail { c.Tail = entry.Prev } if entry.Prev != nil { entry.Prev.Next = entry.Next } if entry.Next != nil { entry.Next.Prev = entry.Prev } entry.Prev = nil entry.Next = c.Head c.Head.Prev = entry c.Head = entry } func (c *Cache) RemoveTail() { if c.Tail == nil { return } prev := c.Tail.Prev if prev != nil { prev.Next = nil } else { c.Head = nil } c.Tail = prev }
#pragma once /**********************************************************************/ // include header files /**********************************************************************/ #include <Arduino.h> /**********************************************************************/ // macro define /**********************************************************************/ /**********************************************************************/ // type define /**********************************************************************/ /* * WildFire scope sender */ class wf_scope_sender { public: /** * const define */ static const uint32_t CH_MAX = 5; static const uint32_t BUF_SIZE = 256; static const uint32_t HEADER = 0x59485a53; /** * FSM state */ enum{ FSM_HEADER_S = 0, FSM_ADDR_S, FSM_LED_S, FSM_DATA_S, FSM_CHECK_S, }; /** * command id define */ enum { CMD_SET_HOST_TARGET = 0x01, CMD_SET_HOST_CURRENT, CMD_SET_HOST_PID, CMD_SET_HOST_START, CMD_SET_HOST_STOP, CMD_SET_HOST_PERIOD, CMD_SET_SLAVE_PID = 0x10, CMD_SET_SLAVE_TARGET, CMD_SET_SLAVE_START, CMD_SET_SLAVE_STOP, CMD_SET_SLAVE_RESET, CMD_SET_SLAVE_PERIED, }; enum { CH_1 = 1, CH_2, CH_3, CH_4, CH_5, }; struct msg{ uint8_t ch; uint8_t cmd; uint16_t param_len; uint8_t param[BUF_SIZE]; }; /** * Channel value */ int _ch_target_v[CH_MAX]; int _ch_current_v[CH_MAX]; /* * */ wf_scope_sender():state(FSM_HEADER_S){}; ~wf_scope_sender(){}; /** * put a stream char to fsm. fsm will rebuild a package from a stream data * @param c - stream data: char c * @return: - true: a pack have been recieve sussessfully * - flase: no pack is available */ bool putchar(char c); /** * return a msg. This msg come from the recieve data * @param m - msg poiter for output * @return: - none */ void get_msg(struct msg* m); /** * build a stream package frome the message * @param m - msg poiter for output * @param out_pack_len - the output stream package lenght * @param out_pack_buf - the output stream package buffer * @return: - none */ void msg_to_pack(struct msg* m, uint32_t *out_pack_len, uint8_t *out_pack_buf); /** * set a channel target value * @param update_ch: - which channel * @param v: - channel value * @return: - none */ void set_ch_target(uint8_t ch, int v); /** * set a channel current value * @param update_ch: - which channel * @param v: - channel value * @return: - none */ void set_ch_current(uint8_t ch, int v); /** * sync all channel value to host * @param out_len: - package lenght * @param buf: - output buffer * @return: - none */ void sync(uint32_t *out_len, uint8_t *buf); private: uint8_t state; uint8_t ch; uint8_t pack_len; uint8_t have_rx_len; uint8_t checksum; uint8_t data[BUF_SIZE]; }; /**********************************************************************/ // extern function declaretion /**********************************************************************/
// // CityModels.swift // CitySearch // // Created by Hernan G. Gonzalez on 09/01/2020. // Copyright © 2020 Hernan. All rights reserved. // import Foundation // MARK: - Models struct Coordinate: Codable { let lat: Double let lon: Double } struct City: Codable { let id: Int let key: String let name: String let country: String let coord: Coordinate enum CodingKeys: String, CodingKey { case id = "_id" case name, key, country, coord } } private extension City { static func == (lhs: Self, rhs: String) -> Bool { lhs.key.starts(with: rhs) } static func < (lhs: City, rhs: String) -> Bool { lhs.key < rhs } } // MARK: - Lookup extension Array where Element == City { func index(of key: String) -> Index? { var lowerBound = 0 var upperBound = count while lowerBound < upperBound { let midIndex = lowerBound + (upperBound - lowerBound) / 2 if self[midIndex] == key { return midIndex } else if self[midIndex] < key { lowerBound = midIndex + 1 } else { upperBound = midIndex } } return nil } private func findBound(at index: Int, key: String, op: (Index) -> (Index)) -> Index { let bounds = 0 ..< count var match = index var next = op(index) while bounds.contains(next) && self[next] == key { match = next next = op(next) } return match } func range(matching key: String) -> Range<Index>? { let key = key.lowercased() guard !isEmpty, !key.isEmpty, let pivot = index(of: key) else { return nil } let upperBound = findBound(at: pivot, key: key) { $0 + 1 } let lowerBound = findBound(at: pivot, key: key) { $0 - 1 } return lowerBound ..< (upperBound + 1) } var range: Range<Index> { startIndex ..< endIndex } }
#include <stdio.h> #include <stdlib.h> #include "unity.h" #include "../../include/gameplay.h" #include "../include/gameplay_test.h" #include "../../include/utils/gameplay_utils.h" // Test case for initialize_Board function void test_initialize_Board(void) { Board board; initialize_Board(&board); TEST_ASSERT_EQUAL(IN_PROGRESS, board.status); TEST_ASSERT_EQUAL(0, board.moves_count); // Test the initialization of the board values for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { TEST_ASSERT_EQUAL(EMPTY, board.value[i][j]); } } } // Test case for initialize_Game function void test_initialize_Game(void) { Game game; initialize_Game(&game); TEST_ASSERT_EQUAL(NOT_STARTED, game.status); TEST_ASSERT_EQUAL(0, game.moves_count); TEST_ASSERT_EQUAL(X, game.turn); for (int i = 0; i < 9; i++) { TEST_ASSERT_NOT_NULL(game.board[i]); TEST_ASSERT_EQUAL(IN_PROGRESS, game.board[i]->status); TEST_ASSERT_EQUAL(0, game.board[i]->moves_count); } } // FIXME: Missing board pointers check // Test case for free_Game function void test_free_Game(void) { Game *test_game = (Game *)malloc(sizeof(Game)); TEST_ASSERT_NOT_NULL(test_game); // Check if memory allocation is successful initialize_Game(test_game); free_Game(test_game); TEST_ASSERT_NULL(test_game->board); free(test_game); } // Test case for check_board_horizontally function void test_check_board_horizontally(void) { Board board; initialize_Board(&board); board.value[0][0] = X; board.value[0][1] = X; board.value[0][2] = X; TEST_ASSERT_TRUE(check_board_horizontally(&board)); TEST_ASSERT_EQUAL(X_WON, board.status); } // Test case for check_board_vertically function void test_check_board_vertically(void) { Board board; initialize_Board(&board); board.value[0][0] = O; board.value[1][0] = O; board.value[2][0] = O; TEST_ASSERT_TRUE(check_board_vertically(&board)); TEST_ASSERT_EQUAL(O_WON, board.status); } // Test case for check_board_diagonally function void test_check_board_diagonally(void) { Board board; initialize_Board(&board); board.value[0][0] = X; board.value[1][1] = X; board.value[2][2] = X; TEST_ASSERT_TRUE(check_board_diagonally(&board)); TEST_ASSERT_EQUAL(X_WON, board.status); } // Test case for modify_board function void test_modify_board(void) { Board board; initialize_Board(&board); modify_board(&board, 0, 0, X); TEST_ASSERT_EQUAL(X, board.value[0][0]); TEST_ASSERT_EQUAL(1, board.moves_count); modify_board(&board, 0, 0, O); TEST_ASSERT_EQUAL(X, board.value[0][0]); // Value shouldn't change TEST_ASSERT_EQUAL(1, board.moves_count); // Moves count remains the same board.status = X_WON; modify_board(&board, 1, 1, O); TEST_ASSERT_EQUAL(X_WON, board.status); // Status should remain X_WON TEST_ASSERT_EQUAL(1, board.moves_count); // Moves count remains the same } // Test case for check_board function void test_check_board(void) { Board board; initialize_Board(&board); board.value[0][0] = X; board.value[0][1] = X; board.value[0][2] = X; Player turn = X; check_board(&board, turn, false); TEST_ASSERT_EQUAL(X_WON, board.status); board.status = IN_PROGRESS; board.value[0][0] = O; board.value[1][0] = O; board.value[2][0] = O; turn = O; check_board(&board, turn, false); TEST_ASSERT_EQUAL(O_WON, board.status); } // Test case for check_game function void test_check_game(void) { Game game; int size = 2; initialize_Game(&game); Player turn = X; check_game(&game, turn); TEST_ASSERT_EQUAL(IN_PROGRESS, game.status); // Simulate a situation where all boards result in a draw for (int i = 0; i < (size * size); i++) { game.board[i]->status = DRAW; } check_game(&game, turn); TEST_ASSERT_EQUAL(DRAW, game.status); } // Test case for gameplay function - integration test void test_gameplay(void) { // Requires user input simulation or mocking for complete testing // This can be challenging to unit test completely without user interaction simulation - consider using the bot. }
import React from 'react'; import { listen } from '../utils/events'; function useMedia(query: string): boolean { const media = React.useMemo(() => globalThis.matchMedia(query), [query]); const [matches, setMatches] = React.useState(media.matches); React.useEffect(() => { const handleChange = (): void => setMatches(media.matches); handleChange(); return listen(media, 'change', handleChange); }, [media]); return matches; } function useReducedMotion(): boolean { return useMedia('(prefers-reduced-motion: reduce)'); } const defaultTransitionDuration = 100; /** * Duration to use for any animations/transitions. Will be set to 0 if user * chose to disable animations */ export function useTransitionDuration(): number { const reduceMotion = useReducedMotion(); return React.useMemo( () => (reduceMotion ? 0 : defaultTransitionDuration), [reduceMotion] ); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./PatchworkNFTInterface.sol"; /** @title Patchwork Protocol @author Runic Labs, Inc @notice Manages data integrity of relational NFTs implemented with Patchwork interfaces */ contract PatchworkProtocol { /** @notice The address is not authorized to perform this action @param addr The address attempting to perform the action */ error NotAuthorized(address addr); /** @notice The scope with the provided name already exists @param scopeName Name of the scope */ error ScopeExists(string scopeName); /** @notice The scope with the provided name does not exist @param scopeName Name of the scope */ error ScopeDoesNotExist(string scopeName); /** @notice Transfer of the scope to the provided address is not allowed @param to Address not allowed for scope transfer */ error ScopeTransferNotAllowed(address to); /** @notice The token with the provided ID at the given address is frozen @param addr Address of the token owner @param tokenId ID of the frozen token */ error Frozen(address addr, uint256 tokenId); /** @notice The token with the provided ID at the given address is locked @param addr Address of the token owner @param tokenId ID of the locked token */ error Locked(address addr, uint256 tokenId); /** @notice The address is not whitelisted for the given scope @param scopeName Name of the scope @param addr Address that isn't whitelisted */ error NotWhitelisted(string scopeName, address addr); /** @notice The token at the given address has already been patched @param addr Address of the token owner @param tokenId ID of the patched token @param patchAddress Address of the patch applied */ error AlreadyPatched(address addr, uint256 tokenId, address patchAddress); /** @notice The provided input lengths are not compatible or valid @dev for any multi array inputs, they must be the same length */ error BadInputLengths(); /** @notice The fragment at the given address is unregistered @param addr Address of the unregistered fragment */ error FragmentUnregistered(address addr); /** @notice The fragment at the given address has been redacted @param addr Address of the redacted fragment */ error FragmentRedacted(address addr); /** @notice The fragment with the provided ID at the given address is already assigned @param addr Address of the fragment @param tokenId ID of the assigned fragment */ error FragmentAlreadyAssigned(address addr, uint256 tokenId); /** @notice The fragment with the provided ID at the given address is already assigned in the scope @param scopeName Name of the scope @param addr Address of the fragment @param tokenId ID of the fragment */ error FragmentAlreadyAssignedInScope(string scopeName, address addr, uint256 tokenId); /** @notice The reference was not found in the scope for the given fragment and target @param scopeName Name of the scope @param target Address of the target token @param fragment Address of the fragment @param tokenId ID of the fragment */ error RefNotFoundInScope(string scopeName, address target, address fragment, uint256 tokenId); /** @notice The fragment with the provided ID at the given address is not assigned @param addr Address of the fragment @param tokenId ID of the fragment */ error FragmentNotAssigned(address addr, uint256 tokenId); /** @notice The fragment at the given address is already registered @param addr Address of the registered fragment */ error FragmentAlreadyRegistered(address addr); /** @notice Ran out of available IDs for allocation @dev Max 255 IDs per NFT */ error OutOfIDs(); /** @notice The provided token ID is unsupported @dev TokenIds may only be 56 bits long @param tokenId The unsupported token ID */ error UnsupportedTokenId(uint256 tokenId); /** @notice Cannot lock the soulbound patch at the given address @param addr Address of the soulbound patch */ error CannotLockSoulboundPatch(address addr); /** @notice The token with the provided ID at the given address is not frozen @param addr Address of the token owner @param tokenId ID of the token */ error NotFrozen(address addr, uint256 tokenId); /** @notice The nonce for the token with the provided ID at the given address is incorrect @dev It may be incorrect or a newer nonce may be present @param addr Address of the token owner @param tokenId ID of the token @param nonce The incorrect nonce */ error IncorrectNonce(address addr, uint256 tokenId, uint256 nonce); /** @notice Self assignment of the token with the provided ID at the given address is not allowed @param addr Address of the token owner @param tokenId ID of the token */ error SelfAssignmentNotAllowed(address addr, uint256 tokenId); /** @notice Transfer of the soulbound token with the provided ID at the given address is not allowed @param addr Address of the token owner @param tokenId ID of the token */ error SoulboundTransferNotAllowed(address addr, uint256 tokenId); /** @notice Transfer of the token with the provided ID at the given address is blocked by an assignment @param addr Address of the token owner @param tokenId ID of the token */ error TransferBlockedByAssignment(address addr, uint256 tokenId); /** @notice The token at the given address is not IPatchworkAssignable @param addr Address of the non-assignable token */ error NotPatchworkAssignable(address addr); /** @notice A data integrity error has been detected @dev Addr+TokenId is expected where addr2+tokenId2 is present @param addr Address of the first token @param tokenId ID of the first token @param addr2 Address of the second token @param tokenId2 ID of the second token */ error DataIntegrityError(address addr, uint256 tokenId, address addr2, uint256 tokenId2); /** @notice Represents a defined scope within the system @dev Contains details about the scope ownership, permissions, and mappings for references and assignments */ struct Scope { /** @notice Owner of this scope @dev Address of the account or contract that owns this scope */ address owner; /** @notice Indicates whether a user is allowed to patch within this scope @dev True if a user can patch, false otherwise. If false, only operators and the scope owner can perform patching. */ bool allowUserPatch; /** @notice Indicates whether a user is allowed to assign within this scope @dev True if a user can assign, false otherwise. If false, only operators and the scope owner can perform assignments. */ bool allowUserAssign; /** @notice Indicates if a whitelist is required for operations within this scope @dev True if whitelist is required, false otherwise */ bool requireWhitelist; /** @notice Mapped list of operator addresses for this scope @dev Address of the operator mapped to a boolean indicating if they are an operator */ mapping(address => bool) operators; /** @notice Mapped list of lightweight references within this scope // TODO: A unique hash of liteRefAddr + reference will be needed for uniqueness */ mapping(uint64 => bool) liteRefs; /** @notice Mapped whitelist of addresses that belong to this scope @dev Address mapped to a boolean indicating if it's whitelisted */ mapping(address => bool) whitelist; /** @notice Mapped list of unique patches associated with this scope @dev Hash of the patch mapped to a boolean indicating its uniqueness */ mapping(bytes32 => bool) uniquePatches; } mapping(string => Scope) private _scopes; /** @notice Emitted when a fragment is assigned @param owner The owner of the target and fragment @param fragmentAddress The address of the fragment's contract @param fragmentTokenId The tokenId of the fragment @param targetAddress The address of the target's contract @param targetTokenId The tokenId of the target */ event Assign(address indexed owner, address fragmentAddress, uint256 fragmentTokenId, address indexed targetAddress, uint256 indexed targetTokenId); /** @notice Emitted when a fragment is unassigned @param owner The owner of the fragment @param fragmentAddress The address of the fragment's contract @param fragmentTokenId The tokenId of the fragment @param targetAddress The address of the target's contract @param targetTokenId The tokenId of the target */ event Unassign(address indexed owner, address fragmentAddress, uint256 fragmentTokenId, address indexed targetAddress, uint256 indexed targetTokenId); /** @notice Emitted when a patch is minted @param owner The owner of the patch @param originalAddress The address of the original NFT's contract @param originalTokenId The tokenId of the original NFT @param patchAddress The address of the patch's contract @param patchTokenId The tokenId of the patch */ event Patch(address indexed owner, address originalAddress, uint256 originalTokenId, address indexed patchAddress, uint256 indexed patchTokenId); /** @notice Emitted when a new scope is claimed @param scopeName The name of the claimed scope @param owner The owner of the scope */ event ScopeClaim(string scopeName, address indexed owner); /** @notice Emitted when a scope is transferred @param scopeName The name of the transferred scope @param from The address transferring the scope @param to The recipient of the scope */ event ScopeTransfer(string scopeName, address indexed from, address indexed to); /** @notice Emitted when a scope has an operator added @param scopeName The name of the scope @param actor The address responsible for the action @param operator The new operator's address */ event ScopeAddOperator(string scopeName, address indexed actor, address indexed operator); /** @notice Emitted when a scope has an operator removed @param scopeName The name of the scope @param actor The address responsible for the action @param operator The operator's address being removed */ event ScopeRemoveOperator(string scopeName, address indexed actor, address indexed operator); /** @notice Emitted when a scope's rules are changed @param scopeName The name of the scope @param actor The address responsible for the action @param allowUserPatch Indicates whether user patches are allowed @param allowUserAssign Indicates whether user assignments are allowed @param requireWhitelist Indicates whether a whitelist is required */ event ScopeRuleChange(string scopeName, address indexed actor, bool allowUserPatch, bool allowUserAssign, bool requireWhitelist); /** @notice Emitted when a scope has an address added to the whitelist @param scopeName The name of the scope @param actor The address responsible for the action @param addr The address being added to the whitelist */ event ScopeWhitelistAdd(string scopeName, address indexed actor, address indexed addr); /** @notice Emitted when a scope has an address removed from the whitelist @param scopeName The name of the scope @param actor The address responsible for the action @param addr The address being removed from the whitelist */ event ScopeWhitelistRemove(string scopeName, address indexed actor, address indexed addr); /** @notice Claim a scope @param scopeName the name of the scope */ function claimScope(string calldata scopeName) public { Scope storage s = _scopes[scopeName]; if (s.owner != address(0)) { revert ScopeExists(scopeName); } s.owner = msg.sender; // s.requireWhitelist = true; // better security by default - enable in future PR emit ScopeClaim(scopeName, msg.sender); } /** @notice Transfer ownership of a scope @param scopeName Name of the scope @param newOwner Address of the new owner */ function transferScopeOwnership(string calldata scopeName, address newOwner) public { Scope storage s = _mustHaveScope(scopeName); _mustBeOwner(s); if (newOwner == address(0)) { revert ScopeTransferNotAllowed(address(0)); } s.owner = newOwner; emit ScopeTransfer(scopeName, msg.sender, newOwner); } /** @notice Get owner of a scope @param scopeName Name of the scope @return owner Address of the scope owner */ function getScopeOwner(string calldata scopeName) public view returns (address owner) { return _scopes[scopeName].owner; } /** @notice Add an operator to a scope @param scopeName Name of the scope @param op Address of the operator */ function addOperator(string calldata scopeName, address op) public { Scope storage s = _mustHaveScope(scopeName); _mustBeOwner(s); s.operators[op] = true; emit ScopeAddOperator(scopeName, msg.sender, op); } /** @notice Remove an operator from a scope @param scopeName Name of the scope @param op Address of the operator */ function removeOperator(string calldata scopeName, address op) public { Scope storage s = _mustHaveScope(scopeName); _mustBeOwner(s); s.operators[op] = false; emit ScopeRemoveOperator(scopeName, msg.sender, op); } /** @notice Set rules for a scope @param scopeName Name of the scope @param allowUserPatch Boolean indicating whether user patches are allowed @param allowUserAssign Boolean indicating whether user assignments are allowed @param requireWhitelist Boolean indicating whether whitelist is required */ function setScopeRules(string calldata scopeName, bool allowUserPatch, bool allowUserAssign, bool requireWhitelist) public { Scope storage s = _mustHaveScope(scopeName); _mustBeOwner(s); s.allowUserPatch = allowUserPatch; s.allowUserAssign = allowUserAssign; s.requireWhitelist = requireWhitelist; emit ScopeRuleChange(scopeName, msg.sender, allowUserPatch, allowUserAssign, requireWhitelist); } /** @notice Add an address to a scope's whitelist @param scopeName Name of the scope @param addr Address to be whitelisted */ function addWhitelist(string calldata scopeName, address addr) public { Scope storage s = _mustHaveScope(scopeName); _mustBeOwnerOrOperator(s); s.whitelist[addr] = true; emit ScopeWhitelistAdd(scopeName, msg.sender, addr); } /** @notice Remove an address from a scope's whitelist @param scopeName Name of the scope @param addr Address to be removed from the whitelist */ function removeWhitelist(string calldata scopeName, address addr) public { Scope storage s = _mustHaveScope(scopeName); _mustBeOwnerOrOperator(s); s.whitelist[addr] = false; emit ScopeWhitelistRemove(scopeName, msg.sender, addr); } /** @notice Create a new patch @param originalNFTAddress Address of the original NFT @param originalNFTTokenId Token ID of the original NFT @param patchAddress Address of the IPatchworkPatch to mint @return tokenId Token ID of the newly created patch */ function createPatch(address originalNFTAddress, uint originalNFTTokenId, address patchAddress) public returns (uint256 tokenId) { IPatchworkPatch patch = IPatchworkPatch(patchAddress); string memory scopeName = patch.getScopeName(); // mint a Patch that is soulbound to the originalNFT using the contract address at patchAddress which must support Patchwork metadata Scope storage scope = _mustHaveScope(scopeName); _mustBeWhitelisted(scopeName, scope, patchAddress); address tokenOwner = IERC721(originalNFTAddress).ownerOf(originalNFTTokenId); if (scope.owner == msg.sender || scope.operators[msg.sender]) { // continue } else if (scope.allowUserPatch && msg.sender == tokenOwner) { // continue } else { revert NotAuthorized(msg.sender); } // limit this to one unique patch (originalNFTAddress+TokenID+patchAddress) bytes32 _hash = keccak256(abi.encodePacked(originalNFTAddress, originalNFTTokenId, patchAddress)); if (scope.uniquePatches[_hash]) { revert AlreadyPatched(originalNFTAddress, originalNFTTokenId, patchAddress); } scope.uniquePatches[_hash] = true; tokenId = patch.mintPatch(tokenOwner, originalNFTAddress, originalNFTTokenId); emit Patch(tokenOwner, originalNFTAddress, originalNFTTokenId, patchAddress, tokenId); return tokenId; } /** @notice Assigns an NFT relation to have an IPatchworkLiteRef form a LiteRef to a IPatchworkAssignableNFT @param fragment The IPatchworkAssignableNFT address to assign @param fragmentTokenId The IPatchworkAssignableNFT Token ID to assign @param target The IPatchworkLiteRef address to hold the reference to the fragment @param targetTokenId The IPatchworkLiteRef Token ID to hold the reference to the fragment */ function assignNFT(address fragment, uint256 fragmentTokenId, address target, uint256 targetTokenId) public mustNotBeFrozen(target, targetTokenId) { address targetOwner = IERC721(target).ownerOf(targetTokenId); uint64 ref = _doAssign(fragment, fragmentTokenId, target, targetTokenId, targetOwner); // call addReference on the target IPatchworkLiteRef(target).addReference(targetTokenId, ref); } /** @notice Assign multiple NFT fragments to a target NFT in batch @param fragments The array of addresses of the fragment IPatchworkAssignableNFTs @param tokenIds The array of token IDs of the fragment IPatchworkAssignableNFTs @param target The address of the target IPatchworkLiteRef NFT @param targetTokenId The token ID of the target IPatchworkLiteRef NFT */ function batchAssignNFT(address[] calldata fragments, uint[] calldata tokenIds, address target, uint targetTokenId) public mustNotBeFrozen(target, targetTokenId) { if (fragments.length != tokenIds.length) { revert BadInputLengths(); } address targetOwner = IERC721(target).ownerOf(targetTokenId); uint64[] memory refs = new uint64[](fragments.length); for (uint i = 0; i < fragments.length; i++) { address fragment = fragments[i]; uint256 fragmentTokenId = tokenIds[i]; refs[i] = _doAssign(fragment, fragmentTokenId, target, targetTokenId, targetOwner); } IPatchworkLiteRef(target).batchAddReferences(targetTokenId, refs); } /** @notice Performs assignment of an IPatchworkAssignableNFT to an IPatchworkLiteRef @param fragment the IPatchworkAssignableNFT's address @param fragmentTokenId the IPatchworkAssignableNFT's tokenId @param target the IPatchworkLiteRef target's address @param targetTokenId the IPatchworkLiteRef target's tokenId @param targetOwner the owner address of the target @return uint64 literef of assignable in target */ function _doAssign(address fragment, uint256 fragmentTokenId, address target, uint256 targetTokenId, address targetOwner) private mustNotBeFrozen(fragment, fragmentTokenId) returns (uint64) { if (fragment == target && fragmentTokenId == targetTokenId) { revert SelfAssignmentNotAllowed(fragment, fragmentTokenId); } IPatchworkAssignableNFT assignableNFT = IPatchworkAssignableNFT(fragment); if (_isLocked(fragment, fragmentTokenId)) { revert Locked(fragment, fragmentTokenId); } // Use the fragment's scope for permissions, target already has to have fragment registered to be assignable string memory scopeName = assignableNFT.getScopeName(); Scope storage scope = _mustHaveScope(scopeName); _mustBeWhitelisted(scopeName, scope, fragment); if (scope.owner == msg.sender || scope.operators[msg.sender]) { // Fragment and target must be same owner if (IERC721(fragment).ownerOf(fragmentTokenId) != targetOwner) { revert NotAuthorized(msg.sender); } } else if (scope.allowUserAssign) { // If allowUserAssign is set for this scope, the sender must own both fragment and target if (IERC721(fragment).ownerOf(fragmentTokenId) != msg.sender) { revert NotAuthorized(msg.sender); } if (targetOwner != msg.sender) { revert NotAuthorized(msg.sender); } // continue } else { revert NotAuthorized(msg.sender); } // reduce stack to stay under limit uint64 ref; { (uint64 _ref, bool redacted) = IPatchworkLiteRef(target).getLiteReference(fragment, fragmentTokenId); ref = _ref; if (ref == 0) { revert FragmentUnregistered(address(fragment)); } if (redacted) { revert FragmentRedacted(address(fragment)); } if (scope.liteRefs[ref]) { revert FragmentAlreadyAssignedInScope(scopeName, address(fragment), fragmentTokenId); } } // call assign on the fragment assignableNFT.assign(fragmentTokenId, target, targetTokenId); // add to our storage of scope->target assignments scope.liteRefs[ref] = true; emit Assign(targetOwner, fragment, fragmentTokenId, target, targetTokenId); return ref; } /** @notice Unassign a NFT fragment from a target NFT @param fragment The IPatchworkAssignableNFT address of the fragment NFT @param fragmentTokenId The IPatchworkAssignableNFT token ID of the fragment NFT */ function unassignNFT(address fragment, uint fragmentTokenId) public mustNotBeFrozen(fragment, fragmentTokenId) { IPatchworkAssignableNFT assignableNFT = IPatchworkAssignableNFT(fragment); string memory scopeName = assignableNFT.getScopeName(); Scope storage scope = _mustHaveScope(scopeName); if (scope.owner == msg.sender || scope.operators[msg.sender]) { // continue } else if (scope.allowUserAssign) { // If allowUserAssign is set for this scope, the sender must own both fragment if (IERC721(fragment).ownerOf(fragmentTokenId) != msg.sender) { revert NotAuthorized(msg.sender); } // continue } else { revert NotAuthorized(msg.sender); } (address target, uint256 targetTokenId) = IPatchworkAssignableNFT(fragment).getAssignedTo(fragmentTokenId); if (target == address(0)) { revert FragmentNotAssigned(fragment, fragmentTokenId); } assignableNFT.unassign(fragmentTokenId); (uint64 ref, ) = IPatchworkLiteRef(target).getLiteReference(fragment, fragmentTokenId); if (ref == 0) { revert FragmentUnregistered(address(fragment)); } if (!scope.liteRefs[ref]) { revert RefNotFoundInScope(scopeName, target, fragment, fragmentTokenId); } scope.liteRefs[ref] = false; IPatchworkLiteRef(target).removeReference(targetTokenId, ref); emit Unassign(IERC721(target).ownerOf(targetTokenId), fragment, fragmentTokenId, target, targetTokenId); } /** @notice Apply transfer rules and actions of a specific token from one address to another @param from The address of the sender @param to The address of the receiver @param tokenId The ID of the token to be transferred */ function applyTransfer(address from, address to, uint256 tokenId) public { address nft = msg.sender; if (IERC165(nft).supportsInterface(type(IPatchworkAssignableNFT).interfaceId)) { IPatchworkAssignableNFT assignableNFT = IPatchworkAssignableNFT(nft); (address addr,) = assignableNFT.getAssignedTo(tokenId); if (addr != address(0)) { revert TransferBlockedByAssignment(nft, tokenId); } } if (IERC165(nft).supportsInterface(type(IPatchworkPatch).interfaceId)) { revert SoulboundTransferNotAllowed(nft, tokenId); } if (IERC165(nft).supportsInterface(type(IPatchworkNFT).interfaceId)) { if (IPatchworkNFT(nft).locked(tokenId)) { revert Locked(nft, tokenId); } } if (IERC165(nft).supportsInterface(type(IPatchworkLiteRef).interfaceId)) { IPatchworkLiteRef liteRefNFT = IPatchworkLiteRef(nft); (address[] memory addresses, uint256[] memory tokenIds) = liteRefNFT.loadAllReferences(tokenId); for (uint i = 0; i < addresses.length; i++) { if (addresses[i] != address(0)) { _applyAssignedTransfer(addresses[i], from, to, tokenIds[i], nft, tokenId); } } } } function _applyAssignedTransfer(address nft, address from, address to, uint256 tokenId, address assignedToNFT_, uint256 assignedToTokenId_) private { if (!IERC165(nft).supportsInterface(type(IPatchworkAssignableNFT).interfaceId)) { revert NotPatchworkAssignable(nft); } (address assignedToNFT, uint256 assignedToTokenId) = IPatchworkAssignableNFT(nft).getAssignedTo(tokenId); // 2-way Check the assignment to prevent spoofing if (assignedToNFT_ != assignedToNFT || assignedToTokenId_ != assignedToTokenId) { revert DataIntegrityError(assignedToNFT_, assignedToTokenId_, assignedToNFT, assignedToTokenId); } IPatchworkAssignableNFT(nft).onAssignedTransfer(from, to, tokenId); if (IERC165(nft).supportsInterface(type(IPatchworkLiteRef).interfaceId)) { address nft_ = nft; // local variable prevents optimizer stack issue in v0.8.18 IPatchworkLiteRef liteRefNFT = IPatchworkLiteRef(nft); (address[] memory addresses, uint256[] memory tokenIds) = liteRefNFT.loadAllReferences(tokenId); for (uint i = 0; i < addresses.length; i++) { if (addresses[i] != address(0)) { _applyAssignedTransfer(addresses[i], from, to, tokenIds[i], nft_, tokenId); } } } } /** @notice Update the ownership tree of a specific Patchwork NFT @param nft The address of the Patchwork NFT @param tokenId The ID of the token whose ownership tree needs to be updated */ function updateOwnershipTree(address nft, uint256 tokenId) public { if (IERC165(nft).supportsInterface(type(IPatchworkLiteRef).interfaceId)) { IPatchworkLiteRef liteRefNFT = IPatchworkLiteRef(nft); (address[] memory addresses, uint256[] memory tokenIds) = liteRefNFT.loadAllReferences(tokenId); for (uint i = 0; i < addresses.length; i++) { if (addresses[i] != address(0)) { updateOwnershipTree(addresses[i], tokenIds[i]); } } } if (IERC165(nft).supportsInterface(type(IPatchworkAssignableNFT).interfaceId)) { IPatchworkAssignableNFT(nft).updateOwnership(tokenId); } else if (IERC165(nft).supportsInterface(type(IPatchworkPatch).interfaceId)) { IPatchworkPatch(nft).updateOwnership(tokenId); } } /** @notice Requires that scopeName is present @dev will revert with ScopeDoesNotExist if not present @return scope the scope */ function _mustHaveScope(string memory scopeName) private view returns (Scope storage scope) { scope = _scopes[scopeName]; if (scope.owner == address(0)) { revert ScopeDoesNotExist(scopeName); } } /** @notice Requires that addr is whitelisted if whitelisting is enabled @dev will revert with NotWhitelisted if whitelisting is enabled and address is not whitelisted @param scopeName the name of the scope @param scope the scope @param addr the address to check */ function _mustBeWhitelisted(string memory scopeName, Scope storage scope, address addr) private view { if (scope.requireWhitelist && !scope.whitelist[addr]) { revert NotWhitelisted(scopeName, addr); } } /** @notice Requires that msg.sender is owner of scope @dev will revert with NotAuthorized if msg.sender is not owner @param scope the scope */ function _mustBeOwner(Scope storage scope) private view { if (msg.sender != scope.owner) { revert NotAuthorized(msg.sender); } } /** @notice Requires that msg.sender is owner or operator of scope @dev will revert with NotAuthorized if msg.sender is not owner or operator @param scope the scope */ function _mustBeOwnerOrOperator(Scope storage scope) private view { if (msg.sender != scope.owner && !scope.operators[msg.sender]) { revert NotAuthorized(msg.sender); } } /** @notice Requires that nft is not frozen @dev will revert with Frozen if nft is frozen @param nft the address of nft @param tokenId the tokenId of nft */ modifier mustNotBeFrozen(address nft, uint256 tokenId) { if (_isFrozen(nft, tokenId)) { revert Frozen(nft, tokenId); } _; } /** @notice Determines if nft is frozen using ownership hierarchy @param nft the address of nft @param tokenId the tokenId of nft @return frozen if the nft or an owner up the tree is frozen */ function _isFrozen(address nft, uint256 tokenId) private view returns (bool frozen) { if (IERC165(nft).supportsInterface(type(IPatchworkNFT).interfaceId)) { if (IPatchworkNFT(nft).frozen(tokenId)) { return true; } if (IERC165(nft).supportsInterface(type(IPatchworkAssignableNFT).interfaceId)) { (address assignedAddr, uint256 assignedTokenId) = IPatchworkAssignableNFT(nft).getAssignedTo(tokenId); if (assignedAddr != address(0)) { return _isFrozen(assignedAddr, assignedTokenId); } } } return false; } /** @notice Determines if nft is locked @param nft the address of nft @param tokenId the tokenId of nft @return locked if the nft is locked */ function _isLocked(address nft, uint256 tokenId) private view returns (bool locked) { if (IERC165(nft).supportsInterface(type(IPatchworkNFT).interfaceId)) { if (IPatchworkNFT(nft).locked(tokenId)) { return true; } } return false; } }
import React, { useState } from 'react'; import axios from 'axios'; import Cookies from 'js-cookie'; import { useNavigate } from 'react-router-dom'; import { Form, Button, Container, Row, Col } from 'react-bootstrap'; import styled from 'styled-components'; import { AiOutlineEye, AiOutlineEyeInvisible } from 'react-icons/ai'; const SignIn = () => { const [userData, setUserData] = useState({ email: '', password: '' }); const navigate = useNavigate(); const [showPassword, setShowPassword] = useState(false); const handleChange = (e) => { setUserData({ ...userData, [e.target.name]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const { data } = await axios.post('http://localhost:5000/api/auth/signin', userData); if(!data) navigate('/signin') Cookies.set('token', data.token, { expires: 10, secure: true }); // Set cookie with token navigate('/profile'); console.log("user signed in successfully", data); } catch (error) { console.error(error); alert("Wrong Credentials"); } }; const toggleShowPassword = () => { setShowPassword(!showPassword); }; const handleGuestSignIn = (email, password) => { setUserData({ email, password }); }; return ( <div style={{ minHeight: '100vh', justifyContent: 'center', alignItems: 'center',background: 'linear-gradient(to bottom, #87CEEB, #FFFFFF)' }}> <Container> <Row className="justify-content-center"> <Col xs={10} sm={8} md={6}> <div className="border border-black p-4 mt-5" style={{borderRadius:"20px",padding:"20px"}}> <h2 className="mb-4 text-center">Sign In</h2> <Form onSubmit={handleSubmit}> <Form.Group controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> <Form.Control type="email" placeholder="Enter email" name="email" value={userData.email} onChange={handleChange} required /> </Form.Group> <Form.Group controlId="formBasicPassword"> <Form.Label>Password</Form.Label> <div className="position-relative"> <Form.Control type={showPassword ? "text" : "password"} placeholder="Password" name="password" value={userData.password} onChange={handleChange} required /> <span className="position-absolute top-50 end-0 translate-middle-y"> {showPassword ? <AiOutlineEyeInvisible onClick={toggleShowPassword} /> : <AiOutlineEye onClick={toggleShowPassword} style={{marginRight:'10px'}}/>} </span> </div> </Form.Group> <br /> <Button variant="primary" type="submit" className="w-100"> Sign In </Button> <Button variant="warning" onClick={() => handleGuestSignIn('guest-viewer@example.com', 'guest123')} className="w-100 mt-2"> Sign In as Guest Viewer </Button> <Button variant="warning" onClick={() => handleGuestSignIn('guest-business@example.com', 'guest123')} className="w-100 mt-2"> Sign In as Guest Business </Button> </Form> </div> </Col> </Row> </Container> </div> ); }; export default SignIn;
@extends('admin.dashboard_layout') @section('content') <!-- Begin Page Content --> <div class="container-fluid"> <!-- Page Heading --> <h1 class="h3 mb-3 text-gray-800">Edit_Products</h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-1 font-weight-bold text-primary">Add-Products</h6> </div> <div class="card-body"> <form action={{ route('products.update', $editProduct->id) }} method="POST"> @csrf @method('PUT') <div class="form-group"> <label for="exampleFormControlInput1">Product Name</label> <input type="text" class="form-control" name="prod_name" id="exampleFormControlInput1" placeholder="Product's Name" value="{{ $editProduct->prod_name }}" @error('prod_name') style = "border-color: red;" @enderror> @error('prod_name') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group"> <label for="exampleFormControlInput1">Product Price</label> <input type="number" class="form-control" name="price" id="exampleFormControlInput1" step="0.001" placeholder="Enter Price" value={{ $editProduct->price }} @error('price') style = "border-color: red;" @enderror> @error('price') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group"> <label for="exampleFormControlSelect1">Category</label> <select name="category_id" class="form-control" id="exampleFormControlSelect1" @error('category_id') style = "border-color: red;" @enderror> <option value="0">--- Select Category ---</option> @foreach ($categories as $item) <option value="{{ $item->id }}" {{ $item->id == $editProduct->category_id ? 'selected' : '' }}>{{ $item->name }} </option> @endforeach </select> @error('category_id') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Short Description</label> <textarea class="form-control ckeditor" name="short_desc" rows="2" @error('price') style = "border-color: red;" @enderror>{{ $editProduct->short_desc }}</textarea> @error('short_desc') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Product Description</label> <textarea class="form-control ckeditor" name="prod_desc" id="editor" rows="8">{{ $editProduct->prod_desc }}</textarea> @error('prod_desc') <div class="alert alert-danger">{{ $message }}</div> @enderror </div> <div class="custom-file"> <input type="file" id="customFile" name="image"> </div> <div class="form-group mt-4"> <input type="submit" value="Update Products" class="btn btn-warning m-2"> <input type="reset" value="Clear" class="btn btn-secondary "> </div> </form> </div> </div> </div> <!-- /.container-fluid --> @endsection
import Layout from "@/components/desktop-layout"; import { selectSession, useAuthStore } from "@/store/auth"; import { Session } from "@supabase/supabase-js"; import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { Menu, X, Sun, Moon, UserCog } from "lucide-react"; import { userDataAPI } from "@/APIs/userdata-api"; import { useSetTheme, useTheme } from "@/store/theme"; import { Avatar } from "@/components/avatar"; import { toast } from "@/components/ui/use-toast"; import "react-device-frameset/styles/marvel-devices.min.css"; import SocmedList from "@/components/socmed-list"; import whatsappIcon from "/assets/whatsapp.svg"; import instagramIcon from "/assets/instagram.svg"; import linkedinIcon from "/assets/linkedin.svg"; import githubIcon from "/assets/github.svg"; import gmailIcon from "/assets/gmail.svg"; import Sidebar from "@/components/sidebar"; const Desktop = () => { const [error, setError] = useState<string | null>(null); const [showSideBar, setShowSidebar] = useState(false); const session: Session = useAuthStore(selectSession) as Session; const theme = useTheme(); const setTheme = useSetTheme(); const navigate = useNavigate(); const [userData, setUserData] = useState({ full_name: "", username: "", greeting: "", about: "", whatsapp: "", instagram: "", linkedin: "", github: "", gmail: "", avatar_url: "", }); useEffect(() => { const avatarBg = document.getElementById("avatar_url") as HTMLImageElement; if (showSideBar && theme === "dark") { avatarBg.classList.add("bg-deep-blue/100"); } else { avatarBg.classList.remove("bg-deep-blue/100"); } }, [showSideBar, theme]); useEffect(() => { document.title = userData.full_name || "MySocialLink - Profile"; }, [userData.full_name]); useEffect(() => { function getProfile() { setError(null); const userData = session as Session; try { userDataAPI.getUserData(userData.user.id).then((data) => { setUserData((prevUserData) => ({ ...prevUserData, ...data, })); }); } catch (err) { if (err instanceof Error) { setError(err.message); } } } getProfile(); }, [session]); useEffect(() => { if (error) toast({ description: error, className: "border-red-500 text-red-500 w-fit text-center fixed top-[12%] left-[52%] -translate-x-1/2 py-2", duration: 1500, }); }, [error]); const socialLink = [ { id: 1, logo: whatsappIcon, link: "https://api.whatsapp.com/send?phone=" + userData.whatsapp, width: "31px", height: "31px", text: "WhatsApp", }, { id: 2, logo: instagramIcon, link: "https://www.instagram.com/" + userData.instagram, width: "30px", height: "30px", text: "Instagram", }, { id: 3, logo: linkedinIcon, link: "https://www.linkedin.com/in/" + userData.linkedin, width: "28px", height: "28px", text: "LinkedIn", }, { id: 4, logo: githubIcon, link: "https://github.com/" + userData.github, width: "30px", height: "30px", text: "GitHub", }, { id: 5, logo: gmailIcon, link: `mailto:${userData.gmail}`, width: "30px", height: "30px", text: "Gmail", }, ]; return ( <div className="flex"> <div className="min-h-screen flex items-center mx-auto"> <div id="desktop" className="w-max"> <Layout className="pointer-events-auto"> <div id="divMenuIcon" className="mt-5 flex justify-between px-3"> <div className=""> {/* <Link to="/settings"> */} <button className="block" onClick={() => navigate("/settings")}> <UserCog className="hover:bg-black hover:bg-opacity-[0.08] w-6 h-fit" /> </button> {/* </Link> */} </div> <div className="z-20"> <button className="block" onClick={() => { setShowSidebar(!showSideBar); }} > {!showSideBar ? ( <Menu id="menuIcon" className={`hover:bg-black hover:bg-opacity-[0.08] w-fit h-fit`} /> ) : ( <X className={`w-[23px] dark:text-slate-600`} /> )} </button> </div> </div> {showSideBar ? ( <Sidebar userData={userData} desktopSideBar=" z-10 h-[91%] mt-[31px] w-[69%] " /> ) : null} <div className="mx-auto py-1"> <button aria-label="Toggle Dark Mode" className="block hover:animate-spin dark:hover:animate-bounce focus:animate-spin dark:focus:animate-bounce focus:bg-black focus:bg-opacity-10 dark:focus:bg-opacity-20 rounded-full delay-200 duration-500 ease-in text-slate-600 dark:text-slate-200" onClick={setTheme} > {theme === "light" ? <Sun className="w-7 h-7" /> : <Moon className="w-7 h-7" />} </button> </div> <div id="photoProfile" className="w-fit mx-auto py-3 z-20"> <Avatar url={userData.avatar_url} isEdit={false} /> </div> <div className="py-4"> <div className="w-fit m-auto gap-[16px] grid"> {socialLink.map((link) => ( <SocmedList key={link.id} gambar={link.logo} width={link.width} height={link.height} text={link.text} link={link.link} /> ))} </div> </div> <div className="flex-1"> <div className="font-inter whitespace-nowrap text-[12px] text-[#737373] bottom-2 absolute -translate-x-1/2 left-1/2 dark:text-[#dfdfdf]"> Copyright © 2023 Naufal Nasrullah ∙ All Rights Reserved </div> </div> </Layout> </div> </div> </div> ); }; export default Desktop;
# 11. Container With Most Water # https://leetcode.com/problems/container-with-most-water/description/ # @param {Integer[]} height # @return {Integer} # O(n) algorithm for largest water container area in array using two indices: def max_area(height) # Initialize left and right index for going through array from each side: l, r = 0, height.length - 1 max_area = 0 # Go through the array until indices meet in the middle: while l < r # 2-D water container area is width (index difference) by height (smallest of the two): current_area = (r - l) * [height[l], height[r]].min # Update area of largest container if new container is largest: max_area = [max_area, current_area].max # Move left index right if left height is smaller: if height[l] < height[r] l += 1 # Move right index left otherwise: else r -= 1 end end # Return area of largest water container: return max_area end
/* * Copyright (C) 2011 Alexandre Quessy * Copyright (C) 2011 Michal Seta * Copyright (C) 2012 Nicolas Bouillot * * This file is part of Tempi. * * This program is free software: you can redistribute it and/or * modify it under the terms of, either version 3 of the License, or * (at your option) any later version. * * Tempi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Tempi. If not, see <http://www.gnu.org/licenses/>. */ /** * @file The tempi application. */ #include <iostream> #include "tempi/config.h" #ifndef HAVE_GLIB int main(int argc, char *argv[]) { std::cout << "No glib support" << std::endl; return 1; } #else // HAVE_GLIB #include "tempi/message.h" #include "tempi/scheduler.h" #include "tempi/threadedscheduler.h" #include "tempi/serializer.h" #include "tempi/log.h" #include <glib.h> #include <sstream> // namespaces: using tempi::INFO; using tempi::DEBUG; // String constants: static const char *PROGRAM_NAME = "tempi-launch"; static const char *GRAPH_NAME = "graph0"; // FIXME: store these options in a struct static gboolean help = FALSE; static gboolean version = FALSE; static gboolean verbose = FALSE; static gboolean debug = FALSE; static gchar** filenames = NULL; static GOptionEntry entries[] = { {"version", 0, 0, G_OPTION_ARG_NONE, &version, "Show program's version number and exit"}, {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Enables a verbose output"}, {"debug", 'd', 0, G_OPTION_ARG_NONE, &debug, "Enables a very verbose output"}, {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &filenames, "Tempi files to read"}, {NULL} }; /** * The TempiLauncher class is the tempi-launch application. */ class TempiLauncher { public: TempiLauncher(); ~TempiLauncher(); /** * Return -1 if it's ok to run the program, or retuns 0 or 1 if we should terminate it. * Call this begore launching the app. */ int parse_options(int argc, char **argv); /** * Creates the tempi::Graph, and the ClutterStage */ bool launch(); bool getVerbose() const; bool getDebug() const; private: std::string fileName_; bool graph_ok_; bool verbose_; bool debug_; tempi::ThreadedScheduler::ptr engine_; tempi::Graph::ptr graph_; bool setupGraph(); }; TempiLauncher::TempiLauncher() : verbose_(false), debug_(false), graph_ok_(false) { } bool TempiLauncher::getVerbose() const { return verbose_; } TempiLauncher::~TempiLauncher() { if (engine_.get() != 0) { { std::ostringstream os; os << __FUNCTION__ << "(): Waiting for Scheduler's thread to join."; tempi::Logger::log(DEBUG, os.str().c_str()); } engine_->stop(); } } bool TempiLauncher::setupGraph() { using tempi::Message; if (graph_ok_) { std::cerr << "tempi-launch: TempiLauncher::" << __FUNCTION__ << ": already called.\n"; return false; } // Check for XML file if (! tempi::serializer::fileExists(fileName_.c_str())) { std::cerr << "tempi-launch: ERROR: File \"" << fileName_ << "\" not found!\n"; return false; } { std::ostringstream os; os << "tempi-launch: Found " << fileName_; tempi::Logger::log(DEBUG, os.str().c_str()); } // Create Scheduler if (tempi::Logger::isEnabledFor(tempi::DEBUG)) { std::ostringstream os; os << "tempi-launch: Create ThreadedScheduler\n"; tempi::Logger::log(DEBUG, os.str().c_str()); } engine_.reset(new tempi::ThreadedScheduler); engine_->start(5); // time precision in ms // TODO: make time precision configurable //if (verbose_) // std::cout << (*engine_.get()) << std::endl; tempi::ScopedLock::ptr lock = engine_->acquireLock(); if (tempi::Logger::isEnabledFor(tempi::DEBUG)) { std::ostringstream os; os << "tempi-launch: Create Graph\n"; tempi::Logger::log(DEBUG, os.str().c_str()); } engine_->createGraph(GRAPH_NAME); graph_ = engine_->getGraph(GRAPH_NAME); // load graph tempi::serializer::load(*graph_.get(), fileName_.c_str()); graph_->tick(); // FIXME graph_ok_ = true; if (debug_) { //engine_->sleepThisThread(6.0f); std::cout << (*engine_.get()) << std::endl; } { std::ostringstream os; os << "tempi-launch: Loaded " << fileName_; tempi::Logger::log(DEBUG, os.str().c_str()); } return true; } bool TempiLauncher::launch() { if (graph_ok_) { std::cerr << "TempiLauncher::" << __FUNCTION__ << "(): Already called\n"; return false; } else { if (setupGraph()) { if (verbose_) std::cout << "Running... Press ctrl-C in the terminal to quit." << std::endl; return true; } else return false; } } int TempiLauncher::parse_options(int argc, char **argv) { GError* error = NULL; GOptionContext* context; context = g_option_context_new(" - Runs Tempi graphs from XML files"); g_option_context_add_main_entries(context, entries, NULL); //g_option_context_add_group(context, g_option_context_get_main_group(context)); if (! g_option_context_parse(context, &argc, &argv, &error)) { return 1; } if (version) { std::cout << PROGRAM_NAME << " " << PACKAGE_VERSION << std::endl; return 0; } if (verbose) { verbose_ = verbose; tempi::Logger::getInstance().setLevel(tempi::INFO); tempi::Logger::log(INFO, "Set logging level to INFO"); } if (debug) { debug_ = debug; tempi::Logger::getInstance().setLevel(tempi::DEBUG); tempi::Logger::log(INFO, "Set logging level to DEBUG"); } if (filenames != NULL) { guint numFiles; numFiles = g_strv_length(filenames); for (guint i = 0; i < numFiles; ++i) { // TODO: load all files } if (numFiles >= 1) { // // At the moment we load just the first file specified fileName_ = filenames[0]; // std::cout << fileName_ << std::endl; } else { std::ostringstream os; os << "No file name specified"; tempi::Logger::log(tempi::ERROR, os.str().c_str()); } } if (tempi::Logger::isEnabledFor(tempi::INFO)) { std::ostringstream os; os << "File name specified on the command line: " << fileName_; tempi::Logger::log(tempi::INFO, os.str().c_str()); } return -1; } int main(int argc, char *argv[]) { int ret; TempiLauncher app; ret = app.parse_options(argc, argv); if (ret != -1) return ret; bool ok = app.launch(); if (! ok) { tempi::Logger::log(tempi::CRITICAL, "Error calling app.launch()"); return 1; } g_thread_init(NULL); GMainLoop *mainLoop = g_main_loop_new(NULL, FALSE); //g_idle_add(on_idle, (gpointer) &app); tempi::Logger::log(DEBUG, "Run main loop."); g_main_loop_run(mainLoop); g_main_loop_unref(mainLoop); return 0; } #endif // HAVE_GLIB
/* * The MIT License * * Copyright 2013 RBC1B. * * 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 uk.org.rbc1b.roms.controller.qualification; import org.springframework.stereotype.Component; import uk.org.rbc1b.roms.db.volunteer.qualification.Qualification; /** * Generate the qualifications models. */ @Component public class QualificationModelFactory { private static final String BASE_URI = "/qualifications"; /** * Generate the uri used to access the qualification pages. * @param qualificationId optional qualification id * @return uri */ public static String generateUri(Integer qualificationId) { return qualificationId != null ? BASE_URI + "/" + qualificationId : BASE_URI; } /** * Create the model. * @param qualification qualification * @return model */ public QualificationModel generateQualificationModel(Qualification qualification) { QualificationModel model = new QualificationModel(); model.setDescription(qualification.getDescription()); model.setName(qualification.getName()); model.setQualificationId(qualification.getQualificationId()); model.setUri(generateUri(qualification.getQualificationId())); model.setEditUri(generateUri(qualification.getQualificationId()) + "/edit"); return model; } }
function loadPlasticitySweepData( folderDataPath, fileListFullPath, figureHandle ) % Load the raw data from the file list and pretreat it (organize it in % sweeps) % Opens the file list and retrieve all options about data files by % parsing their names [nbFiles, fileNames, fileBeginnings, filePaths, options, fileSweepNumbers] = getFilenamesAndOptions( folderDataPath, fileListFullPath ); % The cell containing, for every file, the sweep data : % data{fileIndex}(timeIndex, sweepIndex) data = cell( nbFiles, 1 ); % Load the data for i=1:nbFiles filename = char( fileNames{i} ); filepath = char( filePaths{i} ); if ~( exist( filepath, 'file' ) && ~exist( filepath, 'dir' ) ) warndlg( sprintf('Error : the file "%s" (%s) couldn''t be found', filename, filepath) ); return end % Don't filter the sweeps sweepsToKeep = 1:fileSweepNumbers(i); display(strcat('loading ''', filename, '''...')) ; rawData = load( filepath ) ; display('data loaded') ; %%%%%%%%%%%%%%%%%%%%% ASCII raw Data file to Data matrix %%%%%%%%%%%%%%%%%% % nbSweeps will now contain the number of sweeps actually treated % (taking "sweepsToKeep" into account) : here, nbSweeps remains the % same since sweepsToKeep = 1:nbSweeps [data{i}, sweepSize, fileSweepNumbers(i)] = preteatRawData( rawData, fileSweepNumbers(i), sweepsToKeep ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end display( sprintf('--- Loaded %d files into workspace ---', nbFiles) ); % Informations about the times (beginning and end) of the files dataTimeInfo = cell( nbFiles, 2 ) for i=1:nbFiles dataTimeInfo{i,1} = fileBeginnings(i)Timeinfo; dataTimeInfo{i,2} = fileBeginnings(i) + data{i}( end, nbSweeps+2 ); end % Save the data assignin( 'base', 'plasticityData', data ); assignin( 'base', 'plasticityData', data ); % Plot the data display( '--- Plotting in preview window ---' ); display( '----- one sweep by file' ); axes( figureHandle ); % make the preview axes the current ones for i=1:nbFiles hold on,plot( data{i}( :, fileSweepNumbers(i)+2 ), data{i}( :, fileSweepNumbers(i) ) ); end display( '--- Preview plotting done ---' ); end function [nbFiles, filenames, filebeginnings, filepaths, options, nbSweeps] = getFilenamesAndOptions( folderDataPath, fileListFullPath ) filenames = cell( 0 ); filebeginnings = zeros( 0 ); filepaths = cell( 0 ); options = cell( 0 ); nbSweeps = zeros( 0 ); nbFiles = 0; %%%%%%%%%%%%%%%%%%%%% reading the file list %%%%%%%%%%%%%%%%%%%%% % ex : 20090210_3_07_29_ChR2_GB if exist( fileListFullPath, 'file' ) && ~exist( fileListFullPath, 'dir' ) fid = fopen(fileListFullPath); fileList = textscan(fid, '%s %s %s %s %s %s %s %s') ; % Un champ de plus que dans les autres scripts : % la date de début de l'enregistrement, en ms (dernier champ) % 20090126 3 07 28 ChR2 GB - 123213432 fclose(fid); else warndlg( sprintf('Error : the file "%s" couldn''t be found', fileListFullPath) ); return; end %%%%%%%%%%%%%%%%%%%%% END reading the file list %%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%% Analysis of the file names %%%%%%%%%%%%%%%%%%%%% expdate_cells = fileList{1} ; % class = cell : folder (and date) inf1_cells = fileList{2} ; % class = cell inf2_cells = fileList{3} ; % class = cell inf3_cells = fileList{4} ; % class = cell : number of sweeps in the file type1_cells = fileList{5} ; % class = cell type2_cells = fileList{6} ; % class = cell nbFiles = numel( expdate_cells ) ; filenames = cell( nbFiles, 1 ); filebeginnings = zeros( nbFiles, 1 ); filepaths = cell( nbFiles, 1 ); options = cell( nbFiles, 1 ); nbSweeps = zeros( nbFiles, 1 ); for i = 1:nbFiles path = strcat( folderDataPath, expdate_cells{i}, filesep() ); strfilename = strcat( expdate_cells{i}, '_', inf1_cells{i}, '_', inf2_cells{i}, '_', inf3_cells{i}, '_', type1_cells{i}, '_',type2_cells{i}, '.asc' ); filenames{i,:} = cellstr( strfilename ); strfilename = strcat( path, strfilename ); filebeginnings(i) = str2double( fileList{8}{i} ) ; filepaths{i,:} = cellstr( strfilename ); options{i, :} = fileList{7}{i}; nbSweeps(i) = str2double( inf3_cells{i} ) ; end end
// 풀이 1. function solution1(strings, n) { return strings.sort((a, b) => { if(a[n] > b[n]) return 1; else if(a[n] < b[n]) return -1; else if(a[n] === b[n]) { if(a > b) return 1; else if(a < b) return -1; else return 0; } }); } // sort()는 문자열을 사전순으로 정렬한다. // a > b 이면 사전순 이므로 return 1 // a < b 이면 사전순 반대 이르모 return -1 // a === b 이면 같은 문자열이므로 return 0 // 풀이 2. function solution2(strings, n) { return strings.sort((a, b) => a[n] === b[n] ? a.localeCompare(b) : a[n].localeCompare(b[n])); } // str1.localeCompare(str2) 메서드는 참조 문자열(str1)이 정렬 순서에서 // 주어진 문자열(str2)과 앞인지 뒤인지 또는 같은지 나타내는 숫자를 반환합니다. // str1이 str2보다 앞이면 -1 // str1이 str2보다 뒤면 1 // str1이 str2와 같으면 0 // 쉽게 이해하자면 sort((a, b) => ) 에서 parameter a는 str1, b는 str2로 이해하면 쉽다. // NOTE: 정렬 사용
## 9. Range Queries ![](../__doc__/9_1.jpg) ### 1. Sum Queries Maintain a prefix sum array, i.e. $sum[i] = \sum_{j=0}^{j=i} a[j]$. Thus, each queries `[a,b]` can be calculated as $sum[b] - sum[a-1]$. Time complexity is `o(n)`, and space complexity is `O(n)`. ## 2. Min/Max Queries Min and max queries are similar. Thus, we can only consider min or max operation. Solution: (Pre-Process all power-of-2 ranges): Given the number of queries is very large, we try to minimize the time complexity for each query $min_q(a,b)$. First, we preprocess all possible $min_q(a,b)$ where `b-a+1` (the length of the range) is a power of two, i.e. $2, 4, 8, ..., 2^k$. The time complexity is O(nlogn), since we need to go through the whole array O(n) for each power (at most log n distinct powers). For any query, $min_q(a,b) = min(min_q(a, a+k-1), min_q(a+k, b))$, where `k=x&(-x)` is length of the first range, and `x=b-a+1`. Why? `x` is the length of the range `(a,b)`, `k=x&(-x)` is the least number of power (of 2) compositing of `x`. Thus, the time complexity of each query is O(log M), where $2^M$ is the maximum value of the elements in the array. The problem of this solution is that we can not modify the array, since we need to re-compute all possible power-of-2 ranges again, if we modify some elements. ## 3. Binary Indexed Tree We can modify the array in O(log n), and query in O(log n). For simplisity, we denote `bit(x) = x&(-x)`, i.e. we use `bit` function to get the least number of power of 2 compositing of x. Binary indexed tree holds the condition that: 1. Each position `i` should `care` `k` values just be in front of it: `nums[i-k+1],nums[i-k+2],...,nums[i-k+k]`, where `k=bit(i)`. 2. Here, `care` can be `sum` operation, or any other operations that satify the aggregation principles. 3. For each query, e.g. $sum_q(a,b)$, we can then use $sum_q(1, b) - sum_q(1,a-1)$, and $sum_q(1, i)$ can be computed in O(log n) as follow: ```c++ vector<int> care; vector<int> nums; int bit(x){ return x&(-x); } int sum(int i){ //return the sum of nums[1], nums[2],...nums[i] int s = 0; for(;i>0;i=i^bit(i)){ s += care[i]; } return s; } // how to modify nums and update care? void add_v_to_num_i(int i, int v){ // add v to all care elements that cover i-th elements for(;i<care.size();i+=bit(i)){care[i] += v;} } // initial the care array void init(){ for(int i=0;i<nums.size();i++>){ care.push_back(0); } for(int i=0;i<nums.size();i++){ add_v_to_num_i(i, nums[i]); } } ``` We can find that the `aggregation principles` should satisfy: 1. We can calculate the target (of range `(a,b)`) from another ranges, such as `(1,a-1)` and `(1, b)`. 2. We can modify some elements by updating the care array along the bit path while do not break BIT conditions. ## 4. Segment Tree Support modification and query in O(log n). [307. Range Sum Query - Mutable](https://leetcode.com/problems/range-sum-query-mutable/description/) Solution: ```c++ class NumArray { public: int n, N; vector<int> tree; NumArray(vector<int>& nums) { this->n = nums.size(); this->N = 1; while(this->N < this->n) this->N <<= 1; // calc the N=2^k >= n this->tree.clear(); for(int i=0;i<this->N;i++){ this->tree.push_back(0); // init tree as all zeros this->tree.push_back(0); } for(int i=0;i<this->n;i++){ this->update(i, nums[i]); // update tree according to nums } } void update(int index, int val) { index += this->N; // 1-base, fa(x) = x>>1; left-child(x) = 2x; right-child(x) = 2x+1 val -= this->tree[index]; while(index){ // update from the bottom to top, note that index-1 is the root, index-0 is not used. this->tree[index] += val; index >>= 1; } } int sumRange(int left, int right) { left += this->N; // the leaves are nums right += this->N; // thus, we need to add N to get the right position in the BTree. int s = left==right?this->tree[left]:0; int left_val = this->tree[left]; int right_val = this->tree[right]; while(left < right){ // left/right need to care those values in the left-child/right-child of LCA(left, right). s += left_val + right_val; // after this line, s exactly cover those values under left-sub-tree and right-sub-tree left_val = (left&1)==0?this->tree[left+1]:0; // calc the next potential range answer right_val = right&1?this->tree[right-1]:0; // calc the next potential range answer left >>= 1; // move to parent node right >>= 1; // move to parent node } // if left==right, it means they reach the LCA node. return s; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * obj->update(index,val); * int param_2 = obj->sumRange(left,right); */ ``` note that `LCA` in the comment means `least common ancestor`. `this->tree` is a binary tree. Here, index-1 is the root of the BTree and index-0 is not used. Thus, fa(x)=x//2, left-child(x)=2x, right-child(x)=2x+1. Space complexity is O(n), and time complexity is O(Mlog n), where `M` is the number of queries and `n` is the number of elements in the array. ## 5. Difference Array Given any array `nums`, we define a difference array, `d[i] = nums[i] - nums[i-1]` and `d[0] = nums[0]`. Thus, $nums[i] = \sum_{j=0}^{j=i} d[j]$. For any simple modification (for example, add `v` to all num in the range of `(a,b)`), we can update two points to complete the modification: `d[a] += v` and `d[b+1] -= v`.
#--- # script compares priority network between locking in protected areas and not locking in. # author: Songyan Yu # date created: 31/01/2022 #--- library(dplyr) # species representation rep.sp.files <- list.files("../../Data/R_data/", pattern = "04_PCA_repSp", full.names = TRUE) # objective function values objfun.files <- list.files(path = "../../Data/R_data/", pattern = "04_PCA_objFunc", full.names = TRUE) # solution size size.files <- list.files("../../Data/R_data/", pattern = "04_PCA_size", full.names = TRUE) target <- lapply(size.files, FUN = function(x){ strsplit(strsplit(strsplit(x, split = "/")[[1]][5], split = ".RDS")[[1]][1], split = "_")[[1]][4] }) group <- lapply(size.files, FUN = function(x){ strsplit(strsplit(strsplit(x, split = "/")[[1]][5], split = ".RDS")[[1]][1], split = "_")[[1]][5] }) # combine priority.lst <- lapply(1:6, FUN = function(x){ size <- readRDS(size.files[x]) objfun <- readRDS(objfun.files[x]) repsp <- readRDS(rep.sp.files[x]) data.frame(size, objfun, repsp) %>% mutate(target = target[[x]], group = group[[x]], no = 1:100) }) # find which solution is best best.solution <- do.call(rbind.data.frame, priority.lst) %>% filter(repsp == 25) %>% group_by(group, target) %>% filter(objfun == min(objfun)) # find best solution for each target solution.files <- list.files("../../Data/R_data/", pattern = "04_PCA_solution", full.names = TRUE) best.solution.lst <- lapply(1:length(solution.files), FUN = function(x){ priority.seg <- readRDS(solution.files[x])[[best.solution$no[x]]] }) # read in protected areas protectedArea.shp <- maptools::readShapeLines("../../Data/Shapfile/SEQ_networks_strahler02_withinProtectedAreas.shp") protected.seg <- protectedArea.shp$SegmentNo length(unique(protected.seg)) == length(protected.seg) # check if any duplicates # find newly needed segment for each target best.solution.without.protected.areas.lst <- lapply(best.solution.lst, FUN = function(x){ setdiff(x, protected.seg) }) best.solution$addedSegSize = lengths(best.solution.without.protected.areas.lst) # calculate length of priority network SEQ.network <- maptools::readShapeLines(fn = "../../Data/Shapfile/SEQ_networks_strahler02.shp") SEQ.network$RCHLEN best.solution.length <- sapply(best.solution.lst, FUN = function(x){ sum(SEQ.network$RCHLEN[match(x, SEQ.network$SegmentNo)], na.rm = TRUE) }) best.solution.without.protected.areas.length <- sapply(best.solution.without.protected.areas.lst, FUN = function(x){ sum(SEQ.network$RCHLEN[match(x, SEQ.network$SegmentNo)], na.rm = TRUE) }) # visualise priority network length library(ggplot2) library(reshape2) library(tidyr) best.solution %>% ungroup %>% mutate(length = best.solution.length, addedSegLength = best.solution.without.protected.areas.length, protSegLength = best.solution.length - best.solution.without.protected.areas.length, group = factor(group, levels = c("NO", "protectedAreas"), labels = c("No locked in", "Locked in")), target = factor(target, levels = c("015", "025", "035"), labels = c("15%", "25%", "35%"))) %>% select(target, addedSegLength, protSegLength, group) %>% pivot_longer(cols = c(addedSegLength, protSegLength)) %>% mutate(name = factor(name, levels = c("addedSegLength", "protSegLength"), labels = c("Outside protected areas", "Inside protected areas")), value = round(value, 0)) %>% ggplot(aes(x = group, y = value, fill = name)) + geom_bar(position = 'stack', stat = 'identity') + facet_grid(~target) + theme_bw() + ylab("Length of priority network (km)") + xlab("") + theme(legend.position = 'top', legend.title = element_blank()) + geom_text(aes(label = value),size = 3, position = position_stack(vjust = 0.5)) ggsave(filename = "../../Figures/Fig05_PriorityNetworkSize.jpg", dpi = 800, width = 6, height = 4)
package com.arematics.minecraft.core.language; import com.arematics.minecraft.core.configurations.Config; import com.arematics.minecraft.core.messaging.MessageHighlight; import com.arematics.minecraft.core.server.CorePlayer; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; public class LanguageAPI { private static final Map<String, Language> langs = new HashMap<>(); private static final Map<Player, LanguageUser> users = new HashMap<>(); public static LanguageUser getUser(Player p){ if(!users.containsKey(p)) { LanguageUser user = new LanguageUser(CorePlayer.get(p)); users.put(p, user); } return users.get(p); } public static Language getLanguage(String key){ return langs.get(key); } public static String prepareMessage(CommandSender sender, MessageHighlight highlight, String key){ if(sender instanceof Player){ return Config.getInstance().getPrefix() + highlight.getColorCode() + getUser((Player)sender).getLanguage().getValue(key); } return Config.getInstance().getPrefix() + highlight.getColorCode() + langs.get("ENGLISH").getValue(key); } public static String prepareRawMessage(CommandSender sender, String key){ if(sender instanceof Player){ return getUser((Player)sender).getLanguage().getValue(key); } return langs.get("ENGLISH").getValue(key); } public static void registerMessage(String langName, String key, String message){ Optional<Language> lang = langs.values().stream().filter(language -> language.getName().equals(langName)) .findFirst(); if(!lang.isPresent()) generateLanguage(langName).addText(key, message); else lang.get().addText(key, message.replaceAll("&", "§")); } private static Language generateLanguage(String name){ Language lang = new Language(name); langs.put(name, lang); return lang; } public static boolean registerFile(InputStream stream){ Properties properties = new Properties(); try{ properties.load(stream); String langName = properties.getProperty("language_name").replaceAll("\"", ""); properties.forEach((k, s) -> addVals(langName, k.toString(), s.toString().replaceAll("\"", ""))); }catch (IOException ioe){ Bukkit.getLogger().severe("Could not load File " + ioe.getMessage()); } return false; } private static void addVals(String langName, String key, String value){ if(!key.equals("language_name")) registerMessage(langName, key, value); } }
#include "binary_trees.h" binary_tree_t *trees_ancestor_first( const binary_tree_t *first, const binary_tree_t *second); binary_tree_t *trees_ancestor_second( const binary_tree_t *first, const binary_tree_t *second); /** * binary_trees_ancestor - finds the lowest common ancestor of two nodes * @first: is a pointer to the first node * @second: is a pointer to the second node * Return: Your function must return a pointer to the * lowest common ancestor node of the two given nodes * If no common ancestor was found, your function must return NULL */ binary_tree_t *binary_trees_ancestor( const binary_tree_t *first, const binary_tree_t *second) { binary_tree_t *temp1, *temp2; if (first == NULL || second == NULL) return (NULL); temp1 = trees_ancestor_first(first, second); temp2 = trees_ancestor_second(first, second); if (!temp1 && !temp2) return (NULL); else if (temp1) return (temp1); return (temp2); } /** * trees_ancestor_first - finds the lowest common ancestor * using the first node * @first: node to use to get the lowest common ancestor * @second: node to use for comparison * Return: NULL or lowest common ancestor */ binary_tree_t *trees_ancestor_first( const binary_tree_t *first, const binary_tree_t *second) { if (first == NULL || second == NULL) return (NULL); else if (first == second || first->left == second || first->right == second) return ((binary_tree_t *)first); return (trees_ancestor_first(first->parent, second)); } /** * trees_ancestor_second - finds the lowest common ancestor * using the second node * @first: node to use for comparison * @second: node to use to get the lowest common ancestor * Return: NULL or lowest common ancestor */ binary_tree_t *trees_ancestor_second( const binary_tree_t *first, const binary_tree_t *second) { if (first == NULL || second == NULL) return (NULL); else if (second == first || second->left == first || second->right == first) return ((binary_tree_t *)second); return (trees_ancestor_second(first, second->parent)); }
import { Schema, model, Document } from 'mongoose'; import { IUser } from '../interfaces/IUser'; const User = new Schema( { name: { type: String, require: [true, 'Please enter a full name'], index: true, }, email: { type: String, lowercase: true, unique: true, index: true, }, type: { type: String, enum: ['buyer', 'seller', 'logistics'], require: [true, 'Please enter user type'], default: 'buyer', }, password: String, salt: String, role: { type: String, default: 'user', }, phoneNumbers: [String], address: [ { city: { type: String, require: [true, 'Please enter city'], }, street: { type: String, require: [true, 'Please enter street'], }, state: { type: String, require: [true, 'Please specify state'], }, }, ], }, { timestamps: true }, ); export default model<IUser & Document>('User', User);
import { useContext } from 'react' import useTheme from '@mui/material/styles/useTheme' import Typography from '@mui/material/Typography' import Box from '@mui/material/Box' import Button from '@mui/material/Button' import Dialog from '@mui/material/Dialog' import DialogActions from '@mui/material/DialogActions' import DialogContent from '@mui/material/DialogContent' import DialogContentText from '@mui/material/DialogContentText' import DialogTitle from '@mui/material/DialogTitle' import ReportIcon from '@mui/icons-material/Report' import { ShellContext } from 'contexts/ShellContext' export const ServerConnectionFailureDialog = () => { const theme = useTheme() const { isServerConnectionFailureDialogOpen, setIsServerConnectionFailureDialogOpen, } = useContext(ShellContext) const handleDialogClose = () => { setIsServerConnectionFailureDialogOpen(false) } return ( <Dialog open={isServerConnectionFailureDialogOpen} onClose={handleDialogClose} > <DialogTitle> <Box sx={{ display: 'flex', alignItems: 'center' }}> <ReportIcon fontSize="medium" sx={theme => ({ color: theme.palette.error.main, mr: theme.spacing(1), })} /> Server connection failed </Box> </DialogTitle> <DialogContent> <DialogContentText> A pairing server could not be found. Make sure you are connected to the internet. If you still can't connect, try: </DialogContentText> <Typography component="ul" sx={{ color: theme.palette.text.secondary, m: 1, }} > <li>Refreshing the page</li> <li>Disabling any adblockers</li> <li>Connecting to a different network</li> </Typography> </DialogContent> <DialogActions> <Button onClick={handleDialogClose}>Close</Button> </DialogActions> </Dialog> ) }
using System; using System.Collections.Generic; using System.Linq; using EFSamurai.DataAccess.Migrations; using EFSamurai.Domain; using EFSamurai.Domain.Entities; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Scaffolding.Metadata; namespace EFSamurai.DataAccess { public class EfTddMethods { #region Helper methods public static void RebuildDatabase() { using SamuraiDbContext db = new(); db.Database.EnsureDeleted(); db.Database.Migrate(); //db.Database.EnsureCreated(); } public static void ResetIdentityStartingValue(string tableName, int startingValue = 1) { using (SamuraiDbContext db = new SamuraiDbContext()) { db.Database.ExecuteSqlRaw("IF EXISTS(SELECT * FROM sys.identity_columns " + "WHERE OBJECT_NAME(OBJECT_ID) = @tableName AND last_value IS NOT NULL) " + "DBCC CHECKIDENT(@tableName, RESEED, @startingValueMinusOne);", new SqlParameter("tableName", tableName), new SqlParameter("startingValueMinusOne", startingValue - 1)); } } public static void ClearAllData() { using SamuraiDbContext db = new(); db.RemoveRange(db.Samurai); db.RemoveRange(db.Battle); ResetIdentityStartingValue("Samurai"); ResetIdentityStartingValue("SecretIdentity"); ResetIdentityStartingValue("Quote"); ResetIdentityStartingValue("Battle"); ResetIdentityStartingValue("BattleLog"); ResetIdentityStartingValue("BattleEvent"); db.SaveChanges(); } #endregion Helper methods public static int CreateSamurai(string name, HairStyle hairStyle) { using SamuraiDbContext db = new SamuraiDbContext(); Samurai samurai = new Samurai() { Name = name, HairStyle = hairStyle }; db.Add(samurai); db.SaveChanges(); return samurai.Id; } public static void CreateSamurai(Samurai samurai) { using SamuraiDbContext db = new SamuraiDbContext(); db.Add(samurai); db.SaveChanges(); } public static List<string> ReadAlphabeticallyAllSamuraiNamesWithSpecificHairstyle(HairStyle hairstyle) { using SamuraiDbContext db = new SamuraiDbContext(); List<string> names = db.Samurai.Where(h => h.HairStyle == hairstyle) .OrderBy(s => s.Name) .Select(p => p.Name) .ToList(); return names; } public static List<Quote> ReadAllQuotesWithSpecificQuoteStyle(QuoteStyle quoteStyle) { using SamuraiDbContext db = new SamuraiDbContext(); List<Quote> quotes = db.Quote.Include(s => s.Samurai) .Where(q => q.QuoteStyle == quoteStyle).ToList(); return quotes; } public static int CreateBattle(string name, bool isBrutal, string description, DateTime startDate, DateTime EndDate) { using SamuraiDbContext db = new SamuraiDbContext(); Battle battle = new Battle() { Name = name, IsBrutal = isBrutal, Description = description, StartDate = startDate, EndDate = EndDate }; db.Add(battle); db.SaveChanges(); return battle.Id; } public static Battle? ReadOneBattle(int battleId) { using SamuraiDbContext db = new SamuraiDbContext(); Battle? battle = db.Battle.Where(b => b.Id == battleId).SingleOrDefault(); return battle; } public static void CreateOrUpdateSecretIdentitySetRealName(int samuraiId, string realName) { using SamuraiDbContext db = new SamuraiDbContext(); bool doesExist = db.SecretIdentity.Where(s => s.SamuraiID == samuraiId).Any(); if (!doesExist) { SecretIdentity secretI = new() { SamuraiID = samuraiId, RealName = realName }; db.Add(secretI); db.SaveChanges(); } else { SecretIdentity sI = db.SecretIdentity.Where(s => s.SamuraiID == samuraiId).Single()!; sI.RealName = realName; db.Update(sI); db.SaveChanges(); } } public static SecretIdentity? ReadSecretIdentityOfSpecificSamurai(int samuraiId) { using SamuraiDbContext db = new SamuraiDbContext(); SecretIdentity sI=db.SecretIdentity.Include(s=>s.Samurai).Where(s=>s.SamuraiID==samuraiId).SingleOrDefault()!; return sI; } } }
``escape`` ========== .. versionadded:: 1.9.0 The ``css``, ``url``, and ``html_attr`` strategies were added in Twig 1.9.0. .. versionadded:: 1.14.0 The ability to define custom escapers was added in Twig 1.14.0. The ``escape`` filter escapes a string for safe insertion into the final output. It supports different escaping strategies depending on the template context. By default, it uses the HTML escaping strategy: .. code-block:: jinja {{ user.username|escape }} For convenience, the ``e`` filter is defined as an alias: .. code-block:: jinja {{ user.username|e }} The ``escape`` filter can also be used in other contexts than HTML thanks to an optional argument which defines the escaping strategy to use: .. code-block:: jinja {{ user.username|e }} {# is equivalent to #} {{ user.username|e('html') }} And here is how to escape variables included in JavaScript code: .. code-block:: jinja {{ user.username|escape('js') }} {{ user.username|e('js') }} The ``escape`` filter supports the following escaping strategies: * ``html``: escapes a string for the **HTML body** context. * ``js``: escapes a string for the **JavaScript context**. * ``css``: escapes a string for the **CSS context**. CSS escaping can be applied to any string being inserted into CSS and escapes everything except alphanumerics. * ``url``: escapes a string for the **URI or parameter contexts**. This should not be used to escape an entire URI; only a subcomponent being inserted. * ``html_attr``: escapes a string for the **HTML attribute** context. .. note:: Internally, ``escape`` uses the PHP native `htmlspecialchars`_ function for the HTML escaping strategy. .. caution:: When using automatic escaping, Twig tries to not double-escape a variable when the automatic escaping strategy is the same as the one applied by the escape filter; but that does not work when using a variable as the escaping strategy: .. code-block:: jinja {% set strategy = 'html' %} {% autoescape 'html' %} {{ var|escape('html') }} {# won't be double-escaped #} {{ var|escape(strategy) }} {# will be double-escaped #} {% endautoescape %} When using a variable as the escaping strategy, you should disable automatic escaping: .. code-block:: jinja {% set strategy = 'html' %} {% autoescape 'html' %} {{ var|escape(strategy)|raw }} {# won't be double-escaped #} {% endautoescape %} Custom Escapers --------------- You can define custom escapers by calling the ``setEscaper()`` method on the ``core`` extension instance. The first argument is the escaper name (to be used in the ``escape`` call) and the second one must be a valid PHP callable: .. code-block:: php $twig = new \Twig\Environment($loader); $twig->getExtension('\Twig\Extension\CoreExtension')->setEscaper('csv', 'csv_escaper'); // before Twig 1.26 $twig->getExtension('core')->setEscaper('csv', 'csv_escaper'); When called by Twig, the callable receives the Twig environment instance, the string to escape, and the charset. .. note:: Built-in escapers cannot be overridden mainly they should be considered as the final implementation and also for better performance. Arguments --------- * ``strategy``: The escaping strategy * ``charset``: The string charset .. _`htmlspecialchars`: https://secure.php.net/htmlspecialchars
--- title: "Navigate Through Green Screen Muddle on Mac for Smooth YouTubing for 2024" date: 2024-05-31T12:45:09.700Z updated: 2024-06-01T12:45:09.700Z tags: - ai video - ai youtube categories: - ai - youtube description: "This Article Describes Navigate Through Green Screen Muddle on Mac for Smooth YouTubing for 2024" excerpt: "This Article Describes Navigate Through Green Screen Muddle on Mac for Smooth YouTubing for 2024" keywords: "\"Mac Green Screen Filming,Green Screen Mac Tips,Tackling Green Screen Glitches,Navigate Mac Video Editing,Seamless Green Screen Workflow,Smooth Green Screen Recording Mac,Muddle-Free Green Screen on Mac\"" thumbnail: https://www.lifewire.com/thmb/1GNoj79Wd2P3m5NhvYCQDjqSocU=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/GettyImages-1147622423-211c8ae1f88a4b1bae8f277422e23d3d.jpg --- ## Navigate Through Green Screen Muddle on Mac for Smooth YouTubing # How to Fix the Green Screen on YouTube on Mac ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Oct 26, 2023• Proven solutions When you are watching YouTube, you might notice that the video is green while the sound keeps playing. This can be quite frustrating when you are watching something interesting and the YouTube green screen comes up. There are various reasons as to why you have a green screen while watching videos on YouTube such as some problem with the GPU of Mac. No matter what the instance is, it can be quite overwhelming. In case the YouTube green screen video issue while watching videos is bothering you and you are looking for a permanent fix to solve it, keep reading. In this guide, you can learn about the various issues that lead to the green screen problem on YouTube and how you can fix it. But first, let’s take a look at the various issues that are causing the YouTube videos to turn green. ● Outdated Graphic Card Drivers: The issues associated with the graphics card can be a serious factor responsible for the green screen you are seeing while playing YouTube videos on your Mac device. This happens when the graphic drivers are outdated and can no longer support efficacious processing and playing of videos on the device. Graphics Card Drivers rendering is just the use of graphics cards for all rendering of functions such as videos. In case the drivers are outdated as the operating system, you will see a green screen error. ● Unreliable Third-Party Software: Any software from another source when used on Mac can lead to system errors. This will lead to green screen videos. It is more so when malware finds its way into the system when you are downloading the third-party software. This can even be a virus that comes with the software. ● Other Factors: Other factors might be responsible for the green screen videos such as a corrupt operating system. ## How to Prevent Green Screen on YouTube on Mac? In order to solve the YouTube video playing issue prior to moving on to the tricky troubleshooting methods, try out the simple hacks given below to prevent the problem altogether. These temporary hacks are usually quite helpful when you are in a hurry to watch a video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ● Play the YouTube video in some other browser. Often, a certain browser has a history of displaying a green screen on it when you play the videos on YouTube. ● Delete temporary files and cookies on Mac. This frees up space for the system. ![delete temporary files on mac](https://images.wondershare.com/filmora/Mac-articles/delete-temporary-files-on-mac.jpg) ● Close the other tabs and interfaces in the browser when you are watching the video online. This way the activities on the open window are not going to lead to an error while playing the video. ● Clear the cache data. By doing this, you can make sure that your system has enough space. ● Update the browser you are using to view videos on the latest browser. ![update browser on mac](https://images.wondershare.com/filmora/Mac-articles/update-browser-on-mac.jpg) ● Reboot the Mac device if you are using it for a while. At times, rebooting the computer is all that you have to do to get the video working properly yet again after an error occurs. ## How to Fix YouTube Green Screen? As the video playing problem is primarily related to graphic drivers and hardware in the computer, further troubleshooting methods are for available for fixing these problems. Hence, when the hacks fail to work and you keep seeing YouTube green screen, try out the following methods to fix this issue. ### 1. Disable Hardware Acceleration The computer uses GPU rather than CPU for loading graphic intensive programs during hardware acceleration. ![disable hardware acceleration](https://images.wondershare.com/filmora/Mac-articles/disable-hardware-acceleration.jpg) Nevertheless, some problems might occur when rendering the web pages from the Central Processing Unit to the Graphic Processing Unit. This causes performance problems. You might notice a green or blank screen while you are watching high-quality videos on YouTube. In such a case, you need to disable hardware acceleration for resolving video playing problems. ● Right-click on the video which is displaying the green screen. ● Choose ‘Setting’ from the menu. ● Now, click to uncheck the option ‘Enable hardware acceleration’. ● Next, close the window to reload the page. ● To watch the video, reopen the website. If you don’t find the ‘Settings’ option on the right-clicking the green video screen, disable the option of Hardware Acceleration on the web browser. ### 2. Update the Graphics Card Drivers In case after establishing the hardware acceleration green screen in the YouTube videos to occur, update the graphics card driver. The video playing issue might have been caused due to the old AMD or NVIDIA graphics card. Here are the steps to update the Graphics Card Drivers: ● Right-click on ‘My Computer’. ● Now, click on ‘Follow Manage’ and then ‘Device Manager’. ● Next, click on the option ‘Display Adapters’. ● Right-click on the graphics driver and then click on ‘Update Driver Software’. ● Choose ‘Search automatically for updated driver software’. The system will detect the graphics card and will find the latest driver. Restart the PC and the system. ### 3. Run a Troubleshooter You can also try running a troubleshooter in the system to fix your green screen issue in YouTube videos. Check out what you have to do. ● Open the computer ‘Settings’ app. ● Click on the ‘Update & Security’ section. ● Choose ‘Troubleshoot’ and then ‘Hardware and Devices’. ● As soon as the progress is complete, just restart the PC. Now, you will have to view the videos once more to check if the problem has been resolved. ### 4. Adjust YouTube Settings If you are persistently having this problem with YouTube videos, you can try to change the video quality to make it supported by the device. You need to do this in the following steps. ● Open the browser and play the YouTube video you prefer. ● Click on the ‘Gear’ icon and from the menu opt for ‘Quality’. ![ajust youtube settings](https://images.wondershare.com/filmora/Mac-articles/ajust-youtube-settings.jpg) ● Now, you can choose from different video quality options. #### Conclusion You might have seen how easy it is to solve the YouTube green screen issues while running YouTube videos on Mac. So, when you are encountering one, there is no reason to worry. Moreover, following the few hacks given above, you can easily resolve the YouTube green screen issue. In case you are troubleshooting the issue, make sure that you begin with hardware acceleration and then move on to the other methods. If you want to create a video for YouTube using green screen, you can use[video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) from Filmora. It offers various features that you can use to create a unique video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Learn More: [How do Beginners Make a Cool Video for YouTube on Mac>>>](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Oct 26, 2023• Proven solutions When you are watching YouTube, you might notice that the video is green while the sound keeps playing. This can be quite frustrating when you are watching something interesting and the YouTube green screen comes up. There are various reasons as to why you have a green screen while watching videos on YouTube such as some problem with the GPU of Mac. No matter what the instance is, it can be quite overwhelming. In case the YouTube green screen video issue while watching videos is bothering you and you are looking for a permanent fix to solve it, keep reading. In this guide, you can learn about the various issues that lead to the green screen problem on YouTube and how you can fix it. But first, let’s take a look at the various issues that are causing the YouTube videos to turn green. ● Outdated Graphic Card Drivers: The issues associated with the graphics card can be a serious factor responsible for the green screen you are seeing while playing YouTube videos on your Mac device. This happens when the graphic drivers are outdated and can no longer support efficacious processing and playing of videos on the device. Graphics Card Drivers rendering is just the use of graphics cards for all rendering of functions such as videos. In case the drivers are outdated as the operating system, you will see a green screen error. ● Unreliable Third-Party Software: Any software from another source when used on Mac can lead to system errors. This will lead to green screen videos. It is more so when malware finds its way into the system when you are downloading the third-party software. This can even be a virus that comes with the software. ● Other Factors: Other factors might be responsible for the green screen videos such as a corrupt operating system. ## How to Prevent Green Screen on YouTube on Mac? In order to solve the YouTube video playing issue prior to moving on to the tricky troubleshooting methods, try out the simple hacks given below to prevent the problem altogether. These temporary hacks are usually quite helpful when you are in a hurry to watch a video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ● Play the YouTube video in some other browser. Often, a certain browser has a history of displaying a green screen on it when you play the videos on YouTube. ● Delete temporary files and cookies on Mac. This frees up space for the system. ![delete temporary files on mac](https://images.wondershare.com/filmora/Mac-articles/delete-temporary-files-on-mac.jpg) ● Close the other tabs and interfaces in the browser when you are watching the video online. This way the activities on the open window are not going to lead to an error while playing the video. ● Clear the cache data. By doing this, you can make sure that your system has enough space. ● Update the browser you are using to view videos on the latest browser. ![update browser on mac](https://images.wondershare.com/filmora/Mac-articles/update-browser-on-mac.jpg) ● Reboot the Mac device if you are using it for a while. At times, rebooting the computer is all that you have to do to get the video working properly yet again after an error occurs. ## How to Fix YouTube Green Screen? As the video playing problem is primarily related to graphic drivers and hardware in the computer, further troubleshooting methods are for available for fixing these problems. Hence, when the hacks fail to work and you keep seeing YouTube green screen, try out the following methods to fix this issue. ### 1. Disable Hardware Acceleration The computer uses GPU rather than CPU for loading graphic intensive programs during hardware acceleration. ![disable hardware acceleration](https://images.wondershare.com/filmora/Mac-articles/disable-hardware-acceleration.jpg) Nevertheless, some problems might occur when rendering the web pages from the Central Processing Unit to the Graphic Processing Unit. This causes performance problems. You might notice a green or blank screen while you are watching high-quality videos on YouTube. In such a case, you need to disable hardware acceleration for resolving video playing problems. ● Right-click on the video which is displaying the green screen. ● Choose ‘Setting’ from the menu. ● Now, click to uncheck the option ‘Enable hardware acceleration’. ● Next, close the window to reload the page. ● To watch the video, reopen the website. If you don’t find the ‘Settings’ option on the right-clicking the green video screen, disable the option of Hardware Acceleration on the web browser. ### 2. Update the Graphics Card Drivers In case after establishing the hardware acceleration green screen in the YouTube videos to occur, update the graphics card driver. The video playing issue might have been caused due to the old AMD or NVIDIA graphics card. Here are the steps to update the Graphics Card Drivers: ● Right-click on ‘My Computer’. ● Now, click on ‘Follow Manage’ and then ‘Device Manager’. ● Next, click on the option ‘Display Adapters’. ● Right-click on the graphics driver and then click on ‘Update Driver Software’. ● Choose ‘Search automatically for updated driver software’. The system will detect the graphics card and will find the latest driver. Restart the PC and the system. ### 3. Run a Troubleshooter You can also try running a troubleshooter in the system to fix your green screen issue in YouTube videos. Check out what you have to do. ● Open the computer ‘Settings’ app. ● Click on the ‘Update & Security’ section. ● Choose ‘Troubleshoot’ and then ‘Hardware and Devices’. ● As soon as the progress is complete, just restart the PC. Now, you will have to view the videos once more to check if the problem has been resolved. ### 4. Adjust YouTube Settings If you are persistently having this problem with YouTube videos, you can try to change the video quality to make it supported by the device. You need to do this in the following steps. ● Open the browser and play the YouTube video you prefer. ● Click on the ‘Gear’ icon and from the menu opt for ‘Quality’. ![ajust youtube settings](https://images.wondershare.com/filmora/Mac-articles/ajust-youtube-settings.jpg) ● Now, you can choose from different video quality options. #### Conclusion You might have seen how easy it is to solve the YouTube green screen issues while running YouTube videos on Mac. So, when you are encountering one, there is no reason to worry. Moreover, following the few hacks given above, you can easily resolve the YouTube green screen issue. In case you are troubleshooting the issue, make sure that you begin with hardware acceleration and then move on to the other methods. If you want to create a video for YouTube using green screen, you can use[video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) from Filmora. It offers various features that you can use to create a unique video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Learn More: [How do Beginners Make a Cool Video for YouTube on Mac>>>](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Oct 26, 2023• Proven solutions When you are watching YouTube, you might notice that the video is green while the sound keeps playing. This can be quite frustrating when you are watching something interesting and the YouTube green screen comes up. There are various reasons as to why you have a green screen while watching videos on YouTube such as some problem with the GPU of Mac. No matter what the instance is, it can be quite overwhelming. In case the YouTube green screen video issue while watching videos is bothering you and you are looking for a permanent fix to solve it, keep reading. In this guide, you can learn about the various issues that lead to the green screen problem on YouTube and how you can fix it. But first, let’s take a look at the various issues that are causing the YouTube videos to turn green. ● Outdated Graphic Card Drivers: The issues associated with the graphics card can be a serious factor responsible for the green screen you are seeing while playing YouTube videos on your Mac device. This happens when the graphic drivers are outdated and can no longer support efficacious processing and playing of videos on the device. Graphics Card Drivers rendering is just the use of graphics cards for all rendering of functions such as videos. In case the drivers are outdated as the operating system, you will see a green screen error. ● Unreliable Third-Party Software: Any software from another source when used on Mac can lead to system errors. This will lead to green screen videos. It is more so when malware finds its way into the system when you are downloading the third-party software. This can even be a virus that comes with the software. ● Other Factors: Other factors might be responsible for the green screen videos such as a corrupt operating system. ## How to Prevent Green Screen on YouTube on Mac? In order to solve the YouTube video playing issue prior to moving on to the tricky troubleshooting methods, try out the simple hacks given below to prevent the problem altogether. These temporary hacks are usually quite helpful when you are in a hurry to watch a video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ● Play the YouTube video in some other browser. Often, a certain browser has a history of displaying a green screen on it when you play the videos on YouTube. ● Delete temporary files and cookies on Mac. This frees up space for the system. ![delete temporary files on mac](https://images.wondershare.com/filmora/Mac-articles/delete-temporary-files-on-mac.jpg) ● Close the other tabs and interfaces in the browser when you are watching the video online. This way the activities on the open window are not going to lead to an error while playing the video. ● Clear the cache data. By doing this, you can make sure that your system has enough space. ● Update the browser you are using to view videos on the latest browser. ![update browser on mac](https://images.wondershare.com/filmora/Mac-articles/update-browser-on-mac.jpg) ● Reboot the Mac device if you are using it for a while. At times, rebooting the computer is all that you have to do to get the video working properly yet again after an error occurs. ## How to Fix YouTube Green Screen? As the video playing problem is primarily related to graphic drivers and hardware in the computer, further troubleshooting methods are for available for fixing these problems. Hence, when the hacks fail to work and you keep seeing YouTube green screen, try out the following methods to fix this issue. ### 1. Disable Hardware Acceleration The computer uses GPU rather than CPU for loading graphic intensive programs during hardware acceleration. ![disable hardware acceleration](https://images.wondershare.com/filmora/Mac-articles/disable-hardware-acceleration.jpg) Nevertheless, some problems might occur when rendering the web pages from the Central Processing Unit to the Graphic Processing Unit. This causes performance problems. You might notice a green or blank screen while you are watching high-quality videos on YouTube. In such a case, you need to disable hardware acceleration for resolving video playing problems. ● Right-click on the video which is displaying the green screen. ● Choose ‘Setting’ from the menu. ● Now, click to uncheck the option ‘Enable hardware acceleration’. ● Next, close the window to reload the page. ● To watch the video, reopen the website. If you don’t find the ‘Settings’ option on the right-clicking the green video screen, disable the option of Hardware Acceleration on the web browser. ### 2. Update the Graphics Card Drivers In case after establishing the hardware acceleration green screen in the YouTube videos to occur, update the graphics card driver. The video playing issue might have been caused due to the old AMD or NVIDIA graphics card. Here are the steps to update the Graphics Card Drivers: ● Right-click on ‘My Computer’. ● Now, click on ‘Follow Manage’ and then ‘Device Manager’. ● Next, click on the option ‘Display Adapters’. ● Right-click on the graphics driver and then click on ‘Update Driver Software’. ● Choose ‘Search automatically for updated driver software’. The system will detect the graphics card and will find the latest driver. Restart the PC and the system. ### 3. Run a Troubleshooter You can also try running a troubleshooter in the system to fix your green screen issue in YouTube videos. Check out what you have to do. ● Open the computer ‘Settings’ app. ● Click on the ‘Update & Security’ section. ● Choose ‘Troubleshoot’ and then ‘Hardware and Devices’. ● As soon as the progress is complete, just restart the PC. Now, you will have to view the videos once more to check if the problem has been resolved. ### 4. Adjust YouTube Settings If you are persistently having this problem with YouTube videos, you can try to change the video quality to make it supported by the device. You need to do this in the following steps. ● Open the browser and play the YouTube video you prefer. ● Click on the ‘Gear’ icon and from the menu opt for ‘Quality’. ![ajust youtube settings](https://images.wondershare.com/filmora/Mac-articles/ajust-youtube-settings.jpg) ● Now, you can choose from different video quality options. #### Conclusion You might have seen how easy it is to solve the YouTube green screen issues while running YouTube videos on Mac. So, when you are encountering one, there is no reason to worry. Moreover, following the few hacks given above, you can easily resolve the YouTube green screen issue. In case you are troubleshooting the issue, make sure that you begin with hardware acceleration and then move on to the other methods. If you want to create a video for YouTube using green screen, you can use[video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) from Filmora. It offers various features that you can use to create a unique video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Learn More: [How do Beginners Make a Cool Video for YouTube on Mac>>>](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Oct 26, 2023• Proven solutions When you are watching YouTube, you might notice that the video is green while the sound keeps playing. This can be quite frustrating when you are watching something interesting and the YouTube green screen comes up. There are various reasons as to why you have a green screen while watching videos on YouTube such as some problem with the GPU of Mac. No matter what the instance is, it can be quite overwhelming. In case the YouTube green screen video issue while watching videos is bothering you and you are looking for a permanent fix to solve it, keep reading. In this guide, you can learn about the various issues that lead to the green screen problem on YouTube and how you can fix it. But first, let’s take a look at the various issues that are causing the YouTube videos to turn green. ● Outdated Graphic Card Drivers: The issues associated with the graphics card can be a serious factor responsible for the green screen you are seeing while playing YouTube videos on your Mac device. This happens when the graphic drivers are outdated and can no longer support efficacious processing and playing of videos on the device. Graphics Card Drivers rendering is just the use of graphics cards for all rendering of functions such as videos. In case the drivers are outdated as the operating system, you will see a green screen error. ● Unreliable Third-Party Software: Any software from another source when used on Mac can lead to system errors. This will lead to green screen videos. It is more so when malware finds its way into the system when you are downloading the third-party software. This can even be a virus that comes with the software. ● Other Factors: Other factors might be responsible for the green screen videos such as a corrupt operating system. ## How to Prevent Green Screen on YouTube on Mac? In order to solve the YouTube video playing issue prior to moving on to the tricky troubleshooting methods, try out the simple hacks given below to prevent the problem altogether. These temporary hacks are usually quite helpful when you are in a hurry to watch a video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ● Play the YouTube video in some other browser. Often, a certain browser has a history of displaying a green screen on it when you play the videos on YouTube. ● Delete temporary files and cookies on Mac. This frees up space for the system. ![delete temporary files on mac](https://images.wondershare.com/filmora/Mac-articles/delete-temporary-files-on-mac.jpg) ● Close the other tabs and interfaces in the browser when you are watching the video online. This way the activities on the open window are not going to lead to an error while playing the video. ● Clear the cache data. By doing this, you can make sure that your system has enough space. ● Update the browser you are using to view videos on the latest browser. ![update browser on mac](https://images.wondershare.com/filmora/Mac-articles/update-browser-on-mac.jpg) ● Reboot the Mac device if you are using it for a while. At times, rebooting the computer is all that you have to do to get the video working properly yet again after an error occurs. ## How to Fix YouTube Green Screen? As the video playing problem is primarily related to graphic drivers and hardware in the computer, further troubleshooting methods are for available for fixing these problems. Hence, when the hacks fail to work and you keep seeing YouTube green screen, try out the following methods to fix this issue. ### 1. Disable Hardware Acceleration The computer uses GPU rather than CPU for loading graphic intensive programs during hardware acceleration. ![disable hardware acceleration](https://images.wondershare.com/filmora/Mac-articles/disable-hardware-acceleration.jpg) Nevertheless, some problems might occur when rendering the web pages from the Central Processing Unit to the Graphic Processing Unit. This causes performance problems. You might notice a green or blank screen while you are watching high-quality videos on YouTube. In such a case, you need to disable hardware acceleration for resolving video playing problems. ● Right-click on the video which is displaying the green screen. ● Choose ‘Setting’ from the menu. ● Now, click to uncheck the option ‘Enable hardware acceleration’. ● Next, close the window to reload the page. ● To watch the video, reopen the website. If you don’t find the ‘Settings’ option on the right-clicking the green video screen, disable the option of Hardware Acceleration on the web browser. ### 2. Update the Graphics Card Drivers In case after establishing the hardware acceleration green screen in the YouTube videos to occur, update the graphics card driver. The video playing issue might have been caused due to the old AMD or NVIDIA graphics card. Here are the steps to update the Graphics Card Drivers: ● Right-click on ‘My Computer’. ● Now, click on ‘Follow Manage’ and then ‘Device Manager’. ● Next, click on the option ‘Display Adapters’. ● Right-click on the graphics driver and then click on ‘Update Driver Software’. ● Choose ‘Search automatically for updated driver software’. The system will detect the graphics card and will find the latest driver. Restart the PC and the system. ### 3. Run a Troubleshooter You can also try running a troubleshooter in the system to fix your green screen issue in YouTube videos. Check out what you have to do. ● Open the computer ‘Settings’ app. ● Click on the ‘Update & Security’ section. ● Choose ‘Troubleshoot’ and then ‘Hardware and Devices’. ● As soon as the progress is complete, just restart the PC. Now, you will have to view the videos once more to check if the problem has been resolved. ### 4. Adjust YouTube Settings If you are persistently having this problem with YouTube videos, you can try to change the video quality to make it supported by the device. You need to do this in the following steps. ● Open the browser and play the YouTube video you prefer. ● Click on the ‘Gear’ icon and from the menu opt for ‘Quality’. ![ajust youtube settings](https://images.wondershare.com/filmora/Mac-articles/ajust-youtube-settings.jpg) ● Now, you can choose from different video quality options. #### Conclusion You might have seen how easy it is to solve the YouTube green screen issues while running YouTube videos on Mac. So, when you are encountering one, there is no reason to worry. Moreover, following the few hacks given above, you can easily resolve the YouTube green screen issue. In case you are troubleshooting the issue, make sure that you begin with hardware acceleration and then move on to the other methods. If you want to create a video for YouTube using green screen, you can use[video editor for Mac](https://tools.techidaily.com/wondershare/filmora/download/) from Filmora. It offers various features that you can use to create a unique video. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) Learn More: [How do Beginners Make a Cool Video for YouTube on Mac>>>](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Love in Action: Top 9 Premium Wedding Films on YouTube and Vimeo # 8 Best Wedding Videos on YouTube and Vimeo ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) ##### Ollie Mattison Mar 27, 2024• Proven solutions The day of wedding is always special and happiest to everyone and the wedding video doubles that happiness since it makes the day memorable. To make your wedding celebration and video meaningful, you should plan it in a unique way. If you have no idea how you can do this or if you just wish to get that amazing wedding atmosphere, we have brought some of the beautiful wedding videos for you. * [**Part1: Best Wedding Videos on YouTube**](#part1) * [**Part2: Best Wedding Videos on Vimeo**](#part2) ## Part 1: Best Wedding Videos on YouTube #### 1.JK Wedding Entrance Dance One of the funniest wedding videos you will ever see is this one right here. The video is packed with hilarious moments, especially the moves of those two gentlemen in the beginning. This is what we call a ‘different’ wedding celebration. If you want to do something out of the box, this can be a great idea. At the end, you will find your wedding full of happiness like this video making your day simply unforgettable. Take your call and gather as much contentment as you can. #### 2.OUR WEDDING VIDEO By watching this video, you’ll be crying and being happy at the same time. This couple is setting the strongest example of what true love is. We are certain that the sweetness of this wedding video will make your heart melt forcing you to utter that ‘awww’ expression. After watching this perfect wedding video, we wish the bride, the daughter and the man who have shown such a true love a very happy future and god bless such a beautiful soul. #### 3.A Wedding That Will Move You Oh! And this one! You can’t miss this heart-touching and beautiful wedding video. You will surely get moved and get goose bumps while watching this. The bride and the groom are so devoting to each other making this video no less than a fairytale. The boy started getting diagnosed with liver cancer. The last wish was to get married and the love between the couple made people compelled to make the hospital a church. The man died happily within 10 hours of wedding. #### 4. My Wedding Speech Among loads of stories available there, this is one of the best wedding videos ever. The groom’s speech is a song that truly makes the girl pleased and smile. Well the man gave us an idea that when speech bores you just write a song and sing it. The groom, with rewriting his lovely speech, oh we mean song, simply handles all the nervousness and touches each one’s heart in the crowd. Probably every girl in the world expects such an adorable man as her partner! ## Part 2: Best Wedding Videos on Vimeo #### 1. The Wedding of London and Nathan When there is such pure love between couple, they do look beautiful together. And the best wedding video naturally shows the love glowing on their faces. The groom’s brother expressed his touching childhood wish of having a baby sister. He said with his brother’s wedding, god has gifted him the sister he always so earnestly wished for. This melted the couple’s hearts. The blushing couple in every scene of the wedding video reminded of the fairytales that say ‘happily ever after’. #### 2.IyaVillania and Drew Arellano’s Wedding The white flowers, sunset, the cliff across the beach, what more could a bride ask for to make the wedding the most memorable event of her life. This is one such perfect wedding video, where the couple exchanged their own set of cute wedding vows. The sea in the backdrop was a testament of their beautiful love story unfolding under the golden dawn. And their first dance under the stars touched people’s hearts. #### 3.Greatest wedding toast of all time The most beautiful wedding videos often have a different kind of celebration. The groom’s friends raised the wedding toast in very different way adding more highlights to the celebrations. The newlywed couple kept on bursting with laughter with the toast being sung. Well! Those girls wrote the composition and dedicated it to the bride. How adorable that was! Everyone ended up dancing to their hilarious poem at the end. #### 4.Kelly and Dustin Watching the perfect wedding video always brings goose bumps, when you see the couple so in love with each other. They have exchanged love notes and got teary eyed reading them. What a romantic backdrop for a wedding that took place amidst greenery. The groom even surprised the bride with a gift hidden under the couch. The cutesy invites and the wonderful couple so in love made everything look breathtaking. The recent downpour made the surrounding looks so fresh and lively. Read More to Get: [5 Methods to Go Frame by Frame on YouTube Video >>](https://tools.techidaily.com/wondershare/filmora/download/) ## Final Verdict The list ends here and those were some wedding videos you must watch. We wish that the one reading this post will share his/her story and beautiful wedding video too one day. So, which one is the best wedding video according to you? Tell us your choice and we hope that you like this list. Thanks! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions The day of wedding is always special and happiest to everyone and the wedding video doubles that happiness since it makes the day memorable. To make your wedding celebration and video meaningful, you should plan it in a unique way. If you have no idea how you can do this or if you just wish to get that amazing wedding atmosphere, we have brought some of the beautiful wedding videos for you. * [**Part1: Best Wedding Videos on YouTube**](#part1) * [**Part2: Best Wedding Videos on Vimeo**](#part2) ## Part 1: Best Wedding Videos on YouTube #### 1.JK Wedding Entrance Dance One of the funniest wedding videos you will ever see is this one right here. The video is packed with hilarious moments, especially the moves of those two gentlemen in the beginning. This is what we call a ‘different’ wedding celebration. If you want to do something out of the box, this can be a great idea. At the end, you will find your wedding full of happiness like this video making your day simply unforgettable. Take your call and gather as much contentment as you can. #### 2.OUR WEDDING VIDEO By watching this video, you’ll be crying and being happy at the same time. This couple is setting the strongest example of what true love is. We are certain that the sweetness of this wedding video will make your heart melt forcing you to utter that ‘awww’ expression. After watching this perfect wedding video, we wish the bride, the daughter and the man who have shown such a true love a very happy future and god bless such a beautiful soul. #### 3.A Wedding That Will Move You Oh! And this one! You can’t miss this heart-touching and beautiful wedding video. You will surely get moved and get goose bumps while watching this. The bride and the groom are so devoting to each other making this video no less than a fairytale. The boy started getting diagnosed with liver cancer. The last wish was to get married and the love between the couple made people compelled to make the hospital a church. The man died happily within 10 hours of wedding. #### 4. My Wedding Speech Among loads of stories available there, this is one of the best wedding videos ever. The groom’s speech is a song that truly makes the girl pleased and smile. Well the man gave us an idea that when speech bores you just write a song and sing it. The groom, with rewriting his lovely speech, oh we mean song, simply handles all the nervousness and touches each one’s heart in the crowd. Probably every girl in the world expects such an adorable man as her partner! ## Part 2: Best Wedding Videos on Vimeo #### 1. The Wedding of London and Nathan When there is such pure love between couple, they do look beautiful together. And the best wedding video naturally shows the love glowing on their faces. The groom’s brother expressed his touching childhood wish of having a baby sister. He said with his brother’s wedding, god has gifted him the sister he always so earnestly wished for. This melted the couple’s hearts. The blushing couple in every scene of the wedding video reminded of the fairytales that say ‘happily ever after’. #### 2.IyaVillania and Drew Arellano’s Wedding The white flowers, sunset, the cliff across the beach, what more could a bride ask for to make the wedding the most memorable event of her life. This is one such perfect wedding video, where the couple exchanged their own set of cute wedding vows. The sea in the backdrop was a testament of their beautiful love story unfolding under the golden dawn. And their first dance under the stars touched people’s hearts. #### 3.Greatest wedding toast of all time The most beautiful wedding videos often have a different kind of celebration. The groom’s friends raised the wedding toast in very different way adding more highlights to the celebrations. The newlywed couple kept on bursting with laughter with the toast being sung. Well! Those girls wrote the composition and dedicated it to the bride. How adorable that was! Everyone ended up dancing to their hilarious poem at the end. #### 4.Kelly and Dustin Watching the perfect wedding video always brings goose bumps, when you see the couple so in love with each other. They have exchanged love notes and got teary eyed reading them. What a romantic backdrop for a wedding that took place amidst greenery. The groom even surprised the bride with a gift hidden under the couch. The cutesy invites and the wonderful couple so in love made everything look breathtaking. The recent downpour made the surrounding looks so fresh and lively. Read More to Get: [5 Methods to Go Frame by Frame on YouTube Video >>](https://tools.techidaily.com/wondershare/filmora/download/) ## Final Verdict The list ends here and those were some wedding videos you must watch. We wish that the one reading this post will share his/her story and beautiful wedding video too one day. So, which one is the best wedding video according to you? Tell us your choice and we hope that you like this list. Thanks! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions The day of wedding is always special and happiest to everyone and the wedding video doubles that happiness since it makes the day memorable. To make your wedding celebration and video meaningful, you should plan it in a unique way. If you have no idea how you can do this or if you just wish to get that amazing wedding atmosphere, we have brought some of the beautiful wedding videos for you. * [**Part1: Best Wedding Videos on YouTube**](#part1) * [**Part2: Best Wedding Videos on Vimeo**](#part2) ## Part 1: Best Wedding Videos on YouTube #### 1.JK Wedding Entrance Dance One of the funniest wedding videos you will ever see is this one right here. The video is packed with hilarious moments, especially the moves of those two gentlemen in the beginning. This is what we call a ‘different’ wedding celebration. If you want to do something out of the box, this can be a great idea. At the end, you will find your wedding full of happiness like this video making your day simply unforgettable. Take your call and gather as much contentment as you can. #### 2.OUR WEDDING VIDEO By watching this video, you’ll be crying and being happy at the same time. This couple is setting the strongest example of what true love is. We are certain that the sweetness of this wedding video will make your heart melt forcing you to utter that ‘awww’ expression. After watching this perfect wedding video, we wish the bride, the daughter and the man who have shown such a true love a very happy future and god bless such a beautiful soul. #### 3.A Wedding That Will Move You Oh! And this one! You can’t miss this heart-touching and beautiful wedding video. You will surely get moved and get goose bumps while watching this. The bride and the groom are so devoting to each other making this video no less than a fairytale. The boy started getting diagnosed with liver cancer. The last wish was to get married and the love between the couple made people compelled to make the hospital a church. The man died happily within 10 hours of wedding. #### 4. My Wedding Speech Among loads of stories available there, this is one of the best wedding videos ever. The groom’s speech is a song that truly makes the girl pleased and smile. Well the man gave us an idea that when speech bores you just write a song and sing it. The groom, with rewriting his lovely speech, oh we mean song, simply handles all the nervousness and touches each one’s heart in the crowd. Probably every girl in the world expects such an adorable man as her partner! ## Part 2: Best Wedding Videos on Vimeo #### 1. The Wedding of London and Nathan When there is such pure love between couple, they do look beautiful together. And the best wedding video naturally shows the love glowing on their faces. The groom’s brother expressed his touching childhood wish of having a baby sister. He said with his brother’s wedding, god has gifted him the sister he always so earnestly wished for. This melted the couple’s hearts. The blushing couple in every scene of the wedding video reminded of the fairytales that say ‘happily ever after’. #### 2.IyaVillania and Drew Arellano’s Wedding The white flowers, sunset, the cliff across the beach, what more could a bride ask for to make the wedding the most memorable event of her life. This is one such perfect wedding video, where the couple exchanged their own set of cute wedding vows. The sea in the backdrop was a testament of their beautiful love story unfolding under the golden dawn. And their first dance under the stars touched people’s hearts. #### 3.Greatest wedding toast of all time The most beautiful wedding videos often have a different kind of celebration. The groom’s friends raised the wedding toast in very different way adding more highlights to the celebrations. The newlywed couple kept on bursting with laughter with the toast being sung. Well! Those girls wrote the composition and dedicated it to the bride. How adorable that was! Everyone ended up dancing to their hilarious poem at the end. #### 4.Kelly and Dustin Watching the perfect wedding video always brings goose bumps, when you see the couple so in love with each other. They have exchanged love notes and got teary eyed reading them. What a romantic backdrop for a wedding that took place amidst greenery. The groom even surprised the bride with a gift hidden under the couch. The cutesy invites and the wonderful couple so in love made everything look breathtaking. The recent downpour made the surrounding looks so fresh and lively. Read More to Get: [5 Methods to Go Frame by Frame on YouTube Video >>](https://tools.techidaily.com/wondershare/filmora/download/) ## Final Verdict The list ends here and those were some wedding videos you must watch. We wish that the one reading this post will share his/her story and beautiful wedding video too one day. So, which one is the best wedding video according to you? Tell us your choice and we hope that you like this list. Thanks! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison ##### Ollie Mattison Mar 27, 2024• Proven solutions The day of wedding is always special and happiest to everyone and the wedding video doubles that happiness since it makes the day memorable. To make your wedding celebration and video meaningful, you should plan it in a unique way. If you have no idea how you can do this or if you just wish to get that amazing wedding atmosphere, we have brought some of the beautiful wedding videos for you. * [**Part1: Best Wedding Videos on YouTube**](#part1) * [**Part2: Best Wedding Videos on Vimeo**](#part2) ## Part 1: Best Wedding Videos on YouTube #### 1.JK Wedding Entrance Dance One of the funniest wedding videos you will ever see is this one right here. The video is packed with hilarious moments, especially the moves of those two gentlemen in the beginning. This is what we call a ‘different’ wedding celebration. If you want to do something out of the box, this can be a great idea. At the end, you will find your wedding full of happiness like this video making your day simply unforgettable. Take your call and gather as much contentment as you can. #### 2.OUR WEDDING VIDEO By watching this video, you’ll be crying and being happy at the same time. This couple is setting the strongest example of what true love is. We are certain that the sweetness of this wedding video will make your heart melt forcing you to utter that ‘awww’ expression. After watching this perfect wedding video, we wish the bride, the daughter and the man who have shown such a true love a very happy future and god bless such a beautiful soul. #### 3.A Wedding That Will Move You Oh! And this one! You can’t miss this heart-touching and beautiful wedding video. You will surely get moved and get goose bumps while watching this. The bride and the groom are so devoting to each other making this video no less than a fairytale. The boy started getting diagnosed with liver cancer. The last wish was to get married and the love between the couple made people compelled to make the hospital a church. The man died happily within 10 hours of wedding. #### 4. My Wedding Speech Among loads of stories available there, this is one of the best wedding videos ever. The groom’s speech is a song that truly makes the girl pleased and smile. Well the man gave us an idea that when speech bores you just write a song and sing it. The groom, with rewriting his lovely speech, oh we mean song, simply handles all the nervousness and touches each one’s heart in the crowd. Probably every girl in the world expects such an adorable man as her partner! ## Part 2: Best Wedding Videos on Vimeo #### 1. The Wedding of London and Nathan When there is such pure love between couple, they do look beautiful together. And the best wedding video naturally shows the love glowing on their faces. The groom’s brother expressed his touching childhood wish of having a baby sister. He said with his brother’s wedding, god has gifted him the sister he always so earnestly wished for. This melted the couple’s hearts. The blushing couple in every scene of the wedding video reminded of the fairytales that say ‘happily ever after’. #### 2.IyaVillania and Drew Arellano’s Wedding The white flowers, sunset, the cliff across the beach, what more could a bride ask for to make the wedding the most memorable event of her life. This is one such perfect wedding video, where the couple exchanged their own set of cute wedding vows. The sea in the backdrop was a testament of their beautiful love story unfolding under the golden dawn. And their first dance under the stars touched people’s hearts. #### 3.Greatest wedding toast of all time The most beautiful wedding videos often have a different kind of celebration. The groom’s friends raised the wedding toast in very different way adding more highlights to the celebrations. The newlywed couple kept on bursting with laughter with the toast being sung. Well! Those girls wrote the composition and dedicated it to the bride. How adorable that was! Everyone ended up dancing to their hilarious poem at the end. #### 4.Kelly and Dustin Watching the perfect wedding video always brings goose bumps, when you see the couple so in love with each other. They have exchanged love notes and got teary eyed reading them. What a romantic backdrop for a wedding that took place amidst greenery. The groom even surprised the bride with a gift hidden under the couch. The cutesy invites and the wonderful couple so in love made everything look breathtaking. The recent downpour made the surrounding looks so fresh and lively. Read More to Get: [5 Methods to Go Frame by Frame on YouTube Video >>](https://tools.techidaily.com/wondershare/filmora/download/) ## Final Verdict The list ends here and those were some wedding videos you must watch. We wish that the one reading this post will share his/her story and beautiful wedding video too one day. So, which one is the best wedding video according to you? Tell us your choice and we hope that you like this list. Thanks! [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ![author avatar](https://images.wondershare.com/filmora/article-images/ollie-mattison.jpg) Ollie Mattison Ollie Mattison is a writer and a lover of all things video. Follow @Ollie Mattison <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
<!-- 객체 ==> 배열[객체...] web store(sqlite) --> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> window.onload=function() { //객체 선언 => JSON (Boot는 자동 생성 , Framework: 직접 생성) /* 오라클 ===> 자바 ===> 자바스크립트 ~VO {} List [{},{},{}...] */ let sawon= { sabun:0, //키:값 name:"동길동", dept:"개발부", job: "대리", pay:4500 } //출력 document.write("사번:"+sawon.sabun+"<br>"); document.write("이름:"+sawon.name+"<br>"); document.write("부서:"+sawon.dept+"<br>"); document.write("직위:"+sawon.job+"<br>"); document.write("급여:"+sawon.pay+"<br>"); document.write("<hr>"); document.write("사번:"+sawon['sabun']+"<br>"); document.write("이름:"+sawon['name']+"<br>"); document.write("부서:"+sawon['dept']+"<br>"); document.write("직위:"+sawon['job']+"<br>"); document.write("급여:"+sawon['pay']+"<br>"); document.write("<hr>"); for(let key in sawon) { //cookie document.write(sawon[key]+"<br>"); } } </script> </head> <body> </body> </html>
//Pacote inicial para iniciar o projeto const express = require('express'); //Importando celebrate: faz a validação dos campos const { celebrate, Segments, Joi } = require('celebrate'); //Controllers const UserController = require('./controllers/UserController'); const SessionController = require('./controllers/SessionController'); const SaleController = require('./controllers/SaleController'); const ProfileController = require('./controllers/ProfileController'); const routes = express.Router(); //Login routes.post('/sessions', SessionController.create); //Listar casos especificos de um usuario //Fazendo a validação dos campos routes.get('/profile', celebrate({ [Segments.HEADERS]: Joi.object({ authorization: Joi.string().required(),//Authorization precisa ser uma string e obrigatoria }).unknown(), }), ProfileController.index); //Deletar uma venda //Fazendo a validação dos campos routes.delete('/sales/:id', celebrate({ [Segments.PARAMS]: Joi.object().keys({ id: Joi.number().required(),//ID é um numero e obrigatorio }) }), SaleController.delete); //Listar todas as vendas do banco de dados //Fazendo a validação dos campos routes.get('/sales', celebrate({ [Segments.QUERY]: Joi.object().keys({ page: Joi.number(),//Page precisa ser numerica }) }), SaleController.index); //Cadastro de uma nova venda routes.post('/sales', SaleController.create); //Listar todos os usuarios do banco de dados routes.get('/users', UserController.index); //Cadastro de um novo usuario //Fazendo a validação dos campos routes.post('/users', celebrate({ [Segments.BODY]: Joi.object().keys({ name: Joi.string().required(),//Nome ele é uma string e é obrigatorio email: Joi.string().required().email(),//Email é uma string, é obrigatório e tem que ser no formato de e-mail whatsapp: Joi.string().required().min(12).max(13),//Whatsapp é do tipo numero, no minimo 12 caracteres e no maximo 13 city: Joi.string().required(),//City é uma string e obrigatorio uf: Joi.string().required().length(2),//Uf é uma string obrigatorio e o tamanho no maximo de 2 caracteres }) }), UserController.create); module.exports = routes;
function sinLaPrimeraAparicionDe_En_(elemento, lista) { /* PROPOSITO: Describe la lista "lista" resultante de eliminar el elemento "elemento" PRECONDICION: Ninguna PARAMETROS: "elemento" es un Elemento "lista" es una Lista de tipo Elemento TIPO: Lista de tipo Elemento OBSERVACION: se usa la idea de separar la lista "lista" en 2 partes. */ return (choose listaAntesDelElemento_En_(elemento, lista) ++ resto(listaDesdeElElemento_En_(elemento, lista)) when (contiene_A_(lista, elemento)) lista otherwise ) } function listaAntesDelElemento_En_(elemento,lista) { /* PROPOSITO: Describe una lista con elementos de la lista "lista" que están antes del elemento "elemento" PRECONDICION: ninguna PARAMETROS: "elemento" es un Elemento "lista" es una Lista de tipo Elemento TIPO: Lista de tipo Elemento OBSERVACION: recorrido de búsqueda y acumulación sobre la lista "lista" acumulando los elementos a la lista hasta encontrar el elemento "elemento" */ listaRestante := lista elementosVistos := [] while (not esVacía(listaRestante) && not primero(listaRestante) == elemento) { elementosVistos := elementosVistos ++ [primero(listaRestante)] listaRestante := resto(listaRestante) } return (elementosVistos) } function listaDesdeElElemento_En_(elemento, lista) { /* PROPOSITO: Describe una lista con elementos de la lista "lista" que están a partir del elemento "elemento" PRECONDICION: ninguna PARAMETROS: "elemento" es un Elemento "lista" es una Lista de tipo Elemento TIPO: Lista de tipo Elemento OBSERVACION: recorrido de búsqueda sobre la lista "lista" buscando el elemento "elemento" */ listaRestante := lista while (not esVacía(listaRestante) && not primero(listaRestante) == elemento) { listaRestante := resto(listaRestante) } return (listaRestante) }
package Term::UI::History; use strict; use vars qw[$VERSION]; use base 'Exporter'; use base 'Log::Message::Simple'; $VERSION = '0.46'; =pod =head1 NAME Term::UI::History - history function =head1 SYNOPSIS use Term::UI::History qw[history]; history("Some message"); ### retrieve the history in printable form $hist = Term::UI::History->history_as_string; ### redirect output local $Term::UI::History::HISTORY_FH = \*STDERR; =head1 DESCRIPTION This module provides the C<history> function for C<Term::UI>, printing and saving all the C<UI> interaction. Refer to the C<Term::UI> manpage for details on usage from C<Term::UI>. This module subclasses C<Log::Message::Simple>. Refer to its manpage for additional functionality available via this package. =head1 FUNCTIONS =head2 history("message string" [,VERBOSE]) Records a message on the stack, and prints it to C<STDOUT> (or actually C<$HISTORY_FH>, see the C<GLOBAL VARIABLES> section below), if the C<VERBOSE> option is true. The C<VERBOSE> option defaults to true. =cut BEGIN { use Log::Message private => 0; use vars qw[ @EXPORT $HISTORY_FH ]; @EXPORT = qw[ history ]; my $log = new Log::Message; $HISTORY_FH = \*STDOUT; for my $func ( @EXPORT ) { no strict 'refs'; *$func = sub { my $msg = shift; $log->store( message => $msg, tag => uc $func, level => $func, extra => [@_] ); }; } sub history_as_string { my $class = shift; return join $/, map { $_->message } __PACKAGE__->stack; } } { package # hide this from PAUSE Log::Message::Handlers; sub history { my $self = shift; my $verbose = shift; $verbose = 1 unless defined $verbose; # default to true ### so you don't want us to print the msg? ### return if defined $verbose && $verbose == 0; local $| = 1; my $old_fh = select $Term::UI::History::HISTORY_FH; print $self->message . "\n"; select $old_fh; return; } } =head1 GLOBAL VARIABLES =over 4 =item $HISTORY_FH This is the filehandle all the messages sent to C<history()> are being printed. This defaults to C<*STDOUT>. =back =head1 See Also C<Log::Message::Simple>, C<Term::UI> =head1 AUTHOR This module by Jos Boumans E<lt>kane@cpan.orgE<gt>. =head1 COPYRIGHT This module is copyright (c) 2005 Jos Boumans E<lt>kane@cpan.orgE<gt>. All rights reserved. This library is free software; you may redistribute and/or modify it under the same terms as Perl itself. =cut 1; # Local variables: # c-indentation-style: bsd # c-basic-offset: 4 # indent-tabs-mode: nil # End: # vim: expandtab shiftwidth=4:
import { useEffect, useState } from "react"; const HOC = (Component) => { function HOCtoReturn() { const [date, setDate] = useState(new Date()); useEffect(() => { const interval = setInterval(() => setDate(new Date()), 1000); return () => clearInterval(interval); }, [date]); return ( <div> <h3>{date.toLocaleTimeString()}</h3> <Component /> </div> ); } return HOCtoReturn; }; export default HOC;
#include <string.h> #include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_wifi.h" #include "esp_wpa2.h" #include "esp_event.h" #include "esp_log.h" #include "esp_system.h" #include "nvs_flash.h" #include "esp_netif.h" #include "esp_smartconfig.h" #include "my_time.h" /* FreeRTOS event group to signal when we are connected & ready to make a request */ static EventGroupHandle_t s_wifi_event_group; /* The event group allows multiple bits for each event, but we only care about one event - are we connected to the AP with an IP? */ static const int CONNECTED_BIT = BIT0; static const int ESPTOUCH_DONE_BIT = BIT1; static const char *TAG = "smartconfig_example"; static bool is_smartconfig_started = false; static void smartconfig_example_task(void *parm); void start_smartconfig(void) { // 检查是否已开启smartconfig if (is_smartconfig_started) { ESP_LOGI(TAG, "SmartConfig is already started"); return; } // 开启smartconfig ESP_LOGI(TAG, "SmartConfig start"); xTaskCreate(smartconfig_example_task, "smartconfig_example_task", 4096, NULL, 3, NULL); } static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { static uint8_t ssid[33] = {0}; static uint8_t password[65] = {0}; if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { // 读取存储的wifi信息 nvs_handle_t nvs_handle; ESP_ERROR_CHECK(nvs_open("storage", NVS_READWRITE, &nvs_handle)); size_t ssid_len = 33; size_t password_len = 65; ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_get_str(nvs_handle, "ssid", (char *)ssid, &ssid_len)); ESP_ERROR_CHECK_WITHOUT_ABORT(nvs_get_str(nvs_handle, "password", (char *)password, &password_len)); nvs_close(nvs_handle); if (strlen((char *)ssid) != 0 && strlen((char *)password) != 0) { ESP_LOGI(TAG, "Stored WiFi Credentials: SSID:%s, PASSWORD:%s", ssid, password); wifi_config_t wifi_config = { .sta = { .ssid = "", .password = "", .bssid_set = false, }, }; memcpy(wifi_config.sta.ssid, ssid, sizeof(ssid)); memcpy(wifi_config.sta.password, password, sizeof(password)); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); esp_wifi_connect(); } else { ESP_LOGI(TAG, "Stored WiFi Credentials not found, starting SmartConfig"); start_smartconfig(); } } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { esp_wifi_connect(); xEventGroupClearBits(s_wifi_event_group, CONNECTED_BIT); } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { xEventGroupSetBits(s_wifi_event_group, CONNECTED_BIT); // 连接成功,存储wifi信息 nvs_handle_t nvs_handle; ESP_ERROR_CHECK(nvs_open("storage", NVS_READWRITE, &nvs_handle)); ESP_ERROR_CHECK(nvs_set_str(nvs_handle, "ssid", (char *)ssid)); ESP_ERROR_CHECK(nvs_set_str(nvs_handle, "password", (char *)password)); ESP_ERROR_CHECK(nvs_commit(nvs_handle)); nvs_close(nvs_handle); // 初始化时间 initialize_sntp(); } else if (event_base == SC_EVENT && event_id == SC_EVENT_SCAN_DONE) { ESP_LOGI(TAG, "Scan done"); } else if (event_base == SC_EVENT && event_id == SC_EVENT_FOUND_CHANNEL) { ESP_LOGI(TAG, "Found channel"); } else if (event_base == SC_EVENT && event_id == SC_EVENT_GOT_SSID_PSWD) { ESP_LOGI(TAG, "Got SSID and password"); smartconfig_event_got_ssid_pswd_t *evt = (smartconfig_event_got_ssid_pswd_t *)event_data; wifi_config_t wifi_config; uint8_t rvd_data[33] = {0}; bzero(&wifi_config, sizeof(wifi_config_t)); memcpy(wifi_config.sta.ssid, evt->ssid, sizeof(wifi_config.sta.ssid)); memcpy(wifi_config.sta.password, evt->password, sizeof(wifi_config.sta.password)); wifi_config.sta.bssid_set = evt->bssid_set; if (wifi_config.sta.bssid_set == true) { memcpy(wifi_config.sta.bssid, evt->bssid, sizeof(wifi_config.sta.bssid)); } memcpy(ssid, evt->ssid, sizeof(evt->ssid)); memcpy(password, evt->password, sizeof(evt->password)); ESP_LOGI(TAG, "SSID:%s", ssid); ESP_LOGI(TAG, "PASSWORD:%s", password); if (evt->type == SC_TYPE_ESPTOUCH_V2) { ESP_ERROR_CHECK(esp_smartconfig_get_rvd_data(rvd_data, sizeof(rvd_data))); ESP_LOGI(TAG, "RVD_DATA:"); for (int i = 0; i < 33; i++) { printf("%02x ", rvd_data[i]); } printf("\n"); } ESP_ERROR_CHECK(esp_wifi_disconnect()); ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi_config)); esp_wifi_connect(); } else if (event_base == SC_EVENT && event_id == SC_EVENT_SEND_ACK_DONE) { xEventGroupSetBits(s_wifi_event_group, ESPTOUCH_DONE_BIT); } } void initialise_wifi(void) { s_wifi_event_group = xEventGroupCreate(); esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta(); assert(sta_netif); wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_wifi_init(&cfg)); ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(SC_EVENT, ESP_EVENT_ANY_ID, &event_handler, NULL)); ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); ESP_ERROR_CHECK(esp_wifi_start()); } static void smartconfig_example_task(void *parm) { EventBits_t uxBits; is_smartconfig_started = true; ESP_ERROR_CHECK(esp_smartconfig_set_type(SC_TYPE_ESPTOUCH)); smartconfig_start_config_t cfg = SMARTCONFIG_START_CONFIG_DEFAULT(); ESP_ERROR_CHECK(esp_smartconfig_start(&cfg)); while (1) { uxBits = xEventGroupWaitBits(s_wifi_event_group, CONNECTED_BIT | ESPTOUCH_DONE_BIT, true, false, portMAX_DELAY); if (uxBits & CONNECTED_BIT) { ESP_LOGI(TAG, "WiFi Connected to ap"); } if (uxBits & ESPTOUCH_DONE_BIT) { ESP_LOGI(TAG, "smartconfig over"); esp_smartconfig_stop(); is_smartconfig_started = false; vTaskDelete(NULL); } } }
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:routemaster/routemaster.dart'; import 'package:tiktok_clone/controller/video_controller.dart'; import 'package:tiktok_clone/error_text.dart'; import 'package:tiktok_clone/models/postVideo.dart'; import 'package:tiktok_clone/utl.dart'; import 'package:tiktok_clone/views/widgets/circle_animation.dart'; import 'package:tiktok_clone/views/widgets/video_player_item.dart'; class VideoScreen extends ConsumerWidget { const VideoScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { buildMusicAlbum(String profilePhoto) { return SizedBox( width: 60, height: 60, child: Column( children: [ Container( padding: const EdgeInsets.all(11), height: 50, width: 50, decoration: BoxDecoration( gradient: const LinearGradient(colors: [Colors.grey, Colors.white]), borderRadius: BorderRadius.circular(25), ), child: ClipRRect( borderRadius: BorderRadius.circular(25), child: Image( image: NetworkImage(profilePhoto), fit: BoxFit.cover, ), ), ) ], ), ); } void likingPost(PostVideo post) async { ref.watch(videoControllerProvider.notifier).likingPost(post); } void navigateToCommentScreen(PostVideo post) { Routemaster.of(context).push('/comment_screen/${post.id}'); } final size = MediaQuery.of(context).size; return Scaffold( body: ref.watch(postedVideoProvider).when( data: (data) => PageView.builder( itemCount: data.length, controller: PageController(initialPage: 0, viewportFraction: 1), scrollDirection: Axis.vertical, itemBuilder: (context, index) { final post = data[index]; return Stack( children: [ VideoPlayerItem(videoURl: post.videoUrl), Container( margin: const EdgeInsets.only(left: 15), child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox( height: 100, ), Text( post.userName, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 20), ), Text( post.caption, style: const TextStyle(fontSize: 15), ), Row( children: [ const Icon( Icons.music_note, size: 15, ), Text( post.songName, style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 14), ) ], ) ], ), ), Container( width: 100, margin: EdgeInsets.only( top: size.height * 0.35, left: size.width * 0.75), child: Column( // crossAxisAlignment: CrossAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Container( decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( color: Colors .white, // Set the desired border color width: 2.0, // Set the desired border width ), ), child: ClipRRect( borderRadius: BorderRadius.circular(25), child: CircleAvatar( backgroundImage: NetworkImage(post.profilePhoto), radius: 25, ), ), ), Column( children: [ InkWell( onTap: () { likingPost(post); }, child: const Icon( Icons.favorite, size: 40, color: Colors.red, ), ), const SizedBox( height: 7, ), Text( post.likes.length.toString(), style: const TextStyle(fontSize: 15), ), ], ), Column( children: [ InkWell( onTap: () => navigateToCommentScreen(post), child: const Icon( Icons.comment, size: 40, color: Colors.white, ), ), const SizedBox( height: 7, ), Text( post.commentCount.toString(), style: const TextStyle(fontSize: 15), ), ], ), Column( children: [ InkWell( onTap: () {}, child: const Icon( Icons.reply, size: 40, color: Colors.white, ), ), const SizedBox( height: 7, ), Text( post.shareCount.toString(), style: const TextStyle(fontSize: 15), ), ], ), CircleAnimation( child: buildMusicAlbum(post.profilePhoto), ) ], ), ) ], ); }), error: (error, stackTrace) => ErrorText( text: error.toString(), ), loading: () => loader(), )); } }
import { createError } from 'h3' import { $fetch } from 'ofetch' import { getQuery, parseURL } from 'ufo' import { feedsInfo, validFeeds } from '~/composables/api' import { baseURL } from '~/server/constants' import { configureSWRHeaders } from '~/server/swr' const feedUrls: Record<keyof typeof feedsInfo, string> = { ask: 'askstories', jobs: 'jobstories', show: 'showstories', newest: 'newstories', news: 'topstories' } async function fetchFeed (feed: string, page = '1') { const { fetchItem } = await import('./item') const entries = Object.values( await $fetch(`${baseURL}/${feedUrls[feed as keyof typeof feedsInfo]}.json`) ).slice(Number(page) * 10, Number(page) * 10 + 10) as string[] return Promise.all(entries.map(id => fetchItem(id))) } export default defineEventHandler(({ req, res }) => { configureSWRHeaders(res) const { search } = parseURL(req.url) const { page = '1', feed = 'news' } = getQuery(search) as { page: string, feed: string } if (!validFeeds.includes(feed) || String(Number(page)) !== page) { throw createError({ statusCode: 422, statusMessage: `Must provide one of ${validFeeds.join(', ')} and a valid page number.` }) } return fetchFeed(feed, page) })
<template> <a-form :model="formState" name="validate_other" v-bind="formItemLayout" @finishFailed="onFinishFailed" @finish="onFinish"> <a-form-item label="任务类型" name="type" has-feedback :rules="[{ required: true, message: '请选择任务类型' }]"> <a-select v-model:value="formState.type" placeholder="选择任务类型" :options="types"> </a-select> </a-form-item> <a-form-item label="任务名称" name="name" :rules="[{ required: true, message: '请输入唯一名称' }]"> <a-input v-model:value="formState.name" /> </a-form-item> <a-form-item label="流水号" name="uid" :rules="[{ required: true, message: '请输入唯一流水号' }]"> <a-input v-model:value="formState.uid" /> </a-form-item> <a-form-item label="容器镜像" name="image" :rules="[{ required: true, message: '请输入容器镜像名称' }]"> <a-input v-model:value="formState.image" /> </a-form-item> <a-form-item label="启动命令" name="command" :rules="[{ required: true, message: '请输入容器启动命令' }]"> <a-input v-model:value="formState.command" /> </a-form-item> <a-form-item label="报告名称" name="prefix" :rules="[{ required: false, message: '请输入测试报告路径' }]"> <a-input v-model:value="formState.prefix" /> </a-form-item> <a-form-item :wrapper-col="{ span: 12, offset: 6 }"> <a-button type="primary" html-type="submit">创建</a-button> </a-form-item> </a-form> </template> <script> import { defineComponent, onMounted, ref } from "vue"; import { v4 as uuidv4 } from 'uuid'; import { requestInstance } from '@/api/request' import { notification } from 'ant-design-vue'; const types = ref([ { label: 'jmeter', value: 'jmter' }, { label: 'locust', value: 'locust' }, { label: 'aomaker', value: 'aomaker' } ]) const formState = ref({ type: "aomaker", name: uuidv4().substr(0, 6), uid: uuidv4().substr(0, 7), image: 'dockerhub.qingcloud.com/listen/hpc:4.0', command: 'arun -e testbm -m hpc_fs', prefix: '/data/autotest/reports' }); const formItemLayout = ref({ labelCol: { span: 6, }, wrapperCol: { span: 14, }, }); export default defineComponent({ name: "TaskCreater", components: { }, setup() { const onFinish = async (values) => { await requestInstance({ method: 'post', url: '/tink/job', data: { type: values.type, name: values.name, uid: values.uid, container: { image: values.image, command: values.command, }, prefix: values.prefix } }) notification.open({ message: '创建成功', onClick: () => { console.log('Clicked!'); }, }) }; const onFinishFailed = (errorInfo) => { console.log("Failed:", errorInfo); }; onMounted(() => { }); return { onFinish, onFinishFailed, formItemLayout, types, formState, }; }, }); </script>
import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { NgModule, ApplicationRef } from '@angular/core'; import { removeNgStyles, createNewHosts, createInputTransfer } from '@angularclass/hmr'; import { RouterModule, PreloadAllModules } from '@angular/router'; /* * Platform and Environment providers/directives/pipes */ import { ENV_PROVIDERS } from './environment'; import { ROUTES } from './app.routes'; // App is our top level component import { AppComponent } from './app.component'; import { APP_RESOLVER_PROVIDERS } from './app.resolver'; import { AppState, InternalStateType } from './app.service'; import { HomeComponent } from './home'; import { SearchComponent } from './search'; import { NoContentComponent } from './no-content'; import { XLargeDirective } from './home/x-large'; import { InfiniteScrollModule } from 'ngx-infinite-scroll'; import { ModalModule } from 'ngx-bootstrap/modal'; import { AlertModule } from 'ngx-bootstrap/alert'; import { Release } from './release.component'; import { ReleaseService } from './release.service'; import { ReleaseSearchComponent } from './release-search.component'; import { ReleaseSearchService } from './release-search.service'; import { NZB } from './nzb.component'; import { User } from './user.component'; import { UserService } from './user.service'; import { Angulartics2Module, Angulartics2Piwik } from 'angulartics2'; import { BytesPipe } from './bytes.pipe'; import '../styles/styles.scss'; import '../styles/headings.css'; // Application wide providers const APP_PROVIDERS = [ ...APP_RESOLVER_PROVIDERS, AppState, UserService ]; type StoreType = { state: InternalStateType, restoreInputValues: () => void, disposeOldHosts: () => void }; /** * `AppModule` is the main entry point into Angular2's bootstraping process */ @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent, SearchComponent, HomeComponent, NoContentComponent, XLargeDirective, ReleaseSearchComponent, BytesPipe, ], /** * Import Angular's modules. */ imports: [ BrowserModule, FormsModule, HttpModule, InfiniteScrollModule, ModalModule.forRoot(), AlertModule.forRoot(), Angulartics2Module.forRoot([Angulartics2Piwik]), RouterModule.forRoot(ROUTES, { useHash: false, preloadingStrategy: PreloadAllModules }) ], /** * Expose our Services and Providers into Angular's dependency injection. */ providers: [ ENV_PROVIDERS, APP_PROVIDERS ] }) export class AppModule { constructor( public appRef: ApplicationRef, public appState: AppState ) {} public hmrOnInit(store: StoreType) { if (!store || !store.state) { return; } console.log('HMR store', JSON.stringify(store, null, 2)); /** * Set state */ this.appState._state = store.state; /** * Set input values */ if ('restoreInputValues' in store) { let restoreInputValues = store.restoreInputValues; setTimeout(restoreInputValues); } this.appRef.tick(); delete store.state; delete store.restoreInputValues; } public hmrOnDestroy(store: StoreType) { const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement); /** * Save state */ const state = this.appState._state; store.state = state; /** * Recreate root elements */ store.disposeOldHosts = createNewHosts(cmpLocation); /** * Save input values */ store.restoreInputValues = createInputTransfer(); /** * Remove styles */ removeNgStyles(); } public hmrAfterDestroy(store: StoreType) { /** * Display new elements */ store.disposeOldHosts(); delete store.disposeOldHosts; } }
<template> <a-layout> <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="Chi tiết hóa đơn" sub-title="" /> <a-layout-content style="padding: 0 50px"> <a-table :columns="columns" :data-source="data" :scroll="{ x: 1000, y: 500 }"> <template #bodyCell="{ column, record }"> <template v-if="column.dataIndex === 'image'"> <a-image :width="50" :src="record.image" /> </template> </template> </a-table> <a-divider orientation="right">Tổng cộng: {{this.order.amount}}</a-divider> </a-layout-content> </a-layout> </template> <script> import BaseRequest from '../../core/BaseRequest.js'; import { authStore } from '../../store/auth.store'; import { mapState } from 'pinia'; import { notification } from 'ant-design-vue'; export default({ data() { return { columns: [], order: [], errors: {}, data: [], visible: false } }, mounted() { this.getData() }, computed: { ...mapState(authStore, ['isLoggedIn', 'user']) }, methods: { getData: function() { this.columns = [ { title: 'Hình ảnh', dataIndex: 'image', key: 'image' }, { title: 'Tên sản phẩm', dataIndex: 'name', key: 'name' }, { title: 'Giá', dataIndex: 'price', key: 'price' }, { title: 'Số lượng', dataIndex: 'quantity', key: 'quantity' } ]; this.getOrder() }, getOrder: function() { this.data = [] BaseRequest.get('order/'+ this.$route.params.order_id) .then(response => { this.order = response.data for (const num in this.order.items) { this.data.push({ name: this.order.items[num].product.name, image: this.order.items[num].product.image, price: this.order.items[num].product.price, quantity: this.order.items[num].quantity, }) } }) .catch(error=> { this.errors = error.response.data }); } } }) </script>
/* * jQuery FlexSlider v2.7.2 * Copyright 2012 WooThemes * Contributing Author: Tyler Smith */ ; (function ($) { var focused = true; //FlexSlider: Object Instance $.flexslider = function(el, options) { var slider = $(el); // making variables public //if rtl value was not passed and html is in rtl..enable it by default. if(typeof options.rtl=='undefined' && $('html').attr('dir')=='rtl'){ options.rtl=true; } slider.vars = $.extend({}, $.flexslider.defaults, options); var namespace = slider.vars.namespace, msGesture = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, touch = (( "ontouchstart" in window ) || msGesture || window.DocumentTouch && document instanceof DocumentTouch) && slider.vars.touch, // deprecating this idea, as devices are being released with both of these events eventType = "click touchend MSPointerUp keyup", watchedEvent = "", watchedEventClearTimer, vertical = slider.vars.direction === "vertical", reverse = slider.vars.reverse, carousel = (slider.vars.itemWidth > 0), fade = slider.vars.animation === "fade", asNav = slider.vars.asNavFor !== "", methods = {}; // Store a reference to the slider object $.data(el, "flexslider", slider); // Private slider methods methods = { init: function() { slider.animating = false; // Get current slide and make sure it is a number slider.currentSlide = parseInt( ( slider.vars.startAt ? slider.vars.startAt : 0), 10 ); if ( isNaN( slider.currentSlide ) ) { slider.currentSlide = 0; } slider.animatingTo = slider.currentSlide; slider.atEnd = (slider.currentSlide === 0 || slider.currentSlide === slider.last); slider.containerSelector = slider.vars.selector.substr(0,slider.vars.selector.search(' ')); slider.slides = $(slider.vars.selector, slider); slider.container = $(slider.containerSelector, slider); slider.count = slider.slides.length; // SYNC: slider.syncExists = $(slider.vars.sync).length > 0; // SLIDE: if (slider.vars.animation === "slide") { slider.vars.animation = "swing"; } slider.prop = (vertical) ? "top" : ( slider.vars.rtl ? "marginRight" : "marginLeft" ); slider.args = {}; // SLIDESHOW: slider.manualPause = false; slider.stopped = false; //PAUSE WHEN INVISIBLE slider.started = false; slider.startTimeout = null; // TOUCH/USECSS: slider.transitions = !slider.vars.video && !fade && slider.vars.useCSS && (function() { var obj = document.createElement('div'), props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']; for (var i in props) { if ( obj.style[ props[i] ] !== undefined ) { slider.pfx = props[i].replace('Perspective','').toLowerCase(); slider.prop = "-" + slider.pfx + "-transform"; return true; } } return false; }()); slider.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1; slider.ensureAnimationEnd = ''; // CONTROLSCONTAINER: if (slider.vars.controlsContainer !== "") slider.controlsContainer = $(slider.vars.controlsContainer).length > 0 && $(slider.vars.controlsContainer); // MANUAL: if (slider.vars.manualControls !== "") slider.manualControls = $(slider.vars.manualControls).length > 0 && $(slider.vars.manualControls); // CUSTOM DIRECTION NAV: if (slider.vars.customDirectionNav !== "") slider.customDirectionNav = $(slider.vars.customDirectionNav).length === 2 && $(slider.vars.customDirectionNav); // RANDOMIZE: if (slider.vars.randomize) { slider.slides.sort(function() { return (Math.round(Math.random())-0.5); }); slider.container.empty().append(slider.slides); } slider.doMath(); // INIT slider.setup("init"); // CONTROLNAV: if (slider.vars.controlNav) { methods.controlNav.setup(); } // DIRECTIONNAV: if (slider.vars.directionNav) { methods.directionNav.setup(); } // KEYBOARD: if (slider.vars.keyboard && ($(slider.containerSelector).length === 1 || slider.vars.multipleKeyboard)) { $(document).on('keyup', function(event) { var keycode = event.keyCode; if (!slider.animating && (keycode === 39 || keycode === 37)) { var target = (slider.vars.rtl? ((keycode === 37) ? slider.getTarget('next') : (keycode === 39) ? slider.getTarget('prev') : false) : ((keycode === 39) ? slider.getTarget('next') : (keycode === 37) ? slider.getTarget('prev') : false) ) ; slider.flexAnimate(target, slider.vars.pauseOnAction); } }); } // MOUSEWHEEL: if (slider.vars.mousewheel) { slider.on('mousewheel', function(event, delta, deltaX, deltaY) { event.preventDefault(); var target = (delta < 0) ? slider.getTarget('next') : slider.getTarget('prev'); slider.flexAnimate(target, slider.vars.pauseOnAction); }); } // PAUSEPLAY if (slider.vars.pausePlay) { methods.pausePlay.setup(); } //PAUSE WHEN INVISIBLE if (slider.vars.slideshow && slider.vars.pauseInvisible) { methods.pauseInvisible.init(); } // SLIDSESHOW if (slider.vars.slideshow) { if (slider.vars.pauseOnHover) { slider.on( 'mouseenter', function() { if (!slider.manualPlay && !slider.manualPause) { slider.pause(); } } ).on( 'mouseleave', function() { if (!slider.manualPause && !slider.manualPlay && !slider.stopped) { slider.play(); } }); } // initialize animation //If we're visible, or we don't use PageVisibility API if(!slider.vars.pauseInvisible || !methods.pauseInvisible.isHidden()) { (slider.vars.initDelay > 0) ? slider.startTimeout = setTimeout(slider.play, slider.vars.initDelay) : slider.play(); } } // ASNAV: if (asNav) { methods.asNav.setup(); } // TOUCH if (touch && slider.vars.touch) { methods.touch(); } // FADE&&SMOOTHHEIGHT || SLIDE: if (!fade || (fade && slider.vars.smoothHeight)) { $(window).on("resize orientationchange focus", methods.resize); } slider.find("img").attr("draggable", "false"); // API: start() Callback setTimeout(function(){ slider.vars.start(slider); }, 200); }, asNav: { setup: function() { slider.asNav = true; slider.animatingTo = Math.floor(slider.currentSlide/slider.move); slider.currentItem = slider.currentSlide; slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide"); if(!msGesture){ slider.slides.on(eventType, function(e){ e.preventDefault(); var $slide = $(this), target = $slide.index(); var posFromX; if(slider.vars.rtl){ posFromX = -1*($slide.offset().right - $(slider).scrollLeft()); // Find position of slide relative to right of slider container } else { posFromX = $slide.offset().left - $(slider).scrollLeft(); // Find position of slide relative to left of slider container } if( posFromX <= 0 && $slide.hasClass( namespace + 'active-slide' ) ) { slider.flexAnimate(slider.getTarget("prev"), true); } else if (!$(slider.vars.asNavFor).data('flexslider').animating && !$slide.hasClass(namespace + "active-slide")) { slider.direction = (slider.currentItem < target) ? "next" : "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true); } }); }else{ el._slider = slider; slider.slides.each(function (){ var that = this; that._gesture = new MSGesture(); that._gesture.target = that; that.addEventListener("MSPointerDown", function (e){ e.preventDefault(); if(e.currentTarget._gesture) { e.currentTarget._gesture.addPointer(e.pointerId); } }, false); that.addEventListener("MSGestureTap", function (e){ e.preventDefault(); var $slide = $(this), target = $slide.index(); if (!$(slider.vars.asNavFor).data('flexslider').animating && !$slide.hasClass('active')) { slider.direction = (slider.currentItem < target) ? "next" : "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction, false, true, true); } }); }); } } }, controlNav: { setup: function() { if (!slider.manualControls) { methods.controlNav.setupPaging(); } else { // MANUALCONTROLS: methods.controlNav.setupManual(); } }, setupPaging: function() { var type = (slider.vars.controlNav === "thumbnails") ? 'control-thumbs' : 'control-paging', j = 1, item, slide; slider.controlNavScaffold = $('<ol class="'+ namespace + 'control-nav ' + namespace + type + '"></ol>'); if (slider.pagingCount > 1) { for (var i = 0; i < slider.pagingCount; i++) { slide = slider.slides.eq(i); if ( undefined === slide.attr( 'data-thumb-alt' ) ) { slide.attr( 'data-thumb-alt', '' ); } item = $( '<a></a>' ).attr( 'href', '#' ).text( j ); if (slider.vars.controlNav === "thumbnails") { item = $('<img/>', { onload: 'this.width = this.naturalWidth; this.height = this.naturalHeight', src: slide.attr('data-thumb'), alt: slide.attr('alt') }) } if ( '' !== slide.attr( 'data-thumb-alt' ) ) { item.attr( 'alt', slide.attr( 'data-thumb-alt' ) ); } if ( 'thumbnails' === slider.vars.controlNav && true === slider.vars.thumbCaptions ) { var captn = slide.attr( 'data-thumbcaption' ); if ( '' !== captn && undefined !== captn ) { var caption = $('<span></span>' ).addClass( namespace + 'caption' ).text( captn ); item.append( caption ); } } var liElement = $( '<li>' ); item.appendTo( liElement ); liElement.append( '</li>' ); slider.controlNavScaffold.append(liElement); j++; } } // CONTROLSCONTAINER: (slider.controlsContainer) ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold); methods.controlNav.set(); methods.controlNav.active(); slider.controlNavScaffold.on(eventType, 'a, img', function(event) { event.preventDefault(); if (watchedEvent === "" || watchedEvent === event.type) { var $this = $(this), target = slider.controlNav.index($this); if (!$this.hasClass(namespace + 'active')) { slider.direction = (target > slider.currentSlide) ? "next" : "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction); } } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, setupManual: function() { slider.controlNav = slider.manualControls; methods.controlNav.active(); slider.controlNav.on(eventType, function(event) { event.preventDefault(); if (watchedEvent === "" || watchedEvent === event.type) { var $this = $(this), target = slider.controlNav.index($this); if (!$this.hasClass(namespace + 'active')) { (target > slider.currentSlide) ? slider.direction = "next" : slider.direction = "prev"; slider.flexAnimate(target, slider.vars.pauseOnAction); } } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, set: function() { var selector = (slider.vars.controlNav === "thumbnails") ? 'img' : 'a'; slider.controlNav = $('.' + namespace + 'control-nav li ' + selector, (slider.controlsContainer) ? slider.controlsContainer : slider); }, active: function() { slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active"); }, update: function(action, pos) { if (slider.pagingCount > 1 && action === "add") { slider.controlNavScaffold.append($('<li><a href="#">' + slider.count + '</a></li>')); } else if (slider.pagingCount === 1) { slider.controlNavScaffold.find('li').remove(); } else { slider.controlNav.eq(pos).closest('li').remove(); } methods.controlNav.set(); (slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length) ? slider.update(pos, action) : methods.controlNav.active(); } }, directionNav: { setup: function() { var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li class="' + namespace + 'nav-prev"><a class="' + namespace + 'prev" href="#">' + slider.vars.prevText + '</a></li><li class="' + namespace + 'nav-next"><a class="' + namespace + 'next" href="#">' + slider.vars.nextText + '</a></li></ul>'); // CUSTOM DIRECTION NAV: if (slider.customDirectionNav) { slider.directionNav = slider.customDirectionNav; // CONTROLSCONTAINER: } else if (slider.controlsContainer) { $(slider.controlsContainer).append(directionNavScaffold); slider.directionNav = $('.' + namespace + 'direction-nav li a', slider.controlsContainer); } else { slider.append(directionNavScaffold); slider.directionNav = $('.' + namespace + 'direction-nav li a', slider); } methods.directionNav.update(); slider.directionNav.on(eventType, function(event) { event.preventDefault(); var target; if (watchedEvent === "" || watchedEvent === event.type) { target = ($(this).hasClass(namespace + 'next')) ? slider.getTarget('next') : slider.getTarget('prev'); slider.flexAnimate(target, slider.vars.pauseOnAction); } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, update: function() {console.log('updating...'); var disabledClass = namespace + 'disabled'; if (slider.pagingCount === 1) { slider.directionNav.addClass(disabledClass).attr('tabindex', '-1'); } else if (!slider.vars.animationLoop) { if (slider.animatingTo === 0) { slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "prev").addClass(disabledClass).attr('tabindex', '-1'); } else if (slider.animatingTo === slider.last) { slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "next").addClass(disabledClass).attr('tabindex', '-1'); } else { slider.directionNav.removeClass(disabledClass).prop( 'tabindex', '-1' ); } } else { slider.directionNav.removeClass(disabledClass).prop( 'tabindex', '-1' ); } } }, pausePlay: { setup: function() { var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a href="#"></a></div>'); // CONTROLSCONTAINER: if (slider.controlsContainer) { slider.controlsContainer.append(pausePlayScaffold); slider.pausePlay = $('.' + namespace + 'pauseplay a', slider.controlsContainer); } else { slider.append(pausePlayScaffold); slider.pausePlay = $('.' + namespace + 'pauseplay a', slider); } methods.pausePlay.update((slider.vars.slideshow) ? namespace + 'pause' : namespace + 'play'); slider.pausePlay.on(eventType, function(event) { event.preventDefault(); if (watchedEvent === "" || watchedEvent === event.type) { if ($(this).hasClass(namespace + 'pause')) { slider.manualPause = true; slider.manualPlay = false; slider.pause(); } else { slider.manualPause = false; slider.manualPlay = true; slider.play(); } } // setup flags to prevent event duplication if (watchedEvent === "") { watchedEvent = event.type; } methods.setToClearWatchedEvent(); }); }, update: function(state) { (state === "play") ? slider.pausePlay.removeClass(namespace + 'pause').addClass(namespace + 'play').html(slider.vars.playText) : slider.pausePlay.removeClass(namespace + 'play').addClass(namespace + 'pause').html(slider.vars.pauseText); } }, touch: function() { var startX, startY, offset, cwidth, dx, startT, onTouchStart, onTouchMove, onTouchEnd, scrolling = false, localX = 0, localY = 0, accDx = 0; if(!msGesture){ onTouchStart = function(e) { if (slider.animating) { e.preventDefault(); } else if ( ( window.navigator.msPointerEnabled ) || e.touches.length === 1 ) { slider.pause(); // CAROUSEL: cwidth = (vertical) ? slider.h : slider. w; startT = Number(new Date()); // CAROUSEL: // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 : (carousel && reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) : (carousel && slider.currentSlide === slider.last) ? slider.limit : (carousel) ? ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.currentSlide : (reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth; startX = (vertical) ? localY : localX; startY = (vertical) ? localX : localY; el.addEventListener('touchmove', onTouchMove, false); el.addEventListener('touchend', onTouchEnd, false); } }; onTouchMove = function(e) { // Local vars for X and Y points. localX = e.touches[0].pageX; localY = e.touches[0].pageY; dx = (vertical) ? startX - localY : (slider.vars.rtl?-1:1)*(startX - localX); scrolling = (vertical) ? (Math.abs(dx) < Math.abs(localX - startY)) : (Math.abs(dx) < Math.abs(localY - startY)); var fxms = 500; if ( ! scrolling || Number( new Date() ) - startT > fxms ) { e.preventDefault(); if (!fade && slider.transitions) { if (!slider.vars.animationLoop) { dx = dx/((slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0) ? (Math.abs(dx)/cwidth+2) : 1); } slider.setProps(offset + dx, "setTouch"); } } }; onTouchEnd = function(e) { // finish the touch by undoing the touch session el.removeEventListener('touchmove', onTouchMove, false); if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) { var updateDx = (reverse) ? -dx : dx, target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev'); if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth/2)) { slider.flexAnimate(target, slider.vars.pauseOnAction); } else { if (!fade) { slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true); } } } el.removeEventListener('touchend', onTouchEnd, false); startX = null; startY = null; dx = null; offset = null; }; el.addEventListener('touchstart', onTouchStart, false); }else{ el.style.msTouchAction = "none"; el._gesture = new MSGesture(); el._gesture.target = el; el.addEventListener("MSPointerDown", onMSPointerDown, false); el._slider = slider; el.addEventListener("MSGestureChange", onMSGestureChange, false); el.addEventListener("MSGestureEnd", onMSGestureEnd, false); function onMSPointerDown(e){ e.stopPropagation(); if (slider.animating) { e.preventDefault(); }else{ slider.pause(); el._gesture.addPointer(e.pointerId); accDx = 0; cwidth = (vertical) ? slider.h : slider. w; startT = Number(new Date()); // CAROUSEL: offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 : (carousel && reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) : (carousel && slider.currentSlide === slider.last) ? slider.limit : (carousel) ? ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.currentSlide : (reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth; } } function onMSGestureChange(e) { e.stopPropagation(); var slider = e.target._slider; if(!slider){ return; } var transX = -e.translationX, transY = -e.translationY; //Accumulate translations. accDx = accDx + ((vertical) ? transY : transX); dx = (slider.vars.rtl?-1:1)*accDx; scrolling = (vertical) ? (Math.abs(accDx) < Math.abs(-transX)) : (Math.abs(accDx) < Math.abs(-transY)); if(e.detail === e.MSGESTURE_FLAG_INERTIA){ setImmediate(function (){ el._gesture.stop(); }); return; } if (!scrolling || Number(new Date()) - startT > 500) { e.preventDefault(); if (!fade && slider.transitions) { if (!slider.vars.animationLoop) { dx = accDx / ((slider.currentSlide === 0 && accDx < 0 || slider.currentSlide === slider.last && accDx > 0) ? (Math.abs(accDx) / cwidth + 2) : 1); } slider.setProps(offset + dx, "setTouch"); } } } function onMSGestureEnd(e) { e.stopPropagation(); var slider = e.target._slider; if(!slider){ return; } if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) { var updateDx = (reverse) ? -dx : dx, target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev'); if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth/2)) { slider.flexAnimate(target, slider.vars.pauseOnAction); } else { if (!fade) { slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction, true); } } } startX = null; startY = null; dx = null; offset = null; accDx = 0; } } }, resize: function() { if (!slider.animating && slider.is(':visible')) { if (!carousel) { slider.doMath(); } if (fade) { // SMOOTH HEIGHT: methods.smoothHeight(); } else if (carousel) { //CAROUSEL: slider.slides.width(slider.computedW); slider.update(slider.pagingCount); slider.setProps(); } else if (vertical) { //VERTICAL: slider.viewport.height(slider.h); slider.setProps(slider.h, "setTotal"); } else { // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(); } slider.newSlides.width(slider.computedW); slider.setProps(slider.computedW, "setTotal"); } } }, smoothHeight: function(dur) { if (!vertical || fade) { var $obj = (fade) ? slider : slider.viewport; (dur) ? $obj.animate({"height": slider.slides.eq(slider.animatingTo).innerHeight()}, dur) : $obj.innerHeight(slider.slides.eq(slider.animatingTo).innerHeight()); } }, sync: function(action) { var $obj = $(slider.vars.sync).data("flexslider"), target = slider.animatingTo; switch (action) { case "animate": $obj.flexAnimate(target, slider.vars.pauseOnAction, false, true); break; case "play": if (!$obj.playing && !$obj.asNav) { $obj.play(); } break; case "pause": $obj.pause(); break; } }, uniqueID: function($clone) { // Append _clone to current level and children elements with id attributes $clone.filter( '[id]' ).add($clone.find( '[id]' )).each(function() { var $this = $(this); $this.attr( 'id', $this.attr( 'id' ) + '_clone' ); }); return $clone; }, pauseInvisible: { visProp: null, init: function() { var visProp = methods.pauseInvisible.getHiddenProp(); if (visProp) { var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange'; document.addEventListener(evtname, function() { if (methods.pauseInvisible.isHidden()) { if(slider.startTimeout) { clearTimeout(slider.startTimeout); //If clock is ticking, stop timer and prevent from starting while invisible } else { slider.pause(); //Or just pause } } else { if(slider.started) { slider.play(); //Initiated before, just play } else { if (slider.vars.initDelay > 0) { setTimeout(slider.play, slider.vars.initDelay); } else { slider.play(); //Didn't init before: simply init or wait for it } } } }); } }, isHidden: function() { var prop = methods.pauseInvisible.getHiddenProp(); if (!prop) { return false; } return document[prop]; }, getHiddenProp: function() { var prefixes = ['webkit','moz','ms','o']; // if 'hidden' is natively supported just return it if ('hidden' in document) { return 'hidden'; } // otherwise loop over all the known prefixes until we find one for ( var i = 0; i < prefixes.length; i++ ) { if ((prefixes[i] + 'Hidden') in document) { return prefixes[i] + 'Hidden'; } } // otherwise it's not supported return null; } }, setToClearWatchedEvent: function() { clearTimeout(watchedEventClearTimer); watchedEventClearTimer = setTimeout(function() { watchedEvent = ""; }, 3000); } }; // public methods slider.flexAnimate = function(target, pause, override, withSync, fromNav) { if (!slider.vars.animationLoop && target !== slider.currentSlide) { slider.direction = (target > slider.currentSlide) ? "next" : "prev"; } if (asNav && slider.pagingCount === 1) slider.direction = (slider.currentItem < target) ? "next" : "prev"; if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) { if (asNav && withSync) { var master = $(slider.vars.asNavFor).data('flexslider'); slider.atEnd = target === 0 || target === slider.count - 1; master.flexAnimate(target, true, false, true, fromNav); slider.direction = (slider.currentItem < target) ? "next" : "prev"; master.direction = slider.direction; if (Math.ceil((target + 1)/slider.visible) - 1 !== slider.currentSlide && target !== 0) { slider.currentItem = target; slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide"); target = Math.floor(target/slider.visible); } else { slider.currentItem = target; slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide"); return false; } } slider.animating = true; slider.animatingTo = target; // SLIDESHOW: if (pause) { slider.pause(); } // API: before() animation Callback slider.vars.before(slider); // SYNC: if (slider.syncExists && !fromNav) { methods.sync("animate"); } // CONTROLNAV if (slider.vars.controlNav) { methods.controlNav.active(); } // !CAROUSEL: // CANDIDATE: slide active class (for add/remove slide) if (!carousel) { slider.slides.removeClass(namespace + 'active-slide').eq(target).addClass(namespace + 'active-slide'); } // INFINITE LOOP: // CANDIDATE: atEnd slider.atEnd = target === 0 || target === slider.last; // DIRECTIONNAV: if (slider.vars.directionNav) { methods.directionNav.update(); } if (target === slider.last) { // API: end() of cycle Callback slider.vars.end(slider); // SLIDESHOW && !INFINITE LOOP: if (!slider.vars.animationLoop) { slider.pause(); } } // SLIDE: if (!fade) { var dimension = (vertical) ? slider.slides.filter(':first').height() : slider.computedW, margin, slideString, calcNext; // INFINITE LOOP / REVERSE: if (carousel) { margin = slider.vars.itemMargin; calcNext = ((slider.itemW + margin) * slider.move) * slider.animatingTo; slideString = (calcNext > slider.limit && slider.visible !== 1) ? slider.limit : calcNext; } else if (slider.currentSlide === 0 && target === slider.count - 1 && slider.vars.animationLoop && slider.direction !== "next") { slideString = (reverse) ? (slider.count + slider.cloneOffset) * dimension : 0; } else if (slider.currentSlide === slider.last && target === 0 && slider.vars.animationLoop && slider.direction !== "prev") { slideString = (reverse) ? 0 : (slider.count + 1) * dimension; } else { slideString = (reverse) ? ((slider.count - 1) - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension; } slider.setProps(slideString, "", slider.vars.animationSpeed); if (slider.transitions) { if (!slider.vars.animationLoop || !slider.atEnd) { slider.animating = false; slider.currentSlide = slider.animatingTo; } // Unbind previous transitionEnd events and re-bind new transitionEnd event slider.container.off("webkitTransitionEnd transitionend"); slider.container.on("webkitTransitionEnd transitionend", function() { clearTimeout(slider.ensureAnimationEnd); slider.wrapup(dimension); }); // Insurance for the ever-so-fickle transitionEnd event clearTimeout(slider.ensureAnimationEnd); slider.ensureAnimationEnd = setTimeout(function() { slider.wrapup(dimension); }, slider.vars.animationSpeed + 100); } else { slider.container.animate(slider.args, slider.vars.animationSpeed, slider.vars.easing, function(){ slider.wrapup(dimension); }); } } else { // FADE: if (!touch) { slider.slides.eq(slider.currentSlide).css({"zIndex": 1}).animate({"opacity": 0}, slider.vars.animationSpeed, slider.vars.easing); slider.slides.eq(target).css({"zIndex": 2}).animate({"opacity": 1}, slider.vars.animationSpeed, slider.vars.easing, slider.wrapup); } else { slider.slides.eq(slider.currentSlide).css({ "opacity": 0, "zIndex": 1 }); slider.slides.eq(target).css({ "opacity": 1, "zIndex": 2 }); slider.wrapup(dimension); } } // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(slider.vars.animationSpeed); } } }; slider.wrapup = function(dimension) { // SLIDE: if (!fade && !carousel) { if (slider.currentSlide === 0 && slider.animatingTo === slider.last && slider.vars.animationLoop) { slider.setProps(dimension, "jumpEnd"); } else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && slider.vars.animationLoop) { slider.setProps(dimension, "jumpStart"); } } slider.animating = false; slider.currentSlide = slider.animatingTo; // API: after() animation Callback slider.vars.after(slider); }; // SLIDESHOW: slider.animateSlides = function() { if (!slider.animating && focused ) { slider.flexAnimate(slider.getTarget("next")); } }; // SLIDESHOW: slider.pause = function() { clearInterval(slider.animatedSlides); slider.animatedSlides = null; slider.playing = false; // PAUSEPLAY: if (slider.vars.pausePlay) { methods.pausePlay.update("play"); } // SYNC: if (slider.syncExists) { methods.sync("pause"); } }; // SLIDESHOW: slider.play = function() { if (slider.playing) { clearInterval(slider.animatedSlides); } slider.animatedSlides = slider.animatedSlides || setInterval(slider.animateSlides, slider.vars.slideshowSpeed); slider.started = slider.playing = true; // PAUSEPLAY: if (slider.vars.pausePlay) { methods.pausePlay.update("pause"); } // SYNC: if (slider.syncExists) { methods.sync("play"); } }; // STOP: slider.stop = function () { slider.pause(); slider.stopped = true; }; slider.canAdvance = function(target, fromNav) { // ASNAV: var last = (asNav) ? slider.pagingCount - 1 : slider.last; return (fromNav) ? true : (asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev") ? true : (asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next") ? false : (target === slider.currentSlide && !asNav) ? false : (slider.vars.animationLoop) ? true : (slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next") ? false : (slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next") ? false : true; }; slider.getTarget = function(dir) { slider.direction = dir; if (dir === "next") { return (slider.currentSlide === slider.last) ? 0 : slider.currentSlide + 1; } else { return (slider.currentSlide === 0) ? slider.last : slider.currentSlide - 1; } }; // SLIDE: slider.setProps = function(pos, special, dur) { var target = (function() { var posCheck = (pos) ? pos : ((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo, posCalc = (function() { if (carousel) { return (special === "setTouch") ? pos : (reverse && slider.animatingTo === slider.last) ? 0 : (reverse) ? slider.limit - (((slider.itemW + slider.vars.itemMargin) * slider.move) * slider.animatingTo) : (slider.animatingTo === slider.last) ? slider.limit : posCheck; } else { switch (special) { case "setTotal": return (reverse) ? ((slider.count - 1) - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos; case "setTouch": return (reverse) ? pos : pos; case "jumpEnd": return (reverse) ? pos : slider.count * pos; case "jumpStart": return (reverse) ? slider.count * pos : pos; default: return pos; } } }()); return (posCalc * ((slider.vars.rtl)?1:-1)) + "px"; }()); if (slider.transitions) { target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + (parseInt(target)+'px') + ",0,0)"; dur = (dur !== undefined) ? (dur/1000) + "s" : "0s"; slider.container.css("-" + slider.pfx + "-transition-duration", dur); slider.container.css("transition-duration", dur); } slider.args[slider.prop] = target; if (slider.transitions || dur === undefined) { slider.container.css(slider.args); } slider.container.css('transform',target); }; slider.setup = function(type) { // SLIDE: if (!fade) { var sliderOffset, arr; if (type === "init") { slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({"overflow": "hidden", "position": "relative"}).appendTo(slider).append(slider.container); // INFINITE LOOP: slider.cloneCount = 0; slider.cloneOffset = 0; // REVERSE: if (reverse) { arr = $.makeArray(slider.slides).reverse(); slider.slides = $(arr); slider.container.empty().append(slider.slides); } } // INFINITE LOOP && !CAROUSEL: if (slider.vars.animationLoop && !carousel) { slider.cloneCount = 2; slider.cloneOffset = 1; // clear out old clones if (type !== "init") { slider.container.find('.clone').remove(); } slider.container.append(methods.uniqueID(slider.slides.first().clone().addClass('clone')).attr('aria-hidden', 'true')) .prepend(methods.uniqueID(slider.slides.last().clone().addClass('clone')).attr('aria-hidden', 'true')); } slider.newSlides = $(slider.vars.selector, slider); sliderOffset = (reverse) ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset; // VERTICAL: if (vertical && !carousel) { slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%"); setTimeout(function(){ slider.newSlides.css({"display": "block"}); slider.doMath(); slider.viewport.height(slider.h); slider.setProps(sliderOffset * slider.h, "init"); }, (type === "init") ? 100 : 0); } else { slider.container.width((slider.count + slider.cloneCount) * 200 + "%"); slider.setProps(sliderOffset * slider.computedW, "init"); setTimeout(function(){ slider.doMath(); if(slider.vars.rtl){ slider.newSlides.css({"width": slider.computedW, "marginRight" : slider.computedM, "float": "right", "display": "block"}); } else{ slider.newSlides.css({"width": slider.computedW, "marginRight" : slider.computedM, "float": "left", "display": "block"}); } // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(); } }, (type === "init") ? 100 : 0); } } else { // FADE: if(slider.vars.rtl){ slider.slides.css({"width": "100%", "float": 'right', "marginLeft": "-100%", "position": "relative"}); } else{ slider.slides.css({"width": "100%", "float": 'left', "marginRight": "-100%", "position": "relative"}); } if (type === "init") { if (!touch) { //slider.slides.eq(slider.currentSlide).fadeIn(slider.vars.animationSpeed, slider.vars.easing); if (slider.vars.fadeFirstSlide == false) { slider.slides.css({ "opacity": 0, "display": "block", "zIndex": 1 }).eq(slider.currentSlide).css({"zIndex": 2}).css({"opacity": 1}); } else { slider.slides.css({ "opacity": 0, "display": "block", "zIndex": 1 }).eq(slider.currentSlide).css({"zIndex": 2}).animate({"opacity": 1},slider.vars.animationSpeed,slider.vars.easing); } } else { slider.slides.css({ "opacity": 0, "display": "block", "webkitTransition": "opacity " + slider.vars.animationSpeed / 1000 + "s ease", "zIndex": 1 }).eq(slider.currentSlide).css({ "opacity": 1, "zIndex": 2}); } } // SMOOTH HEIGHT: if (slider.vars.smoothHeight) { methods.smoothHeight(); } } // !CAROUSEL: // CANDIDATE: active slide if (!carousel) { slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide"); } //FlexSlider: init() Callback slider.vars.init(slider); }; slider.doMath = function() { var slide = slider.slides.first(), slideMargin = slider.vars.itemMargin, minItems = slider.vars.minItems, maxItems = slider.vars.maxItems; slider.w = (slider.viewport===undefined) ? slider.width() : slider.viewport.width(); if (slider.isFirefox) { slider.w = slider.width(); } slider.h = slide.height(); slider.boxPadding = slide.outerWidth() - slide.width(); // CAROUSEL: if (carousel) { slider.itemT = slider.vars.itemWidth + slideMargin; slider.itemM = slideMargin; slider.minW = (minItems) ? minItems * slider.itemT : slider.w; slider.maxW = (maxItems) ? (maxItems * slider.itemT) - slideMargin : slider.w; slider.itemW = (slider.minW > slider.w) ? (slider.w - (slideMargin * (minItems - 1)))/minItems : (slider.maxW < slider.w) ? (slider.w - (slideMargin * (maxItems - 1)))/maxItems : (slider.vars.itemWidth > slider.w) ? slider.w : slider.vars.itemWidth; slider.visible = Math.floor(slider.w/(slider.itemW)); slider.move = (slider.vars.move > 0 && slider.vars.move < slider.visible ) ? slider.vars.move : slider.visible; slider.pagingCount = Math.ceil(((slider.count - slider.visible)/slider.move) + 1); slider.last = slider.pagingCount - 1; slider.limit = (slider.pagingCount === 1) ? 0 : (slider.vars.itemWidth > slider.w) ? (slider.itemW * (slider.count - 1)) + (slideMargin * (slider.count - 1)) : ((slider.itemW + slideMargin) * slider.count) - slider.w - slideMargin; } else { slider.itemW = slider.w; slider.itemM = slideMargin; slider.pagingCount = slider.count; slider.last = slider.count - 1; } slider.computedW = slider.itemW - slider.boxPadding; slider.computedM = slider.itemM; }; slider.update = function(pos, action) { slider.doMath(); // update currentSlide and slider.animatingTo if necessary if (!carousel) { if (pos < slider.currentSlide) { slider.currentSlide += 1; } else if (pos <= slider.currentSlide && pos !== 0) { slider.currentSlide -= 1; } slider.animatingTo = slider.currentSlide; } // update controlNav if (slider.vars.controlNav && !slider.manualControls) { if ((action === "add" && !carousel) || slider.pagingCount > slider.controlNav.length) { methods.controlNav.update("add"); } else if ((action === "remove" && !carousel) || slider.pagingCount < slider.controlNav.length) { if (carousel && slider.currentSlide > slider.last) { slider.currentSlide -= 1; slider.animatingTo -= 1; } methods.controlNav.update("remove", slider.last); } } // update directionNav if (slider.vars.directionNav) { methods.directionNav.update(); } }; slider.addSlide = function(obj, pos) { var $obj = $(obj); slider.count += 1; slider.last = slider.count - 1; // append new slide if (vertical && reverse) { (pos !== undefined) ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj); } else { (pos !== undefined) ? slider.slides.eq(pos).before($obj) : slider.container.append($obj); } // update currentSlide, animatingTo, controlNav, and directionNav slider.update(pos, "add"); // update slider.slides slider.slides = $(slider.vars.selector + ':not(.clone)', slider); // re-setup the slider to accomdate new slide slider.setup(); //FlexSlider: added() Callback slider.vars.added(slider); }; slider.removeSlide = function(obj) { var pos = (isNaN(obj)) ? slider.slides.index($(obj)) : obj; // update count slider.count -= 1; slider.last = slider.count - 1; // remove slide if (isNaN(obj)) { $(obj, slider.slides).remove(); } else { (vertical && reverse) ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove(); } // update currentSlide, animatingTo, controlNav, and directionNav slider.doMath(); slider.update(pos, "remove"); // update slider.slides slider.slides = $(slider.vars.selector + ':not(.clone)', slider); // re-setup the slider to accomdate new slide slider.setup(); // FlexSlider: removed() Callback slider.vars.removed(slider); }; //FlexSlider: Initialize methods.init(); }; // Ensure the slider isn't focussed if the window loses focus. $( window ).on( 'blur', function ( e ) { focused = false; }).on( 'focus', function ( e ) { focused = true; }); //FlexSlider: Default Settings $.flexslider.defaults = { namespace: "flex-", //{NEW} String: Prefix string attached to the class of every element generated by the plugin selector: ".slides > li", //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril animation: "fade", //String: Select your animation type, "fade" or "slide" easing: "swing", //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported! direction: "horizontal", //String: Select the sliding direction, "horizontal" or "vertical" reverse: false, //{NEW} Boolean: Reverse the animation direction animationLoop: true, //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end smoothHeight: false, //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode startAt: 0, //Integer: The slide that the slider should start on. Array notation (0 = first slide) slideshow: true, //Boolean: Animate slider automatically slideshowSpeed: 7000, //Integer: Set the speed of the slideshow cycling, in milliseconds animationSpeed: 600, //Integer: Set the speed of animations, in milliseconds initDelay: 0, //{NEW} Integer: Set an initialization delay, in milliseconds randomize: false, //Boolean: Randomize slide order fadeFirstSlide: true, //Boolean: Fade in the first slide when animation type is "fade" thumbCaptions: false, //Boolean: Whether or not to put captions on thumbnails when using the "thumbnails" controlNav. // Usability features pauseOnAction: true, //Boolean: Pause the slideshow when interacting with control elements, highly recommended. pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering pauseInvisible: true, //{NEW} Boolean: Pause the slideshow when tab is invisible, resume when visible. Provides better UX, lower CPU usage. useCSS: true, //{NEW} Boolean: Slider will use CSS3 transitions if available touch: true, //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices video: false, //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches // Primary Controls controlNav: true, //Boolean: Create navigation for paging control of each slide? Note: Leave true for manualControls usage directionNav: true, //Boolean: Create navigation for previous/next navigation? (true/false) prevText: "Previous", //String: Set the text for the "previous" directionNav item nextText: "Next", //String: Set the text for the "next" directionNav item // Secondary Navigation keyboard: true, //Boolean: Allow slider navigating via keyboard left/right keys multipleKeyboard: false, //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present. mousewheel: false, //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel pausePlay: false, //Boolean: Create pause/play dynamic element pauseText: "Pause", //String: Set the text for the "pause" pausePlay item playText: "Play", //String: Set the text for the "play" pausePlay item // Special properties controlsContainer: "", //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found. manualControls: "", //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs. customDirectionNav: "", //{NEW} jQuery Object/Selector: Custom prev / next button. Must be two jQuery elements. In order to make the events work they have to have the classes "prev" and "next" (plus namespace) sync: "", //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care. asNavFor: "", //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider // Carousel Options itemWidth: 0, //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding. itemMargin: 0, //{NEW} Integer: Margin between carousel items. minItems: 1, //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this. maxItems: 0, //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit. move: 0, //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items. allowOneSlide: true, //{NEW} Boolean: Whether or not to allow a slider comprised of a single slide // Browser Specific isFirefox: false, // {NEW} Boolean: Set to true when Firefox is the browser used. // Callback API start: function(){}, //Callback: function(slider) - Fires when the slider loads the first slide before: function(){}, //Callback: function(slider) - Fires asynchronously with each slider animation after: function(){}, //Callback: function(slider) - Fires after each slider animation completes end: function(){}, //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous) added: function(){}, //{NEW} Callback: function(slider) - Fires after a slide is added removed: function(){}, //{NEW} Callback: function(slider) - Fires after a slide is removed init: function() {}, //{NEW} Callback: function(slider) - Fires after the slider is initially setup rtl: false //{NEW} Boolean: Whether or not to enable RTL mode }; //FlexSlider: Plugin Function $.fn.flexslider = function(options) { if (options === undefined) { options = {}; } if (typeof options === "object") { return this.each(function() { var $this = $(this), selector = (options.selector) ? options.selector : ".slides > li", $slides = $this.find(selector); if ( ( $slides.length === 1 && options.allowOneSlide === false ) || $slides.length === 0 ) { $slides.fadeIn(400); if (options.start) { options.start($this); } } else if ($this.data('flexslider') === undefined) { new $.flexslider(this, options); } }); } else { // Helper strings to quickly perform functions on the slider var $slider = $(this).data('flexslider'); switch (options) { case "play": $slider.play(); break; case "pause": $slider.pause(); break; case "stop": $slider.stop(); break; case "next": $slider.flexAnimate($slider.getTarget("next"), true); break; case "prev": case "previous": $slider.flexAnimate($slider.getTarget("prev"), true); break; default: if (typeof options === "number") { $slider.flexAnimate(options, true); } } } }; })(jQuery);
import tkinter as tk from tkinter import ttk import opclabs_quickopc #import .NET namespaces. from OpcLabs.EasyOpc.UA import * from OpcLabs.EasyOpc.UA.OperationModel import * class MyGUI: def __init__(self): # Creating the window self.root = tk.Tk() # setting the geometry of the window self.root.geometry("800x600") # set the window title self.root.title("OPC UA Client") #frame for entering the endpoint url of the opc server self.endpointframe= tk.Frame(self.root) self.endpointframe.columnconfigure(0, weight=1) self.endpointframe.columnconfigure(1, weight=1) self.endpointLabel = tk.Label(self.endpointframe, text='EndPoint:', font=('Arial', 14)) self.endpointLabel.grid(row=0, column=0) self.endpointEntry = tk.Entry(self.endpointframe, width=60) self.endpointEntry.grid(row=0, column=1, sticky='w') self.endpointframe.pack(fill='x', pady=20) self.separator = ttk.Separator(self.root, orient='horizontal') self.separator.pack(fill='x') #frame for entering the nodeID to be read self.nodeFrame = tk.Frame(self.root) self.nodeFrame.columnconfigure(0, weight=1) self.nodeFrame.columnconfigure(1, weight=1) self.nodeFrame.columnconfigure(2, weight=1) self.nodeLabel = tk.Label(self.nodeFrame, text='NodeID:', font=('Arial', 14)) self.nodeLabel.grid(row=0, column=0) self.nodeSpacetxt = tk.Label(self.nodeFrame, text='Namespace:', font=('Arial', 12)) self.nodeSpacetxt.grid(row=0, column=1) self.nodeSpaceEntry = tk.Entry(self.nodeFrame, width=20) self.nodeSpaceEntry.grid(row=0, column=2, sticky='w') self.nodeNametxt = tk.Label(self.nodeFrame, text='Name:', font=('Arial', 12)) self.nodeNametxt.grid(row=1, column=1, pady=10) self.nodeNameEntry = tk.Entry(self.nodeFrame, width=20) self.nodeNameEntry.grid(row=1, column=2, pady=10, sticky='w') self.nodeTypetxt = tk.Label(self.nodeFrame, text='Type:', font=('Arial', 12)) self.nodeTypetxt.grid(row=2, column=1, pady=10) self.nodeTypeEntry = tk.Entry(self.nodeFrame, width=20) self.nodeTypeEntry.grid(row=2, column=2, pady=10, sticky='w') self.nodeFrame.pack(fill='x', pady=20) self.separator2 = ttk.Separator(self.root, orient='horizontal') self.separator2.pack(fill='x') #frame for entering the indexrange to be read self.indexFrame = tk.Frame(self.root) self.indexFrame.columnconfigure(0, weight=1) self.indexFrame.columnconfigure(1, weight=1) self.indexFrame.columnconfigure(2, weight=1) self.indexLabel = tk.Label(self.indexFrame, text='Index Range:', font=('Arial', 14)) self.indexLabel.grid(row=0, column=0) self.indexFirstTxt = tk.Label(self.indexFrame, text='First index:', font=('Arial', 12)) self.indexFirstTxt.grid(row=0, column=1) self.indexFirstEntry = tk.Entry(self.indexFrame, width=20) self.indexFirstEntry.grid(row=0, column=2, sticky='w') self.indexLastTxt = tk.Label(self.indexFrame, text='Last index:', font=('Arial', 12)) self.indexLastTxt.grid(row=1, column=1, pady=10) self.indexLastEntry = tk.Entry(self.indexFrame, width=20) self.indexLastEntry.grid(row=1, column=2, pady=10, sticky='w') self.indexFrame.pack(fill='x', pady=20) self.separator3 = ttk.Separator(self.root, orient='horizontal') self.separator3.pack(fill='x') # output frame self.outputFrame = tk.Frame(self.root) self.outputLabel = tk.Label(self.outputFrame, text='Results:', font=('Arial',14)) self.outputLabel.grid(row=0, sticky='w', padx=80) self.outputButton = tk.Button(self.outputFrame, text='Get Results', font=('Arial', 12), width=20, command=self.opcfunc) self.outputButton.grid(row=0, padx=10) self.outputText = tk.Text(self.outputFrame, font=('Arial', 12)) self.outputText.grid(row=1, padx=20, pady=10) self.outputFrame.pack(fill='x', pady=20) self.root.mainloop() def opcfunc (self): firstindex = int(self.indexFirstEntry.get()) lastindex = int(self.indexLastEntry.get()) if self.endpointEntry.get()=='': endpointDescriptor = UAEndpointDescriptor('opc.tcp://opcua.demo-this.com:51210/UA/SampleServer') # or 'http://opcua.demo-this.com:51211/UA/SampleServer' (currently not supported) # or 'https://opcua.demo-this.com:51211/UA/SampleServer/' else: endpointDescriptor = UAEndpointDescriptor(self.endpointEntry.get()) # Instantiate the client object. client = EasyUAClient() # Obtain the value, indicating that just the elements 2 to 4 should be returned try: arrayValue = IEasyUAClientExtension.ReadValue(client, endpointDescriptor, UANodeDescriptor( 'nsu='+ self.nodeNameEntry.get() +' ;ns='+ self.nodeSpaceEntry.get() + ';i=' + self.nodeTypeEntry.get()), # Data.Static.Array.Int32Value UAIndexRangeList.OneDimension(firstindex, lastindex)) except UAException as uaException: print('*** Failure: ' + uaException.GetBaseException().Message) exit() # Dispaly results. self.outputText.delete("1.0", tk.END) for i, elementValue in enumerate(arrayValue): print('arrayValue[', i, ']: ', elementValue, sep='') self.outputText.insert(tk.END, ('arrayValue[' + str(i) + ']: '+ str(elementValue) +'\n')) print() print('Finished.') self.outputText.insert(tk.END, "Finished.") MyGUI()
package consensus import ( "context" "log" "github.com/alveycoin/alveychain/blockchain" "github.com/alveycoin/alveychain/chain" "github.com/alveycoin/alveychain/helper/progress" "github.com/alveycoin/alveychain/network" "github.com/alveycoin/alveychain/secrets" "github.com/alveycoin/alveychain/state" "github.com/alveycoin/alveychain/txpool" "github.com/alveycoin/alveychain/types" "github.com/hashicorp/go-hclog" "google.golang.org/grpc" ) // Consensus is the public interface for consensus mechanism // Each consensus mechanism must implement this interface in order to be valid type Consensus interface { // VerifyHeader verifies the header is correct VerifyHeader(header *types.Header) error // ProcessHeaders updates the snapshot based on the verified headers ProcessHeaders(headers []*types.Header) error // GetBlockCreator retrieves the block creator (or signer) given the block header GetBlockCreator(header *types.Header) (types.Address, error) // PreCommitState a hook to be called before finalizing state transition on inserting block PreCommitState(header *types.Header, txn *state.Transition) error // GetSyncProgression retrieves the current sync progression, if any GetSyncProgression() *progress.Progression // Initialize initializes the consensus (e.g. setup data) Initialize() error // Start starts the consensus and servers Start() error // Close closes the connection Close() error } // Config is the configuration for the consensus type Config struct { // Logger to be used by the consensus Logger *log.Logger // Params are the params of the chain and the consensus Params *chain.Params // Config defines specific configuration parameters for the consensus Config map[string]interface{} // Path is the directory path for the consensus protocol tos tore information Path string } type Params struct { Context context.Context Config *Config TxPool *txpool.TxPool Network *network.Server Blockchain *blockchain.Blockchain Executor *state.Executor Grpc *grpc.Server Logger hclog.Logger Metrics *Metrics SecretsManager secrets.SecretsManager BlockTime uint64 } // Factory is the factory function to create a discovery consensus type Factory func(*Params) (Consensus, error)
// Copyright 2019-2020 CERN and copyright holders of ALICE O2. // See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. // All rights not expressly granted are reserved. // // This software is distributed under the terms of the GNU General Public // License v3 (GPL Version 3), copied verbatim in the file "COPYING". // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. /// @file RawPageTestData.h /// @author Matthias Richter /// @since 2021-06-21 /// @brief Raw page test data generator #ifndef FRAMEWORK_UTILS_RAWPAGETESTDATA_H #define FRAMEWORK_UTILS_RAWPAGETESTDATA_H #include "Framework/InputRecord.h" #include "Framework/InputSpan.h" #include "Headers/RAWDataHeader.h" #include "Headers/DataHeader.h" #include <vector> #include <memory> using DataHeader = o2::header::DataHeader; using Stack = o2::header::Stack; using RAWDataHeaderV6 = o2::header::RAWDataHeaderV6; namespace o2::framework::test { using RAWDataHeader = RAWDataHeaderV6; static const size_t PAGESIZE = 8192; /// @class DataSet /// @brief Simple helper struct to keep the InputRecord and ownership of messages /// together with some test data. struct DataSet { // not nice with the double vector but for quick unit test ok using Messages = std::vector<std::vector<std::unique_ptr<std::vector<char>>>>; DataSet(std::vector<InputRoute>&& s, Messages&& m, std::vector<int>&& v, ServiceRegistryRef registry) : schema{std::move(s)}, messages{std::move(m)}, span{[this](size_t i, size_t part) { auto header = static_cast<char const*>(this->messages[i].at(2 * part)->data()); auto payload = static_cast<char const*>(this->messages[i].at(2 * part + 1)->data()); return DataRef{nullptr, header, payload}; }, [this](size_t i) { return i < this->messages.size() ? messages[i].size() / 2 : 0; }, this->messages.size()}, record{schema, span, registry}, values{std::move(v)} { } std::vector<InputRoute> schema; Messages messages; InputSpan span; InputRecord record; std::vector<int> values; }; using AmendRawDataHeader = std::function<void(RAWDataHeader&)>; DataSet createData(std::vector<InputSpec> const& inputspecs, std::vector<DataHeader> const& dataheaders, AmendRawDataHeader amendRdh = nullptr); } // namespace o2::framework #endif // FRAMEWORK_UTILS_RAWPAGETESTDATA_H
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ContactoComponent } from './contacto/contacto.component'; import { InicioComponent } from './inicio/inicio.component'; import { NosotrosComponent } from './nosotros/nosotros.component'; const routes: Routes = [ { path:'',children:[ {path:'inicio',component:InicioComponent}, {path:'nosotros',component:NosotrosComponent}, {path:'contacto',component:ContactoComponent}, {path:'',redirectTo:'inicio',pathMatch:'full'}, {path:'**',redirectTo:'inicio',pathMatch:'full'} ] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:instagram_clone/resources/firestore_methods.dart'; import 'package:instagram_clone/utils/colors.dart'; import 'package:instagram_clone/widgets/comments.dart'; import '../widgets/comment_card.dart'; class CommentScreen extends StatefulWidget { final snap; const CommentScreen({super.key, required this.snap}); @override State<CommentScreen> createState() => _CommentScreenState(); } class _CommentScreenState extends State<CommentScreen> { final TextEditingController _commentController = TextEditingController(); String photoUrl = ''; String username = ''; final user = FirebaseAuth.instance.currentUser; @override void dispose() { // TODO: implement dispose super.dispose(); _commentController.dispose(); } @override Widget build(BuildContext context) { final photo = FirebaseFirestore.instance .collection('users') .doc(user!.uid) .get() .then((value) { setState(() { photoUrl = value['photoUrl']; username = value['username']; }); }); return photoUrl == '' || username == '' ? Center( child: CircularProgressIndicator(), ) : Scaffold( appBar: AppBar( backgroundColor: mobileBackgroundColor, title: const Text("Comments"), centerTitle: false, ), body: Comments( snap: widget.snap, ), bottomNavigationBar: SafeArea( child: Container( height: kToolbarHeight, margin: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom, ), padding: const EdgeInsets.only(left: 16, right: 8), child: Row( children: [ CircleAvatar( backgroundImage: NetworkImage(photoUrl), radius: 18, ), Expanded( child: Padding( padding: const EdgeInsets.only( left: 16, right: 8.0, ), child: TextField( controller: _commentController, decoration: InputDecoration( hintText: 'Comment as $username', border: InputBorder.none, ), ), ), ), InkWell( onTap: (() async { await FirestoreMethods().postComment( widget.snap['postId'], _commentController.text, user!.uid, username, photoUrl, ); setState(() { _commentController.text = ""; }); }), child: Container( padding: EdgeInsets.symmetric(vertical: 8, horizontal: 8), child: const Text( 'Post', style: TextStyle( color: blueColor, ), ), ), ), ], ), ), ), ); } }
import { Box, Button, Flex, FormControl, FormLabel, Heading, Input, } from "@chakra-ui/react"; import axios from "axios"; import Head from "next/head"; import { useRouter } from "next/router"; import React, { useState } from "react"; import { useMutation, useQueryClient } from "react-query"; import { dataURItoBlob, imageUrlToDataURI } from "../utils/Util"; const NewAnimation = () => { const [name, setName] = useState(""); const [frameRate, setFrameRate] = useState(8); const queryClient = useQueryClient(); const mutation = useMutation( async () => { let dataUrl = await imageUrlToDataURI( "https://animation-js-server.onrender.com/frame.jpg" ); var blobObject = dataURItoBlob(dataUrl); var fdataobj = new FormData(); fdataobj.append("frame", blobObject); const rsp = await axios.post( "https://animation-js-server.onrender.com/frames", fdataobj, {} ); let dataUrl3 = await imageUrlToDataURI( "https://animation-js-server.onrender.com/frame.png" ); var blobObject3 = dataURItoBlob(dataUrl3); var fdataobj3 = new FormData(); fdataobj3.append("frame", blobObject3); const rsp2 = await axios.post( "https://animation-js-server.onrender.com/frames", fdataobj3, {} ); console.log({ rsp }); let dataUrl2 = await imageUrlToDataURI( "https://animation-js-server.onrender.com/frame_transparent.png" ); var blobObject2 = dataURItoBlob(dataUrl2); var fdataobj2 = new FormData(); fdataobj2.append("frame", blobObject2); const rsp3 = await axios.post( "https://animation-js-server.onrender.com/frames", fdataobj2, {} ); const result = await axios.post( "https://animation-js-server.onrender.com/animation/", { name, frameRate, frames: [ { currentFrameImageWithoutBackground: `https://animation-js-server.onrender.com/${rsp3.data.filename}`, currentFrameImage: `https://animation-js-server.onrender.com/${rsp.data.filename}`, previousFrameImage: null, currentFrameImageTransparent: `https://animation-js-server.onrender.com/${rsp2.data.filename}`, }, ], } ); console.log(result.data); router.push("/"); }, { onSuccess: () => { // Invalidate and refetch queryClient.invalidateQueries("animations"); }, } ); const router = useRouter(); const createAnimation = () => { mutation.mutate(); }; return ( <> <Flex alignItems="center" justifyContent="center" p="3" pb={0} bg="gray.800" h="100vh" color="gray.200" > <Head> <title>Shadan animation</title> <meta name="description" content="Animation app created using next js" /> <link rel="icon" href="/favicon.ico" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" /> </Head> <Box bg="gray.700" p="6" rounded={"lg"} style={{ width: "min(95%, 600px)" }} > <Heading w="full" fontSize={"3xl"} mb="2"> New animation </Heading> <FormControl variant="floating"> <Input placeholder=" " mt="4" value={name} onChange={(event) => setName(event.target.value)} /> <FormLabel>Animation Name</FormLabel> </FormControl> <FormControl variant="floating"> <Input placeholder=" " mt="4" value={frameRate} onChange={(event) => setFrameRate(event.target.value)} /> <FormLabel>Frame Rate</FormLabel> </FormControl> <Button w="full" onClick={createAnimation} colorScheme="green" mt={4}> Create </Button> </Box> </Flex> <div class="animeTWD"> <div class="animeBlurTWD"></div> </div> </> ); }; export default NewAnimation;
<?php /** * @file * Module file for Cesium. */ define('CESIUM_BLOCK_INPUT_APPLICATION_TYPE', 'cesium_block_application_type'); define('CESIUM_BLOCK_INPUT_BING_MAPS_API_KEY', 'cesium_block_bing_maps_api_key'); define('CESIUM_BLOCK_INPUT_CONTAINER_ID', 'cesium_block_container_id'); define('CESIUM_BLOCK_INPUT_JS_VARIABLE', 'cesium_block_js_variable'); define('CESIUM_BLOCK_INPUT_LIBRARY_VARIANT', 'cesium_block_library_variant'); /** * Implements hook_block_info(). */ function cesium_block_block_info() { $blocks['cesium_block'] = array( 'info' => t('Cesium: Cesium Block'), 'cache' => DRUPAL_CACHE_PER_ROLE, 'status' => TRUE, 'region' => 'content', 'visibility' => BLOCK_VISIBILITY_LISTED ); return $blocks; } /** * Implements hook_block_configure(). * @param string $delta * @return array */ function cesium_block_block_configure($delta = '') { $form = []; $form[CESIUM_BLOCK_INPUT_APPLICATION_TYPE] = [ '#type' => 'radios', '#title' => t('Application Type'), '#options' => ['Viewer' => t('Viewer'), 'CesiumWidget' => t('Widget')], '#default_value' => variable_get(CESIUM_BLOCK_INPUT_APPLICATION_TYPE, t('CesiumViewer')), ]; $form[CESIUM_BLOCK_INPUT_BING_MAPS_API_KEY] = [ '#type' => 'textfield', '#title' => t('Bing Maps API Key'), '#size' => 60, '#description' => t('API Key provided by Microsoft for access to Bing Maps'), '#default_value' => variable_get(CESIUM_BLOCK_INPUT_BING_MAPS_API_KEY, '') ]; $form[CESIUM_BLOCK_INPUT_CONTAINER_ID] = [ '#type' => 'textfield', '#title' => t('HTML Container ID'), '#size' => 60, '#description' => t('The html id that will be used for the container div for Cesium'), '#default_value' => variable_get(CESIUM_BLOCK_INPUT_CONTAINER_ID, t('cesiumContainer')) ]; $form[CESIUM_BLOCK_INPUT_JS_VARIABLE] = [ '#type' => 'textfield', '#title' => t('Javascript Variable'), '#size' => 60, '#description' => t('variable to save the cesium object as. example: var window.cesiumViewer = new Cesium...'), '#default_value' => variable_get(CESIUM_BLOCK_INPUT_JS_VARIABLE, t('viewer')) ]; $form[CESIUM_BLOCK_INPUT_LIBRARY_VARIANT] = [ '#type' => 'radios', '#title' => t('Library'), '#options' => ['minified' => t('Production'), 'unminified' => t('Development')], '#default_value' => variable_get(CESIUM_BLOCK_INPUT_LIBRARY_VARIANT, CESIUM_LIBRARY_VARIANT_DEFAULT), ]; // $form['show_base_layer_picker'] = [ // '#type' => 'checkbox', // '#title' => t('Base Layer Picker'), // '#size' => 60, // '#description' => t('show or hide Base Layer Picker'), // '#default_value' => variable_get('show_base_layer_picker', true) // ]; return $form; } /** * Implements hook_block_save(). * @param string $delta * @param array $edit */ function cesium_block_block_save($delta = '', $edit = []) { variable_set(CESIUM_BLOCK_INPUT_APPLICATION_TYPE, $edit[CESIUM_BLOCK_INPUT_APPLICATION_TYPE]); variable_set(CESIUM_BLOCK_INPUT_BING_MAPS_API_KEY, $edit[CESIUM_BLOCK_INPUT_BING_MAPS_API_KEY]); variable_set(CESIUM_BLOCK_INPUT_CONTAINER_ID, $edit[CESIUM_BLOCK_INPUT_CONTAINER_ID]); variable_set(CESIUM_BLOCK_INPUT_JS_VARIABLE, $edit[CESIUM_BLOCK_INPUT_JS_VARIABLE]); variable_set(CESIUM_BLOCK_INPUT_LIBRARY_VARIANT, $edit[CESIUM_BLOCK_INPUT_LIBRARY_VARIANT]); // variable_set('show_base_layer_picker', $edit['show_base_layer_picker']); } /** * Implements hook_block_view(). * @param string $delta * @return array */ function cesium_block_block_view($delta) { $variant = variable_get(CESIUM_BLOCK_INPUT_LIBRARY_VARIANT); $library = libraries_load(CESIUM_LIBRARY_NAME, $variant); if ($library && !empty($library['loaded'])) { $jsVariable = variable_get(CESIUM_BLOCK_INPUT_JS_VARIABLE); $containerId = variable_get(CESIUM_BLOCK_INPUT_CONTAINER_ID); $applicationType = variable_get(CESIUM_BLOCK_INPUT_APPLICATION_TYPE); $content = <<<BLOCK_CONTENT <div id="{$containerId}" class="cesium_block_container"></div> <script type="text/javascript"> var {$jsVariable}; (function() { {$jsVariable} = new Cesium.{$applicationType}('{$containerId}'); }).call(); </script> BLOCK_CONTENT; } else { $content = '<div class="alert"><p>' . t('Unable to Load Cesium Javascript Library') . '</p></div>'; } return ['content' => $content]; }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:p="http://primefaces.org/ui"> <link href="../css/main.css" rel="stylesheet" type="text/css"/> <link href="../css/weather-icons.css" rel="stylesheet" type="text/css"/> <h:body> <composite:interface/> <composite:implementation> <h:form id="currentTemperatureForm"> <span class="icon dimmed wi #{weatherBean.forecast.currently.iconMapping}"/> <h:outputText id="currentForeCast" value="#{weatherBean.forecast.currently.temperature}"> <f:convertNumber pattern="#0.0" locale="en-US"/> </h:outputText> <h:outputText id="someStrangeCharacter" value="°"/><br/> <!--<div class="xsmall dimmed">--> <!--<h:outputText id="currentySummary" value="#{weatherBean.forecast.currently.summary}"/>--> <!--</div>--> <p:poll interval="300" update="currentTemperatureForm"/> </h:form> <h:form id="dailyForecastForm"> <table id="dailyForecastTable" class="xsmall forecast-table"> <ui:repeat id="repeatDailyForecast" value="#{weatherBean.forecast.daily.data}" var="entry"> <tr> <td> <div class="day"> <h:outputText value="#{entry.date}"> <f:convertDateTime locale="DE" timeZone="Europe/Berlin" pattern="EEEE dd.MM"/> </h:outputText> </div> </td> <td> <span class="icon-small wi #{entry.iconMapping}"/> </td> <td> <div class="temp-max"> <h:outputText value="#{entry.temperatureMax}"> <f:convertNumber pattern="#0.0" locale="en-US"/> </h:outputText> <h:outputText value="°"/> </div> </td> <td> <div class="temp-min"> <h:outputText value="#{entry.temperatureMin}"> <f:convertNumber pattern="#0.0" locale="en-US"/> </h:outputText> <h:outputText value="°"/> </div> </td> </tr> </ui:repeat> </table> <p:poll interval="600" listener="#{weatherBean.reloadForecast()}" update="dailyForecastForm"/> </h:form> </composite:implementation> </h:body> </html>
import React, { useState, useEffect } from "react"; import { toast } from "react-toastify"; import { Base_url } from "../../utils/Base_url"; import axios from "axios"; import Input from "../../components/Input"; import Button from "../../components/Button"; import Modal from "../../components/modal"; import { MdClose } from "react-icons/md"; const AddSupporter = ({ isModalOpen, setIsModalOpen, closeModal, setUsers, }) => { const [selectedImage, setSelectedImage] = useState(null); const [selectedImages,setSelectedImages]= useState([]) console.log(selectedImage); const handleFileChange = (e) => { const file = e.target.files[0]; setSelectedImages(file) if (file && file.type.startsWith("image/")) { const reader = new FileReader(); reader.onload = () => { setSelectedImage(reader.result); }; reader.readAsDataURL(file); } }; const bannerSubmit = async (values) => { if (!selectedImage) { toast.error("Please choose your profile!"); } else if (values.name.value.length === 0) { toast.error("Please Enter name!"); } else if (values.phoneNumber.value.length === 0) { toast.error("Please Enter phone Number!"); } else if (values.age.value.length === 0) { toast.error("Please Enter age!"); } else if (values.chatPrice.value.length === 0) { toast.error("Please Enter chat Price!"); } else if (values.audioCallPrice.value.length === 0) { toast.error("Please Enter audio call price!"); } else if (values.videoCallPrice.value.length === 0) { toast.error("Please Enter video call price!"); } else { let profilephoto = " "; try { let param = new FormData(); param.append("avatars",selectedImages); profilephoto = await axios.post(`${Base_url}/UploadImage`, param); console.log(profilephoto, "=====profile photo==="); // console.log(profilephoto?.data?.response,'=====profile photo2==='); } catch (error) { console.log(error); } const params = { name: values.name.value, nickName:values.name.value, phoneNumber: values.phoneNumber.value, usertype:"supporter", gender: values.gender.value, age: values.age.value, audioCall: values.audioCall.value, videoCall: values.videoCall.value, chat: values.chat.value, chatPrice: values.chatPrice.value, audioCallPrice: values.audioCallPrice.value, videoCallPrice: values.videoCallPrice.value, profileImage: profilephoto?.data[0].url, }; await axios .post(`${Base_url}/register`, params) .then((res) => { console.log(res); if (res.data.success === true) { toast.success("Supporter Register Successfully!"); setIsModalOpen(false); axios .get(`${Base_url}/getAllUsers`) .then((res) => { console.log(res.data); setUsers(res.data.data); }) .catch((error) => { console.log(error); }); } }) .catch((error) => { toast.error(error); }); } }; return ( <div> <Modal isOpen={isModalOpen} onClose={closeModal}> {/* Modal Content */} <div className=""> <div className=" p-3 flex justify-between items-center"> <div></div> <h1 className="capitalize h4 font-semibold">Add Supporter</h1> <MdClose onClick={() => setIsModalOpen(false)} size={25} /> </div> <hr /> <div className=" p-5"> <div className=" text-center my-2"> {selectedImage ? ( <img src={selectedImage} className="mx-auto w-28 h-28 rounded-full" alt="" /> ) : ( <> <img src={require("../../assets/image/profile.jpg")} className="mx-auto w-28 h-28 rounded-full" alt="" /> </> )} <div className=" my-5"> <label htmlFor="fileInput" className="px-12 py-2 bg-white font-semibold text-primary border border-gray-200 rounded-lg cursor-pointer" > Browse File </label> <input accept="image/*" onChange={handleFileChange} name="profileImage" type="file" id="fileInput" className="hidden" /> </div> </div> <form onSubmit={(e) => { e.preventDefault(); bannerSubmit(e.target); }} > <div className=" flex gap-5 flex-wrap"> <div className=" md:w-[48%] w-[100%]"> <Input label={"Username"} placeholder={""} name={"name"} className={"border w-full py-3"} /> </div> <div className=" md:w-[48%] w-[100%]"> <label for="Gender" className=' block mb-2 text-sm font-medium text-gray-900'> Gender</label> <select name={"gender"} id="gender" className="outline-none bg-lightGray border w-full py-3 p-2.5 text-primary text-lg placeholder:text-primary rounded-md"> <option>select option...</option> <option value={'male'}>Male</option> <option value={'female'}>Female</option> </select> </div> <div className=" md:w-[48%] w-[100%]"> <Input label={"Age"} placeholder={""} name={"age"} className={"border w-full py-3"} /> </div> <div className=" md:w-[48%] w-[100%]"> <label for="audioCall" className=' block mb-2 text-sm font-medium text-gray-900'>Audio Call</label> <select name={"audioCall"} className="outline-none bg-lightGray border w-full py-3 p-2.5 text-primary text-lg placeholder:text-primary rounded-md"> <option >select option...</option> <option value={'available'}>Available</option> <option value={'notavailable'}>Not available</option> </select> </div> <div className=" md:w-[48%] w-[100%]"> <label for="videoCall" className=' block mb-2 text-sm font-medium text-gray-900'>Video Call</label> <select name={"videoCall"} className="outline-none bg-lightGray border w-full py-3 p-2.5 text-primary text-lg placeholder:text-primary rounded-md"> <option>select option...</option> <option value={'available'}>Available</option> <option value={'notavailable'}>Not available</option> </select> </div> <div className=" md:w-[48%] w-[100%]"> <label for="chat" className=' block mb-2 text-sm font-medium text-gray-900'>Chat</label> <select name={"chat"} className="outline-none bg-lightGray border w-full py-3 p-2.5 text-primary text-lg placeholder:text-primary rounded-md"> <option>select option...</option> <option value={'available'}>Available</option> <option value={'notavailable'}>Not available</option> </select> </div> <div className=" md:w-[48%] w-[100%]"> <Input label={"Phone Number"} placeholder={""} name={"phoneNumber"} className={"border w-full py-3"} /> </div> <div className=" md:w-[48%] w-[100%]"> <Input label={"Chat price"} placeholder={""} name={"chatPrice"} className={"border w-full py-3"} /> </div> <div className=" md:w-[48%] w-[100%]"> <Input label={"Audio call price"} name={"audioCallPrice"} placeholder={""} className={"border w-full py-3"} /> </div> <div className=" md:w-[48%] w-[100%]"> <Input label={"Video call price"} placeholder={""} name={"videoCallPrice"} className={"border w-full py-3"} /> </div> </div> <Button label={"save"} type={"submit"} className={ " bg-[#A47ABF] mt-3 uppercase text-white py-2 w-full" } /> </form> </div> </div> </Modal> </div> ); }; export default AddSupporter;
import { Link, NavLink } from "react-router-dom" export const Navbar = () => { return ( <nav className="navbar navbar-expand-lg bg-body-tertiary rounded-3"> <div className="container-fluid"> <Link className="navbar-brand" to="/">useContext</Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarNav"> <ul className="navbar-nav"> <NavLink to="/" className={({isActive}) => `nav-link ${isActive ? 'active' : ''}`} > Home </NavLink> <NavLink to="/login" className={({isActive}) => `nav-link ${isActive ? 'active' : ''}`} > Login </NavLink> <NavLink to="/about" className={({isActive}) => `nav-link ${isActive ? 'active' : ''}`} > About </NavLink> </ul> </div> </div> </nav> ) }
# -*- coding: utf-8 -*- """ @Time : 2023/6/14 21:21 @Auth : 异世の阿银 @File :test_JavaScript.py @IDE :PyCharm @Motto:ABC(Always Be Coding) """ import re ''' 需求1: 匹配hi 需求2: 加入him,history,high 进行\b边界检测 需求3: 匹配hi jack 加入.*+? 需求4: 匹配三个字符的单词 加入[]{} 需求5: 匹配所有h/H开头的单词,或者a开头的单词.然后后面至少有一个字符的单词 需求6: 匹配字符中号码 加入\d 需求7: 匹配数字和字母 加入 \w 需求8: 匹配号码 加入 ^ $ 开始和结尾 ''' # 功能: 测试正则表达式 def testRegEx(regEx, str): # 参数: regEx 正则字符串 str 源字符串数据 # 1. 将正则字符串在底层编译为一个'正则对象' pattern = re.compile(regEx) # 2. 通过正则对象调用对象的字符串处理行为 result_set = pattern.findall(str) # 3. 查看结果集 for result in result_set: print(result) if __name__ == '__main__': regEx = 'hi' # 边界检测 \b regEx = r'\bhi\b' # 原生字符串 str = 'hi jack how are you doing today? I ahim doing great, How about? hi Rose, Not bad, Thank you, bye! ' \ 'him,history,high' # 调用函数, 查看结果 testRegEx(regEx, str) regEx = 'hi jack' str = 'hi jack how are you doing' testRegEx(regEx, str) regEx = 'hi.jack' str = 'hi爱jack how are you doing' # 点. 含义: 表示除了换行以外的任意单个字符 testRegEx(regEx, str) # 量词 *+? 含义: 前面出现的字符可以出现 * (0个或多个) + (1个或多个) ? (0个或一个) regEx = 'hi.*jack' str = 'hi jack how are you doing' testRegEx(regEx, str) regEx = 'hi.+jack' str = 'hijack how are you doing' testRegEx(regEx, str) regEx = 'hi.?jack' str = 'hijack how are you doing' testRegEx(regEx, str) # 匹配三个字符的单词 # [] 范围 {m,n} 量词 限定前面范围的次数{开始,结束} regEx = r'\b[A-Za-z]{3,}\b' str = 'hi jack how are you doing today? I ahim doing great, How about? hi Rose, Not bad, Thank you, bye! ' \ 'him,history,high' testRegEx(regEx, str) regEx = r'\b[hHa][a-zA-Z]+\b' str = 'hi jack how are you doing today? I ahim doing great, How about? hi Rose, Not bad, Thank you, bye! ' \ 'him,history,high' testRegEx(regEx, str) regEx = '[0-9]+' regEx = r'\d' # [0-9] 可以使用\d替换 str = 'hi jack 666 how are you doing today? 999 I ahim doing great, How about? hi Rose, 888 Not bad, ' \ 'Thank you, bye! ' \ 'him,history,high' testRegEx(regEx, str) # 匹配数字和字母 regEx = r'[0-9A-Za-z_]+' regEx = r'\w+' # [0-9A-Za-z_] 可以使用\w替换 变量命名规则 str = 'hi jack 666how are you doing today? 999I_ahim doing great, How about? hi Rose, 888 Not bad, ' \ 'Thank you, bye! ' \ 'him,history,high' testRegEx(regEx, str) # 匹配号码 # ^ 开头 # $ 结尾 regEx = r'\d{11}' regEx = r'^\d{11}$' # 中间全是数字 str = '13366285946' testRegEx(regEx, str)
/** * This will track all the images and fonts for publishing. */ import.meta.glob(["../images/**", "../fonts/**"]); /** * Main vue bundler. */ import { createApp } from "vue/dist/vue.esm-bundler"; /** * Main root application registry. */ window.app = createApp({ data() { return {}; }, mounted() { this.lazyImages(); this.animateBoxes(); }, methods: { onSubmit() {}, onInvalidSubmit() {}, lazyImages() { var lazyImages = [].slice.call(document.querySelectorAll('img.lazy')); let lazyImageObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { let lazyImage = entry.target; lazyImage.src = lazyImage.dataset.src; lazyImage.classList.remove('lazy'); lazyImageObserver.unobserve(lazyImage); } }); }); lazyImages.forEach(function(lazyImage) { lazyImageObserver.observe(lazyImage); }); }, animateBoxes() { let animateBoxes = document.querySelectorAll('.scroll-trigger'); if (! animateBoxes.length) { return; } animateBoxes.forEach((animateBox) => { let animateBoxObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { animateBox.classList.remove('scroll-trigger--offscreen'); animateBoxObserver.unobserve(animateBox); } }); }); animateBoxObserver.observe(animateBox); }); } }, }); /** * Global plugins registration. */ import Axios from "./plugins/axios"; import Emitter from "./plugins/emitter"; import Shop from "./plugins/shop"; import VeeValidate from "./plugins/vee-validate"; import Flatpickr from "./plugins/flatpickr"; [ Axios, Emitter, Shop, VeeValidate, Flatpickr, ].forEach((plugin) => app.use(plugin)); /** * Load event, the purpose of using the event is to mount the application * after all of our `Vue` components which is present in blade file have * been registered in the app. No matter what `app.mount()` should be * called in the last. */ window.addEventListener("load", function (event) { app.mount("#app"); });
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.geometry; import org.elasticsearch.geo.GeometryTestUtils; import org.elasticsearch.geometry.utils.GeographyValidator; import org.elasticsearch.geometry.utils.GeometryValidator; import org.elasticsearch.geometry.utils.StandardValidator; import org.elasticsearch.geometry.utils.WellKnownText; import java.io.IOException; import java.text.ParseException; public class RectangleTests extends BaseGeometryTestCase<Rectangle> { @Override protected Rectangle createTestInstance(boolean hasAlt) { assumeFalse("3rd dimension is not supported yet", hasAlt); return GeometryTestUtils.randomRectangle(); } public void testBasicSerialization() throws IOException, ParseException { GeometryValidator validator = GeographyValidator.instance(true); assertEquals("BBOX (10.0, 20.0, 40.0, 30.0)", WellKnownText.toWKT(new Rectangle(10, 20, 40, 30))); assertEquals(new Rectangle(10, 20, 40, 30), WellKnownText.fromWKT(validator, true, "BBOX (10.0, 20.0, 40.0, 30.0)")); assertEquals("BBOX EMPTY", WellKnownText.toWKT(Rectangle.EMPTY)); assertEquals(Rectangle.EMPTY, WellKnownText.fromWKT(validator, true, "BBOX EMPTY)")); } public void testInitValidation() { GeometryValidator validator = GeographyValidator.instance(true); IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> validator.validate(new Rectangle(2, 3, 100, 1))); assertEquals("invalid latitude 100.0; must be between -90.0 and 90.0", ex.getMessage()); ex = expectThrows(IllegalArgumentException.class, () -> validator.validate(new Rectangle(200, 3, 2, 1))); assertEquals("invalid longitude 200.0; must be between -180.0 and 180.0", ex.getMessage()); ex = expectThrows(IllegalArgumentException.class, () -> validator.validate(new Rectangle(2, 3, 1, 2))); assertEquals("max y cannot be less than min y", ex.getMessage()); ex = expectThrows(IllegalArgumentException.class, () -> validator.validate(new Rectangle(2, 3, 2, 1, 5, Double.NaN))); assertEquals("only one z value is specified", ex.getMessage()); ex = expectThrows( IllegalArgumentException.class, () -> StandardValidator.instance(false).validate(new Rectangle(50, 10, 40, 30, 20, 60)) ); assertEquals("found Z value [20.0] but [ignore_z_value] parameter is [false]", ex.getMessage()); StandardValidator.instance(true).validate(new Rectangle(50, 10, 40, 30, 20, 60)); } @Override protected Rectangle mutateInstance(Rectangle instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } }
<template> <div class="wrapper"> <img src="https://cdn.jsdelivr.net/gh/ycshang123/image-hosting@master/login.oms6vaklh5c.webp" class="wrapper__img" /> <div class="wrapper__input"> <input type="text" class="wrapper__input__content" placeholder="用户名" v-model="username" /> </div> <div class="wrapper__input"> <input type="password" class="wrapper__input__content" placeholder="密码" v-model="password" autocomplete="new-password" /> </div> <div class="wrapper__input"> <input type="password" class="wrapper__input__content" placeholder="确认密码" v-model="ensurement" /> </div> <div class="wrapper__login-button" @click="handleRegister">注册</div> <div class="wrapper__login-link" @click="handleLoginClick"> 已有账号去登录 </div> </div> </template> <script setup> import { reactive, toRefs } from 'vue' import { useRouter } from 'vue-router' import { post } from '../../utils/request' const data = reactive({ username: 'ycshang', password: '', ensurement: '' }) const router = useRouter() const handleRegister = async () => { if (data.password !== data.ensurement) { console.log('两次密码不一致') data.password = '' data.ensurement = '' return } try { const result = await post('/user/register', { username: data.username, password: data.password }) if (result?.code === 200 && result.message === '注册成功') { router.push({ name: 'LoginPage' }) } else { console.log(res.message) data.username = '' data.password = '' data.ensurement = '' } } catch (e) { console.log('请求失败') } } const { username, password, ensurement } = toRefs(data) const handleLoginClick = () => { router.push({ name: 'LoginPage' }) } </script> <style lang="scss" scoped> @import "../../style/index.scss"; .wrapper { position: absolute; top: 50%; left: 0; right: 0; transform: translateY(-50%); &__img { display: block; margin: 0 auto 0.4rem auto; width: 0.66rem; height: 0.66rem; } &__input { height: 0.48rem; margin: 0 0.4rem 0.16rem 0.4rem; padding: 0 0.16rem; background: #f9f9f9; border: 0.01rem solid rgba(0, 0, 0, 0.1); border-radius: 0.06rem; &__content { margin-top: 0.12rem; line-height: 0.22rem; border: none; outline: none; width: 100%; background: none; font-size: 0.16rem; color: $content-notice-fontcolor; &::placeholder { color: $content-notice-fontcolor; } } } &__login-button { margin: 0.32rem 0.4rem 0.16rem 0.4rem; line-height: 0.48rem; background: #0091ff; box-shadow: 0 0.04rem 0.08rem 0 rgba(0, 145, 255, 0.32); border-radius: 0.04rem; color: $bgColor; font-size: 0.16rem; text-align: center; } &__login-link { text-align: center; font-size: 0.14rem; color: $content-notice-fontcolor; } } </style>
package engine.model.physicalEngine.shape; import java.util.ArrayList; import java.util.List; import engine.model.physicalEngine.movement.*; public class Rectangle { private Position position; private double width; private double height; private boolean moving; private boolean colliding; private Velocity Velocity; private Direction direction; private Position head; /** * Rectangle constructor. * Create an object rectangle which has a @Position, a length, a width, a @Velocity, this rectangle can be moving or not and if it can collide or not. * You can give a @Direction to the rectangle to make it move where you want it to go. * The rectangle have a head, it's also a @Position, the head will move according the direction so if we go right first, and then we go to the left * the rectangle is going to flip. * * @param position * @param width * @param height * @param moving * @param velocity * * @see Position * @see Velocity * @see Direction */ public Rectangle(Position position, double width, double height, boolean moving, Velocity velocity) { this.position = position; this.width = width; this.height = height; this.moving = moving; this.colliding = true; this.Velocity = velocity; this.direction = Direction.NONE; this.head = new Position(position.getX() + height / 2, position.getY()); } public Rectangle(Position position, double width, double height, boolean moving, Velocity velocity, boolean isColliding) { this.position = position; this.width = width; this.height = height; this.moving = moving; this.colliding = isColliding; this.Velocity = velocity; this.direction = Direction.NONE; this.head = new Position(position.getX() + height / 2, position.getY()); } /** * Return the width of the rectangle. * @return width */ public double getWidth() { return this.width; } /** * Set the width of the rectangle. * @param width */ public void setWidth(double width) { this.width = width; } /** * Return the height of the rectangle. * @return height */ public double getHeight() { return this.height; } /** * Set the height of the rectangle. * @param height */ public void setHeight(double height) { this.height = height; } /** * Create the 4 apexes of the rectangle and put them in a list. * The apexes are the 4 corners of the rectangle. * When a rectangle is created, only the center of the rectangle is added to the @Map but we virtually create the other apex. * * * @return a list of the @Position of the 4 apexes of the rectangle * @see Position */ public List<Position> getApex() { List<Position> apex = new ArrayList<>(); apex.add(new Position(this.position.getX() - this.width / 2, this.position.getY() - this.height / 2)); apex.add(new Position(this.position.getX() - this.width / 2, this.position.getY() + this.height / 2)); apex.add(new Position(this.position.getX() + this.width / 2, this.position.getY() - this.height / 2)); apex.add(new Position(this.position.getX() + this.width / 2, this.position.getY() + this.height / 2)); return apex; } /** * Return the head of the rectangle. * * @return the @Position of the head of the rectangle * @see Position */ public Position getHead() { return this.head; } /** * Set the head of the rectangle. * * @param position * @see Position */ public void setHead(Position position) { this.head = position; } /** * Give us the @Position of the rectangle. * * @return the position of the rectangle * @see Position */ public Position getPosition() { return this.position; } /** * Change the @Position of the rectangle by another @Position. * * @param point * @see Position */ public void setPosition(Position point) { this.position = point; } /** * Set the X and/or the Y of the @Position of the rectangle. * * @param x * @param y * @see Position */ public void setPosition(double x, double y) { this.position.setPosition(x, y); } /** * Return the X of the @Position of the rectangle. * * @return the X of the @Position of the rectangle * @see Position */ public double getX() { return this.position.getX(); } /** * Return the Y of the @Position of the rectangle. * * @return the Y of the @Position of the rectangle * @see Position */ public double getY() { return this.position.getY(); } /** * Tell you if the rectangle is moving or not. * * @return true if the rectangle is moving, false if not */ public boolean isMoving() { return this.moving; } /** * Set the rectangle to moving or not. * * @param moving */ public void setMoving(boolean moving) { this.moving = moving; } /** * Tell you if the rectangle can collide or not. * * @return true if the rectangle can collide, false if not */ public boolean isColliding() { return this.colliding; } /** * Set the rectangle to colliding or not. * * @param colliding */ public void setColliding(boolean colliding) { this.colliding = colliding; } /** * Return the @Velocity of the rectangle. * * @return the @Velocity of the rectangle * @see Velocity */ public Velocity getVelocity() { return this.Velocity; } /** * Set the @Velocity of the rectangle with a new @Velocity. * * @param velocity * @see Velocity */ public void setVelocity(Velocity velocity) { this.Velocity = velocity; } /** * Return the @Direction of the rectangle. * * @return the @Direction of the rectangle * @see Direction */ public Direction getDirection() { return this.direction; } /** * Set the @Direction of the rectangle with a new @Direction. * * @param direction * @see Direction */ public void setDirection(Direction direction) { this.direction = direction; } }
探讨数据库的数据存储方式,其实就是探讨数据如何在磁盘上进行有效的组织。因为我们通常以如何高效读取和消费数据为目的,而不是数据存储本身 Hbase语法 https://www.cnblogs.com/guohu/p/13138868.html http://www.vue5.com/hbase/hbase_installation.html HBase对比关系型数据库管理系统(RDBMS) HBase RDBMS 数据类型 只有字符串/字节数组 具有丰富的数据类型 数据操作 只支持增删改查 支持SQL语句 存储模式 列式存储 行式存储 数据更新 数据有多个版本 更新后覆盖 扩展性 高 低 https://blog.csdn.net/qq_36290948/article/details/87096386 1.行键(rowkey) row key是用来检索记录的主键。访问HBase Table中的行,只有3种方式:通过单个rowkey访问;通过rowkey的range;全表扫描 rowkey可以是任意字符串(最大长度是64KB,实际应用中长度一般为10-100bytes)。在HBase内部,rowkey保存为字节数组。存储时,按照rowkey的字典序(byte order)排序存储 设计key时,要充分利用排序存储这个特性,将经常一起读取的行存储放在一起 2.列族(column family) HBase表中的每个列,都归属于某个列族。列族是表的schema的一部分(而不是列),必须在使用表之前定义。列名都是以列族为前缀 3.单元(cell) HBase中通过row和column确定一个 存贮(zhu)单元,称为cell。cell中的数据是没有类型的,全部以字节码格式存储 4.时间戳(timestamp) 每个cell都保存着同一份数据的多个版本,版本通过时间戳来索引。 时间戳可以由hbase在数据写入时自动赋值,精确到毫秒。也可以由用户显式赋值 每个cell中,不同版本的数据按照时间倒序排序,即最新的数据放在最前面 HBase提供了两种数据版本回收方式。一是保存数据的最后n个版本,二是保存最近一段时间内的版本(比如最近7天) 5.HMaster (1)管理用户对表的增删改查等操作 (2)管理regionServer的负载均衡,调整region的分布 (3)region的分配和移除 (4)处理RegionServer的故障转移 (5)HMaster 节点发生故障时,由于客户端是直接与 RegionServer 交互的,且 Meta 表也是存在于 ZooKeeper 当中,整个集群的工作会继续正常运行,所以当 HMaster 发生故障时,集群仍然可以稳定运行 6.RegionServer (1)响应用户的I/O请求,向HDFS文件系统中读写数据 (2)内部管理了一系列HRegion对象 (3)每个HRegion对应了Table中的一个Region,HRegion中由多个HStore组成 (4)每个HStore对应了Table中的一个Column Family (5)HFile是HBase中的KeyValue数据的存储格式,是Hadoop的二进制格式的文件 (6)HRegionServer中都包含一个WAL(write a head log)用来保存还未持久化存储的数据,用于用户数据还原 (7)RegionServer用于切分过大的Region 7.Region HBase使用rowkey将表水平切割成多个HRegion 从HMaster的角度看,每个HRegion都记录了它的StartKey和EndKey。由于RowKey是排序的,因此client可以通过HMaster快速定位每个rowkey在哪个HRegion上 HRegion由HMaster分配到相应的HRegionServer中,然后由HRegionServer负责HRegion的启动和管理,与Client的通信,负责数据的读取(使用HDFS) 每个HRegionServer可以同时管理1000个左右的HRegion 8.Zookeeper zookeeper是一个分布式协调服务 zk管理着HMaster和HRegionServer的状态(avaliable/alive) zk提供了宕机时通知的功能,从而实现HMaster与RegionServer的故障转移(failover)机制 在HMaster和HRegionServer连接到Zookeeper后,创建ephemeral(短暂的)节点,并使用heartbeat(心跳)机制来维持这个节点的存活状态 HMaster监控zookeeper的ephemeral节点来监控RegionServer的存活状态(默认:/hbase/rs/*) 备用HMaster监控zookeeper中的ephemeral节点,如果Active状态的HMaster宕机,备用状态的HMaster收到通知后就会切换为Active状态 命名空间、表名、行、列都必须用引号引起来 1.退出hbase shell客户端:quit 2.名空间 hbase-namespace (1)创建名空间,同时指定属性 create_namespace '<命名空间>' create_namespace '<命名空间>', {'<属性名>'=>'<属性值>'} (2)修改名空间属性 #新增命名空间属性 alter_namespace '<命名空间>', {METHOD => 'set', '<属性名>' => '<属性值>'} alter_namespace '<命名空间>', {METHOD => 'unset', NAME => '<属性名>'} (3)查看命名空间的描述信息 describe_namespace '<命名空间>' (4)删除命名空间(namespacae必须为空,如果有表,不能被删除) drop_namespace '<命名空间>' 3.表 创建表时,如果没有指定命名空间,则默认创建在default命名空间下 ​在创建表时同时,必须至少指定一个列簇
1) --> Every opertaion in O(1) solution: so for N element total, Time Complexity : O(N) Space Complexity : O(N) class CustomStack: def __init__(self, maxSize: int): self.maxSize =maxSize self.s =[] self.incrArray = [] def push(self, x: int) -> None: if len(self.s)<self.maxSize: self.s.append(x) self.incrArray.append(0) def pop(self) -> int: if self.s!=[]: i=len(self.s)-1 if len(self.s) == []: return -1 elif i-1>=0: self.incrArray[i-1] += self.incrArray[i] return self.s.pop() + self.incrArray.pop() return -1 def increment(self, k: int, val: int) -> None: if self.incrArray != []: self.incrArray[min(k,len(self.s))-1] += val 2) --> Every opertaion in O(N) solution: so for N element total, Time Complexity : O(N^2) Space Complexity : O(N) class CustomStack: def __init__(self, maxSize: int): self.maxSize=maxSize self.s=[] def push(self, x: int) -> None: if self.maxSize>len(self.s): self.s.append(x) def pop(self) -> int: if len(self.s)>=1: return self.s.pop(-1) else: return -1 def increment(self, k: int, val: int) -> None: if len(self.s)>=k: for i in range(k): self.s[i]=self.s[i]+val else: for i in range(len(self.s)): self.s[i]=self.s[i]+val
import React from "react"; import { Text } from "react-native"; import { PPTextStyle } from "./PPText.style"; import { useStyle, useTheme } from "../../hooks"; import { TextProps } from "react-native"; export interface IPPText extends TextProps { /** * Weight of the font > light = 300; regular = 400; medium = 500; semiBold = 600; bold = 700; black = 800 */ weight?: "light" | "regular" | "medium" | "semiBold" | "bold" | "black"; /** * Size of the font > heading_1 = 30px; heading_2 = 26px; heading_3 = 22px; heading_4 = 16px; body = 14px; small = 12px; caption = 10px */ size?: | "heading_1" | "heading_2" | "heading_3" | "heading_4" | "body" | "small" | "caption"; /** * Color of the text */ color?: string; align?: "left" | "center" | "right"; } export const PPText: React.FC<IPPText> = (props) => { const { children, align = "left", color, size = "body", weight = "medium", ...rest } = props; const style = useStyle(PPTextStyle); const { theme } = useTheme(); const getWeightStyle = () => { switch (weight) { case "light": return style.light; case "regular": return style.regular; case "medium": return style.medium; case "semiBold": return style.semiBold; case "bold": return style.bold; case "black": return style.black; default: break; } }; const getFontSize = () => { switch (size) { case "heading_1": return theme.fonts.heading_1; case "heading_2": return theme.fonts.heading_2; case "heading_3": return theme.fonts.heading_3; case "heading_4": return theme.fonts.heading_4; case "body": return theme.fonts.body; case "small": return theme.fonts.small; case "caption": return theme.fonts.caption; default: break; } }; return ( <Text {...rest} style={[ { color, textAlign: align, fontSize: getFontSize() }, getWeightStyle(), ]} > {children} </Text> ); };
package com.showmeyourcode.projects.algorithms.launcher; import com.showmeyourcode.projects.algorithms.algorithm.implementation.AlgorithmFactory; import com.showmeyourcode.projects.algorithms.benchmark.BenchmarkDataGenerator; import com.showmeyourcode.projects.algorithms.benchmark.BenchmarkProcessor; import com.showmeyourcode.projects.algorithms.configuration.SortingAppConfiguration; import com.showmeyourcode.projects.algorithms.configuration.SortingAppConfigurationLoader; import com.showmeyourcode.projects.algorithms.console.UserInputInterceptor; import com.showmeyourcode.projects.algorithms.console.UserInputProcessor; import com.showmeyourcode.projects.algorithms.exception.CannotLoadAppPropertiesException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.InputStream; @Slf4j @RequiredArgsConstructor public class SortingAlgorithmsApplication { public static final String DEFAULT_PROPERTIES_FILE = "application.properties"; public static final InputStream DEFAULT_INPUT_STREAM = System.in; private final String propertiesFilename; private final InputStream inputStream; void startApp() throws CannotLoadAppPropertiesException { log.info("\nWelcome to The Sorting Algorithms program."); final SortingAppConfigurationLoader configLoader = new SortingAppConfigurationLoader(propertiesFilename); final SortingAppConfiguration sortingAppConfiguration = configLoader.getConfiguration(); final BenchmarkDataGenerator benchmarkDataGenerator = new BenchmarkDataGenerator(sortingAppConfiguration); final BenchmarkProcessor benchmarkProcessor = new BenchmarkProcessor(benchmarkDataGenerator, sortingAppConfiguration); final AlgorithmFactory algorithmFactory = new AlgorithmFactory(sortingAppConfiguration); final UserInputProcessor userInputProcessor = new UserInputProcessor( sortingAppConfiguration, benchmarkDataGenerator, benchmarkProcessor, algorithmFactory ); final UserInputInterceptor inputInterceptor = new UserInputInterceptor(sortingAppConfiguration, userInputProcessor); inputInterceptor.startListening(inputStream); } }
/* * Copyright (c) 2024 Kodeco LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * This project and source code may use libraries or frameworks that are * released under various Open-Source licenses. Use of those libraries and * frameworks are governed by their own individual licenses. * * 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. */ open class Food( val name: String, var price: String, var origin: String ) { open fun label(): String { return "$name of $origin. Price: $price" } } class Fruit( name: String, price: String, origin: String, val stone: Boolean = false ) : Food(name, price, origin) { fun hasStone(): Boolean { return stone } override fun label(): String { val stonedLabel = if (hasStone()) "Stoned " else "" return "${stonedLabel}Fruit ${super.label()}" } } fun main() { val tomato = Food("Tomato", "1.0", "US") val tomato2 = Fruit("Tomato", "1.0", "US") println(tomato.label()) // Tomato of US. Price: 1.0 println(tomato2.label()) // Fruit Tomato of US. Price: 1.0 val peach = Fruit("Peach", "2.0", "Chile", true) println(peach.label()) // Stoned Fruit Peach of Chile. Price: 2.0 } // Benefits //Flexibility and Extensibility open class Fruit { open fun describeColor() { println("Fruits can be of various colors.") } } class Peach : Fruit() { override fun describeColor() { println("A peach is usually pinkish or yellowish.") } } class Plum : Fruit() { override fun describeColor() { println("A plum is usually purple or reddish.") } } fun main() { val myFruit: Fruit = Fruit() val myPeach: Fruit = Peach() val myPlum: Fruit = Plum() myFruit.describeColor() // Fruits can be of various colors. myPeach.describeColor() // A peach is usually pinkish or yellowish. myPlum.describeColor() // A plum is usually purple or reddish. } // Polymorphism // Override constructor open class Team(open val name: String) class LocalTeam(nameParam: String, val isLocal: Boolean): Team(nameParam) { // Override the name property during initialization override val name = nameParam.toUpperCase() fun secretName(): String { return super.name } } fun main() { val team=LocalTeam("Tigers", false) println(team.name) // TIGERS println(team.secretName()) // Tigers } // Overriding equals and hashcode open class Food( val name: String, var price: String, var origin: String ) { open fun label(): String { return "$name of $origin. Price: $price" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Food) return false return name == other.name } override fun hashCode(): Int { return 1 + price.hashCode() } } class Fruit( name: String, price: String, origin: String, val stone: Boolean = false ) : Food(name, price, origin) { fun hasStone(): Boolean { return stone } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Fruit) return false return name == other.name && stone == other.stone } } fun main() { val tomato = Food("Tomato", "1.0", "US") val stonedtomato = Fruit("Tomato", "1.0", "US", true) println(tomato.equals(stonedtomato)) // true println(stonedtomato.equals(tomato)) // false } // overriding fun main() { val tomato = Food("Tomato", "1.0") val cucumber = Food("Tomato", "2.0") //1 val foods = mutableSetOf<Food>() foods.add(tomato) //2 println(cucumber in foods) // false //3 println(cucumber == foods.first()) // true //4 println(tomato == cucumber) // true }
import * as dotenv from "dotenv"; dotenv.config({ path: "./.env.local" }); import { getAlgodClient } from "../src/clients/index.js"; import algosdk from "algosdk"; import { signAndSubmit } from "../src/algorand/index.js"; const network = process.env.NEXT_PUBLIC_NETWORK || "SandNet"; const algodClient = getAlgodClient(network); // get seller and buyer accounts const buyer = algosdk.mnemonicToSecretKey(process.env.NEXT_PUBLIC_BUYER_MNEMONIC); const deployer = algosdk.mnemonicToSecretKey(process.env.NEXT_PUBLIC_DEPLOYER_MNEMONIC); const seller = deployer; const sendAlgos = async (sender, receiver, amount) => { // create suggested parameters const suggestedParams = await algodClient.getTransactionParams().do(); let txn = algosdk.makePaymentTxnWithSuggestedParams( sender.addr, receiver.addr, amount, undefined, undefined, suggestedParams ); // sign the transaction and submit to network console.log(await signAndSubmit(algodClient, [txn], sender)); }; const createAsset = async (maker) => { const total = 1000; // total supply const decimals = 0; // units of this asset are whole-integer amounts const assetName = "Fungible Token"; //token asset name const unitName = "FT"; //token unit name const metadata = undefined; const defaultFrozen = false; // whether accounts should be frozen by default // create suggested parameters const suggestedParams = await algodClient.getTransactionParams().do(); // create the asset creation transaction const txn = algosdk.makeAssetCreateTxnWithSuggestedParamsFromObject({ from: maker.addr, total, decimals, assetName, unitName, assetURL: "ipfs://cid", assetMetadataHash: metadata, defaultFrozen, freeze: undefined, manager: undefined, clawback: undefined, reserve: undefined, suggestedParams, }); // sign the transaction and submit to network // sign and submit the transaction const { confirmation } = await signAndSubmit(algodClient, [txn], maker); // Extract the asset ID from the confirmation object const assetId = confirmation['asset-index']; return assetId; }; (async () => { //fund accounts console.log("Funding accounts..."); await sendAlgos(deployer, buyer, 1e6); // 1 Algo await sendAlgos(deployer, seller, 1e6); // 1 Algo const suggestedParams = await algodClient.getTransactionParams().do(); // Create asset const assetId = await createAsset(seller); console.log(`Opted in buyer account ${buyer.addr} to asset with ID: ${assetId}`); //buyer opts into asset let optintxn = algosdk.makeAssetTransferTxnWithSuggestedParams( buyer.addr, buyer.addr, undefined, undefined, 0, undefined, assetId, suggestedParams ); console.log(await signAndSubmit(algodClient, [optintxn], buyer)); // Transfer 100 fungible tokens to your buyer account let transferTxn = algosdk.makeAssetTransferTxnWithSuggestedParams( seller.addr, buyer.addr, undefined, undefined, 100, undefined, assetId, suggestedParams ); console.log(await signAndSubmit(algodClient, [transferTxn], seller)); // Check console.log("Receiver assets: ", (await algodClient.accountInformation(seller.addr).do()).assets); console.log("New recipient assets: ", (await algodClient.accountInformation(buyer.addr).do()).assets); console.log(assetId); })(); export {buyer, seller};
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import javax.swing.JTextArea; import javax.swing.SwingUtilities; public class URLChecker implements Runnable { private String host; private File file; private JTextArea resultArea; private static final String ANSI_GREEN = "\u001B[32m"; private static final String ANSI_RED = "\u001B[31m"; private static final String ANSI_RESET = "\u001B[0m"; public URLChecker(String host, File file, JTextArea resultArea) { this.host = host; this.file = file; this.resultArea = resultArea; } @Override public void run() { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { checkUrl(host + "/" + line); } } catch (IOException e) { appendResult("Error reading file: " + e.getMessage(), ANSI_RED); } } private void checkUrl(String urlString) { try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == 200) { appendResult(urlString + " - 200 OK", ANSI_GREEN); } else { appendResult(urlString + " - Bad Request", ANSI_RED); } } catch (IOException e) { appendResult(urlString + " - Bad Request", ANSI_RED); } } private void appendResult(String message, String colorCode) { SwingUtilities.invokeLater(() -> resultArea.append(message + "\n")); System.out.println(colorCode + message + ANSI_RESET); } }
// components/Navbar.js import React, { useState } from "react"; import Link from "next/link"; import Image from "next/image"; // import { Menu } from '@headlessui/react'; const Navbar = () => { const [isOpen, setIsOpen] = useState(false); return ( <nav className="border-b border-gray-300"> <div className="container mx-auto px-4 flex items-center justify-around h-16"> <div className="flex items-center space-x-4"> <Link href="/"> <div className="text-lg flex"> <Image src="/images/image 7.png" alt="Brand" width={98} height={24} /> {/* <div>test</div> */} </div> </Link> <div className="hidden md:flex space-x-4"> <Link href="/dashboard"> <div className="hover:underline">Dashboard</div> </Link> <Link href="/"> <div className="hover:underline">Home</div> </Link> <Link href="/colleges"> <div className="hover:underline">Colleges</div> </Link> <Link href="/exams"> <div className="hover:underline">Exams</div> </Link> <Link href="/courses"> <div className="hover:underline">Courses</div> </Link> <Link href="/news"> <div className="hover:underline">News</div> </Link> </div> </div> <div className="relative hidden md:block"> <div className="absolute left-3 top-1/2 transform -translate-y-1/2"> <Image src="/images/Search.png" alt="Search" width={20} height={20} /> </div> <input type="text" className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Search for Colleges, Exams, Courses & more..." /> </div> <div className="md:hidden flex items-center"> <button onClick={() => setIsOpen(!isOpen)} className="focus:outline-none" > <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d={isOpen ? "M6 18L18 6M6 6l12 12" : "M4 6h16M4 12h16m-7 6h7"} ></path> </svg> </button> </div> </div> {isOpen && ( <div className="md:hidden"> <div className="px-4 pt-2 pb-3 space-y-1"> <Link href="/dashboard"> <div className="block hover:underline">Dashboard</div> </Link> <Link href="/university"> <div className="block hover:underline">University</div> </Link> <Link href="/colleges"> <div className="block hover:underline">Colleges</div> </Link> <Link href="/exams"> <div className="block hover:underline">Exams</div> </Link> <Link href="/courses"> <div className="block hover:underline">Courses</div> </Link> <Link href="/news"> <div className="block hover:underline">News</div> </Link> <div className="relative"> <div className="absolute left-3 top-1/2 transform -translate-y-1/2"> <Image src="/search-icon.png" alt="Search" width={20} height={20} /> </div> <input type="text" className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Search for Colleges, Exams, Courses & more..." /> </div> </div> </div> )} </nav> ); }; export default Navbar;
enum ExpensesDealType { supermarkets, home, taxi, cafe, entertainments, pharmacy; static String toEntity(ExpensesDealType type) { return switch (type) { ExpensesDealType.cafe => 'Кафе', ExpensesDealType.entertainments => 'Развлечения', ExpensesDealType.home => 'Для дома', ExpensesDealType.pharmacy => 'Аптека', ExpensesDealType.supermarkets => 'Супермаркеты', ExpensesDealType.taxi => 'Такси', }; } static ExpensesDealType toEnum(String name) { return switch (name) { 'Кафе' => ExpensesDealType.cafe, 'Развлечения' => ExpensesDealType.entertainments, 'Для дома' => ExpensesDealType.home, 'Аптека' => ExpensesDealType.pharmacy, 'Супермаркеты' => ExpensesDealType.supermarkets, _ => ExpensesDealType.taxi, }; } }