text
stringlengths
184
4.48M
# frozen_string_literal: true require 'request_store' require 'active_support' require 'active_support/core_ext/date' require 'active_support/core_ext/time' require 'active_support/core_ext/date_time' require 'active_support/core_ext/object' require 'forwardable' require 'ostruct' module Bp3 module RequestState # rubocop:disable Metrics/ClassLength, Style/ClassVars class Base extend Forwardable cattr_accessor :hash_key_map, :base_attrs, :hash_attrs @@hash_key_map = { current_site: 'Site', current_tenant: 'Tenant', current_workspace: 'Workspace', current_user: 'User', current_admin: 'Admin', current_root: 'Root', current_visitor: 'Visitor' }.freeze @@base_attrs = %w[current_site current_tenant current_workspace current_user current_admin current_root current_visitor locale view_context].freeze @@hash_attrs = %w[current_site_id current_tenant_id current_workspace_id current_user_id current_admin_id current_root_id current_visitor_id].freeze def self.clear! RequestStore.delete(:bp3_request_state) end def self.current RequestStore.fetch(:bp3_request_state) do { started: DateTime.current } end end def self.with_current(site:, tenant: nil, workspace: nil) clear! self.current_site = site self.current_tenant = tenant || site.default_tenant self.current_workspace = workspace || site.default_workspace yield if block_given? end def self.to_hash { request_id:, started_string: started.utc.to_s, locale: locale&.to_s }.tap do |hash| hash_attrs.each do |id_attr| attr = id_attr.gsub('_id', '') hash[id_attr] = send(id_attr) if respond_to?(attr) end end.stringify_keys end def self.define_accessors base_attrs.each do |attr| define_accessors_for_one_attr(attr) end # current_login picks one of the logged-in user, site-admin or root. # pick the one with least privileges first define_singleton_method :current_login do current_user || current_admin || current_root end define_method :current_login do current_user || current_admin || current_root end define_singleton_method :highest_privilege do # do not include current_visitor, as they are not logged in current_root || current_admin || current_user # || current_visitor end define_method :highest_privilege do # do not include current_visitor, as they are not logged in current_root || current_admin || current_user # || current_visitor end end def self.from_hash(hash) state = OpenStruct.new(hash) # rubocop:disable Style/OpenStructUse fill_from_map(state) fill_details(state) self end def self.fill_from_map(state) hash_key_map.each_key do |attr| attr_with_id = "#{attr}_id" fill_one_from_map(attr.to_sym, state.send(attr_with_id)) if state.send(attr_with_id) end end def self.fill_one_from_map(attr, id) klass = hash_key_map[attr.to_sym]&.constantize writer = "#{attr}=" send(writer, klass.find_by(id:)) end def self.fill_details(state) self.request_id = state.request_id if state.request_id self.started = state.started_string.present? ? DateTime.parse(state.started_string) : nil self.locale = state.locale&.to_sym end def self.either_site target_site || current_site end def_delegator self, :either_site def self.either_site_id target_site_id || current_site_id end def self.either_tenant target_tenant || current_tenant end def_delegator self, :either_tenant def self.either_tenant_id target_tenant_id || current_tenant_id end def self.either_workspace target_workspace || current_workspace end def_delegator self, :either_workspace def self.either_workspace_id target_workspace_id || current_workspace_id end def self.either_admin current_root || current_admin end def_delegator self, :either_admin def self.duration (now - started) * 1.day # in seconds end def_delegator self, :duration def self.now DateTime.current end def_delegator self, :now def self.started current[:started] || now end def_delegator self, :started def self.started=(time) current[:started] = time || now end def self.request_id current[:request_id] end def_delegator self, :request_id def self.request_id=(rqid) current[:request_id] = rqid end def self.define_accessors_for_one_attr(attr) define_getter(attr) define_setter(attr) define_id_getter(attr) define_id_setter(attr) define_method(attr) do self.class.current[attr.to_sym] end end def self.define_getter(attr) define_singleton_method(attr) do current[attr.to_sym] end end def self.define_setter(attr) define_singleton_method("#{attr}=") do |obj| current[attr.to_sym] = obj end end def self.define_id_getter(attr) define_singleton_method("#{attr}_id") do current[attr.to_sym]&.id end end def self.define_id_setter(attr) define_singleton_method("#{attr}_id=") do |id| current[attr.to_sym] = fill_one_from_map(attr.to_sym, id) end end end # rubocop:enable Metrics/ClassLength, Style/ClassVars end end
#pragma once template<typename T> class TreeNode { public: TreeNode() {}; TreeNode(T value); ~TreeNode() {}; /// <summary> /// Returns whether or not this node has a left child /// </summary> bool hasLeft(); /// <summary> /// Returns whether or not this node has a right child /// </summary> bool hasRight(); /// <summary> /// Returns the data this node contains /// </summary> T getData(); /// <summary> /// Gets the child to the left of this node /// </summary> TreeNode<T>* getLeft(); /// <summary> /// Gets the child to the right of this node /// </summary> TreeNode<T>* getRight(); /// <summary> /// Sets the value of the data this node is storing to be the given value /// </summary> /// <param name="value">The value to change the data to</param> void setData(T value); /// <summary> /// Sets the left child of this node to be the given node /// </summary> /// <param name="node">The node to set as this nodes new child</param> void setLeft(TreeNode<T>* node); /// <summary> /// Sets the left child of this node to be the given node /// </summary> /// <param name="node">The node to set as this nodes new child</param> void setRight(TreeNode<T>* node); void draw(int x, int y, bool selected = false); private: T m_value; TreeNode<T>* m_left; TreeNode<T>* m_right; }; template<typename T> inline TreeNode<T>::TreeNode(T value) { m_value = value; m_left = nullptr; m_right = nullptr; } template<typename T> inline bool TreeNode<T>::hasLeft() { return m_left; } template<typename T> inline bool TreeNode<T>::hasRight() { return m_right; } template<typename T> inline T TreeNode<T>::getData() { return m_value; } template<typename T> inline TreeNode<T>* TreeNode<T>::getLeft() { return m_left; } template<typename T> inline TreeNode<T>* TreeNode<T>::getRight() { return m_right; } template<typename T> inline void TreeNode<T>::setData(T value) { m_value = value; } template<typename T> inline void TreeNode<T>::setLeft(TreeNode<T>* node) { m_left = node; } template<typename T> inline void TreeNode<T>::setRight(TreeNode<T>* node) { m_right = node; } template<typename T> inline void TreeNode<T>::draw(int x, int y, bool selected) { //Creates an array to store the string representation of the value static char buffer[10]; //Converts the value to a string and stores it in the array sprintf(buffer, "%d", m_value); //Draws the circle to represent the node DrawCircle(x, y, 30, YELLOW); //If the the node is the current selected node change its color. if (selected) DrawCircle(x, y, 28, GREEN); else DrawCircle(x, y, 28, BLACK); //Draw the value of the node inside its circle DrawText(buffer, x - 12, y - 12, 12, WHITE); }
"""Use case for getting threads.""" from __future__ import annotations from typing import TYPE_CHECKING from .dto import ThreadDTO if TYPE_CHECKING: from chat.domain.thread import AbstractThreadRepository class ListThreads: """Use case for getting threads.""" def __init__(self, repository: AbstractThreadRepository) -> None: """Initialize the use case. Args: repository: The repository to use for thread operations. """ self._repository = repository def execute(self) -> list[ThreadDTO]: """Execute the use case. Returns: The list of threads. """ threads = self._repository.list_all() threads.sort(key=lambda x: x.id_) return [ThreadDTO.from_model(thread) for thread in threads]
require_relative 'spec_helper' require 'date' RSpec.describe Rental do let(:book) { Book.new('El viejo y el mar', 'Ernest Hemingway') } let(:person) { Person.new(30) } describe '#initialize' do it 'creates a new Rental instance' do rental = Rental.new('2023/9/6', book, person) expect(rental).to be_an_instance_of(Rental) end it 'initializes the date, book, and person' do rental = Rental.new('2023/9/6', book, person) expect(rental.date).to eq('2023/9/6') expect(rental.book).to eq(book) expect(rental.person).to eq(person) end it 'adds the rental to the book and person' do rental = Rental.new('2023/9/6', book, person) expect(book.rentals).to include(rental) expect(person.rentals).to include(rental) end end describe '#to_hash' do it 'returns a hash representation of the rental' do rental = Rental.new('2023/9/6', book, person) rental_hash = rental.to_hash expect(rental_hash).to be_a(Hash) expect(rental_hash[:date]).to eq('2023/9/6') expect(rental_hash[:book]).to eq(book.to_hash) expect(rental_hash[:person]).to eq(person.to_hash) end end describe '.from_hash' do it 'creates a Rental object from a hash' do rental_hash = { 'date' => '2023/9/6', 'book' => { 'title' => 'El viejo y el mar', 'author' => 'Ernest Hemingway' }, 'person' => { 'name' => 'Sample Person' } } rental = Rental.from_hash(rental_hash) expect(rental).to be_an_instance_of(Rental) expect(rental.date).to eq(Date.new(2023, 9, 6)) expect(rental.book.title).to eq('El viejo y el mar') expect(rental.person.name).to eq('Sample Person') end end end
import { Injectable } from '@angular/core'; import {HttpClient, HttpErrorResponse, HttpHeaders} from "@angular/common/http"; import {Observable, throwError } from 'rxjs'; import { catchError } from 'rxjs/operators'; import {Etudiant} from "../models/Etudiant"; import {Module} from "../Entities/Module"; import {Inscription} from "../models/Inscription"; @Injectable({ providedIn: 'root' }) export class EtudiantService { //data based url private serverUrl : string = 'http://localhost:8222/etudiant-service/api/v1/Etudiants'; private serverUrl_2 : string = 'http://localhost:8222/etudiant-service/api/v1/inscriptions/cin'; //injecter HttpClient constructor(private httpClient: HttpClient) { } //get all Etudiant from DB public getEtudiants(): Observable<Etudiant[]> { return this.httpClient.get<Etudiant[]>(`${this.serverUrl}`).pipe( catchError(this.handleError) ); } //get Etudiant by id getEtudiantByid(id: string): Observable<Etudiant> { const url = `${this.serverUrl}/id/${id}`; return this.httpClient.get<Etudiant>(url).pipe( catchError(this.handleError) ); } //get Etudiant by cin getEtudiantByCin(cin: string ): Observable<Etudiant> { const url = `${this.serverUrl}/cin/${cin}`; return this.httpClient.get<Etudiant>(url).pipe( catchError(this.handleError) ); } //get Etudiant Info by cin getEtudiantInfoByCin(cin: string ): Observable<Inscription> { const url = `${this.serverUrl_2}/${cin}`; return this.httpClient.get<Inscription>(url).pipe( catchError(this.handleError) ); } //get Etudiant by apogee getEtudiantByApogee(apogee: string ): Observable<Etudiant[]> { const url = `${this.serverUrl}/apogee/${apogee}`; return this.httpClient.get<Etudiant[]>(url).pipe( catchError(this.handleError) ); } getEtudiantByFilierId(idFilier:string){ return this.httpClient.get<Etudiant[]>(`${this.serverUrl}/filier/${idFilier}`); } //Save Etudiant saveEtudiant(etudiant: Etudiant): Observable<Etudiant> { return this.httpClient.post<Etudiant>(this.serverUrl, etudiant).pipe( catchError(this.handleError) ); } //Updating etudaint updateEtudiant(etudiant: Etudiant): Observable<Etudiant> { return this.httpClient.put<Etudiant>(this.serverUrl,etudiant ).pipe( catchError(this.handleError) ); } //Deleting etudaint deleteEtudiant(id: string): Observable<any> { const url = `${this.serverUrl}/${id}`; return this.httpClient.delete(url).pipe( catchError(this.handleError) ); } // Errors Handling public handleError(error: HttpErrorResponse){ let errorMessage: string = ''; if(error.error instanceof ErrorEvent){ //client error errorMessage = `Error : ${error.error.message}`; }else{ //server error errorMessage = `Status : ${error.status}` +"......" +` Message : ${error.message}`; } return throwError(errorMessage); } }
<div class="container-fluid head col-md-12" #Home (scroll)="scrollMe($event)"> <p style="color:white; width:150px;float: left;" ><i class="fa fa-phone fa-flip-horizontal" aria-hidden="true"></i>&nbsp; 7767858952</p> <p style="color:white;width:250px;float: left; " ><i class="fa fa-envelope" aria-hidden="true"></i>&nbsp; shubhamdigole@gmail.com</p> <p style="color:white;width:250px;float: left; " ><i class="fa fa-clock" aria-hidden="true"></i>&nbsp; Opening: 10:00am - 5:00pm</p> <p class="icons" style="padding-top:0px;color:white;float:right; right: 0; font-size: 20px;" ><i class="fab fa-facebook" style="margin-right:5px;"></i><i class="fab fa-instagram" style="margin-right:5px;" aria-hidden="true"></i><i class="fab fa-youtube" style="margin-right:5px;" aria-hidden="true"></i><i class="fab fa-twitter" style="margin-right:5px;" aria-hidden="true"></i></p> </div> <div class="arrow" (click)="scrollToElement(Home)"><i class="fas fa-chevron-up"></i></div> <div class="jumbotron navbar na" #navbar> <nav class="navbar navbar-expand-sm "> <a class="navbar-brand" href="#"> <img src="assets\logo.jpg" alt="Logo" style="width:40px;"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="fas fa-bars"></span> </button> <!-- Navbar links --> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav mx-auto"> <li class="nav-item"> <a class="nav-link" (click)="scrollToElement(Home)" >Home</a> </li> <li class="nav-item"> <a class="nav-link" (click)="scrollToElement(about)">About Us</a> </li> <li class="nav-item"> <a class="nav-link" (click)="scrollToElement(target)"> Gallery</a> </li> <li class="nav-item"> <a class="nav-link" (click)="scrollToElement(contact)">Contact Us</a> </li> </ul> <ul class="navbar-nav mx-right" > <li class="nav-item"> <a href="" [routerLink]="['/login']" routerLinkActive="router-link-active" class="nav-link"><i class="fas fa-sign-in-alt"></i>&nbsp;Login</a> </li> </ul> </div> </nav> </div> <div id="carouselExampleIndicators" class="carousel slide imagesl" data-ride="carousel" > <div class="carousel-inner"> <div class="carousel-item" [ngClass]="{'active': i === 0 }" *ngFor="let item of imageData ; index as i"> <img class="d-block w-100" src="{{item.img}}" alt="First slide"> <div class="carousel-caption"> <h1>{{item.heading}}</h1> <h5>{{item.text}}</h5> </div> </div> </div> <a class="carousel-control-prev sliderbutton" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="fas fa-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next sliderbutton" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="fas fa-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <div class="container information" #about> <h3 align="center" id="welcome"> Welcome To Sabaramati</h3><br> <div class="row"> <mat-card class="col-md-6 cardimage"> <mat-card-header> <mat-card-title><h3 style="margin-left:-20px;">Welcome To Our School</h3></mat-card-title> </mat-card-header> <mat-card-content> <p style="color:red"> Lorem ipsum dolor sit amet, consectetur adipisic ming elit, sed do ei Excepteur sint occaecat cupida proident, sunt in culpa qui dese runt mol anim id est lai aborum. Sed ut perspiciatis unde omnis iste natus error svolupt accu doloremque laudantium, totam rem. </p> </mat-card-content> <mat-card-actions> <button class="btn" [disabled]="!buttonDisabled" (click)="openDialog()">Read More</button> </mat-card-actions> </mat-card> <mat-card class="col-md-6"> <img mat-card-image src="assets\1.png" alt="Photo of a Shiba Inu"> </mat-card> </div> </div> <div class="container-fluid test"> <div class="container features " fxLayout="row"> <H3 class="text-center" >Why Choose US</H3> <div class="row"> <div class="card col-md-4 " *ngFor="let item of featuresData"> <div class="card-body"> <h5 class="card-title"><img src="{{item.img}}" id="about" alt="">&nbsp;{{item.heading}}</h5> <p id="info">{{item.info}}</p> </div> </div> </div> </div> </div> <div class="container-fluid staff"> <h5 align="center">Our Awesome Teachers</h5> <p align="center"> We Have Best Teachers From india</p> <div class="container cards"> <div class="row"> <div class="col-md-3 col-sm-6" *ngFor="let teacher of teachersData"> <mat-card class="col-md-12"> <div class="teachers"> <h6>{{teacher.name}}</h6> <p>{{ teacher.profile}}</p> </div> <img mat-card-image src="{{teacher.img}}" alt=""></mat-card> </div> </div> </div> </div> <div class="container-fluid name"> <h3 align="center" style="margin-top:20px;color:white">Feedback</h3> <p align="center" style="color:white">Some Responses By Parents To Our school</p> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel" data-interval="5000"> <div class="carousel-inner"> <div class="carousel-item" [ngClass]="{'active': i === 0 }" *ngFor="let item of feedback ; index as i"> <img class="d-block w-100" id="feed" src="{{item.img}}" alt="First slide"> <div class="carousel-caption align-middle"> <h4>{{item.heading}}</h4> <p>{{item.Brief}}</p> <p>Mr. {{item.name}}</p> </div> </div> </div> </div> </div> <div class="container-fluid staff" #target> <h5 align="center">Our Gallery</h5> <p align="center"> Our Best Moments</p> <div class="container cards"> <div class="row"> <div class="col-md-3 col-sm-6" *ngFor="let teacher of teachersData"> <mat-card class="col-md-12"> <div class="teachers"> <h6>{{teacher.name}}</h6> <p>{{ teacher.profile}}</p> </div> <img mat-card-image src="{{teacher.img}}" alt=""></mat-card> </div> </div> </div> </div> <div @myInsertRemoveTrigger *ngIf="isShown" class="insert-remove-container"> <p>The box is inserted</p> </div>
import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { addProduct } from "../redux/productSlice"; import "./product.css"; import { HeartOutlined } from "@ant-design/icons"; import { useNavigate } from "react-router-dom"; import { addtocart } from "../redux/cartSlice"; import { BASE_URL, handleCat, handleWishlist } from "../utils/utils"; import { addToFilter } from "../redux/Filtered"; function Products() { const [wishlist, setWishlist] = useState(false); const [product, setProducts] = useState(); const productFromStore = useSelector((state) => state.products); const dispatch = useDispatch(); const navigate = useNavigate(); const user = useSelector((state) => state.user); useEffect(() => { async function getProducts() { if (productFromStore.length === 0) { const req = await fetch(`${BASE_URL}/products`); const res = await req.json(); setProducts(res); dispatch(addProduct(res)); } else { setProducts(productFromStore); } } getProducts(); }, []); const handleproduct = (product) => { navigate(`/product-description/${product._id}`); handleCat(product.category); }; const handleCat = (category) => { const filter = product?.filter((item) => item.category == category); dispatch(addToFilter(filter)); }; const tocart = (e) => { dispatch(addtocart(e)); }; const handlewishlist = (product) => { const data = { productId: product._id, customerId: user._id }; if (user._id) { handleWishlist(data); } else { console.log("login in"); } }; return ( <div className="product-wrapper"> {product ? ( product?.map((product) => { return ( <div key={product._id} className="product" loading="lazy"> <div className="img-div"> {" "} <img onClick={() => handleproduct(product)} className="product-img" src={product.images[0]} alt="" /> </div> <div className="product-details"> <div className="detail-top" onClick={() => handleproduct(product)} > <h4 className="title"> {product.title.substring(0, 60)}{" "} {product.title.length > 72 && <span>...</span>} </h4> <h6 className="category-product-detail"> {product.category} </h6> <h4 className="price">Rs {product.price}</h4> </div> <div className="button-div"> <button onClick={() => tocart(product)} className="add-to-cart" > Add to cart </button> <button onClick={() => handlewishlist(product)} className={`${wishlist ? "red-heart" : ""}heart`} > <HeartOutlined /> </button> </div> </div> </div> ); }) ) : ( <div className="loading"></div> )} </div> ); } export default Products;
import { CommonModule } from '@angular/common'; import { ChangeDetectionStrategy, Component } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MatIconModule } from '@angular/material/icon'; import { MatToolbarModule } from '@angular/material/toolbar'; import { RouterModule } from '@angular/router'; import { TranslocoModule } from '@ngneat/transloco'; import { injectAppConfig } from '../../app.config'; import { ExternalLinkDirective } from '../../directives/external-link.directive'; import { injectGitHubIcon } from '../../icons/github.icon'; import { LanguageSelectComponent } from '../../l10n/language-select/language-select.component'; import { injectToolbarColor } from '../toolbar-color'; @Component({ selector: 'app-vertical-layout', standalone: true, imports: [ CommonModule, RouterModule, TranslocoModule, MatButtonModule, MatIconModule, MatToolbarModule, ExternalLinkDirective, LanguageSelectComponent, ], template: ` <mat-toolbar [color]="color" *transloco="let t; read: '_'"> <span>{{ t('APP_NAME', {name}) }}</span> <span class="spacer"></span> <app-language-select></app-language-select> <a mat-icon-button aria-label="Share" href="https://github.com/armanozak"> <mat-icon svgIcon="github"></mat-icon> </a> </mat-toolbar> <router-outlet></router-outlet> `, styles: [ ` .spacer { flex: 1 1 auto; } `, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class VerticalLayoutComponent { color = injectToolbarColor(); name = injectAppConfig().name; constructor() { injectGitHubIcon(); } }
from enum import Enum from typing import Optional from pydantic import EmailStr, BaseModel, Field from datetime import datetime class Role(str, Enum): SALESPERSON = "salesperson" ADMIN = "admin" class NewUserSchema(BaseModel): email: EmailStr username: str = Field(min_length=4) password: str = Field(min_length=8) class UserResponseSchema(BaseModel): id: int username: str email: EmailStr role: Role created_at: datetime updated_at: datetime class Config: from_attributes = True class CustomerLoginSchema(BaseModel): username: Optional[str] = None email: Optional[EmailStr] = None password: str
# [621. Task Scheduler](https://leetcode.com/problems/task-scheduler/description/?envType=daily-question&envId=2024-03-19) You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, `n`. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: **identical** tasks must be separated by at least `n` intervals due to cooling time. ​Return the *minimum number* of intervals required to complete all tasks. ## Solutions from Editorial ### Approach 1: Using Priority Queue / Max Heap ```python class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: counter = Counter(tasks) pq = [-f for f in counter.values()] heapify(pq) time = 0 while pq: cycle = n + 1 store = [] task_count = 0 while cycle > 0 and pq: current_freq = -heappop(pq) if current_freq > 1: store.append(-(current_freq - 1)) task_count += 1 cycle -= 1 for x in store: heappush(pq, x) time += task_count if not pq else n + 1 return time ``` 1. We DO NOT need to get an order. Just how long it takes is required. 2. Minimum frequency is first to be taken into consideration. While `cycle` is left, those considered are appended to store decremented by one. 3. `task_count` is kept recorded for `time` in case that task does not endure for full cycle `n + 1`. Otherwise, full cycle `n + 1` is added to `time`. Since priority queue operation have a time complexity of `O(log k)`, `k` being the number of alphabets - 26, the overall time complexity is `O(N * log k) == O(N)`. ### Approach 2: Filling the Slots and Sorting ```python class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: counter = Counter(tasks) freq = [f for f in counter.values()] freq.sort(reverse=True) # this calculates the number of idle slots between tasks of maximum frequency. max_freq = freq[0] - 1 idle_slots = max_freq * n # there're this many of idle slots. # from the second tasks in frequency, fills the idle slots that are left. for f in freq[1:]: idle_slots -= min(max_freq, f) return idle_slots + len(tasks) if idle_slots > 0 else len(tasks) ``` Try with `["A", "A", "B", "B", "C"]` or `["A", "A", "B", "B", "C", "C", "C"]`. With much understanding of the essence of the problem, this approach is contrived. Just astonishing. The time complexity of the algorithm is `O(26 log 26 + N)`, which is `O(N)`. The space complexity is `O(26 + 26)`, so `O(1)`: 26 for storing frequencies, and 26 for sorting(python's built in `sort` method uses Timsort which is a combination of Merge sort and Insertion sort). ### Approach 3: Greedy Approach This approach starts from determining the required number of idle intervals. First, it arranges tasks from those with the highest frequency. ```python class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: counter = [0] * 26 max_val = 0 max_count = 0 for task in tasks: index = ord(task) - ord('A') counter[index] += 1 if max_val == counter[index]: max_count += 1 elif max_val < counter[index]: max_val = counter[index] max_count = 1 part_count = max_val - 1 part_length = n - (max_count - 1) empty_slots = part_count * part_length available_tasks = len(tasks) - max_val * max_count idles = max(0, empty_slots - available_tasks) return len(tasks) + idles ``` This approach is similar to the previous one, but with little bit of tweak. Calculating empty slots and filling it, it ends up with the length of the whole thing. --- There are other approaches and a lot more to learn, but for the time being, I have to leave it as it is, and come back later if there be a chance.
import bcrypt from 'bcrypt'; import { Schema, model } from 'mongoose'; import config from '../../config'; import { TUser, TUserModel } from './user.interface'; const userSchema = new Schema<TUser, TUserModel>( { username: { type: String, required: [true, 'Username is required'], unique: true, trim: true, }, email: { type: String, required: [true, 'Email is required'], unique: true, validate: { validator: (value: string) => { const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(value); }, message: (props) => `${props.value} is not a valid email address`, }, }, password: { type: String, required: [true, 'Password is required'], minlength: [6, 'Password should be at least 6 characters long'], validate: { validator: (value: string) => { // Password must contain at least one letter and one numeric character const passwordRegex = /^(?=.*[a-zA-Z])(?=.*[0-9])/; return passwordRegex.test(value); }, message: () => 'Password should contain at least one letter and one numeric character', }, }, role: { type: String, enum: { values: ['user', 'admin'], message: '{VALUE} is not a valid role. Choose either "user" or "admin".', }, default: 'user', }, lastTwoPasswords: [ { oldPassword: String, changedAt: Date, }, ], }, { timestamps: true, toJSON: { transform(doc, ret) { delete ret.password; delete ret.lastTwoPasswords; }, }, }, ); // hashing the password before saving it to the database userSchema.pre<TUser>('save', async function (next) { this.password = await bcrypt.hash( this.password, Number(config.bcrypt_salt_rounds), ); next(); }); // another layer of making sure that the password is not returned in the response userSchema.post<TUser>('save', function (doc, next) { doc.password = ''; next(); }); //custom static method to check if the user exists or not userSchema.statics.isUserExistsWithUsername = async function ( username: string, ) { const userFoundWithUsername = await UserModel.findOne({ username }); return userFoundWithUsername; }; userSchema.statics.isUserExistsWithEmail = async function (email: string) { const userFoundWithEmail = await UserModel.findOne({ email }); return userFoundWithEmail; }; export const UserModel = model<TUser, TUserModel>('users', userSchema);
package com.example.memories; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.view.LayoutInflater; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.ArrayList; public class AlbumHomeAdapter extends RecyclerView.Adapter<AlbumHomeAdapter.MyView> { private ArrayList<Album> list; private Context context; public class MyView extends RecyclerView.ViewHolder { TextView textView; ImageView imageView; public MyView(View view) { super(view); textView = (TextView) view.findViewById(R.id.albumName); imageView = (ImageView) view.findViewById(R.id.albumImage); } } public AlbumHomeAdapter(Context context, ArrayList<Album> horizontalList) { this.context = context; this.list = horizontalList; } @Override public MyView onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.album_home, parent, false); return new MyView(itemView); } @Override public void onBindViewHolder(final MyView holder, final int position) { holder.textView.setText(list.get(position).getName()); String imageUrl = list.get(position).getImgUrl(); Glide.with(holder.imageView).load(imageUrl).into(holder.imageView); holder.imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, PhotoActivity.class); intent.putExtra("album_id", list.get(holder.getAdapterPosition()).getId()); context.startActivity(intent); } }); } @Override public int getItemCount() { return list.size(); } }
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JPanel.java to edit this template */ package view.panels; import dao.TransactionDao; import java.io.IOException; import java.time.format.DateTimeFormatter; import javax.swing.JFrame; import javax.swing.JOptionPane; import models.Transaction; import view.AddProductPopup; import view.AddPurchasePopup; import view.AddSalePopup; import view.TransactionDetailsPopup; /** * * @author silva */ public class TransactionsPanel extends javax.swing.JPanel { private final TransactionDao dao; private Object[][] data; private final String[] columnNames = {"Código", "Valor (R$)", "Tipo", "Data"}; public TransactionsPanel() { initComponents(); this.dao = new TransactionDao(); updateTable(); } public void updateTable(){ getData(); table.setModel(new javax.swing.table.DefaultTableModel(data, columnNames) { @Override public boolean isCellEditable(int row, int column) { return false; } }); table.getTableHeader().setReorderingAllowed(false); table.repaint(); table.revalidate(); } private Transaction getSelectedTransaction(){ int i = table.getSelectedRow(); if(i != -1){ int code = (int) table.getValueAt(i, 0); return dao.getTransaction(code); } else{ JOptionPane.showMessageDialog(null, "Nenhum produto selecionado."); return null; } } private void getData(){ try{ dao.load(); } catch (ClassNotFoundException | IOException ex) { JOptionPane.showMessageDialog(null, "Não foi possível carregar as transações."); System.out.println(ex); } var transactions = dao.getTransactions(); data = new Object[transactions.size()][4]; int i = 0; for(var t : transactions){ data[i][0] = t.getCode(); data[i][1] = t.getTotalValue(); data[i][2] = t.getType(); data[i][3] = t.getDateTime().format(DateTimeFormatter.ISO_DATE); i++; } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); details = new javax.swing.JButton(); purchase = new javax.swing.JButton(); sale = new javax.swing.JButton(); remove = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); setLayout(new java.awt.BorderLayout()); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); details.setText("Ver Detalhes"); details.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { detailsActionPerformed(evt); } }); jPanel1.add(details); purchase.setText("Adicionar Compra"); purchase.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { purchaseActionPerformed(evt); } }); jPanel1.add(purchase); sale.setText("Adicionar Venda"); sale.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saleActionPerformed(evt); } }); jPanel1.add(sale); remove.setText("Remover"); remove.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeActionPerformed(evt); } }); jPanel1.add(remove); add(jPanel1, java.awt.BorderLayout.PAGE_START); table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Código", "Nome", "Preço", "Quantidade" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Float.class, java.lang.Integer.class }; boolean[] canEdit = new boolean [] { false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane2.setViewportView(table); add(jScrollPane2, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void saleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saleActionPerformed var popup = new AddSalePopup(); popup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); popup.setVisible(true); popup.setParent(this); }//GEN-LAST:event_saleActionPerformed private void removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeActionPerformed var transaction = getSelectedTransaction(); if(transaction != null){ int option = JOptionPane.showConfirmDialog(null, "Você tem certeza?", "selecione uma opção", 0); if(option == 0){ try{ if(dao.deleteTransaction(transaction.getCode())){ dao.save(); updateTable(); } else JOptionPane.showMessageDialog(null, "Não foi possível remover a transação."); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Não foi possível remover a transação."); } } } }//GEN-LAST:event_removeActionPerformed private void purchaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_purchaseActionPerformed var popup = new AddPurchasePopup(); popup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); popup.setVisible(true); popup.setParent(this); }//GEN-LAST:event_purchaseActionPerformed private void detailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_detailsActionPerformed var transaction = getSelectedTransaction(); if(transaction != null){ var popup = new TransactionDetailsPopup(); popup.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); popup.setVisible(true); popup.setParent(this); popup.setSelectedTransaction(transaction); popup.updateData(); } }//GEN-LAST:event_detailsActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton details; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton purchase; private javax.swing.JButton remove; private javax.swing.JButton sale; public javax.swing.JTable table; // End of variables declaration//GEN-END:variables }
import {Component, Input, OnInit} from '@angular/core'; import {FormBuilder, FormGroup} from "@angular/forms"; import {NgbActiveModal, NgbDateStruct} from "@ng-bootstrap/ng-bootstrap"; import {catchError, Observable, throwError} from "rxjs"; import {AccountDto, ResponseDto} from "../../../common"; import {AccountTransactionDto} from "../../../common/model/account-transaction-dto"; import {LoadingService} from "../../../common/service/loading.service"; import {MessagesService} from "../../../common/messages/messages.service"; import {AccountBalanceHttpService} from "../../balances/services/account-balance-http.service"; @Component({ selector: 'app-transaction-history', templateUrl: './transaction-history.component.html', styleUrls: ['./transaction-history.component.scss'], providers: [MessagesService, LoadingService] }) export class TransactionHistoryComponent implements OnInit { @Input() data: { dto: AccountDto; }; searchForm: FormGroup; accountsTransactions$: Observable<ResponseDto<AccountTransactionDto[]>>; constructor(public activeModal: NgbActiveModal, public loadingService: LoadingService, private messagesService: MessagesService, private accountBalanceService: AccountBalanceHttpService, private fb: FormBuilder) { } ngOnInit(): void { this.searchForm = this.fb.group({ startDate: null, endDate: null }); } loadTransactions() { const startDateStruct: NgbDateStruct = this.searchForm?.get('startDate')?.value; const endDateStruct: NgbDateStruct = this.searchForm?.get('endDate')?.value; const transactions$ = this.accountBalanceService.getAccountTransactions( this.data.dto.id, `${startDateStruct.year}-${startDateStruct.month}-${startDateStruct.day}`, `${endDateStruct.year}-${endDateStruct.month}-${endDateStruct.day}`) .pipe( catchError(err => { const message = 'Could not Fetch Account Balances'; this.messagesService.showErrors(message); console.log(message, err); return throwError(err); }), ); this.accountsTransactions$ = this.loadingService.showLoaderUntilCompleted(transactions$); } onStartDateSelection(date: NgbDateStruct) { if (date) { this.searchForm.get('startDate')?.setValue(date); } } onEndDateSelection(date: NgbDateStruct) { if (date) { this.searchForm.get('endDate')?.setValue(date); } } }
'use client'; import Link from 'next/link'; import { useRouter } from 'next/navigation'; import React, { useState } from 'react'; import Button from '@/components/ui/Button'; import { handleRequest } from '@/utils/auth-helpers/client'; import { signInWithPassword } from '@/utils/auth-helpers/server'; // Define prop type with allowEmail boolean interface PasswordSignInProps { allowEmail: boolean; redirectMethod: string; } export default function PasswordSignIn({ allowEmail, redirectMethod }: PasswordSignInProps) { const router = redirectMethod === 'client' ? useRouter() : null; const [isSubmitting, setIsSubmitting] = useState(false); const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { setIsSubmitting(true); // Disable the button while the request is being handled await handleRequest(e, signInWithPassword, router); setIsSubmitting(false); }; return ( <div className="my-8"> <form className="mb-4" noValidate onSubmit={(e) => handleSubmit(e)}> <div className="grid gap-2"> <div className="grid gap-1"> <label htmlFor="email">Email</label> <input autoCapitalize="none" autoComplete="email" autoCorrect="off" className="w-full p-3 rounded-md bg-zinc-800" id="email" name="email" placeholder="name@example.com" type="email" /> <label htmlFor="password">Password</label> <input autoComplete="current-password" className="w-full p-3 rounded-md bg-zinc-800" id="password" name="password" placeholder="Password" type="password" /> </div> <Button className="mt-1" loading={isSubmitting} type="submit" variant="slim" > Sign in </Button> </div> </form> <p> <Link className="font-light text-sm" href="/signin/forgot_password"> Forgot your password? </Link> </p> {allowEmail && ( <p> <Link className="font-light text-sm" href="/signin/email_signin"> Sign in via magic link </Link> </p> )} <p> <Link className="font-light text-sm" href="/signin/signup"> Don't have an account? Sign up </Link> </p> </div> ); }
// // BirthdayView.swift // Disco // // Created by Ethan McRae on 7/27/23. // import SwiftUI struct BirthdayView: View { @Environment(\.presentationMode) var presentationMode @State private var name = "" @State private var date = Date() var onComplete: (String, Date) -> Void = { _,_ in } var body: some View { NavigationView { Form { TextField("Name", text: $name) DatePicker("Date", selection: $date, displayedComponents: .date) } .navigationBarTitle("Add a birthday", displayMode: .inline) .navigationBarItems( leading: Button("Cancel") { presentationMode.wrappedValue.dismiss() }, trailing: Button("Done") { guard !name.isEmpty else { return } onComplete(name, date) presentationMode.wrappedValue.dismiss() } ) } } } struct BirthdayView_Previews: PreviewProvider { static var previews: some View { BirthdayView() } }
import { NgModule, InjectionToken } from "@angular/core"; import { RouterModule, Routes, ActivatedRouteSnapshot } from "@angular/router"; import { TestSiteComponent } from "../app/test-site/test-site.component"; import { AboutComponent } from "../app/about/about.component"; import { LearnMoreComponent } from "../app/learn-more/learn-more.component"; import { TermsOfUseComponent } from "../app/terms-of-use/terms-of-use.component"; const externalUrlProvider = new InjectionToken("externalUrlRedirectResolver"); const routes: Routes = [ { path: "", component: TestSiteComponent }, { path: "LearnMore", component: LearnMoreComponent }, { path: "About", component: AboutComponent }, { path: "TermsOfUse", component: TermsOfUseComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { useHash: false, anchorScrolling: "enabled", initialNavigation: "enabled" }) ], exports: [RouterModule], providers: [ { provide: externalUrlProvider, useValue: (routeSnapshot: ActivatedRouteSnapshot) => { const externalUrl = routeSnapshot.paramMap.get("externalUrl"); window.open(externalUrl as string, "_self"); } } ] }) export class AppRoutingModule {}
<template> <div class="main"> <div class="desc"> {{ hitokoto }} </div> <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit"> <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"> <a-tab-pane key="tab1" tab="开始起航"> <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" message="账户或密码错误" /> <a-form-item> <a-input size="large" type="text" placeholder="请输入管理员账户" v-decorator="[ 'account', {rules: [{ required: true, message: '请输入帐户名' }], validateTrigger: 'blur'} ]" > <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" /> </a-input> </a-form-item> <a-form-item> <a-input size="large" type="password" autocomplete="false" placeholder="请输入密码" v-decorator="[ 'password', {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'} ]" > <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" /> </a-input> </a-form-item> </a-tab-pane> </a-tabs> <a-form-item style="margin-top:24px"> <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="state.loginBtn" :disabled="state.loginBtn">登录</a-button> </a-form-item> </a-form> <two-step-captcha v-if="requiredTwoStepCaptcha" :visible="stepCaptchaVisible" @success="stepCaptchaSuccess" @cancel="stepCaptchaCancel"></two-step-captcha> </div> </template> <script> import { mapActions } from 'vuex' import { timeFix } from '@/utils/util' import { getHitokoto } from '@/api/tools' export default { components: {}, data() { return { customActiveKey: 'tab1', loginBtn: false, isLoginError: false, requiredTwoStepCaptcha: false, stepCaptchaVisible: false, form: this.$form.createForm(this), state: { time: 60, loginBtn: false, smsSendBtn: false }, hitokoto: '' } }, created () { getHitokoto('c=d').then(res => { this.hitokoto = res.hitokoto }) }, methods: { ...mapActions(['Login', 'Logout']), // handler handleSubmit(e) { e.preventDefault() const { form: { validateFields }, state, Login } = this state.loginBtn = true const validateFieldsKey = ['account', 'password'] validateFields(validateFieldsKey, { force: true }, (err, values) => { if (!err) { const loginParams = { ...values } Login(loginParams) .then(res => this.loginSuccess(res)) .catch(err => this.requestFailed(err)) .finally(() => { state.loginBtn = false }) } else { setTimeout(() => { state.loginBtn = false }, 600) } }) }, // 登录成功 loginSuccess(res) { this.isLoginError = false this.$router.push({ path: '/' }) // 延迟 1 秒显示欢迎信息 setTimeout(() => { this.$notification.success({ message: '欢迎', description: `${timeFix()},欢迎回来` }) }, 1000) }, requestFailed() { this.isLoginError = true } } } </script> <style lang="less" scoped> .user-layout-login { label { font-size: 14px; } .getCaptcha { display: block; width: 100%; height: 40px; } .forge-password { font-size: 14px; } button.login-button { padding: 0 15px; font-size: 16px; height: 40px; width: 100%; } .user-login-other { text-align: left; margin-top: 24px; line-height: 22px; .item-icon { font-size: 24px; color: rgba(0, 0, 0, 0.2); margin-left: 16px; vertical-align: middle; cursor: pointer; transition: color 0.3s; &:hover { color: #1890ff; } } .register { float: right; } } } .desc { display: flex; margin-top: 20px; margin-bottom: 20px; justify-content: center; } </style>
import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {Router} from "@angular/router"; import * as queryString from 'query-string'; import {environment} from "../../../../../environments/environment"; import {AuthService} from '../../services/auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'] }) export class LoginComponent implements OnInit { public form !: FormGroup; public errorWithSignIn: string = ''; constructor( private formBuilder: FormBuilder, private auth: AuthService, private router: Router ) { } ngOnInit(): void { this.form = this.formBuilder.group({ email: ['vitaliy@test.com', [Validators.required, Validators.email]], password: ['123456', [Validators.required, Validators.minLength(6)]] }); if (this.auth.currentUserValue) { this.router.navigate(['/study-sets']); } this.getInfoAboutUrl(); } private getInfoAboutUrl() { const urlParams = queryString.parse(window.location.search); if (Object.keys(urlParams).length) { const code = <string>urlParams['code']; if (urlParams['scope']) { this.doSignInWithGoogle(code); } else { this.doSignInWithFacebook(code); } } } signIn(): void { if (this.form.valid) { const email = this.form.controls['email'].value; const password = this.form.controls['password'].value; this.auth.doSignIn(email, password).subscribe({ next : () => { localStorage.setItem('confirm', JSON.stringify(true)); this.router.navigate(['/study-sets']); }, error: error => { this.errorWithSignIn = error.message; } }); } } doSignInWithGoogle(code: string): void { this.auth.doSignInWithGoogle(code).subscribe({ next: () => { localStorage.setItem('confirm', JSON.stringify(true)); this.router.navigate(['/study-sets']); }, error: error => { console.log(error); } }); } doSignInWithFacebook(code: string): void { this.auth.doSignInWithFacebook(code).subscribe({ next: () => { localStorage.setItem('confirm', JSON.stringify(true)); this.router.navigate(['/study-sets']); }, error: error => { console.log(error); } }); } getGoogleLink(): void { const stringParamsForGoogle = queryString.stringify({ client_id: environment.google.google_client_id, redirect_uri: environment.google.google_redirect_url, scope: [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', ].join(' '), response_type: 'code', access_type: 'offline', prompt: 'consent', }); const link = document.createElement('a'); link.href = `${environment.google.google_auth_url}?${stringParamsForGoogle}`; link.click(); } getFacebookLink(): void { const stringParamsForFacebook = queryString.stringify({ client_id: environment.facebook.facebook_client_id, redirect_uri: environment.facebook.facebook_redirect_url, scope: ['email', 'user_friends'].join(','), response_type: 'code', auth_type: 'rerequest', display: 'popup', }); const link = document.createElement('a'); link.href = `${environment.facebook.facebook_auth_url}?${stringParamsForFacebook}`; link.click(); } errorHandling = (control: string, error: string) => { return this.form.controls[control].hasError(error); }; checkChange(control: string) { const field = this.form.controls[control]; if (!field.value) { field.markAsUntouched(); } } }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import {RouterModule, Routes} from "@angular/router"; import {StudentCreateComponent} from "./student-create/student-create.component"; import {StudentListComponent} from "./student-list/student-list.component"; import {StudentDetailComponent} from "./student-detail/student-detail.component"; import {StudentComponent} from "./student.component"; const routes: Routes = [ // {path:"student/create", component: StudentCreateComponent}, // {path:"student",component:StudentListComponent}, {path:"",component:StudentListComponent}, // {path:"student/detail/:name",component: StudentDetailComponent} { path: "student", component: StudentComponent, children: [ {path:"",component:StudentListComponent}, {path: "create", component: StudentCreateComponent}, {path: "detail/:name", component: StudentDetailComponent} ] } ] @NgModule({ declarations: [], imports: [ CommonModule, RouterModule.forChild(routes) ] }) export class StudentRoutingModule { }
************************Looping Techniques in Python************************* 1) ---Using enumerate()------- for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']): print(key, value) ---------<Output>---------- 0 The 1 Big 2 Bang 3 Theory 2) -----Using zip()----- questions = ['name', 'colour', 'shape'] answers = ['apple', 'red', 'a circle'] for question, answer in zip(questions, answers): print('What is your {0}? I am {1}.'.format(question, answer)) ---------<Output>---------- What is your name? I am apple. What is your color? I am red. What is your shape? I am a circle. 3) ------Using iteritem()-------- d = { "geeks" : "for", "only" : "geeks" } print ("The key value pair using iteritems is : ") for i,j in d.items(): print i,j -------<Output>--------- The key value pair using items is : geeks for only geeks king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya', 'Modi' : 'The Changer'} # using items to print the dictionary key-value pair for key, value in king.items(): print(key, value) -------<Output>--------- Akbar The Great Modi The Changer Chandragupta The Maurya 4) -------Using sorted() and set()---------- lis = [ 1 , 3, 5, 6, 2, 1, 3 ] # using sorted() to print the list in sorted order print ("The list in sorted order is : ") for i in sorted(lis) : print (i,end=" ") print () print ("The list in sorted order (without duplicates) is : ") for i in sorted(set(lis)) : print (i,end=" ") -------<Output>------- The list in sorted order is : 1 1 2 3 3 5 6 The list in sorted order (without duplicates) is : 1 2 3 5 6 5) --------Using reversed()------- lis = [ 1 , 3, 5, 6, 2, 1, 3 ] print ("The list in reversed order is : ") for i in reversed(lis) : print (i,end=" ") -------<Output>------- The list in reversed order is : 3 1 2 6 5 3 1
/* * Copyright 2022 Evgenii Plugatar * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.plugatar.xteps.unchecked.chain.impl; import com.plugatar.xteps.base.ExceptionHandler; import com.plugatar.xteps.base.HooksContainer; import com.plugatar.xteps.base.HooksOrder; import com.plugatar.xteps.base.StepReporter; import com.plugatar.xteps.base.ThrowingConsumer; import com.plugatar.xteps.base.ThrowingFunction; import com.plugatar.xteps.base.ThrowingRunnable; import com.plugatar.xteps.base.ThrowingSupplier; import com.plugatar.xteps.base.XtepsException; import com.plugatar.xteps.base.hook.ThreadHooks; import com.plugatar.xteps.unchecked.chain.CtxSC; import com.plugatar.xteps.unchecked.chain.MemNoCtxSC; import com.plugatar.xteps.unchecked.chain.base.BaseCtxSC; import com.plugatar.xteps.unchecked.stepobject.RunnableStep; import com.plugatar.xteps.unchecked.stepobject.SupplierStep; import static com.plugatar.xteps.base.HookPriority.MAX_HOOK_PRIORITY; import static com.plugatar.xteps.base.HookPriority.MIN_HOOK_PRIORITY; import static com.plugatar.xteps.base.HookPriority.NORM_HOOK_PRIORITY; import static com.plugatar.xteps.unchecked.chain.impl.StepsChainUtils.sneakyThrow; /** * Memorizing no context steps chain implementation. * * @param <PS> the previous context steps chain type */ public class MemNoCtxSCOf<PS extends BaseCtxSC<PS>> implements MemNoCtxSC<PS> { private final StepReporter stepReporter; private final ExceptionHandler exceptionHandler; private final HooksContainer hooksContainer; private final PS previousStepsChain; /** * Ctor. * * @param stepReporter the step reporter * @param exceptionHandler the exception handler * @param hooksContainer the hooks container * @param previousStepsChain the previous steps chain * @throws NullPointerException if {@code stepReporter} or {@code exceptionHandler} * or {@code hooksContainer} or {@code previousStepsChain} is null */ public MemNoCtxSCOf(final StepReporter stepReporter, final ExceptionHandler exceptionHandler, final HooksContainer hooksContainer, final PS previousStepsChain) { if (stepReporter == null) { throw new NullPointerException("stepReporter arg is null"); } if (exceptionHandler == null) { throw new NullPointerException("exceptionHandler arg is null"); } if (hooksContainer == null) { throw new NullPointerException("hooksContainer arg is null"); } if (previousStepsChain == null) { throw new NullPointerException("previousStepsChain arg is null"); } this.stepReporter = stepReporter; this.exceptionHandler = exceptionHandler; this.hooksContainer = hooksContainer; this.previousStepsChain = previousStepsChain; } @Override public final MemNoCtxSC<PS> callChainHooks() { try { this.hooksContainer.callHooks(); } catch (final Throwable ex) { this.exceptionHandler.handle(ex); throw ex; } return this; } @Override public final MemNoCtxSC<PS> chainHooksOrder(final HooksOrder order) { if (order == null) { this.throwNullArgException("order"); } this.hooksContainer.setOrder(order); return this; } @Override public final MemNoCtxSC<PS> threadHooksOrder(final HooksOrder order) { if (order == null) { this.throwNullArgException("order"); } ThreadHooks.setOrder(order); return this; } @Override public final MemNoCtxSC<PS> chainHook( final ThrowingRunnable<?> hook ) { return this.chainHook(NORM_HOOK_PRIORITY, hook); } @Override public final MemNoCtxSC<PS> chainHook( final int priority, final ThrowingRunnable<?> hook ) { if (hook == null) { this.throwNullArgException("hook"); } this.checkPriorityArg(priority); this.hooksContainer.addHook(priority, hook); return this; } @Override public final MemNoCtxSC<PS> threadHook( final ThrowingRunnable<?> hook ) { return this.threadHook(NORM_HOOK_PRIORITY, hook); } @Override public final MemNoCtxSC<PS> threadHook( final int priority, final ThrowingRunnable<?> hook ) { if (hook == null) { this.throwNullArgException("hook"); } this.checkPriorityArg(priority); ThreadHooks.addHook(priority, hook); return this; } @Override public final PS previousStepsChain() { return this.previousStepsChain; } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> withCtx(final U context) { return newCtxStepsChain(context); } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> withCtx( final ThrowingSupplier<? extends U, ?> supplier ) { if (supplier == null) { this.throwNullArgException("supplier"); } return this.newCtxStepsChain(this.execAction(supplier)); } @Override public final MemNoCtxSC<PS> action( final ThrowingRunnable<?> action ) { if (action == null) { this.throwNullArgException("action"); } this.execAction(() -> { action.run(); return null; }); return this; } @Override public final <R> R actionTo( final ThrowingSupplier<? extends R, ?> action ) { if (action == null) { this.throwNullArgException("action"); } return this.execAction(action); } @Override public final MemNoCtxSCOf<PS> step(final String name) { return this.step(name, ""); } @Override public final MemNoCtxSCOf<PS> step( final String name, final String desc ) { if (name == null) { this.throwNullArgException("name"); } if (desc == null) { this.throwNullArgException("desc"); } this.reportStep(name, desc, () -> null); return this; } @Override public final MemNoCtxSC<PS> step( final RunnableStep step ) { if (step == null) { this.throwNullArgException("step"); } this.execAction(() -> { step.run(); return null; }); return this; } @Override public final MemNoCtxSC<PS> step( final SupplierStep<?> step ) { if (step == null) { this.throwNullArgException("step"); } this.execAction(step); return this; } @Override public final MemNoCtxSC<PS> step( final String keyword, final RunnableStep step ) { if (keyword == null) { this.throwNullArgException("keyword"); } if (step == null) { this.throwNullArgException("step"); } this.execAction(() -> { step.withKeyword(keyword).run(); return null; }); return this; } @Override public final MemNoCtxSC<PS> step( final String keyword, final SupplierStep<?> step ) { if (keyword == null) { this.throwNullArgException("keyword"); } if (step == null) { this.throwNullArgException("step"); } this.execAction(step.withKeyword(keyword)); return this; } @Override public final MemNoCtxSC<PS> step( final ThrowingRunnable<?> action ) { return this.step("", "", action); } @Override public final MemNoCtxSCOf<PS> step( final String name, final ThrowingRunnable<?> action ) { return this.step(name, "", action); } @Override public final MemNoCtxSCOf<PS> step( final String name, final String desc, final ThrowingRunnable<?> action ) { if (name == null) { this.throwNullArgException("name"); } if (desc == null) { this.throwNullArgException("desc"); } if (action == null) { this.throwNullArgException("action"); } this.reportStep(name, desc, () -> { action.run(); return null; }); return this; } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> stepToCtx( final SupplierStep<? extends U> step ) { if (step == null) { this.throwNullArgException("step"); } return this.newCtxStepsChain(this.execAction(step)); } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> stepToCtx( final String keyword, final SupplierStep<? extends U> step ) { if (keyword == null) { this.throwNullArgException("keyword"); } if (step == null) { this.throwNullArgException("step"); } return this.newCtxStepsChain(this.execAction(step.withKeyword(keyword))); } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> stepToCtx( final ThrowingSupplier<? extends U, ?> action ) { return this.stepToCtx("", "", action); } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> stepToCtx( final String name, final ThrowingSupplier<? extends U, ?> action ) { return this.stepToCtx(name, "", action); } @Override public final <U> CtxSC<U, MemNoCtxSC<PS>> stepToCtx( final String name, final String desc, final ThrowingSupplier<? extends U, ?> action ) { if (name == null) { this.throwNullArgException("name"); } if (desc == null) { this.throwNullArgException("desc"); } if (action == null) { this.throwNullArgException("action"); } return this.newCtxStepsChain(this.reportStep(name, desc, action)); } @Override public final <R> R stepTo( final SupplierStep<? extends R> step ) { if (step == null) { this.throwNullArgException("step"); } return this.execAction(step); } @Override public final <R> R stepTo( final String keyword, final SupplierStep<? extends R> step ) { if (keyword == null) { this.throwNullArgException("keyword"); } if (step == null) { this.throwNullArgException("step"); } return this.execAction(step.withKeyword(keyword)); } @Override public final <R> R stepTo( final ThrowingSupplier<? extends R, ?> action ) { return this.stepTo("", "", action); } @Override public final <R> R stepTo( final String name, final ThrowingSupplier<? extends R, ?> action ) { return this.stepTo(name, "", action); } @Override public final <R> R stepTo( final String name, final String desc, final ThrowingSupplier<? extends R, ?> action ) { if (name == null) { this.throwNullArgException("name"); } if (desc == null) { this.throwNullArgException("desc"); } if (action == null) { this.throwNullArgException("action"); } return this.reportStep(name, desc, action); } @Override public final MemNoCtxSC<PS> nestedSteps( final ThrowingConsumer<MemNoCtxSC<PS>, ?> stepsChain ) { return this.nestedSteps("", "", stepsChain); } @Override public final MemNoCtxSC<PS> nestedSteps( final String name, final ThrowingConsumer<MemNoCtxSC<PS>, ?> stepsChain ) { return this.nestedSteps(name, "", stepsChain); } @Override public final MemNoCtxSC<PS> nestedSteps( final String name, final String desc, final ThrowingConsumer<MemNoCtxSC<PS>, ?> stepsChain ) { if (name == null) { this.throwNullArgException("name"); } if (desc == null) { this.throwNullArgException("desc"); } if (stepsChain == null) { this.throwNullArgException("stepsChain"); } this.reportStep(name, desc, () -> { stepsChain.accept(this); return null; }); return this; } @Override public final <R> R nestedStepsTo( final ThrowingFunction<MemNoCtxSC<PS>, ? extends R, ?> stepsChain ) { return this.nestedStepsTo("", "", stepsChain); } @Override public final <R> R nestedStepsTo( final String name, final ThrowingFunction<MemNoCtxSC<PS>, ? extends R, ?> stepsChain ) { return this.nestedStepsTo(name, "", stepsChain); } @Override public final <R> R nestedStepsTo( final String name, final String desc, final ThrowingFunction<MemNoCtxSC<PS>, ? extends R, ?> stepsChain ) { if (name == null) { this.throwNullArgException("name"); } if (desc == null) { this.throwNullArgException("desc"); } if (stepsChain == null) { this.throwNullArgException("stepsChain"); } return this.reportStep(name, desc, () -> stepsChain.apply(this)); } @Override public final MemNoCtxSC<PS> branchSteps( final ThrowingConsumer<MemNoCtxSC<PS>, ?> stepsChain ) { if (stepsChain == null) { this.throwNullArgException("stepsChain"); } this.execAction(() -> { stepsChain.accept(this); return null; }); return this; } private <R> R reportStep( final String stepName, final String stepDescription, final ThrowingSupplier<R, ?> step ) { return this.stepReporter.report(this.hooksContainer, this.exceptionHandler, stepName, stepDescription, new Object[]{}, ThrowingSupplier.unchecked(step)); } private <R> R execAction( final ThrowingSupplier<R, ?> action ) { try { return action.get(); } catch (final Throwable ex) { this.hooksContainer.callHooks(ex); this.exceptionHandler.handle(ex); throw sneakyThrow(ex); } } private <U> CtxSC<U, MemNoCtxSC<PS>> newCtxStepsChain(final U newContext) { return new CtxSCOf<>(this.stepReporter, this.exceptionHandler, this.hooksContainer, newContext, this); } private void throwNullArgException(final String argName) { final XtepsException baseEx = new XtepsException(argName + " arg is null"); this.hooksContainer.callHooks(baseEx); this.exceptionHandler.handle(baseEx); throw baseEx; } private void checkPriorityArg(final int priority) { if (priority < MIN_HOOK_PRIORITY || priority > MAX_HOOK_PRIORITY) { final XtepsException baseEx = new XtepsException("priority arg not in the range " + MIN_HOOK_PRIORITY + " to " + MAX_HOOK_PRIORITY); this.hooksContainer.callHooks(baseEx); this.exceptionHandler.handle(baseEx); throw baseEx; } } }
import React from 'react' import { useDispatch } from 'react-redux' import { useState } from 'react'; import { loginAction,signupAction } from '../../actions/userActions'; import { useEffect } from 'react'; import { useSelector } from 'react-redux'; import { useNavigate } from 'react-router-dom'; import { VERIFY_EMAIL } from '../../constants/actionTypes'; import "./LoginOrSignupPanel.css" const LoginOrSignupPanel = () => { const dispatch = useDispatch(); const navigate =useNavigate(); const messageStore=useSelector(state=>state.message); function handleLogin(){ dispatch(loginAction(loginData)); } function handleSignup(){ if(document.getElementById("password-input").value!=document.getElementById("password-input-repeat").value) { document.getElementById("signup-message").style.display='block'; document.getElementById("signup-message").innerHTML="The two passwords you typed do not match"; } else { dispatch(signupAction(signupData)); } } const [loginData,setLoginData]=useState({ email:'', password:'' }) const [signupData,setSignupData]=useState({ name:'', email:'', password:'' }) //hide message since the beginning useEffect(()=>{ document.getElementById("signup-message").style.display='none'; document.getElementById("login-message").style.display='none'; },[]); function sendEmail(emailAdress){ console.log("email has been sent to:"+emailAdress); } // set sign up message useEffect(()=>{ if(messageStore){ if(messageStore.operation==="SIGNUP"){ console.log(messageStore); if(messageStore.message){ document.getElementById("signup-message").style.display='block'; document.getElementById("signup-message").innerHTML=messageStore.message; if(messageStore.operationSuccess){ sendEmail(signupData.email); } } } } },[messageStore]) const currentUserStore= useSelector(state=>state.currentUser); useEffect(()=>{ console.log("currentUserStore"); console.log(currentUserStore); if(currentUserStore){ if(currentUserStore.loggedIn){ navigate('/'); } else{ if(currentUserStore.loginErrorMsg){ document.getElementById("login-message").style.display='block'; document.getElementById("login-message").innerHTML=currentUserStore.loginErrorMsg; } } } },[currentUserStore]) return ( <div className="login-register-wrapper pt-40 pb-40"> <div className="container"> <div className="member-area-from-wrap"> <div className="row"> {/* Login Content Start */} <div className="col-lg-6"> <div className="login-reg-form-wrap"> <h2>Log In</h2> {/* <form action="/login" method="post"> */} <p id='login-message'>this is the message section</p> <div className="single-input-item"> <input type="email" name='email' placeholder="Your email" value={loginData.email} onChange={(e)=>setLoginData({...loginData,email:e.target.value})} required /> </div> <div className="single-input-item"> <input type="password" placeholder="Enter your Password" value={loginData.password} onChange={(e)=>setLoginData({...loginData,password:e.target.value})} required /> </div> <div className="single-input-item"> <div className="login-reg-form-meta d-flex align-items-center justify-content-between"> <div className="remember-meta"> <div className="custom-control custom-checkbox"> <input type="checkbox" className="custom-control-input" id="rememberMe" /> <label className="custom-control-label" htmlFor="rememberMe">Remember Me</label> </div> </div> <a href="#" className="forget-pwd">Forget Password?</a> </div> </div> <div className="single-input-item"> <button className="btn btn__bg" onClick={handleLogin}>Login</button> </div> {/* </form> */} </div> </div> {/* Login Content End */} {/* Register Content Start */} <div className="col-lg-6"> <div className="login-reg-form-wrap sign-up-form"> <h2>Sign up </h2> {/* <form action="#" method="post"> */} {/* <form > */} <p id='signup-message'>this is the message section</p> <div className="single-input-item"> <input type="text" placeholder="Enter your Username" value={signupData.name} onChange={(e)=>{setSignupData({...signupData,name:e.target.value})}} required/> </div> <div className="single-input-item"> <input type="email" placeholder="Enter your Email" value={signupData.email} onChange={(e)=>{setSignupData({...signupData,email:e.target.value})}} required /> </div> <div className="row"> <div className="col-lg-6"> <div className="single-input-item"> <input id="password-input" type="password" placeholder="Enter your Password" value={signupData.password} onChange={(e)=>{setSignupData({...signupData,password:e.target.value})}} required /> </div> </div> <div className="col-lg-6"> <div className="single-input-item"> <input id="password-input-repeat" type="password" placeholder="Repeat your Password" required /> </div> </div> </div> <div className="single-input-item"> <div className="login-reg-form-meta"> <div className="remember-meta"> <div className="custom-control custom-checkbox"> <input type="checkbox" className="custom-control-input" id="subnewsletter" /> <label className="custom-control-label" htmlFor="subnewsletter">Subscribe Our Newsletter</label> </div> </div> </div> </div> <div className="single-input-item"> <button className="btn btn__bg" onClick={handleSignup}>Register</button> </div> {/* </form> */} </div> </div> {/* Register Content End */} </div> </div> </div> </div> ) } export default LoginOrSignupPanel
# cache-manager I guess coming from a Laravel background I enjoyed/am used to using their syntax for interacting with cache and wanted to continue that in the browser/Node. Current drivers out of the box are (simply because these are the ones I use): - Plain object (browser/server) - Map (browser/server) - Local storage (browser) - Session storage (browser) - Redis (server) Any others you'll have to write yourself, feel free to open a PR if you want to have another provider included. ## Installation Create/add registry scope to your `.npmrc` file. ``` @jaspargupta:registry=https://npm.pkg.github.com/ ``` Install the package via `npm`. ``` npm i @jaspargupta/cache-manager ``` ## Usage ```typescript // cache.ts import register from '@jaspargupta/cache-manager'; import PlainObjectDriver from '@jaspargupta/cache-manager/dist/drivers/plain-object'; import MapDriver from '@jaspargupta/cache-manager/dist/drivers/map'; import StorageDriver from './@jaspargupta/cache-manager/dist/drivers/storage'; /** * Create your cache manager by registering cache drivers. * Set the default driver as the second argument. */ const cache = register({ main: new PlainObjectDriver(), secondary: new PlainObjectDriver(), map: new MapDriver(), localStorage: new StorageDriver(window.localStorage), sessionStorage: new StorageDriver(window.sessionStorage), }, 'main'); export default cache; ``` ```typescript // example.ts import insufferablySlowFunction from 'third-party'; import addHours from 'date-fns/addHours'; import cache from './cache'; // Cache result indefinitely. const standard = cache().remember('cache.key', () => { return insufferablySlowFunction(); }); // Cache result for 24 hours. const expires = cache().remember('cache.key', () => { return insufferablySlowFunction(); }, addHours(Date.now(), 24)); // Cache result indefinitely using secondary driver. const swapDriver = cache('secondary').remember('cache.key', () => { return insufferablySlowFunction(); }); // Supports `async` callbacks. const asynchrounous = await cache().remember('cache.key', async () => { return insufferablySlowFunction(); }); ``` ### [Config](./src/drivers/types/config.ts) You can pass optional config to your cache drivers. - `prefix` allows you to prefix your cache keys with the given value. By default it will place a dot (`.`) between the given prefix and the cache key. This will automatically be overridden if your prefix ends with a non-alphanumeric character. ``` // Config: { prefix: 'foo' } cache().put('bar', true); // => Cached under "foo.bar" // Config: { prefix: 'foo-' } cache().put('bar', true); // => Cached under "foo-bar" ``` - `ttl` allows you to set a default cache time. By default all keys are cached indefinitely. It will accept either a `number` which represents the amount of seconds the key will be cached for. Or it will accept a `callback` which must return a `Date` instance of the time of expiration. ``` // Config: { ttl: 1000 * 60 * 5 } => Cache everything by default for 5 minutes. // Config: { ttl: () => endOfToday() } => Use date-fns function to cache everything by default until the end of the current day. ``` ## `RedisDriver` If you want to use the `RedisDriver` you'll have to `npm i redis` and create a [redis](https://www.npmjs.com/package/redis) client to pass to the driver yourself. ```typescript import { createClient } from 'redis'; import RedisDriver from '@jaspargupta/cache-manager/dist/drivers/redis'; const client = createClient(); const redisDriver = new RedisDriver(client); ``` ## Writing your own drivers. Each driver extends the `CacheDriver` base class, write the implementation for each of the abstract methods and voila! ```typescript // my-cache-driver.ts import CacheDriver from '@jaspargupta/cache-manager/dist/drivers/driver'; export default class MyCacheDriver extends CacheDriver { public flush() { // 🚽 } public get() { // 🫱 } public put() { // ⛳️ } public remove() { // 🗑 } } // cache.ts const cache = register({ main: new MyCacheDriver(), }, 'main'); export default cache; ``` ## API ### `register` function ``` const cache = register(drivers: Record<string, CacheDriver>, defaultDriver: string): (driver: string) => CacheDriver; ``` ### `CacheDriver` instance | Method | Description | |-------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------| | `driver.api()` | Returns the underlying cache API. | | `driver.decrement(key, count)` | Decrement the cache value. Optionally provide the amount to increment by. Sets cache to `0` if cache doesn't already exist. | | `driver.flush()` | Removed all cached items. | | `driver.get(key, fallback)` | Retrieves a cached item by the provided key. Optionally provide default value if no cache is found. | | `driver.has(key)` | Returns whether cache exists. | | `driver.increment(key, count)` | Increment the cache value. Optionally provide the amount to increment by. Sets cache to `0` if cache doesn't already exist. | | `driver.put(key, value, expires)` | Store an item in the cache. Optionally set expires at argument. | | `driver.remember(key, callback, expires)` | Stores the return value of the callback in the cache for the provided key. Optionally set expires at argument. Supports async callbacks. | | `driver.remove(key)` | Remove a cached item for the provided key. |
@webUI @insulated @disablePreviews @email Feature: add users As a subadmin I want to add users So that unauthorised access is impossible Background: Given these users have been created with default attributes and without skeleton files: | username | | Alice | And group "grp1" has been created And user "Alice" has been added to group "grp1" And user "Alice" has been made a subadmin of group "grp1" And user "Alice" has logged in using the webUI And the user has browsed to the users page Scenario: a subadmin uses the webUI to create a simple user When the subadmin creates a user with the name "guiusr1" and the password "%regular%" using the webUI And the user logs out of the webUI And user "guiusr1" logs in using the webUI Then the user should be redirected to a webUI page with the title "Files - %productname%" @skipOnLDAP Scenario: a subadmin uses the webUI to create a simple user with an Email address but without a password When the subadmin creates a user with the name "guiusr1" and the email "guiusr1@owncloud" without a password using the webUI Then the email address "guiusr1@owncloud" should have received an email with the body containing """ just letting you know that you now have an %productname% account. Your username: guiusr1 Access it: """ @skipOnLDAP Scenario: user sets his own password after being created with an Email address only by a subadmin When the subadmin creates a user with the name "guiusr1" and the email "guiusr1@owncloud" without a password using the webUI And the user logs out of the webUI And the user follows the password set link received by "guiusr1@owncloud" using the webUI And the user sets the password to "%regular%" and confirms with the same password using the webUI Then the user should be redirected to the login page And the email address "guiusr1@owncloud" should have received an email with the body containing """ Password changed successfully """ When the user logs in with username "guiusr1" and password "%regular%" using the webUI Then the user should be redirected to a webUI page with the title "Files - %productname%" @skipOnLDAP Scenario: user sets his own password after being created with an Email address only and invitation link resent by a subadmin When the subadmin creates a user with the name "guiusr1" and the email "guiusr1@owncloud" without a password using the webUI And the subadmin resends the invitation email for user "guiusr1" using the webUI And the user logs out of the webUI And the user follows the password set link received by "guiusr1@owncloud" in Email number 2 using the webUI Then the user should see an error message saying "The token provided is invalid." And the user follows the password set link received by "guiusr1@owncloud" in Email number 1 using the webUI And the user sets the password to "%regular%" and confirms with the same password using the webUI And the user should be redirected to the login page And the email address "guiusr1@owncloud" should have received an email with the body containing """ Password changed successfully """ When the user logs in with username "guiusr1" and password "%regular%" using the webUI Then the user should be redirected to a webUI page with the title "Files - %productname%"
import { Test } from '@nestjs/testing'; import { INestApplication, ValidationPipe } from '@nestjs/common'; import * as request from 'supertest'; import { Repository } from 'typeorm'; import { getRepositoryToken, TypeOrmModule } from '@nestjs/typeorm'; import { randomUUID } from 'crypto'; import { CardTagController } from '../src/cards/cardtag/cardtag.controller'; import { CardTagService } from '../src/cards/cardtag/cardtag.service'; import { CardTag } from '../src/cards/cardtag/cardtag.entity'; import { CardTagModule } from '../src/cards/cardtag/cardtag.module'; describe('CardTagController (e2e)', () => { let app: INestApplication; let controller: CardTagController; let service: CardTagService; let repository: Repository<CardTag>; const mockRepository = { find: jest.fn(() => Promise.resolve([])), create: jest.fn((dto) => dto), save: jest.fn((dto) => Promise.resolve({ id: randomUUID(), ...dto, }), ), }; beforeAll(async () => { const moduleRef = await Test.createTestingModule({ imports: [CardTagModule, TypeOrmModule.forFeature([CardTag])], }) .overrideProvider(getRepositoryToken(CardTag)) .useValue(mockRepository) .compile(); app = moduleRef.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true })); await app.init(); repository = moduleRef.get(getRepositoryToken(CardTag)); service = new CardTagService(repository); controller = new CardTagController(service); }); it('/cardtags (GET)', async () => { return request(app.getHttpServer()) .get('/cardtags') .expect('Content-type', /json/) .expect(200) .expect(await controller.findAll()); }); it('/cardtags (POST)', () => { const dto = { fr_name: 'tester', en_name: 'test', }; return request(app.getHttpServer()) .post('/cardtags') .send(dto) .expect('Content-type', /json/) .expect(201) .then((response) => { expect(response.body).toEqual({ id: expect.stringMatching( /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i, ), ...dto, }); }); }); it('/cardtags (POST) --> Validation Error en_name is empty', () => { const dto = { fr_name: 'test', }; return request(app.getHttpServer()) .post('/cardtags') .send(dto) .expect('Content-type', /json/) .expect(400) .then((response) => { expect(response.body.message).toContain('en_name should not be empty'); }); }); it('/cardtags (POST) --> Validation Error en_name is not a string', () => { const dto = { fr_name: 'test', en_name: 123, }; return request(app.getHttpServer()) .post('/cardtags') .send(dto) .expect('Content-type', /json/) .expect(400) .then((response) => { expect(response.body.message).toContain('en_name must be a string'); }); }); it('/cardtags (POST) --> Validation Error fr_name is empty', () => { const dto = { en_name: 'test', }; return request(app.getHttpServer()) .post('/cardtags') .send(dto) .expect('Content-type', /json/) .expect(400) .then((response) => { expect(response.body.message).toContain('fr_name should not be empty'); }); }); it('/cardtags (POST) --> Validation Error fr_name is not a string', () => { const dto = { fr_name: 123, en_name: 'test', }; return request(app.getHttpServer()) .post('/cardtags') .send(dto) .expect('Content-type', /json/) .expect(400) .then((response) => { expect(response.body.message).toContain('fr_name must be a string'); }); }); });
package toy.board.service.comment; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*; import jakarta.persistence.EntityManager; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import toy.board.domain.post.Comment; import toy.board.domain.post.CommentType; import toy.board.domain.post.Post; import toy.board.domain.user.Member; import toy.board.domain.user.MemberTest; import toy.board.exception.BusinessException; import toy.board.exception.ExceptionCode; @SpringBootTest @Transactional class CommentServiceTest { @Autowired private EntityManager em; @Autowired private CommentService commentService; private Long memberId; private Post post; private String nickname; private String content = "content"; private String title = "title"; @BeforeEach void init() { Member member = MemberTest.create(); em.persist(member); memberId = member.getId(); nickname = member.getProfile().getNickname(); Post newPost = new Post(member.getId(), nickname, title, content); em.persist(newPost); post = newPost; em.flush(); em.clear(); } //create @DisplayName("create 성공") @Test public void create_success() throws Exception { //given Optional parentId = Optional.empty(); Long postId = post.getId(); Long memberId = this.memberId; //when Long commentId = commentService.create(content, CommentType.COMMENT, parentId, postId, memberId); Long replyId = commentService.create(content, CommentType.REPLY, Optional.of(commentId), postId, memberId); Comment comment = em.find(Comment.class, commentId); Comment reply = em.find(Comment.class, replyId); //then assertThat(comment).isNotNull(); assertThat(reply).isNotNull(); assertThat(comment).isEqualTo(reply.getParent()); assertThat(comment.getReplies().contains(reply)).isTrue(); } @DisplayName("create 실패: post id에 맞는 post가 존재하지 않음") @Test public void whenTryToCreateWithNotExistPostId_thenThrowException() throws Exception { //given Optional parentId = Optional.empty(); Long memberId = this.memberId; //when Long invalidPostId = 12132L; //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.create(content, CommentType.COMMENT, parentId, invalidPostId, memberId)); assertThat(e.getCode()).isEqualTo(ExceptionCode.POST_NOT_FOUND); } @DisplayName("create 실패: memberId에 맞는 회원 닉네임이 존재하지 않음") @Test public void whenTryToCreateWithNotExistMemberId_thenThrowException() throws Exception { //given Optional parentId = Optional.empty(); Long postId = post.getId(); //when Long invalidMemberId = 2243L; //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.create(content, CommentType.COMMENT, parentId, postId, invalidMemberId)); assertThat(e.getCode()).isEqualTo(ExceptionCode.ACCOUNT_NOT_FOUND); } @DisplayName("create 실패: 대댓글 생성 시 주어진 CommentId에 해당하는 Comment가 존재하지 않음") @Test public void whenTryToCreateWithNotExistComment_thenThrowException() throws Exception { //given Optional parentId = Optional.of(21342L); Long postId = post.getId(); Long memberId = this.memberId; //when //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.create(content, CommentType.COMMENT, parentId, postId, memberId)); assertThat(e.getCode()).isEqualTo(ExceptionCode.COMMENT_NOT_FOUND); } @DisplayName("create 실패: 대댓글 생성 시 주어진 CommentId가 NULL임") @Test public void CommentServiceTest() throws Exception { //given Optional parentId = Optional.empty(); Long postId = post.getId(); Long memberId = this.memberId; //when //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.create(content, CommentType.REPLY, parentId, postId, memberId)); assertThat(e.getCode()).isEqualTo(ExceptionCode.NULL_COMMENT); } // update @DisplayName("update 성공") @Test public void update_success() throws Exception { //given Long commentId = createComment(); String updateContent = "update comment"; //when Long updatedCommentId = commentService.update(commentId, updateContent, memberId); Comment findComment = em.find(Comment.class, updatedCommentId); //then assertThat(findComment.getId()).isEqualTo(commentId); assertThat(findComment.getContent()).isEqualTo(updateContent); } @DisplayName("update 실패: member가 수정 권한 없음") @Test public void whenMemberHasNoRightForUpdate_thenThrowException() throws Exception { //given Long commentId = createComment(); String updateContent = "update comment"; //when Long noRightMember = 234L; //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.update(commentId, updateContent, noRightMember)); assertThat(e.getCode()).isEqualTo(ExceptionCode.COMMENT_NOT_WRITER); } @DisplayName("update 실패: comment id에 해당하는 comment가 없음") @Test public void whenCommentNotExist_thenThrowException() throws Exception { //given String updateContent = "update comment"; //when Long invalidCommentId = 234L; //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.update(invalidCommentId, updateContent, memberId)); assertThat(e.getCode()).isEqualTo(ExceptionCode.COMMENT_NOT_FOUND); } // delete @DisplayName("delete 성공") @Test public void delete_success() throws Exception { //given Long commentId = createComment(); Long memberId = this.memberId; //when commentService.delete(commentId, memberId); Comment findComment = em.find(Comment.class, commentId); //then assertThat(findComment.isDeleted()).isTrue(); } @DisplayName("delete 실패: member가 삭제 권한 없음") @Test public void whenMemberHasNoRightForDelete_thenThrowException() throws Exception { //given Long commentId = createComment(); //when Long noRightMember = 234L; //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.delete(commentId, noRightMember)); assertThat(e.getCode()).isEqualTo(ExceptionCode.COMMENT_NOT_WRITER); } @DisplayName("delete 실패: comment id에 해당하는 comment가 없음") @Test public void whenCommentNotExistToDelete_thenThrowException() throws Exception { //given //when Long invalidCommentId = 234L; //then BusinessException e = assertThrows(BusinessException.class, () -> commentService.delete(invalidCommentId, memberId)); assertThat(e.getCode()).isEqualTo(ExceptionCode.COMMENT_NOT_FOUND); } private Long createComment() { Optional parentId = Optional.empty(); Long postId = post.getId(); Long memberId = this.memberId; return commentService.create(content, CommentType.COMMENT, parentId, postId, memberId); } }
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class NoisyLinear(nn.Module): def __init__(self, in_features, out_features, sigma_init=0.017): super(NoisyLinear, self).__init__() self.in_features = in_features self.out_features = out_features self.sigma_init = sigma_init self.weight_mu = nn.Parameter(torch.Tensor(out_features, in_features)) self.weight_sigma = nn.Parameter(torch.Tensor(out_features, in_features)) self.register_buffer('weight_epsilon', torch.Tensor(out_features, in_features)) self.bias_mu = nn.Parameter(torch.Tensor(out_features)) self.bias_sigma = nn.Parameter(torch.Tensor(out_features)) self.register_buffer('bias_epsilon', torch.Tensor(out_features)) self.reset_parameters() def reset_parameters(self): mu_range = 1 / self.in_features ** 0.5 self.weight_mu.data.uniform_(-mu_range, mu_range) self.weight_sigma.data.fill_(self.sigma_init) self.bias_mu.data.uniform_(-mu_range, mu_range) self.bias_sigma.data.fill_(self.sigma_init) def forward(self, input): if self.training: weight = self.weight_mu + self.weight_sigma * self.weight_epsilon.normal_() bias = self.bias_mu + self.bias_sigma * self.bias_epsilon.normal_() else: weight = self.weight_mu bias = self.bias_mu return F.linear(input, weight, bias) class DQN(nn.Module): def __init__(self, layers, n_actions, n, m): super(DQN, self).__init__() self.conv1 = nn.Conv2d(layers, 16, 5, padding=2) self.conv2 = nn.Conv2d(16, 32, 3, padding=1) self.noisy_linear1 = NoisyLinear(32 * n * m, 256) self.noisy_linear2 = NoisyLinear(256, n_actions) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = torch.flatten(x, 1) x = F.relu(self.noisy_linear1(x)) x = self.noisy_linear2(x) return x
import React from 'react' import { LoadingButton } from '@mui/lab'; import { Alert, Box, Button, Stack, TextField } from '@mui/material'; import { useFormik } from 'formik'; import { useState } from 'react'; import { useDispatch } from 'react-redux'; import { toast } from 'react-toastify'; import * as Yup from 'yup'; import userApi from "../../api/modules/user.api"; import { setAuthModalOpen } from '../../redux/features/authModalSlice'; import { setUser } from '../../redux/features/userSlice'; const LoginForm = ({ switchAuthState }) => { const dispatch = useDispatch(); const [isLoginRequest, setIsLoginRequest] = useState(false); const [errorMessage, setErrorMessage] = useState(); const loginForm = useFormik({ initialValues: { password: "", username: "" }, validationSchema: Yup.object({ username: Yup.string() .min(8, "Username minimum 8 characters") .required("Username is required"), password: Yup.string() .min(8, "Password minimum 8 characters") .required("Password is required") }), onSubmit: async values => { setErrorMessage(undefined); setIsLoginRequest(true); const { response, err } = await userApi.signin(values); setIsLoginRequest(false); if (response) { loginForm.resetForm(); dispatch(setUser(response)); dispatch(setAuthModalOpen(false)); toast.success("Login Successfully !"); } if (err) setErrorMessage(err.message); } }) return ( <Box component={"form"} onSubmit={loginForm.handleSubmit} > <Stack spacing={3}> <TextField type='text' placeholder='Enter your username' name='username' fullWidth value={loginForm.values.username} onChange={loginForm.handleChange} color='success' error={loginForm.touched.username && loginForm.errors.username !== undefined} helperText={loginForm.touched.username && loginForm.errors.username} > </TextField> <TextField type='password' placeholder='Enter your password' name='password' fullWidth value={loginForm.values.password} onChange={loginForm.handleChange} color='success' error={loginForm.touched.password && loginForm.errors.password !== undefined} helperText={loginForm.touched.password && loginForm.errors.password} > </TextField> </Stack> <LoadingButton type='submit' fullWidth size='large' variant='contained' sx={{ marginTop: 4 }} loading={isLoginRequest} > Log In </LoadingButton> <Button fullWidth sx={{ marginTop: 1 }} onClick={() => switchAuthState()} > Sign Up </Button> {errorMessage && ( <Box sx={{ marginTop: 2 }}> <Alert severity='error' variant='outlined'>{errorMessage}</Alert> </Box> )} </Box> ) } export default LoginForm;
import axios from "axios"; import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { BasePath } from "../utils/BasePathApi"; import { peliculaDetalle } from "./PeliculasModelD"; import "./PeliculaDetalle.css"; import { generoModelConId } from "./generos/GeneroModel"; import Button from "../utils/Button"; import moment from "moment"; import "moment/locale/es"; // without this line it didn't work import Rating from "../utils/Rating"; import { toast } from "react-toastify"; moment.locale("es"); export default function DetallePelicula() { var fecha = moment.locale("es"); const { id } = useParams(); const [pelicula, setPelicula] = useState<peliculaDetalle>(); const [generos, setGeneros] = useState<generoModelConId[]>(); useEffect(() => { detallePelicula(); detallePeliculaGeneros(); }, [pelicula]); async function detallePelicula() { const URL = `${BasePath}/peliculas/${id}`; await axios.get(URL).then((response) => { setPelicula(response.data); }); } async function detallePeliculaGeneros() { const URL = `${BasePath}/peliculas/generos/${id}`; await axios.get(URL).then((response) => { setGeneros(response.data); }); } function generarURLYoutubeEMbebido(url: any) { if (!url) { return ""; } var video_id = url.split("v=")[1]; var posicionAmpersand = video_id.indexOf("&"); if (posicionAmpersand !== -1) { video_id = video_id.substring(0, posicionAmpersand); } return `https://www.youtube.com/embed/${video_id}`; } async function onVote(voto:number){ const URL = `${BasePath}/rating` await axios.post(URL,{peliculaId:id, puntuacion : voto}).then(response =>{ if(response.data.code === 200){ toast.success((response.data.message).toString(),{ position: toast.POSITION.TOP_RIGHT, theme:"colored", autoClose:1500 }) } }) } return ( pelicula? <div className="container mt-lg-4 "> <div className="row col-12 "> <h1 className="ml-3 mb-4">{pelicula.titulo}</h1> </div> <div className="row col-12"> <label className="col-12"> Voto Promedio: {pelicula.promedioVoto} </label> </div> <div className="row col-12"> <label className="col-12"> Tu voto:{" "} <span> <Rating maximoValor={5} valorSeleccionado={pelicula.votoUsuario!} onChange={(voto) => onVote(voto)} /> </span> </label> </div> <div className="row col-lg-12 mt-3"> <div className="col-lg-4 mb-3"> <img className="" src={pelicula?.poster} alt="poster pelicula" style={{ width: "250px", height: "316px" }} /> </div> <div> <iframe className="ml-3" title="youtube-trailer" width="560" height="315" src={generarURLYoutubeEMbebido(pelicula.trailer)} frameBorder={0} allow="accelerometer:autoplay;encrypted-media;gyroscope;picture-in-picture" allowFullScreen ></iframe> </div> <div className="col-lg-8 mt-5"> <p className="font-weight-light">{pelicula.resumen}</p> {generos?.map((genero) => ( <Button key={genero.id}>{genero.nombre}</Button> ))} <br></br> <label className="mt-1"> {moment(pelicula.fechaLanzamiento).format("LL")} </label> </div> </div> </div> : null ); }
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Player extends Model { use HasFactory, SoftDeletes; protected $guarded = []; /** * Accessor method to get the full name attribute. * * @return string */ public function getFullNameAttribute() { return "{$this->first_name} {$this->middle_name} {$this->last_name}"; } public function currentTeam() { return $this->belongsTo(Team::class); } public function teams() { return $this->belongsToMany(Team::class); } public function country() { return $this->belongsTo(Country::class,'country_id'); } }
import React from 'react'; import { Route } from 'react-router-dom'; import { useDispatch, useSelector } from 'react-redux'; import { LinkContainer } from 'react-router-bootstrap'; import { Navbar, Nav, Container, NavDropdown } from 'react-bootstrap'; import { logout } from '../actions/userActions'; import SearchBox from './SearchBox'; import './NavBar.css'; const NavBar = () => { const dispatch = useDispatch(); const userLogin = useSelector((state) => state.userLogin); const { userInfo } = userLogin; const logoutHandler = () => { dispatch(logout()); window.location = '/signin'; }; return ( <header className="nav1"> <Navbar className="Navibar" bg="black" variant="dark" fixed="top" expand="md" collapseOnSelect > <Container> <LinkContainer to="/"> <Navbar.Brand className="EimskyBrand">Eimsky</Navbar.Brand> </LinkContainer> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Route render={({ history }) => <SearchBox history={history} />} ></Route> <Nav className="ml-auto"> <LinkContainer to="/products"> <Nav.Link> <p className="NavLinks"> <i className="fas fa-shopping-basket"></i> Products </p> </Nav.Link> </LinkContainer> <LinkContainer to="/cart"> <Nav.Link href="#cart"> <p className="NavLinks"> <i className="fas fa-shopping-cart"></i> Cart </p> </Nav.Link> </LinkContainer> {userInfo && userInfo.isAdmin && ( <LinkContainer to="/admin/dashboard"> <Nav.Link href="#sign-in"> <p className="NavLinks"> <i className="fas fa-user"></i> Dashboard </p> </Nav.Link> </LinkContainer> )} {userInfo && userInfo.isEmployee && ( <LinkContainer to="/employee/dashboard"> <Nav.Link href="#sign-in"> <p className="NavLinks"> <i className="fas fa-user"></i> Dashboard </p> </Nav.Link> </LinkContainer> )} {userInfo ? ( <NavDropdown className="navUserName" title={userInfo.name} id="username" > {' '} {userInfo.isAdmin ? ( <> <LinkContainer to="/admin/updateprofile"> <NavDropdown.Item className="navdropitem"> Update profile </NavDropdown.Item> </LinkContainer> <NavDropdown.Item className="navdropitem" onClick={logoutHandler} > Logout </NavDropdown.Item> </> ) : userInfo.isEmployee ? ( <> <LinkContainer to="/employee/updateprofile"> <NavDropdown.Item className="navdropitem"> Update profile </NavDropdown.Item> </LinkContainer> <NavDropdown.Item className="navdropitem" onClick={logoutHandler} > Logout </NavDropdown.Item> </> ) : ( <> <LinkContainer to="/profile"> <NavDropdown.Item className="navdropitem"> Profile </NavDropdown.Item> </LinkContainer> <NavDropdown.Item className="navdropitem" onClick={logoutHandler} > Logout </NavDropdown.Item> </> )} </NavDropdown> ) : ( <LinkContainer to="/signin"> <Nav.Link href="#sign-in"> <p className="NavLinks"> <i className="fas fa-user"></i> Sign in </p> </Nav.Link> </LinkContainer> )} </Nav> </Navbar.Collapse> </Container> </Navbar> </header> ); }; export default NavBar;
// App.js or relevant component import React, { useState } from 'react'; import CategorySelector from './Components/CategorySelector'; import ProductComponent from './Components/ProductComponent'; const App = () => { const [selectedCategory, setSelectedCategory] = useState(''); const handleSelectCategory = (category) => { setSelectedCategory(category); }; return ( <div className="App"> <h1>E-commerce App</h1> <CategorySelector onSelectCategory={handleSelectCategory} /> <ProductComponent selectedCategory={selectedCategory} /> </div> ); }; export default App;
<?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; class UserProfileResource extends JsonResource { /** * Transform the resource we return to client. We can format the data any how without exposing how the backend structure looks like. * * @param Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'email' => $this->email, 'status' => (bool) $this->active, 'fullName' => $this->profile ? $this->profile->last_name .' '.$this->profile->last_name : null, 'nationality' => $this->profile && $this->profile->nationality ? $this->profile->nationality->name: null, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } }
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.2 <0.9.0; /** * @title Storage * @dev Store & retrieve value in a variable */ interface IStorage { // EVENTS event Stored(uint256 indexed num); /** * @dev Store value in variable * @param num value to store */ function store(uint256 num) external; /** * @dev Return value * @return value of 'number' */ function retrieve() external view returns (uint256); }
import React from 'react'; import { connect } from 'react-redux'; import Apprise from '../components/Apprise'; import { formUpdate } from '../actions/forms'; import { newApprisal } from '../actions/apprisals'; import { UserType } from '../../apiserver/models/constants'; class AppriseMenu extends React.Component { // eslint-disable-line react/no-multi-comp constructor() { super(); this.onChange = this.onChange.bind(this); this.onSubmit = this.onSubmit.bind(this); } onSubmit() { const recipientIds = []; this.props.selectedRecipientIds.forEach((recipientId) => { recipientIds.push({ recipientId: recipientId, canRespond: true, }); }); this.props.dispatch( newApprisal( { postId: this.props.postId, recipients: recipientIds, }, this.props.postId, this.props.formId, ), ); } onChange(recipientId) { let newRecipientIds = this.props.selectedRecipientIds; const foundIndex = this.props.selectedRecipientIds.findIndex(selRecipientId => ( selRecipientId === recipientId ), ); if (foundIndex > -1) { const frontPart = this.props.selectedRecipientIds.slice(0, foundIndex); const endPart = this.props.selectedRecipientIds.slice(foundIndex + 1); newRecipientIds = frontPart.concat(endPart); } else { newRecipientIds = this.props.selectedRecipientIds.concat(recipientId); } this.props.dispatch( formUpdate( this.props.formId, { selectedRecipientIds: newRecipientIds, }, ), ); } render() { let canNotSubmitMsg = null; let canSubmit = true; if (this.props.accountType === UserType.DEMO) { canNotSubmitMsg = 'Can not share - demo account.'; canSubmit = false; } else if (!this.props.accountValidated) { canNotSubmitMsg = 'Can not share - account has not been validated.'; canSubmit = false; } return ( <div className="apprisal-menu--holder"> <Apprise selectedRecipientIds={this.props.selectedRecipientIds} recipients={this.props.recipients} apprisals={this.props.apprisals} formId={this.props.formId} onChange={this.onChange} onSubmit={this.onSubmit} submitting={this.props.submitting} userCanSubmit={canSubmit} userCannotSubmitMessage={canNotSubmitMsg} /> </div> ); } } AppriseMenu.propTypes = { selectedRecipientIds: React.PropTypes.arrayOf(React.PropTypes.string), recipients: React.PropTypes.array, // eslint-disable-line react/forbid-prop-types apprisals: React.PropTypes.array, // eslint-disable-line react/forbid-prop-types dispatch: React.PropTypes.func.isRequired, submitting: React.PropTypes.bool.isRequired, accountType: React.PropTypes.string.isRequired, accountValidated: React.PropTypes.bool.isRequired, postId: React.PropTypes.string.isRequired, formId: React.PropTypes.string.isRequired, }; /** redux store map **/ const mapStateToProps = function mapStateToProps(state, ownProps) { const formId = `appriseForm${ownProps.postId}`; let selectedRecipientIds = []; let submitting = false; const ourForm = state.forms[formId]; if (ourForm && ourForm.selectedRecipientIds && ourForm.selectedRecipientIds.length > 0) { selectedRecipientIds = ourForm.selectedRecipientIds; } if (ourForm && typeof ourForm.submitting !== 'undefined') { submitting = ourForm.submitting; } return { recipients: state.recipients.recipients, selectedRecipientIds: selectedRecipientIds, formId: formId, submitting: submitting, accountType: state.account.accountType, accountValidated: state.account.validated, }; }; const Container = connect(mapStateToProps)(AppriseMenu); export default Container;
<?php /** * implements wp-cli extension for bulk optimizing */ class EWWWIO_CLI extends WP_CLI_Command { /** * Bulk Optimize Images * * ## OPTIONS * * <library> * : valid values are 'all' (default), 'media', 'nextgen', 'flagallery', and 'other' * : media: Media Library only * : nextgen: Nextcellent and NextGEN 2.x * : flagallery: Grand FlaGallery * : other: everything else including theme images and other specified folders * * <delay> * : optional, number of seconds to pause between images * * <force> * : optional, should the plugin re-optimize images that have already been processed. * * <reset> * : optional, start the optimizer back at the beginning instead of resuming from last position * * <noprompt> * : do not prompt, just start optimizing * * ## EXAMPLES * * wp-cli ewwwio optimize media 5 --force --reset --noprompt * * @synopsis <library> [<delay>] [--force] [--reset] [--noprompt] */ function optimize( $args, $assoc_args ) { global $ewww_defer; $ewww_defer = false; // because NextGEN hasn't flushed it's buffers... while( @ob_end_flush() ); $library = $args[0]; if ( empty( $args[1] ) ) { $delay = ewww_image_optimizer_get_option ( 'ewww_image_optimizer_delay' ); } else { $delay = $args[1]; } $ewww_reset = false; if ( ! empty( $assoc_args['reset'] ) ) { $ewww_reset = true; } if ( ! empty( $assoc_args['force'] ) ) { WP_CLI::line( __('Forcing re-optimization of previously processed images.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); $_REQUEST['ewww_force'] = true; } WP_CLI::line( sprintf( _x('Optimizing %1$s with a %2$d second pause between images.', 'string will be something like "media" or "nextgen"', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $library, $delay ) ); // let's get started, shall we? ewww_image_optimizer_admin_init(); // and what shall we do? switch( $library ) { case 'all': if ( $ewww_reset ) { update_option('ewww_image_optimizer_bulk_resume', ''); update_option('ewww_image_optimizer_aux_resume', ''); update_option('ewww_image_optimizer_bulk_ngg_resume', ''); update_option('ewww_image_optimizer_bulk_flag_resume', ''); WP_CLI::line( __('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } WP_CLI::line( __( 'Scanning, this could take a while', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); list( $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) = ewww_image_optimizer_count_optimized ('media'); WP_CLI::line( sprintf( __( '%1$d images in the Media Library have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) ); if ( class_exists( 'ewwwngg' ) ) { global $ngg; if ( preg_match( '/^2/', $ngg->version ) ) { list( $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) = ewww_image_optimizer_count_optimized ('ngg'); WP_CLI::line( 'Nextgen: ' . sprintf( __( '%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) ); } else { $attachments = ewww_image_optimizer_scan_next(); WP_CLI::line( 'Nextgen: ' . sprintf( __( 'We have %d images to optimize.', EWWW_IMAGE_OPTIMIZER_DOMAIN ), count( $attachments ) ) ); } } if ( class_exists( 'ewwwflag' ) ) { list( $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) = ewww_image_optimizer_count_optimized ('flag'); WP_CLI::line( 'Flagallery: ' . sprintf( __( '%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) ); } $other_attachments = ewww_image_optimizer_scan_other(); if ( empty( $assoc_args['noprompt'] ) ) { WP_CLI::confirm( sprintf( __( '%1$d images in other folders need optimizing.', EWWW_IMAGE_OPTIMIZER_DOMAIN ), count($other_attachments) ) ); } ewww_image_optimizer_bulk_media( $delay ); if ( class_exists( 'ewwwngg' ) ) { global $ngg; if ( preg_match( '/^2/', $ngg->version ) ) { ewww_image_optimizer_bulk_ngg( $delay ); } else { $attachments = ewww_image_optimizer_scan_next(); ewww_image_optimizer_bulk_next( $delay, $attachments ); } } if ( class_exists( 'ewwwflag' ) ) { ewww_image_optimizer_bulk_flag( $delay ); } ewww_image_optimizer_bulk_other( $delay, $other_attachments ); break; case 'media': if ( $ewww_reset ) { update_option('ewww_image_optimizer_bulk_resume', ''); WP_CLI::line( __('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } list( $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) = ewww_image_optimizer_count_optimized ('media'); if ( empty( $assoc_args['noprompt'] ) ) { WP_CLI::confirm( sprintf( __( '%1$d images in the Media Library have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) ); } ewww_image_optimizer_bulk_media( $delay ); break; case 'nextgen': if ( $ewww_reset ) { update_option('ewww_image_optimizer_bulk_ngg_resume', ''); WP_CLI::line( __('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } if ( class_exists( 'ewwwngg' ) ) { global $ngg; if ( preg_match( '/^2/', $ngg->version ) ) { list( $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) = ewww_image_optimizer_count_optimized ('ngg'); if ( empty( $assoc_args['noprompt'] ) ) { WP_CLI::confirm( sprintf( __( '%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) ); } ewww_image_optimizer_bulk_ngg( $delay ); } else { $attachments = ewww_image_optimizer_scan_next(); if ( empty( $assoc_args['noprompt'] ) ) { WP_CLI::confirm( sprintf( __( 'We have %d images to optimize.', EWWW_IMAGE_OPTIMIZER_DOMAIN ), count( $attachments ) ) ); } ewww_image_optimizer_bulk_next( $delay, $attachments ); } } else { WP_CLI::error( __( 'NextGEN/Nextcellent not installed.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } break; case 'flagallery': if ( $ewww_reset ) { update_option('ewww_image_optimizer_bulk_flag_resume', ''); WP_CLI::line( __('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } if ( class_exists( 'ewwwflag' ) ) { list( $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) = ewww_image_optimizer_count_optimized ('flag'); if ( empty( $assoc_args['noprompt'] ) ) { WP_CLI::confirm( sprintf( __( '%1$d images have been selected (%2$d unoptimized), with %3$d resizes (%4$d unoptimized).', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $fullsize_count, $unoptimized_count, $resize_count, $unoptimized_resize_count ) ); } ewww_image_optimizer_bulk_flag( $delay ); } else { WP_CLI::error( __( 'Grand Flagallery not installed.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } break; case 'other': if ( $ewww_reset ) { update_option('ewww_image_optimizer_aux_resume', ''); WP_CLI::line( __('Bulk status has been reset, starting from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } WP_CLI::line( __( 'Scanning, this could take a while', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); $other_attachments = ewww_image_optimizer_scan_other(); if ( empty( $assoc_args['noprompt'] ) ) { WP_CLI::confirm( sprintf( __( '%1$d images in other folders need optimizing.', EWWW_IMAGE_OPTIMIZER_DOMAIN ), count($other_attachments) ) ); } ewww_image_optimizer_bulk_other( $delay, $other_attachments ); break; default: if ( $ewww_reset ) { update_option('ewww_image_optimizer_bulk_resume', ''); update_option('ewww_image_optimizer_aux_resume', ''); update_option('ewww_image_optimizer_bulk_ngg_resume', ''); update_option('ewww_image_optimizer_bulk_flag_resume', ''); WP_CLI::success( __('Bulk status has been reset, the next bulk operation will start from the beginning.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } else { WP_CLI::line( __('Please specify a valid library option, see "wp-cli help ewwwio optimize" for more information.', EWWW_IMAGE_OPTIMIZER_DOMAIN ) ); } } } } WP_CLI::add_command( 'ewwwio', 'EWWWIO_CLI' ); // prepares the bulk operation and includes the javascript functions function ewww_image_optimizer_bulk_media( $delay = 0 ) { $attachments = null; // check if there is a previous bulk operation to resume if ( get_option('ewww_image_optimizer_bulk_resume') ) { // retrieve the attachment IDs that have not been finished from the 'bulk attachments' option $attachments = get_option('ewww_image_optimizer_bulk_attachments'); // since we aren't resuming, and weren't given a list of IDs, we will optimize everything } else { // load up all the image attachments we can find $attachments = get_posts( array( 'numberposts' => -1, 'post_type' => array('attachment', 'ims_image'), 'post_status' => 'any', 'post_mime_type' => 'image', 'fields' => 'ids' )); } // store the attachment IDs we retrieved in the 'bulk_attachments' option so we can keep track of our progress in the database update_option('ewww_image_optimizer_bulk_attachments', $attachments); // update the 'bulk resume' option to show that an operation is in progress update_option('ewww_image_optimizer_bulk_resume', 'true'); foreach ($attachments as $attachment_ID) { // get the 'bulk attachments' with a list of IDs remaining $attachments_left = get_option('ewww_image_optimizer_bulk_attachments'); $meta = wp_get_attachment_metadata( $attachment_ID ); if ( ! empty( $meta['file'] ) ) { // let the user know the file we are currently optimizing WP_CLI::line( __('Optimizing', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " {$meta['file']}:" ); } sleep( $delay ); // retrieve the time when the optimizer starts $started = microtime(true); // do the optimization for the current attachment (including resizes) $meta = ewww_image_optimizer_resize_from_meta_data ( $meta, $attachment_ID, false ); if ( empty ( $meta['file'] ) ) { WP_CLI::warning( __( 'Skipped image, ID:', EWWW_IMAGE_OPTIMIZER_DOMAIN ) . " $attachment" ); } if ( ! empty( $meta['ewww_image_optimizer'] ) ) { // tell the user what the results were for the original image WP_CLI::line( sprintf( __( 'Full size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $meta['ewww_image_optimizer'] ) ) ); } // check to see if there are resized version of the image if ( isset($meta['sizes']) && is_array( $meta['sizes'] ) ) { // cycle through each resize foreach ( $meta['sizes'] as $size ) { if ( ! empty( $size['ewww_image_optimizer'] ) ) { // output the results for the current resized version WP_CLI::line( "{$size['file']} – " . html_entity_decode( $size['ewww_image_optimizer'] ) ); } } } // calculate how much time has elapsed since we started $elapsed = microtime(true) - $started; // output how much time has elapsed since we started WP_CLI::line( sprintf( __( 'Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $elapsed ) ); // update the metadata for the current attachment wp_update_attachment_metadata( $attachment_ID, $meta ); // remove the first element from the $attachments array if ( ! empty( $attachments_left ) ) { array_shift( $attachments_left ); } // store the updated list of attachment IDs back in the 'bulk_attachments' option update_option('ewww_image_optimizer_bulk_attachments', $attachments_left); } // all done, so we can update the bulk options with empty values update_option('ewww_image_optimizer_bulk_resume', ''); update_option('ewww_image_optimizer_bulk_attachments', ''); // and let the user know we are done WP_CLI::success( __('Finished Optimization!', EWWW_IMAGE_OPTIMIZER_DOMAIN) ); } // displays the 'Optimize Everything Else' section of the Bulk Optimize page function ewww_image_optimizer_scan_other () { global $wpdb; // $aux_resume = get_option('ewww_image_optimizer_aux_resume'); // initialize the $attachments variable for auxiliary images $attachments = null; // check the 'bulk resume' option // $resume = get_option('ewww_image_optimizer_aux_resume'); // check if there is a previous bulk operation to resume if ( get_option( 'ewww_image_optimizer_aux_resume' ) ) { // retrieve the attachment IDs that have not been finished from the 'bulk attachments' option $attachments = get_option('ewww_image_optimizer_aux_attachments'); } else { // collect a list of images from the current theme $child_path = get_stylesheet_directory(); $parent_path = get_template_directory(); $attachments = ewww_image_optimizer_image_scan($child_path); if ($child_path !== $parent_path) { $attachments = array_merge($attachments, ewww_image_optimizer_image_scan($parent_path)); } // collect a list of images for buddypress if ( ! function_exists( 'is_plugin_active' ) ) { // need to include the plugin library for the is_plugin_active function require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); } if (is_plugin_active('buddypress/bp-loader.php') || is_plugin_active_for_network('buddypress/bp-loader.php')) { // get the value of the wordpress upload directory $upload_dir = wp_upload_dir(); // scan the 'avatars' and 'group-avatars' folders for images $attachments = array_merge($attachments, ewww_image_optimizer_image_scan($upload_dir['basedir'] . '/avatars'), ewww_image_optimizer_image_scan($upload_dir['basedir'] . '/group-avatars')); } if (is_plugin_active('buddypress-activity-plus/bpfb.php') || is_plugin_active_for_network('buddypress-activity-plus/bpfb.php')) { // get the value of the wordpress upload directory $upload_dir = wp_upload_dir(); // scan the 'avatars' and 'group-avatars' folders for images $attachments = array_merge($attachments, ewww_image_optimizer_image_scan($upload_dir['basedir'] . '/bpfb')); } if (is_plugin_active('grand-media/grand-media.php') || is_plugin_active_for_network('grand-media/grand-media.php')) { // scan the grand media folder for images $attachments = array_merge($attachments, ewww_image_optimizer_image_scan(WP_CONTENT_DIR . '/grand-media')); } if (is_plugin_active('wp-symposium/wp-symposium.php') || is_plugin_active_for_network('wp-symposium/wp-symposium.php')) { $attachments = array_merge($attachments, ewww_image_optimizer_image_scan(get_option('symposium_img_path'))); } if (is_plugin_active('ml-slider/ml-slider.php') || is_plugin_active_for_network('ml-slider/ml-slider.php')) { $slide_paths = array(); $sliders = get_posts(array( 'numberposts' => -1, 'post_type' => 'ml-slider', 'post_status' => 'any', 'fields' => 'ids' )); foreach ($sliders as $slider) { $slides = get_posts(array( 'numberposts' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', 'post_type' => 'attachment', 'post_status' => 'inherit', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'ml-slider', 'field' => 'slug', 'terms' => $slider ) ) ) ); foreach ($slides as $slide) { $backup_sizes = get_post_meta($slide, '_wp_attachment_backup_sizes', true); $type = get_post_meta($slide, 'ml-slider_type', true); $type = $type ? $type : 'image'; // backwards compatibility, fall back to 'image' if ($type === 'image') { foreach ($backup_sizes as $backup_size => $meta) { if (preg_match('/resized-/', $backup_size)) { $path = $meta['path']; $image_size = filesize($path); $query = $wpdb->prepare("SELECT id FROM $wpdb->ewwwio_images WHERE path LIKE %s AND image_size LIKE '$image_size'", $path); $optimized_query = $wpdb->get_results( $query, ARRAY_A ); if (!empty($optimized_query)) { foreach ( $optimized_query as $image ) { if ( $image['path'] == $path ) { // $ewww_debug .= "{$image['path']} does not match $path, continuing our search<br>"; $already_optimized = $image; } } } $mimetype = ewww_image_optimizer_mimetype($path, 'i'); if (preg_match('/^image\/(jpeg|png|gif)/', $mimetype) && empty($already_optimized)) { $slide_paths[] = $path; } } } } } } $attachments = array_merge($attachments, $slide_paths); } // collect a list of images in auxiliary folders provided by user if ( $aux_paths = ewww_image_optimizer_get_option( 'ewww_image_optimizer_aux_paths' ) ) { foreach ($aux_paths as $aux_path) { $attachments = array_merge($attachments, ewww_image_optimizer_image_scan($aux_path)); } } // store the filenames we retrieved in the 'bulk_attachments' option so we can keep track of our progress in the database update_option('ewww_image_optimizer_aux_attachments', $attachments); } return $attachments; } function ewww_image_optimizer_bulk_other( $delay = 0, $attachments ) { // update the 'aux resume' option to show that an operation is in progress update_option('ewww_image_optimizer_aux_resume', 'true'); // store the time and number of images for later display $count = count( $attachments ); update_option('ewww_image_optimizer_aux_last', array(time(), $count)); foreach ( $attachments as $attachment ) { sleep($delay); // retrieve the time when the optimizer starts $started = microtime(true); // get the 'aux attachments' with a list of attachments remaining $attachments_left = get_option('ewww_image_optimizer_aux_attachments'); // do the optimization for the current image $results = ewww_image_optimizer($attachment, 4, false, false); // remove the first element fromt the $attachments array if (!empty($attachments_left)) { array_shift($attachments_left); } // store the updated list of attachment IDs back in the 'bulk_attachments' option update_option('ewww_image_optimizer_aux_attachments', $attachments_left); // output the path WP_CLI::line( __('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . ' ' . esc_html($attachment) ); // tell the user what the results were for the original image WP_CLI::line( html_entity_decode( $results[1] ) ); // calculate how much time has elapsed since we started $elapsed = microtime(true) - $started; // output how much time has elapsed since we started WP_CLI::line( sprintf( __( 'Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $elapsed) ); } $stored_last = get_option('ewww_image_optimizer_aux_last'); update_option('ewww_image_optimizer_aux_last', array(time(), $stored_last[1])); // all done, so we can update the bulk options with empty values update_option('ewww_image_optimizer_aux_resume', ''); update_option('ewww_image_optimizer_aux_attachments', ''); // and let the user know we are done WP_CLI::success( __('Finished Optimization!', EWWW_IMAGE_OPTIMIZER_DOMAIN) ); } function ewww_image_optimizer_bulk_flag( $delay = 0 ) { $ids = null; // if there is an operation to resume, get those IDs from the db if ( get_option('ewww_image_optimizer_bulk_flag_resume') ) { $ids = get_option('ewww_image_optimizer_bulk_flag_attachments'); // otherwise, if we are on the main bulk optimize page, just get all the IDs available } else { global $wpdb; $ids = $wpdb->get_col("SELECT pid FROM $wpdb->flagpictures ORDER BY sortorder ASC"); } // store the IDs to optimize in the options table of the db update_option('ewww_image_optimizer_bulk_flag_attachments', $ids); // set the resume flag to indicate the bulk operation is in progress update_option('ewww_image_optimizer_bulk_flag_resume', 'true'); // need this file to work with flag meta require_once(WP_CONTENT_DIR . '/plugins/flash-album-gallery/lib/meta.php'); foreach ( $ids as $id ) { sleep( $delay ); // record the starting time for the current image (in microseconds) $started = microtime(true); // retrieve the meta for the current ID $meta = new flagMeta($id); $file_path = $meta->image->imagePath; // optimize the full-size version $fres = ewww_image_optimizer($file_path, 3, false, false, true); $meta->image->meta_data['ewww_image_optimizer'] = $fres[1]; // let the user know what happened WP_CLI::line( __( 'Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN ) . " " . esc_html($meta->image->filename) ); WP_CLI::line( sprintf( __( 'Full size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $fres[1] ) ) ); if ( ! empty( $meta->image->meta_data['webview'] ) ) { // determine path of the webview $web_path = $meta->image->webimagePath; $wres = ewww_image_optimizer($web_path, 3, false, true); $meta->image->meta_data['webview']['ewww_image_optimizer'] = $wres[1]; WP_CLI::line( sprintf( __( 'Optimized size – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $wres[1] ) ) ); } $thumb_path = $meta->image->thumbPath; // optimize the thumbnail $tres = ewww_image_optimizer($thumb_path, 3, false, true); $meta->image->meta_data['thumbnail']['ewww_image_optimizer'] = $tres[1]; // and let the user know the results WP_CLI::line( sprintf( __( 'Thumbnail – %s', EWWW_IMAGE_OPTIMIZER_DOMAIN), html_entity_decode( $tres[1] ) ) ); flagdb::update_image_meta($id, $meta->image->meta_data); // determine how much time the image took to process $elapsed = microtime(true) - $started; // and output it to the user WP_CLI::line( sprintf( __( 'Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $elapsed ) ); // retrieve the list of attachments left to work on $attachments = get_option('ewww_image_optimizer_bulk_flag_attachments'); // take the first image off the list if (!empty($attachments)) array_shift($attachments); // and send the list back to the db update_option('ewww_image_optimizer_bulk_flag_attachments', $attachments); } // reset the bulk flags in the db update_option('ewww_image_optimizer_bulk_flag_resume', ''); update_option('ewww_image_optimizer_bulk_flag_attachments', ''); // and let the user know we are done WP_CLI::success( __('Finished Optimization!', EWWW_IMAGE_OPTIMIZER_DOMAIN) ); } function ewww_image_optimizer_scan_ngg() { $images = null; // see if there is a previous operation to resume // $resume = get_option('ewww_image_optimizer_bulk_ngg_resume'); // if we've been given a bulk action to perform // otherwise, if we have an operation to resume if ( get_option('ewww_image_optimizer_bulk_ngg_resume') ) { // get the list of attachment IDs from the db $images = get_option('ewww_image_optimizer_bulk_ngg_attachments'); // otherwise, get all the images in the db } else { global $wpdb; $images = $wpdb->get_col("SELECT pid FROM $wpdb->nggpictures ORDER BY sortorder ASC"); } // store the image IDs to process in the db update_option('ewww_image_optimizer_bulk_ngg_attachments', $images); return $images; } function ewww_image_optimizer_bulk_ngg( $delay = 0 ) { if ( get_option('ewww_image_optimizer_bulk_ngg_resume') ) { // get the list of attachment IDs from the db $images = get_option('ewww_image_optimizer_bulk_ngg_attachments'); // otherwise, get all the images in the db } else { global $wpdb; $images = $wpdb->get_col("SELECT pid FROM $wpdb->nggpictures ORDER BY sortorder ASC"); } // store the image IDs to process in the db update_option('ewww_image_optimizer_bulk_ngg_attachments', $images); // toggle the resume flag to indicate an operation is in progress update_option('ewww_image_optimizer_bulk_ngg_resume', 'true'); global $ewwwngg; foreach ( $images as $id ) { sleep( $delay ); // find out what time we started, in microseconds $started = microtime(true); // creating the 'registry' object for working with nextgen $registry = C_Component_Registry::get_instance(); // creating a database storage object from the 'registry' object $storage = $registry->get_utility('I_Gallery_Storage'); // get an image object $image = $storage->object->_image_mapper->find($id); $image = $ewwwngg->ewww_added_new_image ($image, $storage); // output the results of the optimization WP_CLI::line( __('Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN) . " " . basename($storage->object->get_image_abspath($image, 'full'))); // get an array of sizes available for the $image $sizes = $storage->get_image_sizes(); // output the results for each $size foreach ($sizes as $size) { if ($size === 'full') { WP_CLI::line( sprintf( __( 'Full size - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $image->meta_data['ewww_image_optimizer'] ) ) ); } elseif ($size === 'thumbnail') { // output the results of the thumb optimization WP_CLI::line( sprintf( __( 'Thumbnail - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $image->meta_data[$size]['ewww_image_optimizer'] ) ) ); } else { // output savings for any other sizes, if they ever exist... WP_CLI::line( ucfirst($size) . " - " . html_entity_decode( $image->meta_data[$size]['ewww_image_optimizer'] ) ); } } // outupt how much time we spent $elapsed = microtime(true) - $started; WP_CLI::line( sprintf( __( 'Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $elapsed ) ); // get the list of attachments remaining from the db $attachments = get_option('ewww_image_optimizer_bulk_ngg_attachments'); // remove the first item if (!empty($attachments)) array_shift($attachments); // and store the list back in the db update_option('ewww_image_optimizer_bulk_ngg_attachments', $attachments); } // reset all the bulk options in the db update_option('ewww_image_optimizer_bulk_ngg_resume', ''); update_option('ewww_image_optimizer_bulk_ngg_attachments', ''); // and let the user know we are done WP_CLI::success( __('Finished Optimization!', EWWW_IMAGE_OPTIMIZER_DOMAIN) ); } function ewww_image_optimizer_scan_next() { $images = null; // see if there is a previous operation to resume // $resume = get_option('ewww_image_optimizer_bulk_ngg_resume'); // otherwise, if we have an operation to resume if ( get_option('ewww_image_optimizer_bulk_ngg_resume') ) { // get the list of attachment IDs from the db $images = get_option('ewww_image_optimizer_bulk_ngg_attachments'); // otherwise, if we are on the standard bulk page, get all the images in the db } else { //$ewww_debug .= "starting from scratch, grabbing all the images<br />"; global $wpdb; $images = $wpdb->get_col("SELECT pid FROM $wpdb->nggpictures ORDER BY sortorder ASC"); } // store the image IDs to process in the db update_option('ewww_image_optimizer_bulk_ngg_attachments', $images); return $images; } function ewww_image_optimizer_bulk_next( $delay, $attachments ) { // toggle the resume flag to indicate an operation is in progress update_option('ewww_image_optimizer_bulk_ngg_resume', 'true'); // need this file to work with metadata require_once(WP_CONTENT_DIR . '/plugins/nextcellent-gallery-nextgen-legacy/lib/meta.php'); foreach ( $attachments as $id ) { sleep( $delay ); // find out what time we started, in microseconds $started = microtime(true); // get the metadata $meta = new nggMeta($id); // retrieve the filepath $file_path = $meta->image->imagePath; // run the optimizer on the current image $fres = ewww_image_optimizer($file_path, 2, false, false, true); // update the metadata of the optimized image nggdb::update_image_meta($id, array('ewww_image_optimizer' => $fres[1])); // output the results of the optimization WP_CLI::line( __( 'Optimized image:', EWWW_IMAGE_OPTIMIZER_DOMAIN ) . $meta->image->filename ); WP_CLI::line( sprintf( __( 'Full size - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $fres[1] ) ) ); // get the filepath of the thumbnail image $thumb_path = $meta->image->thumbPath; // run the optimization on the thumbnail $tres = ewww_image_optimizer($thumb_path, 2, false, true); // output the results of the thumb optimization WP_CLI::line( sprintf( __( 'Thumbnail - %s', EWWW_IMAGE_OPTIMIZER_DOMAIN ), html_entity_decode( $tres[1] ) ) ); // outupt how much time we spent $elapsed = microtime(true) - $started; WP_CLI::line( sprintf( __( 'Elapsed: %.3f seconds', EWWW_IMAGE_OPTIMIZER_DOMAIN ), $elapsed ) ); // get the list of attachments remaining from the db $attachments = get_option('ewww_image_optimizer_bulk_ngg_attachments'); // remove the first item if (!empty($attachments)) array_shift($attachments); // and store the list back in the db update_option('ewww_image_optimizer_bulk_ngg_attachments', $attachments); } // reset all the bulk options in the db update_option('ewww_image_optimizer_bulk_ngg_resume', ''); update_option('ewww_image_optimizer_bulk_ngg_attachments', ''); // and let the user know we are done WP_CLI::success( __('Finished Optimization!', EWWW_IMAGE_OPTIMIZER_DOMAIN) ); }
import type { FC } from 'react'; import { useState } from 'react'; import PlusIcon from '@untitled-ui/icons-react/build/esm/Plus'; import { Avatar, Box, Button, Chip, IconButton, Stack, SvgIcon, TextField, Typography } from '@mui/material'; import { MobileDatePicker } from '@mui/x-date-pickers'; export const Form8: FC = () => { const [startDate, setStartDate] = useState<Date | null>(new Date()); const [endDate, setEndDate] = useState<Date | null>(new Date()); const tags: string[] = ['Full-Time']; return ( <Box sx={{ p: 3 }}> <form onSubmit={(event) => event.preventDefault()}> <Stack spacing={4}> <Stack spacing={1}> <Typography variant="h5"> Please select one option </Typography> <Typography color="text.secondary" variant="body1" > Proin tincidunt lacus sed ante efficitur efficitur. Quisque aliquam fringilla velit sit amet euismod. </Typography> </Stack> <Stack spacing={4}> <TextField fullWidth label="Project Name" name="projectName" /> <Stack spacing={2}> <Stack alignItems="center" direction="row" spacing={2} > <TextField fullWidth label="Tags" name="tags" /> <IconButton> <SvgIcon> <PlusIcon /> </SvgIcon> </IconButton> </Stack> <Stack alignItems="center" direction="row" flexWrap="wrap" spacing={1} > {tags.map((tag) => ( <Chip avatar={( <Avatar> {tag.slice(0, 1)} </Avatar> )} key={tag} label={tag} onDelete={() => {}} variant="outlined" /> ))} </Stack> </Stack> <Stack alignItems="center" direction="row" spacing={3} > <MobileDatePicker label="Start Date" onChange={(newDate) => setStartDate(newDate)} renderInput={(inputProps) => ( <TextField {...inputProps} /> )} value={startDate} /> <MobileDatePicker label="End Date" onChange={(newDate) => setEndDate(newDate)} renderInput={(inputProps) => ( <TextField{...inputProps} /> )} value={endDate} /> </Stack> </Stack> <Box sx={{ display: 'flex', justifyContent: 'flex-end' }} > <Button color="primary" type="submit" variant="contained" > Next </Button> </Box> </Stack> </form> </Box> ); };
import React from 'react'; import { render, fireEvent } from '@testing-library/react-native'; import PrimaryButton from '../src/components/PrimaryButton'; import { View } from 'react-native'; describe('PrimaryButton', () => { it('renders the button with the correct title', () => { const { getByText } = render( <PrimaryButton title="Click Me" onPress={() => {}} /> ); expect(getByText('Click Me')).toBeDefined(); }); it('calls onPress when pressed', () => { const mockOnPress = jest.fn(); const { getByText } = render( <PrimaryButton title="Click Me" onPress={mockOnPress} /> ); fireEvent.press(getByText('Click Me')); expect(mockOnPress).toHaveBeenCalled(); }); it('renders an icon when provided', () => { const TestIcon = <View testID="test-icon" />; const { getByTestId } = render( <PrimaryButton title="Button With Icon" onPress={() => {}} icon={TestIcon} /> ); expect(getByTestId('test-icon')).toBeDefined(); }); });
import React, { Component } from 'react' import PropTypes from 'prop-types' import { inject, observer } from 'mobx-react' import Translate from 'react-translate-component' import translate from 'counterpart' import styled from 'styled-components' import AddedActors from './addedActors' import { SectionTitle } from '../general/section' import { Container } from '../general/card' import Tooltip from '../general/tooltip' import { HelpIcon } from '../general/form' import ActorsInfoTooltip from './actorsInfoTooltip' import ActorModal from './actorModal' import Button from '../../general/button' import { Actor } from '../../../stores/view/qvain.actors' export class ActorsBase extends Component { static propTypes = { Stores: PropTypes.object.isRequired, } state = { tooltipOpen: false, } createActor = () => { const { editActor } = this.props.Stores.Qvain.Actors editActor(Actor()) } render() { const { readonly } = this.props.Stores.Qvain return ( <div className="container"> <SectionTitle> <Translate content="qvain.actors.title" /> <Tooltip isOpen={this.state.tooltipOpen} close={() => this.setState(prevState => ({ tooltipOpen: !prevState.tooltipOpen }))} align="Right" text={<ActorsInfoTooltip />} > <HelpIcon aria-label={translate('qvain.actors.infoTitle')} onClick={() => this.setState(prevState => ({ tooltipOpen: !prevState.tooltipOpen }))} /> </Tooltip> </SectionTitle> <ActorModal /> <Container> <AddedActors /> <ButtonContainer> <AddNewButton type="button" onClick={() => this.createActor()} disabled={readonly}> <Translate content="qvain.actors.addButton" /> </AddNewButton> </ButtonContainer> </Container> </div> ) } } const ButtonContainer = styled.div` text-align: right; ` const AddNewButton = styled(Button)` margin: 0; margin-top: 11px; ` export default inject('Stores')(observer(ActorsBase))
# Compulsory Task 1 # Re-submitted for review after necessary corrections # Create Email class class Email: # Initialise the instance variables for email class def __init__(self, from_address, subject_line, email_contents): self.from_address = from_address self.subject_line = subject_line self.email_contents = email_contents self.has_been_read = False self.is_spam = False # Define a method to mark email as read def mark_as_read(self): self.has_been_read = True # Define a method to mark email as spam def mark_as_spam(self): self.is_spam = True # Create Inbox class class Inbox: # Initialise the instance variable for Inbox class def __init__(self): self.inbox_list = [] # Define a method to add email in the inbox list def add_email(self, from_address, subject_line, email_contents): email = Email(from_address, subject_line, email_contents) self.inbox_list.append(email) # Define a method to list emails from a specific sender def list_messages_from_sender(self, sender_address): emails = [e for e in self.inbox_list if e.from_address == sender_address] if not emails: return f"No emails from {sender_address}" else: output = f"Emails from {sender_address}:\n" for count, email in enumerate(emails): output += f"{count} {email.subject_line}" return output # Define a method to get email from a specific sender and at a specific index def get_email(self, sender_address, index): emails = [e for e in self.inbox_list if e.from_address == sender_address] if not emails: return None elif index < 0 or index >= len(emails): return None email = emails[index] email.has_been_read = True return email # Define a method to mark email as spam def mark_as_spam(self, sender_address, index): emails = [e for e in self.inbox_list if e.from_address == sender_address] if not emails: return f"No emails from {sender_address}" elif index < 0 or index >= len(emails): return f"Invalid index!" email = emails[index] email.is_spam = True return "Email has been marked as spam." # Define a method to get the unread emails def get_unread_email(self): unread_emails = [e for e in self.inbox_list if not e.has_been_read] if not unread_emails: return "No unread emails" else: output = "" for email in unread_emails: output += email.subject_line + "\n" return output # Define a method to get the emails which are marked as spam def get_spam_email(self): spam_emails = [e for e in self.inbox_list if e.is_spam] if not spam_emails: return "No spam emails" else: output = "" for email in spam_emails: output += email.subject_line + "\n" return output # Define a method to delete emails from specific sender and at a specif index def delete(self, sender_address, index): emails = [e for e in self.inbox_list if e.from_address == sender_address] if not emails: return f"No emails from {sender_address}" elif index < 0 or index >= len(emails): return f"Invalid index!" email = emails[index] self.inbox_list.remove(email) return "Email deleted!" usage_message = ''' Welcome to the email system! What would you like to do? s - send email. l - list emails from a sender. r - read email. m - mark email as spam. gu - get unread emails. gs - get spam emails. d - delete email. e - exit this program. : ''' # An Email Simulation inbox = Inbox() user_choice = "" while True: user_choice = input(usage_message).strip().lower() if user_choice == "s": # Send an email (Create a new Email object) sender_address = input("Please enter the address of the sender\n:") subject_line = input("Please enter the subject line of the email\n:") contents = input("Please enter the contents of the email\n:") # Now add the email to the Inbox inbox.add_email(sender_address, subject_line, contents) # Print a success message print("Email has been added to inbox.") pass elif user_choice == "l": # List all emails from a sender_address sender_address = input("Please enter the address of the sender\n:") # Now list all emails from this sender output = inbox.list_messages_from_sender(sender_address) print(output) pass elif user_choice == "r": # Read an email # Step 1: show emails from the sender sender_address = input("Please enter the address of the sender of the email\n:") # Step 2: show all emails from this sender (with indexes) inbox.list_messages_from_sender(sender_address) # Step 3: ask the user for the index of the email email_index = int(input("Please enter the index of the email that you would like to read\n:")) # Step 4: display the email email_object = inbox.get_email(sender_address, email_index) print(email_object.email_contents) pass elif user_choice == "m": # Mark an email as spam # Step 1: show emails from the sender sender_address = input("Please enter the address of the sender of the email\n:") # Step 2: show all emails from this sender (with indexes) inbox.list_messages_from_sender(sender_address) # Step 3: ask the user for the index of the email email_index = int(input("Please enter the index of the email to be marked as spam\n:")) # Step 4: mark the email as spam inbox.mark_as_spam(sender_address, email_index) # Step 5: print a success message print("Email has been marked as spam") pass elif user_choice == "gu": # List all unread emails unread_email_list = inbox.get_unread_email() print(unread_email_list) pass elif user_choice == "gs": # List all spam emails spam_email_list = inbox.get_spam_email() print(spam_email_list) pass elif user_choice == "e": print("Goodbye") break elif user_choice == "d": # Delete an email # Step 1: show emails from the sender sender_address = input("Please enter the address of the sender of the email\n:") # Step 2: show all emails from this sender (with indexes) inbox.list_messages_from_sender(sender_address) # Step 3: ask the user for the index of the email email_index = int(input("Please enter the index of the email to be deleted\n:")) # Step 4: delete the email inbox.delete(sender_address, email_index) # Step 5: print a success message print("Email has been deleted") pass else: print("Oops - incorrect input")
package core import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "math/big" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type Hash [32]byte // Hex returns a hex string from the Hash type func (hash Hash) Hex() string { return fmt.Sprintf("0x%s", hex.EncodeToString(hash[:])) } // hashBytes performs a sha256 hash over the bytes func hashBytes(b []byte) (hash Hash) { h := sha256.Sum256(b) copy(hash[:], h[:]) return hash } func TestIDparsers(t *testing.T) { // Generate ID0 var typ0 [2]byte typ0Hex, _ := hex.DecodeString("0000") copy(typ0[:], typ0Hex[:2]) var genesis0 [27]byte genesis032bytes := hashBytes([]byte("genesistest")) copy(genesis0[:], genesis032bytes[:]) id0 := NewID(typ0, genesis0) // Check ID0 assert.Equal(t, "114vgnnCupQMX4wqUBjg5kUya3zMXfPmKc9HNH4m2E", id0.String()) // Generate ID1 var typ1 [2]byte typ1Hex, _ := hex.DecodeString("0001") copy(typ1[:], typ1Hex[:2]) var genesis1 [27]byte genesis132bytes := hashBytes([]byte("genesistest")) copy(genesis1[:], genesis132bytes[:]) id1 := NewID(typ1, genesis1) // Check ID1 assert.Equal(t, "1GYjyJKqdDyzo927FqJkAdLWB64kV2NVAjaQFHtq4", id1.String()) emptyChecksum := []byte{0x00, 0x00} assert.True(t, !bytes.Equal(emptyChecksum, id0[29:])) assert.True(t, !bytes.Equal(emptyChecksum, id1[29:])) id0FromBytes, err := IDFromBytes(id0.Bytes()) assert.Nil(t, err) assert.Equal(t, id0.Bytes(), id0FromBytes.Bytes()) assert.Equal(t, id0.String(), id0FromBytes.String()) assert.Equal(t, "114vgnnCupQMX4wqUBjg5kUya3zMXfPmKc9HNH4m2E", id0FromBytes.String()) id1FromBytes, err := IDFromBytes(id1.Bytes()) assert.Nil(t, err) assert.Equal(t, id1.Bytes(), id1FromBytes.Bytes()) assert.Equal(t, id1.String(), id1FromBytes.String()) assert.Equal(t, "1GYjyJKqdDyzo927FqJkAdLWB64kV2NVAjaQFHtq4", id1FromBytes.String()) id0FromString, err := IDFromString(id0.String()) assert.Nil(t, err) assert.Equal(t, id0.Bytes(), id0FromString.Bytes()) assert.Equal(t, id0.String(), id0FromString.String()) assert.Equal(t, "114vgnnCupQMX4wqUBjg5kUya3zMXfPmKc9HNH4m2E", id0FromString.String()) } func TestIDAsDID(t *testing.T) { typ, err := BuildDIDType(DIDMethodIden3, Polygon, Mumbai) require.NoError(t, err) var genesis1 [27]byte genesisbytes := hashBytes([]byte("genesistes1t2")) copy(genesis1[:], genesisbytes[:]) id := NewID(typ, genesis1) fmt.Println(id.String()) } func TestIDjsonParser(t *testing.T) { id, err := IDFromString("11AVZrKNJVqDJoyKrdyaAgEynyBEjksV5z2NjZogFv") assert.Nil(t, err) idj, err := json.Marshal(&id) assert.Nil(t, err) assert.Equal(t, "11AVZrKNJVqDJoyKrdyaAgEynyBEjksV5z2NjZogFv", strings.Replace(string(idj), "\"", "", 2)) var idp ID err = json.Unmarshal(idj, &idp) assert.Nil(t, err) assert.Equal(t, id, idp) idsMap := make(map[ID]string) idsMap[id] = "first" idsMapJSON, err := json.Marshal(idsMap) assert.Nil(t, err) var idsMapUnmarshaled map[ID]string err = json.Unmarshal(idsMapJSON, &idsMapUnmarshaled) assert.Nil(t, err) } func TestCheckChecksum(t *testing.T) { typ := TypeDefault var genesis [27]byte genesis32bytes := hashBytes([]byte("genesistest")) copy(genesis[:], genesis32bytes[:]) id := NewID(typ, genesis) var checksum [2]byte copy(checksum[:], id[len(id)-2:]) assert.Equal(t, CalculateChecksum(typ, genesis), checksum) assert.True(t, CheckChecksum(id)) // check that if we change the checksum, returns false on CheckChecksum id = NewID(typ, genesis) copy(id[29:], []byte{0x00, 0x01}) assert.True(t, !CheckChecksum(id)) // check that if we change the type, returns false on CheckChecksum id = NewID(typ, genesis) copy(id[:2], []byte{0x00, 0x01}) assert.True(t, !CheckChecksum(id)) // check that if we change the genesis, returns false on CheckChecksum id = NewID(typ, genesis) // changedGenesis := utils.HashBytes([]byte("changedgenesis")) var changedGenesis [27]byte changedGenesis32bytes := hashBytes([]byte("changedgenesis")) copy(changedGenesis[:], changedGenesis32bytes[:27]) copy(id[2:27], changedGenesis[:]) assert.True(t, !CheckChecksum(id)) // test with a empty id var empty [31]byte _, err := IDFromBytes(empty[:]) assert.Equal(t, errors.New("IDFromBytes error: byte array empty"), err) } func TestIDFromInt(t *testing.T) { id, err := IDFromString("11AVZrKNJVqDJoyKrdyaAgEynyBEjksV5z2NjZogFv") assert.Nil(t, err) intID := id.BigInt() got, err := IDFromInt(intID) assert.Nil(t, err) assert.Equal(t, id, got) } func TestIDFromIntStr(t *testing.T) { idStr := "11BBCPZ6Zq9HX1JhHrHT3QKUFD9kFDEyJFoAVMptVs" idFromStr, err := IDFromString(idStr) require.NoError(t, err) intFromIDFromStr := idFromStr.BigInt() id, err := IDFromInt(intFromIDFromStr) require.NoError(t, err) require.Equal(t, idStr, id.String()) } func TestProfileID(t *testing.T) { idInt, ok := new(big.Int).SetString( "23630567111950550539435915649280822148510307443797111728722609533581131776", 10) require.True(t, ok) id, err := IDFromInt(idInt) require.NoError(t, err) nonce := big.NewInt(10) id2, err := ProfileID(id, nonce) require.NoError(t, err) require.Equal(t, "25425363284463910957419549722021124450832239517990785975889689633068548096", id2.BigInt().String()) } func TestProfileID_emptyNonce(t *testing.T) { id, err := IDFromString("11BBCPZ6Zq9HX1JhHrHT3QKUFD9kFDEyJFoAVMptVs") require.NoError(t, err) profile, err := ProfileID(id, nil) require.NoError(t, err) require.Equal(t, id, profile) nonce := big.NewInt(0) profile2, err := ProfileID(id, nonce) require.NoError(t, err) require.Equal(t, id, profile2) } func TestFirstNBytes(t *testing.T) { t.Run("bytes more then required", func(t *testing.T) { i := big.NewInt(422733233635437384) res := firstNBytes(i, 3) want := []byte{72, 171, 151} require.Equal(t, want, res) }) t.Run("bytes less then required", func(t *testing.T) { i := big.NewInt(422384) res := firstNBytes(i, 5) want := []byte{240, 113, 6, 0, 0} require.Equal(t, want, res) }) } func TestIDinDIDFormat(t *testing.T) { typ, _ := BuildDIDType(DIDMethodIden3, Ethereum, Main) var genesis [27]byte genesis32bytes := hashBytes([]byte("genesistest")) copy(genesis[:], genesis32bytes[:]) id := NewID(typ, genesis) var checksum [2]byte copy(checksum[:], id[len(id)-2:]) assert.Equal(t, CalculateChecksum(typ, genesis), checksum) fmt.Println(id.String()) did := DID{ ID: id, Blockchain: Polygon, NetworkID: Mumbai, } fmt.Println(did.String()) } func TestIDFromDIDString(t *testing.T) { didFromStr, err := ParseDID("did:iden3:polygon:mumbai:wyFiV4w71QgWPn6bYLsZoysFay66gKtVa9kfu6yMZ") require.NoError(t, err) typ, err := BuildDIDType(didFromStr.Method, didFromStr.Blockchain, didFromStr.NetworkID) require.NoError(t, err) var genesis [27]byte genesis32bytes := hashBytes([]byte("genesistest")) copy(genesis[:], genesis32bytes[:]) id := NewID(typ, genesis) var checksum [2]byte copy(checksum[:], id[len(id)-2:]) assert.Equal(t, CalculateChecksum(typ, genesis), checksum) assert.Equal(t, didFromStr.ID.String(), id.String()) } func TestID_Type(t *testing.T) { id, err := IDFromString("1MWtoAdZESeiphxp3bXupZcfS9DhMTdWNSjRwVYc2") assert.Nil(t, err) assert.Equal(t, id.Type(), TypeReadOnly) } func TestCheckGenesisStateID(t *testing.T) { userDID, err := ParseDID("did:iden3:polygon:mumbai:x6suHR8HkEYczV9yVeAKKiXCZAd25P8WS6QvNhszk") require.NoError(t, err) genesisID, ok := big.NewInt(0).SetString("7521024223205616003431860562270429547098131848980857190502964780628723574810", 10) require.True(t, ok) isGenesis, err := CheckGenesisStateID(userDID.ID.BigInt(), genesisID) require.NoError(t, err) require.True(t, isGenesis) notGenesisState, ok := big.NewInt(0).SetString("6017654403209798611575982337826892532952335378376369712724079246845524041042", 10) require.True(t, ok) isGenesis, err = CheckGenesisStateID(userDID.ID.BigInt(), notGenesisState) require.NoError(t, err) require.False(t, isGenesis) }
import Vue from 'vue' import App from './App.vue' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import { VueJsonp } from 'vue-jsonp' import store from '../store/store' // 全局引入axios import axios from 'axios' // 引入全局样式 import '../public/css/inddex.css' import infiniteScroll from 'vue-infinite-scroll' Vue.use(infiniteScroll) Vue.config.productionTip = false // 配置路径(请求后台路径); axios.defaults.baseURL = 'http://localhost:8082' // 在请求头添加token axios.interceptors.request.use( config => { // 判断是否存在token,如果存在的话,则每个http header都加上token const token = sessionStorage.getItem('token') if (token) { config.headers.Authorization = token // console.log('请求头token:', config.headers.Authorization) } else { config.headers.Authorization = null } return config }, error => { return Promise.reject(error) } ) // 2.0的方法 全局挂载axios Vue.prototype.$axios = axios Vue.use(ElementUI) Vue.use(VueJsonp) new Vue({ router, store, render: h => h(App) }).$mount('#app')
import { AxiosResponse } from "axios"; import { createContext, ReactNode, useCallback, useContext, useState, } from "react"; import { api } from "../services/api"; interface CartProviderProps { children: ReactNode; } interface Product { id: number; name: string; category: string; price: number; img: string; quantity: number; userId: string; } interface CartContextData { cart: Product[]; setCart: (cart: Product[]) => void; loadCart: (userId: string, accessToken: string) => Promise<void>; createProduct: ( data: Omit<Product, "id">, accessToken: string ) => Promise<void>; addProduct: ( quantity: number, productId: number, userId: string, accessToken: string ) => Promise<void>; subtractProduct: ( quantity: number, productId: number, userId: string, accessToken: string ) => Promise<void>; removeProduct: (productId: number, accessToken: string) => Promise<void>; } const CartContext = createContext<CartContextData>({} as CartContextData); const useCart = () => { const context = useContext(CartContext); if (!context) { throw new Error("useCart must be used within an ProductProvider"); } return context; }; const CartProvider = ({ children }: CartProviderProps) => { const [cart, setCart] = useState<Product[]>([]); const loadCart = useCallback(async (userId: string, accessToken: string) => { try { const response = await api.get(`/cart?userId=${userId}`, { headers: { Authorization: `Bearer ${accessToken}`, }, }); setCart(response.data); } catch (err) { console.log(err); } }, []); const createProduct = useCallback( async (data: Omit<Product, "id">, accessToken: string) => { api .post("/cart", data, { headers: { Authorization: `Bearer ${accessToken}`, }, }) .then((response: AxiosResponse<Product>) => { setCart((oldCart) => [...oldCart, response.data]); }) .catch((err) => console.log("Erro no createProduct", err)); }, [] ); const addProduct = useCallback( async ( quantity: number, productId: number, userId: string, accessToken: string ) => { await api .patch( `/cart/${productId}`, { quantity: quantity + 1, userId }, { headers: { Authorization: `Bearer ${accessToken}`, }, } ) .then((_) => { loadCart(userId, accessToken); }) .catch((err) => console.log("Erro no addProduct", err)); }, [cart] ); const subtractProduct = useCallback( async ( quantity: number, productId: number, userId: string, accessToken: string ) => { await api .patch( `/cart/${productId}`, { quantity: quantity - 1, userId }, { headers: { Authorization: `Bearer ${accessToken}`, }, } ) .then((_) => { loadCart(userId, accessToken); }) .catch((err) => console.log("Erro no addProduct", err)); }, [cart] ); const removeProduct = useCallback( async (productId: number, accessToken: string) => { await api .delete(`/cart/${productId}`, { headers: { Authorization: `Bearer ${accessToken}`, }, }) .then((_) => { const filteredCart = cart.filter( (product) => product.id !== productId ); setCart(filteredCart); }) .catch((err) => console.log(err)); }, [cart] ); return ( <CartContext.Provider value={{ cart, setCart, loadCart, createProduct, addProduct, subtractProduct, removeProduct, }} > {children} </CartContext.Provider> ); }; export { useCart, CartProvider };
--- title: How do you wrap text content in CSS? description: We'll look at the CSS features that allow us to wrap overflowing text in containers. slug: css-text-wrap authors: peter_osah tags: [css] image: https://refine.ams3.cdn.digitaloceanspaces.com/blog/2024-03-05-css-wrap-text/social.png hide_table_of_contents: false --- ## Introduction Text overflow happens when text does not fit completely within its container element. As a result, it goes outside of its boundaries, which might lead to broken layouts. However minor, this issue has been common among web developers. Fortunately, CSS has supplied certain CSS attributes that can control text-overflow. In this article, we'll look at the CSS features that allow us to wrap overflowing text in containers. Steps we'll cover: - [How does content wrapping work in browsers?](#how-does-content-wrapping-work-in-browsers) - [What's the distinction between a soft word wrap break and forceful line breaks?](#whats-the-distinction-between-a-soft-word-wrap-break-and-forceful-line-breaks) - [Explore the values of the overflow-wrap property](#explore-the-values-of-the-overflow-wrap-property) - [Explore the values of the word-break property](#explore-the-values-of-the-word-break-property) - [What makes a word-break different from an overflow-wrap?](#what-makes-a-word-break-different-from-an-overflow-wrap) - [Wrap text using word-break and overflow-wrap properties](#wrap-text-using-word-break-and-overflow-wrap-properties) ## How does content wrapping work in browsers? Content (like words) are often wrapped at "**soft wrap opportunities**", which are places in content where you'd expect it to break naturally, like after a hyphen or in between words like with spaces or punctuation. When browsers and [user-agents](https://www.link-assistant.com/seo-wiki/user-agent/) notice soft text wrap opportunities, they wrap text to minimize content overflow. Soft wrap opportunities vary between languages and it is determined by the language system that is being utilized in your HTML document (the value of the `lang` attribute that you supply on the `HTML` element or the default language). ## What's the distinction between a soft word wrap break and forceful line breaks? A soft wrap break is any content wrap that takes place during a soft wrap opportunity. For this to happen, ensure that wrapping is enabled on the element (For example, setting the value of `white-space` `CSS` property to `nowrap` will disable wrapping therefore, ensure that the `white-space` `CSS` property is set to `normal`). On the other hand, Forced line breaks are created by explicit line-breaking controls (line or new line breaking intentionally done using `CSS`) or line breaks (line breaks done directly on the `HTML` element) and not a soft wrap opportunity. ## Explore the values of the overflow-wrap property The `overflow-wrap` `CSS` property was previously known as `word-wrap`. For legacy reasons, browsers see `word-wrap` as a legacy name alias for the `overflow-wrap` property. This property determines whether the browser may break at disallowed points within a line to prevent overflow when an ordinarily unbreakable `string` is too long to fit within the line box. In order or an element to set an `overflow-wrap` value, it should have a `white-space` property that is set to `normal` (which is the default for elements). The following are the values of the `overflow-wrap` property: ### `normal`: Using the `overflow-wrap: break-word` value causes the browser to utilize the system's default line-breaking behavior. ```css .text { overflow-wrap: normal; } ``` We will illustrate the use of `overflow-wrap: normal` value with a Codepen. In the codepen example below, a word that is longer than its container appears in the text. The word overflows its container because there is no soft wrap opportunity(due to the presence of a very long word) and the `overflow-wrap`property value is set to `normal`.This is the system's default line-breaking behavior. > <iframe height="300" style={{ width: "100%" }} scrolling="no" title="overflow-wrap-normal example" src="https://codepen.io/Necati-zmen/embed/ZEZGopL?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/ZEZGopL"> overflow-wrap-normal example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> <br/><br/> ### `break-word`: Using `overflow-wrap: break-word` value on text wraps an element allows text to only break words in mid-word if necessary. It will first try to maintain a word unbroken by moving it to the next line, but will subsequently break the word if there is still not enough space. ```css .text { overflow-wrap: break-word; } ``` We will illustrate the use of `overflow-wrap: break-word` value with a Codepen. in the example, the long word is wrapped to the next line due to the `overflow-wrap`property value set to `break-word`. <iframe height="300" style={{ width: "100%" }} scrolling="no" title="overflow-wrap-break-word-example" src="https://codepen.io/Necati-zmen/embed/zYXGjKd?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/zYXGjKd"> overflow-wrap-break-word-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ### `anywhere`: The `overflow-wrap: anywhere` value which breaks words in the same way as the `overflow-wrap: break-word` property. ```css .text { overflow-wrap: anywhere; } ``` An example is illustrated on the Codepen below <iframe height="300" style={{ width: "100%" }} scrolling="no" title="overflow-wrap-anywhere-example" src="https://codepen.io/Necati-zmen/embed/mdgJLrv?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/mdgJLrv"> overflow-wrap-anywhere-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> <br/> <br/> One thing to note is while the `overflow-wrap: break-word` value and the `overflow-wrap: anywhere` value breaks words in the same manner by default, The distinction lies in its impact on the elements `min-content` width computation. When the width of the elements is both set to `min-content`, it is rather obvious. ```css .text-anywhere { width: min-content; overflow-wrap: anywhere; } ``` ```css .text-break-word { width: min-content; overflow-wrap: anywhere; } ``` An example of this is illustrated in the Codepen below. The element(with class `text-break-word`) with `overflow-wrap:break-word`, makes its `width` equal to the longest word by calculating `min-content` as if no words were broken. The other element(with class `text-anywhere`) with `overflow-wrap: anywhere` uses all possible breaks to compute `min-content`. The `width` of a single character is what happens to `min-content` because a line break can occur anywhere. <iframe height="300" style={{ width: "100%" }} scrolling="no" title="difference-between-overflow-wrap-breakword-and-overflow-wrap-anywhere" src="https://codepen.io/Necati-zmen/embed/WNWvJov?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/WNWvJov"> difference-between-overflow-wrap-breakword-and-overflow-wrap-anywhere</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## Explore the values of the word-break property The `word-break` property is another `CSS` property that determines how long words should break at the end of a line. The following are the values of the `word-break` property: ### `normal`: Setting the value of the `word-break` property to `normal` will apply the default word-break rules. ```css .text { word-break: normal; } ``` The following Codepen example shows what happens when you apply the styling `word-break: normal` to a block of text that contains a word longer than its container. <iframe height="300" style={{ width: "100%" }} scrolling="no" title="word-break-normal-example" src="https://codepen.io/Necati-zmen/embed/MWRwGbb?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/MWRwGbb"> word-break-normal-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## `keep-all`: Setting the value of the `word-break` property to `keep-all` will also apply the default word-break rules. Additionally, it should not be used in Chinese, Japanese, or Korean (CJK) texts as the browser will not apply word breaks to it even if there is an overflow. ```css .text { word-break: keep-all; } ``` An example is illustrated on the Codepen below <iframe height="300" style={{ width: "100%" }} scrolling="no" title="word-break-keep-all-example" src="https://codepen.io/Necati-zmen/embed/abxOGBE?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/abxOGBE"> word-break-keep-all-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## `break-all`: Setting the value of the `word-break` property to `break-all` will break a word at any character to prevent overflow of the word out of its container. ```css .text { word-break: break-all; } ``` An example is illustrated on the Codepen below: <iframe height="300" style={{ width: "100%" }} scrolling="no" title="word-break-break-all-example" src="https://codepen.io/Necati-zmen/embed/LYvVmbr?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/LYvVmbr"> word-break-break-all-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## `break-word`: Setting the value of the `word-break` property to `break-word` will break a word at soft wrap opportunities (like hyphens or in between words like with spaces or punctuation) to prevent overflow of the word out of its container. ```css .text { word-break: break-word; } ``` An example is illustrated on the Codepen below: <iframe height="300" style={{ width: "100%" }} scrolling="no" title="word-break-break-word-example" src="https://codepen.io/Necati-zmen/embed/GRLJdNL?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/GRLJdNL"> word-break-break-word-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## What makes a word-break different from an overflow-wrap? The differences between these properties are listed below: | `overflow-wrap` | `word-break` | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The `overflow-wrap: break-word`, `overflow-wrap: anywhere` properties will wrap the full overflowing word wrap break even at soft wrap opportunities if the content exceeds its container. | The `Word-break: break-all` property will break word between two characters, even if placing it on its own line eliminates the need for word break. <br/> Also, the`Word-break: break-word` property is similar to the `overflow-wrap: break-word`, `overflow-wrap: anywhere` properties as it wraps break words at soft wrap opportunities as well. | ## Wrap text using word-break and overflow-wrap properties As previously stated, the `overflow-wrap` property (legacy called `word-wrap`) is your best option for wrapping text or breaking a word that has overflowed its box or container. However, you can also consider using the `word-break` property if the `overflow-wrap` property does not work for you. However, keep in mind the distinctions between `overflow-wrap` and `word-break`, as discussed above. Here's a Codepen example of the `overflow-wrap` and `word-wrap` properties in use. You can experiment with it to understand its effects: <iframe height="300" style={{ width: "100%" }} scrolling="no" title="text-wrap-with-css-example" src="https://codepen.io/Necati-zmen/embed/NWmqMdq?default-tab=css%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true"> See the Pen <a href="https://codepen.io/Necati-zmen/pen/NWmqMdq"> text-wrap-with-css-example</a> by Necati Özmen (<a href="https://codepen.io/Necati-zmen">@Necati-zmen</a>) on <a href="https://codepen.io">CodePen</a>. </iframe> ## Conclusion In this article, we looked at `CSS`-based content wrapping. We also looked at the numerous `CSS` properties for efficiently wrapping content in any form. With this article, you should be able to effortlessly manage the presentation style of contents (words) on your webpages or web applications using `CSS`.
import { client, urlFor } from "@/lib/sanity"; import Image from "next/image"; import Link from "next/link"; async function getBlogs() { const query = ` *[_type == 'blogs'] | order(_createdAt desc){ title, body, description, "currentSlug": slug.current, "imageUrl": main_image.asset._ref, } `; const data = await client.fetch(query); return data; } export default async function Blogs() { const blogs = await getBlogs(); return ( <section> <div className="container mx-auto "> <div className="flex justify-center pt-8 "> <div className="w-full grid-cols-6 grid-rows-3 mx-auto xl:grid"> <div className="col-span-5 col-start-1 row-span-2 row-start-1 py-8 xl:bg-dark xl:p-14"> <div className="flex items-center gap-5 xl:pb-16 "> <div className="w-1/4 h-1 bg-black xl:bg-white"></div> <h2 className="text-3xl xl:text-white lg:text-7xl font-playfair"> Latest Blogs </h2> </div> </div> <div className="col-span-5 col-start-1 row-span-2 row-start-2 2xl:translate-x-24 "> <div className="flex flex-col items-center w-full gap-5 lg:gap-24 xl:flex-row "> {blogs.map((blog) => ( <Link key={blog.title} href={`/blog/${blog.currentSlug}`}> <figure className=" w-[20rem] lg:min-w-[370px] grid-rows-6 grid h-[448px] relative" key={blog.title} > <Image src={urlFor(blog.imageUrl).url()} fill="true" alt="" className="object-cover h-full row-span-5 row-start-1 " placeholder="blur" blurDataURL={urlFor(blog.imageUrl).url()} key={blog.title} /> <figcaption className="absolute p-3.5 text-2xl text-center text-white bg-dark font-playfair bottom-8 w-[90%] right-5 "> <p>{blog.title}</p> </figcaption> </figure> </Link> ))} </div> </div> </div> </div> </div> </section> ); }
import React, { useEffect, useState } from "react"; import { ShippingTimeRates, TestRateCalculation, ShippingAdditionalSetting, StoreFronts, ShippingSuppliers, ShippingMethodGeneral, } from "../.."; import { Breadcrumb, Button, Result } from "antd"; import { useParams, useNavigate, Link } from "react-router-dom"; import styles from "./ViewShippingMethod.module.css"; import cx from "classnames"; import { useQueryClient } from "@tanstack/react-query"; import { useGetCarriers, useGetCountries, useGetRecipient, useGetSender, useGetShippingMethodByID, useGetStates, useGetStoreFrontData, useUpdateShippingMethod, } from "../../../apis/ShippingMethodApi"; import Spinner from "../../../component/Spinner/Spinner"; const tabs = [ "General", "Shipping time and rates", "Test rate calculation", "Additional settings", "Storefronts", "Suppliers", ]; const { id: company_id } = JSON.parse(sessionStorage.getItem("userinfo")); function EditShipping() { const [singleShipment, setSingleShipment] = useState({}); const [destinations, setDestinations] = useState([]); const [storefronts, setStorefronts] = useState([]); const [allDestination, setAllDestination] = useState([]); const [isDisabled, setIsDisabled] = useState(false); const [haveRate, setHaveRate] = useState([]); const [shippingTimeRates, setShippingTimeRates] = useState([]); const [sender, setSender] = useState({}); const [recipient, setRecipient] = useState({}); const [image, setImage] = useState(""); const { id } = useParams(); const navigate = useNavigate(); const queryClient = useQueryClient(); const [active, setActive] = useState(tabs[0]); const { data: generalData, isLoading: generalLoading, isError, error, } = useGetShippingMethodByID(id); const { data: carriers, isLoading: carriersLoading } = useGetCarriers(); const { mutate: mutateUpdate, isLoading: updateLoading } = useUpdateShippingMethod(); const { data: countryData } = useGetCountries(); const { data: stateData } = useGetStates(); const { data: senderData, isLoading: senderLoading } = useGetSender(); const { data: recipientData, isLoading: recipientLoading } = useGetRecipient(); const { data: storeFrontData, isLoading: storefrontLoading } = useGetStoreFrontData(id); // set sender data useEffect(() => { if (senderData?.data) { setSender(senderData?.data); } }, [senderData]); useEffect(() => { if (storeFrontData?.data) { setStorefronts( Object.values(storeFrontData?.data?.storefronts || {})?.map((el) => ({ ...el, key: el["id"], })) || {} ); } }, [storeFrontData]); // set recipient data useEffect(() => { if (recipientData?.data) { setRecipient(recipientData?.data); } }, [recipientData]); // to get general data we can write useEffect hook useEffect(() => { if (generalData?.data) { setIsDisabled(company_id == generalData?.data?.company_id); setSingleShipment(generalData?.data); getDestinations(); } }, [generalData]); // function for getting carriers const getCarriers = () => { if (carriers?.data) { let carrier = Object.entries(carriers?.data)?.map((el, i) => ({ value: el[0], label: el[1], key: i, })); return carrier; } return []; }; // Get country data const getCountries = () => { if (countryData?.data) { let countries = Object.entries(countryData?.data)?.map((item) => ({ label: item[1], value: item[0], })); return countries; } return []; }; // function for getting states const getStates = () => { if (stateData?.data) { let states = stateData?.data; return states; } return {}; }; // get shipping time and rates const getDestinations = () => { let temp = Object.values(generalData?.data?.rates || {}) ?.filter((el, i) => el?.status === "A") ?.map((item) => ({ label: item?.destination, value: item?.destination_id, })); let temp_rate = Object.values(generalData?.data?.rates || {})?.filter( (el, i) => (el?.status === "D" || el?.status === "A") && el?.rate_id ) || []; let temp_all_rate = Object.values(generalData?.data?.rates || {})?.filter( (el, i) => el?.status === "A" ) || []; setAllDestination(temp_all_rate); setHaveRate(temp_rate.reverse()); setDestinations(temp); }; // submit changes const onOkay = async () => { var formData = new FormData(); let time_and_shipping = [...haveRate]; let temp_time_rate_data = { 0: "", ...time_and_shipping?.reduce((accumulator, currentValue, i) => { accumulator[currentValue?.destination_id] = currentValue || ""; return accumulator; }, {}), delivery_time: { ...time_and_shipping?.reduce((accumulator, currentValue, i) => { accumulator[currentValue?.destination_id] = parseInt(currentValue?.delivery_time) || ""; return accumulator; }, {}), }, }; let data_for_image = image ? { shipping_image_data: { 0: { pair_id: singleShipment?.icon?.pair_id || "", type: "M", object_id: singleShipment?.icon?.object_id || "", image_alt: singleShipment?.icon?.icon?.alt || "", }, }, file_shipping_image_icon: { 0: "shipping", }, type_shipping_image_icon: { 0: "local", }, is_high_res_shipping_image_icon: { 0: "N", }, } : {}; const data = { shipping_id: id, shipping_data: { ...singleShipment, rates: { ...temp_time_rate_data } }, ...data_for_image, sender: { ...sender }, recipient: { ...recipient }, result_ids: "rates", }; formData.append("shipping_data", JSON.stringify(data)); formData.append("file", image); // function for update mutateUpdate(formData, { onSuccess: (res) => { queryClient.invalidateQueries(["single_shipping_method", id]); }, onError: (error) => { console.log(error.message); }, }); }; const getContainerFromTab = () => { switch (active) { case tabs[1]: return ( <ShippingTimeRates destinations={destinations} setShippingTimeRates={setShippingTimeRates} shippingTimeRates={shippingTimeRates} haveRate={haveRate} setHaveRate={setHaveRate} allDestination={allDestination} /> ); case tabs[2]: return ( <TestRateCalculation countries={getCountries()} states={getStates()} sender={sender} setSender={setSender} recipient={recipient} setRecipient={setRecipient} /> ); case tabs[3]: return ( <ShippingAdditionalSetting singleShipment={singleShipment} setSingleShipment={setSingleShipment} /> ); case tabs[4]: return ( <StoreFronts storefronts={storefronts} setStorefront={setStorefronts} singleShipment={singleShipment} setSingleShipment={setSingleShipment} /> ); case tabs[5]: return ( <ShippingSuppliers singleShipment={singleShipment} setSingleShipment={setSingleShipment} /> ); default: return Object.values(singleShipment).length ? ( <ShippingMethodGeneral setSingleShipment={setSingleShipment} singleShipment={singleShipment} carriers={getCarriers()} image={image} setImage={setImage} /> ) : ( "" ); } }; if ( generalLoading || carriersLoading || updateLoading || recipientLoading || senderLoading || storefrontLoading ) { return <Spinner />; } if (isError) { return ( <Result status={error?.response?.status} title={error?.response?.status} subTitle={error?.message} extra={ <Button type="primary" onClick={() => navigate("/")}> Back Home </Button> } /> ); } return ( <div> <div className={styles.breadcrumb}> <Breadcrumb> <Breadcrumb.Item> <Link to="/">Home</Link> </Breadcrumb.Item> <Breadcrumb.Item>Settings</Breadcrumb.Item> <Breadcrumb.Item> <Link to="/Setting/Shipping Methods">Shipping Methods</Link> </Breadcrumb.Item> <Breadcrumb.Item>{id}</Breadcrumb.Item> </Breadcrumb> <div className={styles.action_btn}> <Button className={styles.button1} onClick={() => navigate(-1)}> Back </Button> <Button style={!isDisabled ? { display: "none" } : {}} className={styles.button1} onClick={() => onOkay()} > Save </Button> </div> </div> <div className={styles.tabContainer}> <div className={styles.left}> {tabs.map((dat, i) => ( <div className={cx( styles.button, active === dat ? styles.bgColor : null )} key={i} onClick={() => setActive(dat)} > {dat} </div> ))} </div> </div> <div className={isDisabled ? "" : styles.area_disabled}> {getContainerFromTab()} </div> </div> ); } export default EditShipping;
import { IsNotEmpty } from '@nestjs/class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class LoginUserDto { @ApiProperty() @IsNotEmpty() readonly email: string; @ApiProperty() @IsNotEmpty() readonly password: string; } export class CreateUserDto { @IsNotEmpty() @ApiProperty() email: string; @ApiProperty() @IsNotEmpty() password: string; } export class UpdatePasswordDto { @IsNotEmpty() @ApiProperty() new_password: string; @IsNotEmpty() @ApiProperty() old_password: string; }
<!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css" /> <title>Студія</title> <link rel="stylesheet" href="./css/styles.css" /> <link rel="stylesheet" href="./css/main.min.css" /> </head> <body> <header class="header"> <div class="container header__container"> <nav class="nav"> <a class="logo header__logo" href="./index.html" lang="en" >Web<span class="header__logo-black">Studio</span></a > <ul class="navigation"> <li class="navigation__item"> <a class="navigation__link navigation__link--current-page" href="./index.html">Студія</a> </li> <li class="navigation__item"> <a class="navigation__link" href="./portfolio.html">Портфоліо</a> </li> <li class="navigation__item"> <a class="navigation__link" href="#">Контакти</a> </li> </ul> </nav> <ul class="contacts"> <li class="contacts__item"> <a class="contacts__link" href="mailto:info@devstudio.com"> <svg class="contacts__icon" width="16" height="12"> <use href="./images/icons.svg#icon-envelope"></use> </svg> info@devstudio.com</a > </li> <li class="contacts__item"> <a class="contacts__link" href="tel:+380961111111"> <svg class="contacts__icon" width="10" height="16"> <use href="./images/icons.svg#icon-tell"></use> </svg> +38 096 111 11 11</a > </li> </ul> </div> </header> <main> <section class="hero"> <div class="container"> <h1 class="hero__title">Ефективні рішення для вашого бізнесу</h1> <button class="hero__btn" type="button" data-modal-open>Замовити послугу</button> </div> </section> <section class="section"> <div class="container"> <h2 class="section__title visually-hidden">Наші переваги</h2> <ul class="features"> <li class="features__item"> <div class="features__icon-div"> <svg width="70" height="70"> <use href="./images/icons.svg#icon-antenna-1"></use> </svg> </div> <h3 class="features__title">Увага до деталей</h3> <p class="features__text"> Ідейні міркування, і навіть початок повсякденної роботи з формування позиції. </p> </li> <li class="features__item"> <div class="features__icon-div"> <svg width="70" height="70"> <use href="./images/icons.svg#icon-clock-1"></use> </svg> </div> <h3 class="features__title">Пунктуальність</h3> <p class="features__text"> Завдання організації, особливо рамки і місце навчання кадрів тягне у себе. </p> </li> <li class="features__item"> <div class="features__icon-div"> <svg width="70" height="70"> <use href="./images/icons.svg#icon-diagram-1"></use> </svg> </div> <h3 class="features__title">Планування</h3> <p class="features__text"> Так само консультація з широким активом значною мірою зумовлює. </p> </li> <li class="features__item"> <div class="features__icon-div"> <svg width="70" height="70"> <use href="./images/icons.svg#icon-astronaut-1"></use> </svg> </div> <h3 class="features__title">Сучасні технології</h3> <p class="features__text"> Значимість цих проблем настільки очевидна, що реалізація планових завдань. </p> </li> </ul> </div> </section> <section class="section section--no-padding-top"> <div class="container"> <h2 class="section__title">Чим ми займаємося</h2> <ul class="works"> <li class="works__item"> <img src="./images/box1.jpg" alt="Програміст пише програмний код" width="370" /> <div class="works__thumb"> <h3 class="works__title">Десктопні додатки</h3> </div> </li> <li class="works__item"> <img src="./images/box2.jpg" alt="Лодина трима телефон перед ноутбуком" width="370" /> <div class="works__thumb"> <h3 class="works__title">Мобільні додатки</h3> </div> </li> <li class="works__item"> <img src="./images/box3.jpg" alt="Людина тримає планшеті на якому зображенна палітра кольорів" width="370" /> <div class="works__thumb"> <h3 class="works__title">Дизайнерські рішення</h3> </div> </li> </ul> </div> </section> <section class="section section--other-background"> <div class="container"> <h2 class="section__title">Наша команда</h2> <ul class="team"> <li class="team__item"> <img src="./images/foto1.jpg" alt="Чоловік до 35 років, посміхається, носить очки і бороду" width="270" /> <div class="team__tank"> <h3 class="team__title">Ігор Дем'яненко</h3> <p class="team__text" lang="en">Product designer</p> <ul class="socials"> <li class="socials__item"> <a href="https://www.instagram.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-instagram-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.twitter.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-twitter-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.facebook.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-facebook-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.linkedin.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-linkedin-2"></use> </svg> </a> </li> </ul> </div> </li> <li class="team__item"> <img src="./images/foto2.jpg" alt="Жінка до 35 років, посміхається, блондинка з довгим волоссям, в очках" width="270" /> <div class="team__div"> <h3 class="team__title">Ольга Рєпіна</h3> <p class="team__text" lang="en">Frontend developer</p> <ul class="socials"> <li class="socials__item"> <a href="https://www.instagram.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-instagram-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.twitter.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-twitter-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.facebook.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-facebook-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.linkedin.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-linkedin-2"></use> </svg> </a> </li> </ul> </div> </li> <li class="team__item"> <img src="./images/foto3.jpg" alt="Чоловік до 35 років, русявий, посміхається, в білій рубашці" width="270" /> <div class="team__div"> <h3 class="team__title">Микола Тарасов</h3> <p class="team__text" lang="en">Marketing</p> <ul class="socials"> <li class="socials__item"> <a href="https://www.instagram.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-instagram-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.twitter.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-twitter-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.facebook.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-facebook-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.linkedin.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-linkedin-2"></use> </svg> </a> </li> </ul> </div> </li> <li class="team__item"> <img src="./images/foto4.jpg" alt="Чоловік до 35 років, посміхається, носить очки і бороду" width="270" /> <div class="team__div"> <h3 class="team__title">Михайло Єрмаков</h3> <p class="team__text" lang="en">UI designer</p> <ul class="socials"> <li class="socials__item"> <a href="https://www.instagram.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-instagram-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.twitter.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-twitter-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.facebook.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-facebook-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.linkedin.com/" class="socials__link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-linkedin-2"></use> </svg> </a> </li> </ul> </div> </li> </ul> </div> </section> <section class="section"> <div class="container"> <h2 class="section__title">Постійні клієнти</h2> <ul class="clients"> <li class="clients__item"> <a href="#" class="clients__link" target="_blank" rel="noopener noreferrer"> <svg class="clients__icon" width="106" height="60"> <use href="./images/icons.svg#icon-Logo-31"></use> </svg> </a> </li> <li class="clients__item"> <a href="#" class="clients__link" target="_blank" rel="noopener noreferrer"> <svg class="clients__icon" width="106" height="60"> <use href="./images/icons.svg#icon-Logo-32"></use> </svg> </a> </li> <li class="clients__item"> <a href="#" class="clients__link" target="_blank" rel="noopener noreferrer"> <svg class="clients__icon" width="106" height="60"> <use href="./images/icons.svg#icon-Logo-33"></use> </svg> </a> </li> <li class="clients__item"> <a href="#" class="clients__link" target="_blank" rel="noopener noreferrer"> <svg class="clients__icon" width="106" height="60"> <use href="./images/icons.svg#icon-Logo-34"></use> </svg> </a> </li> <li class="clients__item"> <a href="#" class="clients__link" target="_blank" rel="noopener noreferrer"> <svg class="clients__icon" width="106" height="60"> <use href="./images/icons.svg#icon-Logo-35"></use> </svg> </a> </li> <li class="clients__item"> <a href="#" class="clients__link" target="_blank" rel="noopener noreferrer"> <svg class="clients__icon" width="106" height="60"> <use href="./images/icons.svg#icon-Logo-36"></use> </svg> </a> </li> </ul> </div> </section> </main> <footer class="footer"> <div class="container"> <div class="footer__web-address"> <a class="logo footer__logo" href="./index.html" lang="en" >Web<span class="footer__logo-white">Studio</span></a > <address class="address"> <ul class="address__list"> <li class="address__item"> <a class="adrress__link-map" href="https://goo.gl/maps/zViUr5ABomGoPzUZA" target="_blank" rel="noopener noreferrer" > м. Київ, пр-т Лесі Українки, 26 </a> </li> <li class="address__item"> <a class="address__link-contacts" href="mailto:info@devstudio.com" >info@devstudio.com</a > </li> <li class="address__item"> <a class="address__link-contacts" href="tel:+380961111111">+38 096 111 11 11</a> </li> </ul> </address> </div> <div> <p class="footer__title">Приєднуйтесь</p> <ul class="socials"> <li class="socials__item"> <a href="https://www.instagram.com/" class="socials__link footer_socials--link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-instagram-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.twitter.com/" class="socials__link footer_socials--link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-twitter-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.facebook.com/" class="socials__link footer_socials--link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-facebook-2"></use> </svg> </a> </li> <li class="socials__item"> <a href="https://www.linkedin.com/" class="socials__link footer_socials--link" target="_blank" rel="noopener noreferrer" > <svg class="socials__icon" width="20" height="20"> <use href="./images/icons.svg#icon-linkedin-2"></use> </svg> </a> </li> </ul> </div> <div class="footer__form-container"> <p class="footer__title">Підпишіться на розсилку</p> <form class="form"> <label> <input class="form__input" type="email" name="email" placeholder="E-mail" /> </label> <button class="form__send" type="submit">Підписатися <svg width="24" height="24"> <use href="./images/icons.svg#icon-send"></use> </svg> </button> </form> </div> </div> </footer> <div class="backdrop is-hidden" data-modal> <div class="modal"> <button class="modal__close" type="button" data-modal-close> <svg width="18px" height="18px"> <use href="./images/icons.svg#icon-modal-close"></use> </svg> </button> <p class="modal__title">Залиште свої дані, ми вам передзвонимо</p> <form name="contact-form"> <label class="contact-form__label" for="person-name">Ім'я</label> <div class="contact-form__control"> <input class="contact-form__input" id="person-name" type="text" name="person-name" /> <svg class="contact-form__icon" width="18px" height="18px"> <use href="./images/icons.svg#icon-person"></use> </svg> </div> <label class="contact-form__label" for="person-phone">Телефон</label> <div class="contact-form__control"> <input class="contact-form__input" id="person-phone" type="tel" name="person-phone" /> <svg class="contact-form__icon" width="18px" height="18px"> <use href="./images/icons.svg#icon-phone"></use> </svg> </div> <label class="contact-form__label" for="person-mail">Пошта</label> <div class="contact-form__control"> <input class="contact-form__input" id="person-mail" type="email" name="person-mail" /> <svg class="contact-form__icon" width="18px" height="18px"> <use href="./images/icons.svg#icon-email"></use> </svg> </div> <div class="contact-form__field"> <label class="contact-form__label" for="person-comment">Коментар</label> <textarea class="contact-form__textarea" id="person-comment" type="email" name="person-comment" placeholder="Введіть текст" > </textarea> </div> <label class="checkbox" > <input class="checkbox__input visually-hidden" type="checkbox" name="accept"/> <span class="checkbox__box"> <svg class="checkbox__icon" width="16" height="15"> <use href="./images/icons.svg#icon-check"></use> </svg> </span> Погоджуюся з розсилкою та приймаю<a class="checkbox__terms" href="#"><span>Умови договору</span></a> </label> <button class="form-send" type="submit">Відправити </button> </form> </div> </div> <script src="./js/modal.js"></script> </body> </html>
import { Observable } from './Observable'; import { Observer } from './Observer'; export class DataSource extends Observable { constructor(private _value: number) { super(); } public get value(): number { return this._value; } public set value(newValue: number) { this._value = newValue; this.notify(); } public attach(observer: Observer): void { this.observers.push(observer); observer.update(); } public detach(observer: Observer): void { const index = this.observers.indexOf(observer); if (!index) return; this.observers.splice(index); } protected notify(): void { for (const observer of this.observers) { observer.update(); } } }
import React from 'react' import { useForm } from 'react-hook-form' import styles from './FullName.scss' import { ITenant, ITenantHandlers } from '@typings/' import { LabelInput } from '@styles/LabelInput/LabelInput' import { Button } from '@styles/Button/Button' import { Wrapper } from '@styles/Wrapper/Wrapper' export const FullName: React.FC<ITenant & ITenantHandlers> = ({ fullName, nextStep, handleTenantInputs }) => { const { register, errors } = useForm() return ( <Wrapper> <LabelInput id="fullName" type="text" name="fullName" labelText="Full Name" placeholder="Provide a full name" data-testid="full-name" defaultValue={fullName} register={register({ required: true, pattern: { value: /^[a-z]+$/i, message: 'Invalid name' } })} onChange={(event: React.ChangeEvent<HTMLInputElement>) => handleTenantInputs(event, 'fullName')} /> {errors.fullName && ( <p data-testid="name-error" className={styles.error}> {errors.fullName.message} </p> )} {fullName !== '' && ( <Button className={styles.nextButton} type="button" data-testid="next-button" onClick={nextStep}> Go next </Button> )} </Wrapper> ) }
package com.ssafy.kkoma.api.member.service; import com.ssafy.kkoma.api.area.service.AreaService; import com.ssafy.kkoma.api.member.dto.request.UpdateMemberPreferredPlaceRequest; import com.ssafy.kkoma.api.member.dto.response.*; import com.ssafy.kkoma.api.product.dto.ProductSummary; import com.ssafy.kkoma.domain.area.entity.Area; import com.ssafy.kkoma.domain.member.entity.Member; import com.ssafy.kkoma.domain.product.entity.Product; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Slf4j @Service @Transactional @RequiredArgsConstructor public class MemberInfoService { private final MemberService memberService; private final AreaService areaService; @Transactional(readOnly = true) public MemberInfoResponse getMemberInfo(Long memberId) { Member member = memberService.findMemberByMemberId(memberId); return MemberInfoResponse.fromEntity(member); } public MemberSummaryResponse getMemberSummary(Long memberId) { Member member = memberService.findMemberByMemberId(memberId); if (member.getPreferredPlaceRegionCode() == null) { return MemberSummaryResponse.fromEntity(member); } else { Area area = areaService.findAreaById(member.getPreferredPlaceRegionCode()); MemberSummaryResponse memberSummaryResponse = MemberSummaryResponse.fromEntity(member); memberSummaryResponse.setPreferredPlace(area.getFullArea()); return memberSummaryResponse; } } public MyPageMemberProfileResponse getMyPageMemberProfile(Long memberId) { Member member = memberService.findMemberByMemberId(memberId); List<Product> products = member.getProducts(); return MyPageMemberProfileResponse.builder() .memberProfileResponse(MemberProfileResponse.fromEntity(member)) .myProductList(products.stream().map(ProductSummary::fromEntity).toList()) .build(); } public MemberPreferredPlaceResponse updateMemberPreferredPlace(Long memberId, UpdateMemberPreferredPlaceRequest updateMemberPreferredPlaceRequest) { Member member = memberService.findMemberByMemberId(memberId); member.setPreferredPlaceRegionCode(updateMemberPreferredPlaceRequest.getPreferredPlaceRegionCode()); return MemberPreferredPlaceResponse.builder() .preferredPlaceRegionCode(member.getPreferredPlaceRegionCode()) .build(); } public MemberPreferredPlaceResponse getMemberPreferredPlace(Long memberId) { Member member = memberService.findMemberByMemberId(memberId); return MemberPreferredPlaceResponse.builder() .preferredPlaceRegionCode(member.getPreferredPlaceRegionCode()) .build(); } }
import Image from "next/image"; import styles from "../../styles/Profile.module.css"; import { BiLogInCircle } from "react-icons/bi"; import { signOut } from "next-auth/react"; import Button from "../button/button"; import { toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { useRouter } from "next/router"; export default function Profile({ data, userType }) { const router = useRouter(); const handleSelect = async (e) => { const payload = { userType: e.target.value, }; const res = await fetch(`/api/${data.user.email}`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(payload), }); const dataRes = await res.json(); if (res.status == 200) { toast.success(dataRes.message); router.reload(); } }; const handleLogOut = () => { localStorage.clear(); signOut(); }; return ( <> {data && ( <div className={`container mt-5 ${styles.profileContainer}`}> <div className={`card shadow ${styles.profileCard} rounded`}> &nbsp; <div className={`${styles.imageContainerProfile} shadow-lg`}> <Image className={`${styles.imageCustom}`} alt="Picture of the user" width={80} height={80} src={data.user.image} unoptimized={true} priority={true} /> </div> &nbsp; <h4>{data.user.name}</h4> <h5>{data.user.email}</h5> {!userType && ( <select className="form-select form-select-lg mb-3 shadow" aria-label=".form-select-lg example" onChange={handleSelect} > <option defaultValue>Select User Type</option> <option value={1}>Therapist</option> <option value={2}>Patient</option> </select> )} <Button title={"Sign Out"} style={`${styles.logOutBtn} shadow`} icon={<BiLogInCircle size={20} />} handleClick={handleLogOut} /> &nbsp; </div> </div> )} </> ); }
# Rog-O-Matic ## A Modern Beligerent Expert System ## by Robin Adams ### Introduction #### Rogue In 1980, the game Rogue appeared on the PLATO system, written by Michael C. Toy and Ken Arnold. It was one of the first computer RPGs and extremely influential - we still describe games as "roguelike" if, like Rogue, they have procedurally generated worlds and permadeath. Rogue used the new "curses" library (written by Ken Arnold) for placing characters at an arbitrary location on the screen, which allowed Rogue to display a 2D display of the dungeon map. ``` wielding a +1,+1 mace ------------------- |.................+ |......@)...S.....| -----------+------- Level: 1 Gold: 0 Hp: 12(12) Str: 16(16) Arm: 4 Exp: 1/0 ``` The game had the feature that magic items were unidentified when first picked up. A potion would just be described as, say, "a red potion", and which colour has which effect is randomized at the start of the game. Apart from Scrolls of Identify (which are rare!), the only way to find out what something does is to try it and see, a dangerous process! The game is also extremely difficult as the strength of the monsters increases rapidly as the dungeon level increases. The game has permadeath - on death, your save game file is deleted. Of course you can get around this by copying the save file, but this is cheating - you haven't beaten the game as the authors intended until you have done it in one run. #### Rog-O-Matic In 1984, Michael L. Mauldin, Guy Jacobson, Andrew Appel and Leonard Hamey presented their system called Rog-O-Matic, a bot for playing Rogue: https://www.cs.princeton.edtheu/~appel/papers/rogomatic.html They presented the design of the system and some experimental data, proving that Rog-O-Matic plays the game better than the best human player they tested (as judged by average score). But even given this, it was an extremely rare event that Rog-O-Matic wins the game. The paper only mentions that it has happened twice. #### My Motivation I am on a project to finish every game that I started as a child but never completed. The project has been on pause for a few years as a much bigger game in the form of a toddler came along for my wife and myself, but I now occasionally have a bit of time to start working on it again. You can follow my progress here: https://beatallthegames.blogspot.com/ I got to 1980 and was having trouble beating Rogue and started reading about the game. I found out about Rog-O-Matic, and in particular learned that it plays the game better than the best human player and very rarely wins. At that point, I gave up on beating the game "manually". I also had trouble compiling the source code for Rog-O-Matic on a modern machine, so I decided instead to create my own version of Rog-O-Matic. If I can write a version that beats Rogue, that counts for me. As I started, I quickly found that the design of Rog-O-Matic does not really match the neat diagram displayed in Figure 3-1 in the paper. Everything depends on everything else: the Behavior Rules update the World Model and each other's parameters, the Sensory Interface changes the Behavior Rules' parameters, the Behavior Rules call each other not necessarily in the sequence shown in Figure 3-2, etc. This was not going to be a simple port - I was going to have to start from scratch, but with the old source code as a guide. #### Technologies Used * Scala - Following the Pragmatic Programmers' advice that every new project should use one unfamiliar technology, I am using this project to teach myself Scala. The system is written in Scala 3.1.0 * Jediterm - The library JediTerm (https://github.com/JetBrains/jediterm) is used to interpret the output from Rogue. This is used under the GNU Lesser Public License v3, see lgpl-3.0.txt #### How to Play Rogue If you want to play Rogue yourself and you have a Linux system, it is in the bsdgames-nonfree package. Or you can play it online here: https://www.myabandonware.com/game/rogue-4n/play-4n
<template> <div class="app-container"> <el-form :model="queryParams" ref="queryRef" :inline="true"> <el-form-item label="名称检索" prop="name"> <el-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" /> </el-form-item> <el-form-item label="状态" prop="status"> <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px"> <el-option v-for="dict in commonStatusOptions" :key="dict.id" :label="dict.text" :value="dict.id" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" icon="search" @click="handleQuery" v-hasPermi="['consume:goodType:treeList']">搜索</el-button> <el-button icon="refresh" @click="resetQuery">重置</el-button> <el-button type="primary" icon="plus" @click="handleCreate" v-hasPermi="['consume:goodsType:create']">新增</el-button> </el-form-item> </el-form> <!--列表数据--> <el-table v-loading="loading" :data="goodsTypeList" row-key="typeId" ref="tableRef" lazy :load="loadChildren" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"> <el-table-column label="名称" min-width="200px" fixed="left" :show-overflow-tooltip="true"> <template #default="scope"> <span v-if="scope.row.children!=null&&scope.row.children.length>0"> <svg-icon icon-class="tree" /> </span> <span v-else-if="scope.row.pid==0"> <svg-icon icon-class="tree" /> </span> <span v-else> <i class="user-solid"></i> </span> <span class="link-type" @click="handleEdit(scope.row)">{{ scope.row.typeName }}</span> </template> </el-table-column> <el-table-column label="行为名称" width="180px"> <template #default="scope"> <span>{{ scope.row.behaviorName }}</span> </template> </el-table-column> <el-table-column label="排序号" align="center"> <template #default="scope"> <span>{{ scope.row.orderIndex }}</span> </template> </el-table-column> <el-table-column label="统计" align="center" width="100"> <template #default="scope"> <span v-if="scope.row.stat==true"> <el-icon color="green"><CircleCheckFilled /></el-icon> </span> <span v-else> <el-icon color="red"><CircleCloseFilled /></el-icon> </span> </template> </el-table-column> <el-table-column label="状态" align="center" width="100"> <template #default="scope"> <span v-if="scope.row.status=='ENABLE'"> <el-icon color="green"><CircleCheckFilled /></el-icon> </span> <span v-else> <el-icon color="red"><CircleCloseFilled /></el-icon> </span> </template> </el-table-column> <el-table-column label="操作" align="center" fixed="right" width="210" class-name="small-padding fixed-width"> <template #default="scope"> <el-button type="success" link icon="edit" @click="handleEdit(scope.row)" v-hasPermi="['consume:goodsType:edit']">修改</el-button> <el-button type="primary" link icon="plus" @click="handleCreate(scope.row)" v-hasPermi="['consume:goodsType:create']">新增</el-button> <el-button type="danger" link icon="delete" @click="handleDelete(scope.row)" v-hasPermi="['consume:goodsType:delete']">删除</el-button> </template> </el-table-column> </el-table> <!-- 表单 --> <GoodsTypeForm ref="formRef" @success="refreshRow" /> </div> </template> <script setup name="GoodsType"> import { fetchTreeList, deleteGoodsType, getGoodsType } from "@/api/consume/goodsType"; import GoodsTypeForm from './form.vue' const { proxy } = getCurrentInstance(); const formRef = ref(); // 遮罩层 const loading = ref(true); // 选中数组 const ids = ref([]); // 非单个禁用 const single = ref(true); // 非多个禁用 const multiple = ref(true); // 总条数 const total = ref(0); // 查询列表数据 const goodsTypeList = ref([]); //旧的父id const oldPid = ref(undefined); const data = reactive({ queryParams: { page: 0, pageSize: 10, name: undefined, pid: 0 } }); const { queryParams } = toRefs(data); /** 查询列表 */ function getList() { loading.value = true; goodsTypeList.value = []; fetchTreeList(queryParams.value).then( response => { goodsTypeList.value = response; loading.value = false; } ); } /** 搜索按钮操作 */ function handleQuery() { getList(); } /** 重置按钮操作 */ function resetQuery() { proxy.resetForm("queryRef"); queryParams.value.page = 1; handleQuery(); } //局部刷新使用 let tableRef = ref(); //加载子节点 function loadChildren(tree, treeNode, resolve) { //this.loading = true; const para = { pid: tree.typeId } fetchTreeList(para).then( response => { resolve(response); } ); } /** 刷新节点 */ function refreshRow(pid) { if (pid == 0) { //第一级菜单,刷新整个列表 getList(); return; } if (pid !== oldPid.value) { //先刷新原来的节点,否则会导致重复key,因为该节点在新老父节点里都存在 refreshRowData(oldPid.value); } refreshRowData(pid); } /** 刷新节点 */ function refreshRowData(pid) { if (pid == undefined || pid == null) { return; } getGoodsType(pid).then(response => { let row = response; //不管父节点之前有没有加载过数据,重置父节点 tableRef.value.store.states.treeData.value[row.typeId].loaded = false; //加载数据并展开父节点 tableRef.value.store.loadOrToggle(row); }); } /** 新增按钮操作 */ function handleCreate(row) { let pid = null; if (row != null) { pid = row.typeId; } formRef.value.openForm(null, 'create', pid); } /** 修改按钮操作 */ function handleEdit(row) { const id = row.typeId || ids.value.join(","); formRef.value.openForm(id, 'edit', null); } /** 删除按钮操作 */ function handleDelete(row) { const deleteIds = row.typeId || ids.value.join(","); proxy.$confirm('是否确认删除编号为"' + deleteIds + '"的数据项?', "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }).then(function() { return deleteGoodsType(deleteIds); }).then(() => { proxy.$modal.msgSuccess("删除成功"); getList(); }).catch(function() {}); } // 多选框选中数据 function handleSelectionChange(selection) { ids.value = selection.map(item => item.typeId) single.value = selection.length != 1 multiple.value = !selection.length } /** 初始化 **/ onMounted(() => { getList(); }) </script>
from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.urls import reverse from django.utils.text import slugify class MenuItem(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(unique=True, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('menu:item', args=(self.slug,)) def __str__(self): return self.title class Menu(models.Model): title = models.CharField(max_length=100, unique=True) menu_items = models.ManyToManyField(MenuItem, related_name='menus', through='MenuItemOrder') def __str__(self): return self.title class MenuItemOrder(models.Model): menu_item = models.ForeignKey(MenuItem, related_name='menu_order', on_delete=models.CASCADE) menu = models.ForeignKey(Menu, related_name='ordered_menu_items', on_delete=models.CASCADE) parent = models.ForeignKey('self', related_name='children', on_delete=models.SET_NULL, blank=True, null=True) menu_position = models.CharField(max_length=150, editable=False) def __str__(self): return f"{self.menu_item.title}" @property def formatted_id(self): if self.id: return f"{self.id:03}" elif self._meta.model.objects.count() > 0: obj = self._meta.model.objects.latest('id') return f"{obj.id+1:03}" else: return f"{1:03}" def update_position(self): if self.parent: self.menu_position = "-".join((self.parent.menu_position, self.formatted_id)) else: self.menu_position = self.formatted_id def save(self, started=None, *args, **kwargs): self.update_position() super().save(*args, **kwargs) class Meta: ordering = ('menu_position', ) unique_together = (['menu', 'menu_item'],) @receiver(post_save, sender=MenuItemOrder, dispatch_uid="update_menu_position") def update_position(sender, instance, **kwargs): for child in instance.children.all(): try: child.save() except Exception as e: print(e)
<!-- "Copyright 2020 Infosys Ltd. Use of this source code is governed by GPL v3 license that can be found in the LICENSE file or at https://opensource.org/licenses/GPL-3.0 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3" --> <mat-toolbar color="primary"> <a mat-icon-button [routerLink]="'/my-skills'"> <mat-icon>arrow_back</mat-icon> </a> <span i18n="page title: Add Role" class="margin-left-xs">Add Role</span> <span class="spacer"></span> <a *ngIf="!noRoles" mat-icon-button (click)="onNoRoles()"> <mat-icon>close</mat-icon> </a> </mat-toolbar> <div *ngIf="!noRoles" class="roles-container flex flex-center flex-wrapped margin-top-xl"> <div class="margin-bottom-xl "> <h2 class="mat-title" i18n="section heading add new role"> Add New Role </h2> <mat-card class="add-role-card"> <mat-tab-group class="tab-width"> <mat-tab label="Pick from Suggested Roles"> <ng-container *ngIf="loader" class="margin-left-s margin-top-m padding-top-m"> <app-spinner [spinMode]="'indeterminate'" [spinSize]="'large'" [spinWidth]="'thin'" [spinValue]="70" [spinColor]="'primary'" class="progress-circular-full"> </app-spinner> </ng-container> <mat-accordion *ngIf="!loader"> <mat-expansion-panel *ngFor="let role of availableRoles"> <mat-expansion-panel-header> <mat-panel-title> {{ role.role_name}} </mat-panel-title> <mat-panel-description> </mat-panel-description> </mat-expansion-panel-header> <div> <mat-list> <mat-list-item *ngFor="let i of role.skills"> <h4 mat-line class="margin-right-m"> {{ i?.skill_name }} </h4> <p mat-line class="margin-right-m">{{ i?.description }}</p> </mat-list-item> </mat-list> <button mat-raised-button color="primary" i18n (click)="addPredefinedRole(role.role_id)"> Add </button> </div> </mat-expansion-panel> </mat-accordion> </mat-tab> <mat-tab label="Create your Own" class="width-1-1"> <form class="mat-form-field"> <mat-form-field class="width-1-1"> <input matInput minlength="4" maxlength="100" [(ngModel)]="role_name" i18n-placeholder="input placeholder Role Title" placeholder="Role Title (required)" name="role_name" autocomplete="off" ngModel required /> </mat-form-field> </form> <mat-chip-list> <mat-chip *ngFor="let skill of selectedSkills" [selectable]="selectable" [removable]="removable" (removed)="remove(skill)"> {{ skill?.skill_name }} <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon> </mat-chip> </mat-chip-list> <form class="example-form"> <mat-form-field> <input type="text" name="skillName" placeholder="Search for skills(required)" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" [(ngModel)]="skill_id" (ngModelChange)="onAutoComplete($event)" ngModel required /> <mat-icon matSuffix>search</mat-icon> <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onOptionSelected($event.option.value)" [displayWith]="displayFn"> <mat-option *ngFor="let option of options" [value]="option"> {{ option?.skill_name }} </mat-option> </mat-autocomplete> </mat-form-field> <!-- <mat-form-field class="text-width"> <mat-label>Select a skill level</mat-label> <mat-select name="level" formControlName="level" [(value)]="selected"> <mat-option (click)="addLevel('Basic')" value="Basic">Basic</mat-option> <mat-option (click)="addLevel('Advanced')" value="Advanced">Advanced</mat-option> <mat-option (click)="addLevel('Expert')" value="Expert">Expert</mat-option> </mat-select> </mat-form-field> --> <div class="flex"> <span class="spacer"></span> <button mat-raised-button color="primary" type="submit" (click)="createNewRole(role_name, skill_id)" i18n> Add </button> </div> </form> </mat-tab> </mat-tab-group> </mat-card> </div> </div> <div *ngIf="noRoles"> <div class="margin-top-xl margin-right-m text-right cursor-pointer"> <button color="primary" mat-raised-button i18n-matTooltip="Goals Action Btn Tooltip" matTooltip="Create Role" (click)="onCreateRole()" color="primary" accesskey="+" i18n> <mat-icon>add</mat-icon> CREATE </button> </div> <div class="flex flex-center flex-wrapped margin-top-xl"> <h2 class="flex flex-center flex-wrapped" i18n> You have no roles </h2> </div> </div>
package com.mineplex.studio.example.survivalgames.modules.manager.ui; import com.mineplex.studio.example.survivalgames.modules.manager.GameManagerModule; import com.mineplex.studio.sdk.gui.MineplexGUI; import com.mineplex.studio.sdk.modules.game.MineplexGame; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.geysermc.cumulus.form.Form; import org.geysermc.cumulus.form.ModalForm; import xyz.xenondevs.inventoryaccess.component.AdventureComponentWrapper; import xyz.xenondevs.invui.gui.Gui; import xyz.xenondevs.invui.item.impl.SimpleItem; import xyz.xenondevs.invui.window.Window; /** * {@link MineplexGUI} example that is opened through {@link com.mineplex.studio.example.survivalgames.modules.manager.commands.GameCommand}. * The {@link GameGUI} provides a way to stop an ongoing {@link com.mineplex.studio.sdk.modules.game.MineplexGame}. */ @RequiredArgsConstructor public class GameGUI implements MineplexGUI { // Modules /** * The {@link GameManagerModule} is responsible for stopping the game. */ private final GameManagerModule module; /** * Create a Bedrock {@link Form} for stopping a {@link MineplexGame}. * * @param player The player for whom the form is being created. * @return The Bedrock form for stopping the game. */ @Override public Form createBedrockForm(@NonNull final Player player) { return ModalForm.builder() .title(GameGUIMessageComponent.GUI_TITLE.renderBedrock(player)) .content(GameGUIMessageComponent.GUI_CONTENT.renderBedrock(player)) .button1(GameGUIMessageComponent.GUI_STOP.renderBedrock(player)) .button2(GameGUIMessageComponent.GUI_CANCEL.renderBedrock(player)) .validResultHandler(response -> { if (response.clickedFirst()) { this.module.stopGame(); } }) .build(); } /** * Create a Java GUI for stopping a {@link MineplexGame}. * * @param player The player for whom the menu is being created. * @return The Java GUI for stopping the game. */ @Override public Window createJavaInventoryMenu(@NonNull final Player player) { final ItemStack display = new ItemStack(Material.REDSTONE_BLOCK); display.editMeta(displayItemMeta -> displayItemMeta.displayName(GameGUIMessageComponent.GUI_CONTENT.apply())); final Gui gui = Gui.normal() .setStructure("# # # # C # # # #") .addIngredient('C', new SimpleItem(display, click -> { final Player pl = click.getPlayer(); pl.closeInventory(); this.module.stopGame(); })) .build(); return Window.single() .setViewer(player) .setTitle(new AdventureComponentWrapper(GameGUIMessageComponent.GUI_TITLE.apply())) .setGui(gui) .build(); } }
__ ______ ____ ________ __ __ ____ / //_/ __ \/ __ \/ ____/ //_// / / __ \ / ,< / / / / / / / __/ / ,< / / / / / / / /| / /_/ / /_/ / /___/ /| |/ /___/ /_/ / /_/ |_\____/_____/_____/_/ |_/_____/\____/ __ ______ / / / / __ \ / / / / / / / / /_/ / /_/ / \____/_____/ All rights reserved $ touch Dockerfile $ vi Dockerfile FROM node:10-alpine WORKDIR /app COPY . . RUN yarn install --production CMD ["node", "/app/src/index.js"] $ docker build -t docker-101 . Sending build context to Docker daemon 557.Sending build context to Docker daemon 2.78Sending build context to Docker daemon 3.216MB Step 1/5 : FROM node:10-alpine 10-alpine: Pulling from library/node ddad3d7c1e96: Pull complete de915e575d22: Pull complete 7150aa69525b: Pull complete d7aa47be044e: Pull complete Digest: sha256:dc98dac24efd4254f75976c40bce46944697a110d06ce7fa47e7268470cf2e28 Status: Downloaded newer image for node:10-alpine ---> aa67ba258e18 Step 2/5 : WORKDIR /app ---> Running in 488a113b4f78 Removing intermediate container 488a113b4f78 ---> 5f995a705e36 Step 3/5 : COPY . . ---> c7082d278516 Step 4/5 : RUN yarn install --production ---> Running in 6cac6b34182d yarn install v1.22.5 info No lockfile found. [1/4] Resolving packages... [2/4] Fetching packages... [3/4] Linking dependencies... [4/4] Building fresh packages... success Saved lockfile. Done in 0.19s. Removing intermediate container 6cac6b34182d ---> d719a53cfdbd Step 5/5 : CMD ["node", "/app/src/index.js"] ---> Running in ca9c42377aa1 Removing intermediate container ca9c42377aa1 ---> e4059261d624 Successfully built e4059261d624 Successfully tagged docker-101:latest $ Start your container using the docker run command: $ docker run -dp 3000:3000 docker-101 8754151d0e9d9836b2fcb6b33e6d1d52f4e0d481b98c87b89e81be75d81737dc $ > $ docker run -dp 3000:3000 docker-101 8754151d0e9d9836b2fcb6b33e6d1d52f4e0d481b98c87b89e81be75d81737dc $ docker build -t docker-101 . Sending build context to Docker daemon 55Sending build context to Docker daemon 3.216MB Step 1/5 : FROM node:10-alpine ---> aa67ba258e18 Step 2/5 : WORKDIR /app ---> Using cache ---> 5f995a705e36 Step 3/5 : COPY . . ---> Using cache ---> c7082d278516 Step 4/5 : RUN yarn install --production ---> Using cache ---> d719a53cfdbd Step 5/5 : CMD ["node", "/app/src/index.js"] ---> Using cache ---> e4059261d624 Successfully built e4059261d624 Successfully tagged docker-101:latest $ >> $ docker run -dp 3000:3000 docker-101 8681e988693849db54c33859634e4e63e98b6f773192a5dbb3f9d04b667aeeef $ >> $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 8681e9886938 docker-101 "docker-entrypoint.s…" 44 seconds ago Exited (1) 42 seconds ago exciting_kepler 8754151d0e9d docker-101 "docker-entrypoint.s…" 2 minutes ago Exited (1) 2 minutes ago gallant_spence $ docker rm docker exciting_kepler exciting_kepler Error: No such container: docker $ $ docker run -dp 3000:3000 docker-101 ab704d5278bb6afbfdbd1d0a77048ac810e70cb9a5c6cc46de4b5392bb9d6665 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $ >> $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ab704d5278bb docker-101 "docker-entrypoint.s…" 35 seconds ago Exited (1) 32 seconds ago epic_ptolemy 8754151d0e9d docker-101 "docker-entrypoint.s…" 4 minutes ago Exited (1) 4 minutes ago gallant_spence $ docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE docker-101 latest e4059261d624 6 minutes ago 85.9MB redis latest eca1379fe8b5 7 months ago 117MB mysql latest 8189e588b0e8 7 months ago 564MB nginx latest 6efc10a0510f 7 months ago 142MB postgres latest ceccf204404e 7 months ago 379MB nginx alpine 8e75cbc5b25c 7 months ago 41MB alpine latest 9ed4aefc74f6 7 months ago 7.04MB ubuntu latest 08d22c0ceb15 8 months ago 77.8MB node 10-alpine aa67ba258e18 2 years ago 82.7MB kodekloud/simple-webapp-mysql latest 129dd9f67367 5 years ago 96.6MB kodekloud/simple-webapp latest c6e3cd9aae36 5 years ago 84.8MB $ docker image prune WARNING! This will remove all dangling images. Are you sure you want to continue? [y/N] y Total reclaimed space: 0B $ >> $ docker login Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one. Username: kalyanjs Password: WARNING! Your password will be stored unencrypted in /root/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded $ >> Use the docker tag command to give the docker-101 image a new name. Be sure to swap out YOUR-USER-NAME with your Docker ID. docker tag docker-101 YOUR-USER-NAME/101-todo-app Now try your push command again. If you're copying the value from Docker Hub, you can drop the tagname portion, as we didn't add a tag to the image name. docker push YOUR-USER-NAME/101-todo-app >> $ docker run -dp 3000:3000 kalyanjs/101-todo-app 1057e4b77fe2a212ba526607dded03fff20b9142797140ed8b67eb8d9e181e8c $ Persisting our DB: In case you didn't notice, our todo list is being wiped clean every single time we launch the container. Why is this? Let's dive into how the container is working. The Container's Filesystem: When a container runs, it uses the various layers from an image for its filesystem. Each container also gets its own "scratch space" to create/update/remove files. Any changes won't be seen in another container, even if they are using the same image. we're going to start two containers and create a file in each. What you'll see is that the files created in one container aren't available in another. Start a ubuntu container that will create a file named /data.txt with a random number between 1 and 10000. docker run -d ubuntu bash -c "shuf -i 1-10000 -n 1 -o /data.txt && tail -f /dev/null" $ docker run -d ubuntu bash -c "shuf -i 1-10000 -n 1 -o /data.txt && tail -f /dev/null" 6e2a248e03bb5d03f12401faf5bf50240ed1e01f953aee54d9892e694e91c9f7 $ In case you're wondering about the command, we're starting a bash shell and invoking two commands (why we have the &&). The first portion picks a single random number and writes it to /data.txt. The second command is simply watching a file to keep the container running. >> $ docker exec 6e2a cat /data.txt 7563 $ >> $ docker run -it ubuntu ls / bin dev home lib32 libx32 mnt proc run srv tmp var boot etc lib lib64 media opt root sbin sys usr $ >> $ docker rm -f 6e2a 6e2a $ >> Container Volumes¶: Volumes provide the ability to connect specific filesystem paths of the container back to the host machine. If a directory in the container is mounted, changes in that directory are also seen on the host machine. If we mount that same directory across container restarts, we'd see the same files. There are two main types of volumes: Persisting our Todo Data¶ By default, the todo app stores its data in a SQLite Database at /etc/todos/todo.db. If you're not familiar with SQLite, no worries! It's simply a relational database in which all of the data is stored in a single file. While this isn't the best for large-scale applications, it works for small demos. We'll talk about switching this to an actual database engine later. With the database being a single file, if we can persist that file on the host and make it available to the next container, it should be able to pick up where the last one left off. By creating a volume and attaching (often called "mounting") it to the directory the data is stored in, we can persist the data. As our container writes to the todo.db file, it will be persisted to the host in the volume. As mentioned, we are going to use a named volume. Think of a named volume as simply a bucket of data. Docker maintains the physical location on the disk and you only need to remember the name of the volume. Every time you use the volume, Docker will make sure the correct data is provided. >> $ docker volume create todo-db todo-db $ >> $ docker run -dp 3000:3000 -v todo-db:/etc/todos docker-101 b0967afc7c29bc315cbbe1c3c34a2bea6931731491220813b6c6508ce4c0d071 $ >> $ docker rm -f b096 b096 $ >> $ docker run -dp 3000:3000 -v todo-db:/etc/todos docker-101 54b9c5d131deedf3e15adadab7ffe495bda3cb7a4700d0dc5bb00590180e3861 $ >> $ docker rm -f 54b 54b $ Diving into our Volume¶ A lot of people frequently ask "Where is Docker actually storing my data when I use a named volume?" If you want to know, you can use the docker volume inspect command. docker volume inspect todo-db [ { "CreatedAt": "2019-09-26T02:18:36Z", "Driver": "local", "Labels": {}, "Mountpoint": "/var/lib/docker/volumes/todo-db/_data", "Name": "todo-db", "Options": {}, "Scope": "local" } ] The Mountpoint is the actual location on the disk where the data is stored. Note that on most machines, you will need to have root access to access this directory from the host. But, that's where it is! >> $ docker volume inspect todo-db [ { "CreatedAt": "2023-11-17T09:03:52Z", "Driver": "local", "Labels": {}, "Mountpoint": "/var/lib/docker/volumes/todo-db/_data", "Name": "todo-db", "Options": {}, "Scope": "local" } ] $ >> Using Bind Mounts In the previous chapter, we talked about and used a named volume to persist the data in our database. Named volumes are great if we simply want to store data, as we don't have to worry about where the data is stored. With bind mounts, we control the exact mountpoint on the host. We can use this to persist data, but is often used to provide additional data into containers. When working on an application, we can use a bind mount to mount our source code into the container to let it see code changes, respond, and let us see the changes right away. For Node-based applications, nodemon is a great tool to watch for file changes and then restart the application. There are equivalent tools in most other languages and frameworks. Starting a Dev-Mode Container¶ To run our container to support a development workflow, we will do the following: Mount our source code into the container Install all dependencies, including the "dev" dependencies Start nodemon to watch for filesystem changes So, let's do it! Make sure you don't have any previous docker-101 containers running. Run the following command. We'll explain what's going on afterwards: docker run -dp 3000:3000 \ -w /app -v $PWD:/app \ node:10-alpine \ sh -c "yarn install && yarn run dev" -dp 3000:3000 - same as before. Run in detached (background) mode and create a port mapping -w /app - sets the "working directory" or the current directory that the command will run from node:10-alpine - the image to use. Note that this is the base image for our app from the Dockerfile sh -c "yarn install && yarn run dev" - the command. We're starting a shell using sh (alpine doesn't have bash) and running yarn install to install all dependencies and then running yarn run dev. If we look in the package.json, we'll see that the dev script is starting nodemon. >> $ docker run -dp 3000:3000 \ > -w /app -v $PWD:/app \ > node:10-alpine \ > sh -c "yarn install && yarn run dev" c06f2deafd3a9a13908e6baf9233b88ab8d0024c5a3c2b76e54463821853cd26 $ >> $ docker logs -f c06 yarn install v1.22.5 info No lockfile found. [1/4] Resolving packages... [2/4] Fetching packages... [3/4] Linking dependencies... [4/4] Building fresh packages... success Saved lockfile. Done in 0.27s. yarn run v1.22.5 error Couldn't find a package.json file in "/app" info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. $ >> $ docker build -t docker-101 . Sending build context to Docker daemon 55Sending build context to Docker daemon 2.Sending build context to Docker daemon 3.22MB Step 1/5 : FROM node:10-alpine ---> aa67ba258e18 Step 2/5 : WORKDIR /app ---> Using cache ---> 5f995a705e36 Step 3/5 : COPY . . ---> b71d6293f2eb Step 4/5 : RUN yarn install --production ---> Running in 780825afb985 yarn install v1.22.5 [1/4] Resolving packages... success Nothing to install. success Saved lockfile. Done in 0.20s. Removing intermediate container 780825afb985 ---> bce72a41764b Step 5/5 : CMD ["node", "/app/src/index.js"] ---> Running in 019d22fc5e36 Removing intermediate container 019d22fc5e36 ---> 39377c432a14 Successfully built 39377c432a14 Successfully tagged docker-101:latest $ Using bind mounts is very common for local development setups. The advantage is that the dev machine doesn't need to have all of the build tools and environments installed. With a single docker run command, the dev environment is pulled and ready to go. We'll talk about Docker Compose in a future step, as this will help simplify our commands (we're already getting a lot of flags). Multi-Container Apps Up to this point, we have been working with single container apps. But, we now want to add MySQL to the application stack. The following question often arises - "Where will MySQL run? Install it in the same container or run it separately?" In general, each container should do one thing and do it well. A few reasons: There's a good chance you'd have to scale APIs and front-ends differently than databases Separate containers let you version and update versions in isolation While you may use a container for the database locally, you may want to use a managed service for the database in production. You don't want to ship your database engine with your app then. Running multiple processes will require a process manager (the container only starts one process), which adds complexity to container startup/shutdown And there are more reasons. So, we will update our application to work like this: Todo App connected to MySQL container Container Networking¶ Remember that containers, by default, run in isolation and don't know anything about other processes or containers on the same machine. So, how do we allow one container to talk to another? The answer is networking. Now, you don't have to be a network engineer (hooray!). Simply remember this rule... If two containers are on the same network, they can talk to each other. If they aren't, they can't. Starting MySQL¶ There are two ways to put a container on a network: 1) Assign it at start or 2) connect an existing container. For now, we will create the network first and attach the MySQL container at startup. >> $ docker network create todo-app ae67faca5831d4ebbe1099bd0e498c1afa198f87addfbfc7500524d23ba0ef03 $ >> Start a MySQL container and attach it the network. We're also going to define a few environment variables that the database will use to initialize the database (see the "Environment Variables" section in the MySQL Docker Hub listing). docker run -d \ --network todo-app --network-alias mysql \ -v todo-mysql-data:/var/lib/mysql \ -e MYSQL_ROOT_PASSWORD=secret \ -e MYSQL_DATABASE=todos \ mysql:5.7 >> $ docker run -d \ > --network todo-app --network-alias mysql \ > -v todo-mysql-data:/var/lib/mysql \ > -e MYSQL_ROOR_PASSWORD=secret \ > -e MYSQL_DATABASE=todos \ > mysql:5.7 Unable to find image 'mysql:5.7' locally 5.7: Pulling from library/mysql 11a38aebcb7a: Pull complete 91ab01309bd6: Pull complete 6c91fabb88c2: Pull complete 8f46e806ab5c: Pull complete 29f5af1d1661: Pull complete 62aca7179a54: Pull complete 85023e6de3be: Pull complete 6d5934a87cbb: Pull complete c878502d3f70: Pull complete 4756467c684a: Pull complete ee9043dd2677: Pull complete Digest: sha256:f566819f2eee3a60cf5ea6c8b7d1bfc9de62e34268bf62dc34870c4fca8a85d1 Status: Downloaded newer image for mysql:5.7 97f0d1f5767c8ef03fa9c11d30d9f50e6d192038c7412ceff42a12583c6f6197 $ >> $ docker exec -it 97f0 mysql -p Error response from daemon: Container 97f0d1f5767c8ef03fa9c11d30d9f50e6d192038c7412ceff42a12583c6f6197 is not running $ >> When the password prompt comes up, type in secret. In the MySQL shell, list the databases and verify you see the todos database. mysql> SHOW DATABASES; You should see output that looks like this: +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | todos | +--------------------+ 5 rows in set (0.00 sec) Hooray! We have our todos database and it's ready for us to use! >> Connecting to MySQL¶: If we run another container on the same network, how do we find the container (remember each container has its own IP address)? To figure it out, we're going to make use of the nicolaka/netshoot container, which ships with a lot of tools that are useful for troubleshooting or debugging networking issues. Start a new container using the nicolaka/netshoot image. Make sure to connect it to the same network. docker run -it --network todo-app nicolaka/netshoot >> $ docker run -it --network todo-app nicolaka/netshoot Unable to find image 'nicolaka/netshoot:latest' locally latest: Pulling from nicolaka/netshoot 8a49fdb3b6a5: Pull complete f08cc7654b42: Pull complete bacdb080ad6d: Pull complete df75a2676b1d: Pull complete d30ac41fb6a9: Pull complete 3f3eebe79603: Pull complete 086410b5650d: Pull complete 4f4fb700ef54: Pull complete 5a7fe97d184f: Pull complete a6d1b2d7a50e: Pull complete 599ae1c27c63: Pull complete dd5e50b27eb9: Pull complete 2681a5bf3176: Pull complete 2517e0a2f862: Pull complete 7b5061a1528d: Pull complete Digest: sha256:a7c92e1a2fb9287576a16e107166fee7f9925e15d2c1a683dbb1f4370ba9bfe8 Status: Downloaded newer image for nicolaka/netshoot:latest dP dP dP 88 88 88 88d888b. .d8888b. d8888P .d8888b. 88d888b. .d8888b. .d8888b. d8888P 88' `88 88ooood8 88 Y8ooooo. 88' `88 88' `88 88' `88 88 88 88 88. ... 88 88 88 88 88. .88 88. .88 88 dP dP `88888P' dP `88888P' dP dP `88888P' `88888P' dP Welcome to Netshoot! (github.com/nicolaka/netshoot) Version: 0.11 0b90f9b5ec9c  ~  0b90f9b5ec9c  ~  dig mysql ; <<>> DiG 9.18.13 <<>> mysql ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47863 ;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;mysql. IN A ;; Query time: 4 msec ;; SERVER: 127.0.0.11#53(127.0.0.11) (UDP) ;; WHEN: Fri Nov 17 09:30:55 UTC 2023 ;; MSG SIZE rcvd: 23 0b90f9b5ec9c  ~  In the "ANSWER SECTION", you will see an A record for mysql that resolves to 172.23.0.2 (your IP address will most likely have a different value). While mysql isn't normally a valid hostname, Docker was able to resolve it to the IP address of the container that had that network alias (remember the --network-alias flag we used earlier?). What this means is... our app only simply needs to connect to a host named mysql and it'll talk to the database! It doesn't get much simpler than that! unning our App with MySQL¶ The todo app supports the setting of a few environment variables to specify MySQL connection settings. They are: MYSQL_HOST - the hostname for the running MySQL server MYSQL_USER - the username to use for the connection MYSQL_PASSWORD - the password to use for the connection MYSQL_DB - the database to use once connected With all of that explained, let's start our dev-ready container! We'll specify each of the environment variables above, as well as connect the container to our app network. docker run -dp 3000:3000 \ -w /app -v $PWD:/app \ --network todo-app \ -e MYSQL_HOST=mysql \ -e MYSQL_USER=root \ -e MYSQL_PASSWORD=secret \ -e MYSQL_DB=todos \ node:10-alpine \ sh -c "yarn install && yarn run dev" >> $ docker run -dp 3000:3000 \ > -w /app -v $PWD:/app \ > --network todo-app \ > -e MYSQL_HOST=mysql \ > -e MYSQL_USER=root \ > -e mysql_DB=todos \ > node:10-alpine \ > sh -c "yarn install && yarn run dev" a9124a49660b2169d79270d6086c775df716d9ceb37618c8e14b7685843000a9 $ >> $ docker logs a912 yarn install v1.22.5 [1/4] Resolving packages... success Already up-to-date. Done in 0.21s. yarn run v1.22.5 error Couldn't find a package.json file in "/app" info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. $ Connect to the mysql database and prove that the items are being written to the database. Remember, the password is secret. >> Connect to the mysql database and prove that the items are being written to the database. Remember, the password is secret. docker exec -ti <mysql-container-id> mysql -p todos And in the mysql shell, run the following: mysql> select * from todo_items; +--------------------------------------+--------------------+-----------+ | id | name | completed | +--------------------------------------+--------------------+-----------+ | c906ff08-60e6-44e6-8f49-ed56a0853e85 | Do amazing things! | 0 | | 2912a79e-8486-4bc3-a4c5-460793a575ab | Be awesome! | 0 | +--------------------------------------+--------------------+-----------+ Obviously, your table will look different because it has your items. But, you should see them stored there! >> $ touch docker-compose.yml $ vi docker-compose.yml >> version: "3.7" services: app: image: node:10-alpine command: sh -c "yarn install && yarn run dev" ports: - 3000:3000 working_dir: /app volumes: - ./:/app environment: MYSQL_HOST: mysql MYSQL_USER: root MYSQL_PASSWORD: secret MYSQL_DB: todos mysql: image: mysql:5.7 volumes: - todo-mysql-data:/var/lib/mysql environment: MYSQL_ROOT_PASSWORD: secret MYSQL_DATABASE: todos volumes: todo-mysql-data: >> docker-compose up -d >> docker image history >> You'll notice that several of the lines are truncated. If you add the --no-trunc flag, you'll get the full output (yes... funny how you use a truncated flag to get untruncated output, huh?) docker image history --no-trunc docker-101 Update the Dockerfile to copy in the package.json first, install dependencies, and then copy everything else in. FROM node:10-alpine WORKDIR /app COPY package.json yarn.lock ./ RUN yarn install --production COPY . . CMD ["node", "/app/src/index.js"] Build a new image using docker build. >> docker build -t docker-101 .
<template> <!-- 上方背景 --> <div class="w-full h-[400px] md:h-[460px] lg:h-[600px] 2xl:h-[700px] bg-no-repeat bg-cover absolute top-0 -z-10 bg-bottom shadow" :style="`background-image: url(${venue.picture?.horizontal})`"></div> <!-- 場地體驗 --> <section class="container pb-20 lg:pb-32 pt-[400px] md:pt-[460px] lg:pt-[600px] 2xl:pt-[700px] space-y-6 lg:space-y-10"> <main class="space-y-6 lg:space-y-10"> <div class="text-center"> <h1 class="text-4xl lg:text-5xl font-black">{{ venue.title }}</h1> <div class="py-4 lg:hidden text-center text-black-40"> {{ venue.address }} </div> <div class="hidden lg:grid grid-cols-3 text-lg text-center text-black-40" @mouseover="hoverTitle" @mouseleave="removeHoverTitle"> <div class="collapse-left py-4">{{ venue.seat_amount }} 席次</div> <div class="col-start-2 py-4">{{ venue.eng_title }}</div> <div class="collapse-right py-4">{{ venue.address }}</div> </div> </div> <TitleComponent class="flex justify-center"> <template #subTitle> VENUES </template> <template #mainTitle> 場地體驗 </template> </TitleComponent> <div class="grid grid-cols-1 lg:grid-cols-5 gap-6"> <!-- 場地點擊區 --> <article class="lg:order-2 lg:col-span-2 py-10 sm:py-14 px-7 xs:px-9 sm:px-12 lg:px-14 rounded-[40px] bg-shadow-trans-text venue-section"> <!-- Venue Title --> <p class="text-gray-500 text-base sm:text-xl lg:pt-5 font-lato text-center">_____ STAGE _____</p> <!-- Venue Seats --> <div class="h-[200px] sm:h-[300px] w-[80%] xl:w-[60%] text-sm sm:text-base grid grid-flow-row auto-row-max gap-2 md:gap-4 mx-auto my-3 lg:my-5"> <div @click="activeArea(area)" v-for="(area, index) in venue.seat_areas" :key="`${index + 123}`" class="text-[12px] md:text-base lg:text-lg gradient-border flex justify-center items-center transition-transform xl:hover:-translate-x-1 xl:hover:-translate-y-1 cursor-pointer" :class="area === seatArea ? 'active' : ''"> <p> {{ area }} </p> </div> </div> </article> <!-- 評論區 --> <div class="space-y-6 lg:space-y-10 box-shadow-light2 px-6 py-10 sm:p-10 rounded-btn2 lg:col-span-3"> <div class="flex justify-between items-center"> <Select v-model="seatArea"> <!-- <SelectTrigger class="w-1/3 border-0 text-primary bg-pink box-shadow-pink-blur box-shadow-pink-blur-hover focus-visible:outline-0 h-10 p-4 md:py-4 md:px-6 rounded-btn1"> --> <SelectTrigger class="w-2/3 sm:w-1/3 border-2 text-white border-black-40 hover:text-black hover:bg-white hover:box-shadow-light1-hover focus-visible:outline-0 h-10 p-4 md:py-4 md:px-6 rounded-btn1"> <SelectValue placeholder="全部座位區" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>座位區</SelectLabel> <SelectItem value="all"> 全部座位區 </SelectItem> <SelectItem :value="seat" v-for="seat in venue.seat_areas" :key="seat"> {{ seat }} </SelectItem> </SelectGroup> </SelectContent> </Select> <!-- 新增評論區 --> <div class="text-center"> <template v-if="AccessToken === undefined"> <AlertDialog> <AlertDialogTrigger as-child> <Button variant="white-outline" class="rounded-full p-2 hover:bg-pink hover:text-primary hover:box-shadow-pink-blur-hover hover:border-pink hover:text-white"> <font-awesome-icon icon="fa-solid fa-plus" class="text-xl size-6" /> </Button> </AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>登入才能進行評論 ᓫ(°⌑°)ǃ</AlertDialogTitle> <AlertDialogDescription></AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>取消</AlertDialogCancel> <AlertDialogAction asChild> <router-link to="/login"> 前往登入 </router-link> </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </template> <template v-else> <Dialog :open="isToggleCommentModal" @update:open="toggleModal"> <DialogTrigger as-child> <Button variant="white-outline" class="rounded-full p-2 hover:bg-pink hover:text-primary hover:box-shadow-pink-blur-hover hover:border-pink hover:text-white"> <font-awesome-icon icon="fa-solid fa-plus" class="text-xl size-6" /> </Button> </DialogTrigger> <DialogScrollContent class="max-w-sm md:max-w-3xl"> <DialogHeader class="mb-6"> <DialogTitle>留下評論</DialogTitle> <DialogDescription> <p class="text-sm text-black-60 pb-4">※ 座位區、演唱會與評論皆需填寫,若有缺漏會新增失敗。</p> </DialogDescription> </DialogHeader> <form @submit="onSubmit" class="space-y-6 lg:space-y-10" ref="modalForm"> <div class="relative flex items-center"> <Label for="seat-select" class="absolute text-white bg-black-85 border-black-85 border rounded-md pl-6 pr-20 -z-10 py-2 px-3">座位區</Label> <Select v-model="commentSeatArea" id="seat-select"> <SelectTrigger class="ml-[7rem] border-white w-[220px] md:w-full"> <SelectValue placeholder="選取座位區" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>選取座位區</SelectLabel> <SelectItem :value="seat" v-for="seat in venue.seat_areas" :key="seat"> {{ seat }} </SelectItem> </SelectGroup> </SelectContent> </Select> </div> <div class="flex items-center"> <Label for="concert-select" class="absolute text-white bg-black-85 border-black-85 border rounded-md pl-6 pr-20 -z-10 py-2 px-3">演唱會</Label> <Select id="concert-select" v-model="concertId"> <SelectTrigger class="ml-[7rem] border-white w-[220px] md:w-full"> <SelectValue placeholder="選取演唱會" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectLabel>選取演唱會</SelectLabel> <SelectItem :value="concert.id.toString()" v-for="concert in venue.concerts" :key="concert.id"> {{ concert.title }} <time class="text-black-40">{{ concert.holding_time.split(' ')[0] }}</time> </SelectItem> </SelectGroup> </SelectContent> </Select> </div> <div> <div class="relative flex items-center mb-4"> <Label for="commentPictures" class="absolute text-white bg-black-85 border-black-85 border rounded-md pl-6 pr-20 -z-10 py-2 px-3">評論圖片</Label> <input id="commentPictures" ref="commentPicturesInput" multiple class="hidden" type="file" accept="image/png, image/jpeg" @change="readURL" /> <Button type="button" class="ml-[7rem] border-white border w-[220px] md:w-full rounded-md justify-start text-sm px-3" @click="handleFileButton"> <span v-if="!images.length">未選擇任何檔案</span> <span v-else>已選擇{{ images.length }}個檔案</span> </Button> </div> <div class="space-y-4"> <span class="text-sm text-black-60">圖片至多可傳三張(單一圖檔不能超過3MB)</span> <div class="flex justify-center space-x-4"> <img id="commentImage1" class="size-[80px] lg:size-[150px]" src="http://placehold.it/150" alt="your image" v-if="images[0]" /> <img id="commentImage2" class="size-[80px] lg:size-[150px]" src="http://placehold.it/150" alt="your image" v-if="images[1]" /> <img id="commentImage3" class="size-[80px] lg:size-[150px]" src="http://placehold.it/150" alt="your image" v-if="images[2]" /> </div> </div> </div> <div> <Textarea v-model="commentContent" placeholder="留下你的評論..." /> </div> <DialogFooter class="justify-center sm:justify-center flex-col sm:flex-col space-y-2"> <div class="flex justify-center items-center"> <Button for="commentPolicy" type="button" class="text-sm text-black-60 text-right cursor-pointer px-0" @click="showCommentPolicy">送出即代表您同意遵守評論規範</Button> </div> <div class="flex justify-center items-center space-x-2"> <DialogClose as-child> <Button type="button" size="base" class="bg-black-80 hover:bg-black-80 px-14 md:px-14 lg:px-14">取消</Button> </DialogClose> <Button variant="tiffany-fill" size="base" type="submit" class="px-14 md:px-14 lg:px-14">送出評論</Button> </div> </DialogFooter> </form> </DialogScrollContent> </Dialog> </template> </div> </div> <ScrollArea class="lg:h-[350px]"> <div v-for="(comment, index) in filterSeatComment" :key="comment.id" class="grid grid-cols-12 gap-x-3 border-b border-black-60 py-4 min-h-[150px]" :class="{ 'border-t': index === 0 }"> <div class="col-span-2 sm:col-span-1 lg:col-span-1"> <img :src="comment.user.profile_image_url" :alt="comment.user.name" class="rounded-full size-8 bg-white/25 object-cover" /> </div> <div class="col-span-8 sm:col-span-10 lg:col-span-10 xl:col-span-10 flex flex-col space-y-4"> <div class="space-x-3"> <span>{{ comment.user.name }}</span> <span class="text-black-40">{{ comment.seat_area }}</span> </div> <div class="text-sm md:text-base lg:flex lg:flex-wrap lg:justify-between"> <p class="mb-4 lg:mb-0">{{ comment.comment }}</p> <div class="flex space-x-3 w-full lg:w-auto" v-if="comment.images.length"> <template v-for="(image, index) in comment.images" :key="index"> <img :src="image" alt="" class="size-20 object-cover rounded-xl" /> </template> </div> </div> <div class="text-tiny text-black-60"> <p class="truncate">{{ comment.concert.title }}</p> <time>{{ comment.created_at }}</time> </div> </div> <div class="col-span-2 sm:col-span-1 lg:col-span-1 lg:-ml-4 xl:ml-0"> <Popover> <PopoverTrigger as-child> <Button variant="ghost" class="p-1"> <MoreHorizontal /> </Button> </PopoverTrigger> <PopoverContent> <AlertDialog v-if="AccessToken === undefined"> <AlertDialogTrigger as-child> <Button class="justify-between w-full"> <span>檢舉該名使用者</span> <AlertCircle /> </Button> </AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>登入才能檢舉 ᓫ(°⌑°)ǃ</AlertDialogTitle> <AlertDialogDescription></AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>取消</AlertDialogCancel> <AlertDialogAction asChild> <router-link to="/login"> 前往登入 </router-link> </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> <Button v-else @click="reportUser(comment.user.name)" class="justify-between w-full"> <span>檢舉該名使用者</span> <AlertCircle /> </Button> </PopoverContent> </Popover> </div> </div> </ScrollArea> </div> </div> </main> </section> <!-- 場地名稱跑馬燈 --> <div> <div class="bg-tiffany"> <div ref="marquee" class="flex text-[5rem] md:text-[6.5rem] lg:text-[8rem] font-black text-black tracking-[-1px] whitespace-nowrap overflow-hidden mb-6 lg:mb-10 leading-[1]"> <p class="marquee space-x-4"> <span>{{ venue.title }}</span> <span class="text-stroke-black font-display uppercase">{{ venue.eng_title }}</span> <span>{{ venue.title }}</span> <span class="text-stroke-black font-display uppercase">{{ venue.eng_title }}</span> </p> <p class="marquee space-x-4"> <span>{{ venue.title }}</span> <span class="text-stroke-black font-display uppercase">{{ venue.eng_title }}</span> <span>{{ venue.title }}</span> <span class="text-stroke-black font-display uppercase">{{ venue.eng_title }}</span> </p> </div> </div> </div> <!-- 交通方式 --> <section class="container pb-[128px] lg:pb-[192px]"> <TitleComponent class="overflow-x-hidden"> <template #subTitle> TRANSPORT </template> <template #mainTitle> 交通方式 </template> </TitleComponent> <div class="mt-4 lg:mt-6"> <!-- 地圖 --> <div class="mb-4 lg:mb-6"> <iframe :src="venue.map_link" frameborder="0" class="w-full h-[375px] md:h-[600px] rounded-md"></iframe> </div> <!-- 查看交通方式 --> <div class="space-y-6 lg:space-y-10"> <Accordion type="single" collapsible> <AccordionItem class="lg:relative border-b-4" v-for="method in transportation" :key="method.type" :value="method.value"> <AccordionTrigger :hideIcon="true" :value="method.value" class="accordion-button hover:no-underline"> <div class="flex gap-4 font-black -mb-[18px] lg:-mb-[33px] pt-8 lg:pt-[42px]"> <ArrowDownRight class="size-10 lg:size-16 pb-2 sm:pb-0 lg:pb-2" /> <span class="text-lg sm:text-2xl lg:text-4xl">{{ method.type }}</span> </div> </AccordionTrigger> <AccordionContent class="lg:flex lg:justify-end"> <ul class="list-disc text-base px-6 space-y-4 lg:-mt-16 lg:w-3/4 hidden lg:block lg:opacity-0"> <li v-for="(t, index) in method.info" :key="index">{{ t }}</li> </ul> <ul class="list-disc text-base px-6 lg:px-0 space-y-4 mt-6 lg:mt-4 lg:w-2/3 lg:absolute lg:top-0"> <li v-for="(t, index) in method.info" :key="index">{{ t }}</li> </ul> </AccordionContent> </AccordionItem> </Accordion> </div> </div> </section> </template> <script setup> import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { Textarea } from '@/components/ui/textarea'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'; import { Dialog, DialogScrollContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, DialogClose } from '@/components/ui/dialog'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from '@/components/ui/alert-dialog'; import TitleComponent from '@/components/custom/TitleComponent.vue'; import { MoreHorizontal, ArrowDownRight, AlertCircle } from 'lucide-vue-next'; </script> <script> import { mapActions, mapState, mapWritableState } from 'pinia'; import { useVenuesStore } from '@/stores/venues'; import { http } from '@/api'; import { loadingStore } from '@/stores/isLoading'; import { useUserStore } from '@/stores/user'; import { useToast } from '@/components/ui/toast/use-toast'; const { setIsLoading } = loadingStore(); const { toast } = useToast(); export default { data() { return { commentSeatArea: '', concertId: '', commentContent: '', images: [], checkPolicy: true, isToggleCommentModal: false, accordionItems: [], }; }, props: ['id'], inject: ['http', 'path'], methods: { hoverTitle(e) { e.currentTarget.childNodes.forEach((element, index) => { if (index !== 1) { element.classList.add('show'); } }); }, removeHoverTitle(e) { e.currentTarget.childNodes.forEach((element, index) => { if (index !== 1) { element.classList.remove('show'); } }); }, readURL(input) { if (input.target.files && input.target.files[0]) { if (input.target.files.length > 3) { toast({ title: '圖片最多3張', description: '', }); return; } for (let i = 0; i < input.target.files.length; i++) { const reader = new FileReader(); // console.log(reader); if (input.target.files[i].size > 3 * 1024 ** 2) { toast({ title: '圖片不得超過3MB', description: '', }); return; } if (input.target.files[i].type !== 'image/png' && input.target.files[i].type !== 'image/jpg' && input.target.files[i].type !== 'image/jpeg' && input.target.files[i].type !== 'image/webp') { toast({ title: '圖片格式需為 png 或 jpg 或 webp', description: '', }); return; } reader.onload = (e) => { // console.log(e); document.querySelector('#commentImage' + (i + 1)).setAttribute('src', e.target.result); }; reader.readAsDataURL(input.target.files[i]); } this.images = [...input.target.files]; } }, handleFileButton() { this.$refs.commentPicturesInput.click(); }, onSubmit(e) { e.preventDefault(); this.postComment(); }, postComment() { if (this.concertId === '') { toast({ title: '請選擇演唱會', description: '', }); return; } if (this.commentSeatArea === '') { toast({ title: '請選擇座位區', description: '', }); return; } if (this.commentContent === '') { toast({ title: '請輸入評論', description: '', }); return; } if (!this.checkPolicy) { toast({ title: '請先勾選同意評論規範', description: '', }); return; } const payload = { concert_id: this.concertId, seat_area: this.commentSeatArea, comment: this.commentContent, images: this.images, }; if (this.images.length === 0) { delete payload.images; } setIsLoading(); http .post(`${this.path.venues}/${this.$route.params.id}/comment`, payload) .then((res) => { this.resetComment(); toast({ title: '已新增評論', description: '', }); this.getVenue(this.$route.params.id); this.isToggleCommentModal = false; }) .catch((err) => { console.error(err); }) .finally(() => { setIsLoading(); }); }, resetComment() { this.concertId = ''; this.commentSeatArea = ''; this.commentContent = ''; this.images = []; }, showCommentPolicy() { toast({ title: '評論規範', description: '(1)請勿留言不實評論 (2)請物留言惡意評論 (3)請勿留言腥羶色內容。請注意警告五次將被永久停權。', }); }, toggleModal(val) { this.isToggleCommentModal = val; if (val === false) { this.resetComment(); } }, activeArea(area) { if (this.seatArea === area) { this.seatArea = ''; } else { this.seatArea = area; } }, ...mapActions(useVenuesStore, ['getVenue', 'reportUser']), }, computed: { ...mapState(useVenuesStore, ['venue', 'pagination', 'filterSeatComment', 'transportation']), ...mapState(useUserStore, ['AccessToken']), ...mapWritableState(useVenuesStore, ['seatArea']), }, watch: { id(newId) { this.getVenue(newId); this.seatArea = ''; }, }, mounted() { this.getVenue(this.id); // AOS.init(); }, updated() { // 單一場地標題 document.title = `Concert Now - ${this.venue.title}`; }, unmounted() { this.seatArea = ''; }, }; </script> <style lang="scss" scoped> .shadow { box-shadow: inset 0px 40px 150px rgba(0, 0, 0, 0.7); } .text-stroke-black { color: transparent; -webkit-text-stroke: 1px #000; } .marquee { @apply animate-[right-to-left_40s_linear_infinite]; } .collapse-left.show { animation: expand-left 0.5s ease; opacity: 1; } .collapse-left { animation: collapse-left 0.5s ease; opacity: 0; } .collapse-right.show { animation: expand-right 0.5s ease; opacity: 1; } .collapse-right { animation: collapse-right 0.5s ease; opacity: 0; } @keyframes expand-left { from { transform: translateX(70%); opacity: 0; } to { transform: translateX(0%); opacity: 1; } } @keyframes collapse-left { from { transform: translateX(0%); opacity: 1; } to { transform: translateX(70%); opacity: 0; } } @keyframes expand-right { from { transform: translateX(-70%); opacity: 0; } to { transform: translateX(0%); opacity: 1; } } @keyframes collapse-right { from { transform: translateX(0%); opacity: 1; } to { transform: translateX(-70%); opacity: 0; } } </style>
import csv import re from collections import Counter, namedtuple import requests MARVEL_CSV = "https://raw.githubusercontent.com/pybites/marvel_challenge/master/marvel-wikia-data.csv" # noqa E501 Character = namedtuple("Character", "pid name sid align sex appearances year") # csv parsing code provided so this Bite can focus on the parsing def _get_csv_data(): """Download the marvel csv data and return its decoded content""" with requests.Session() as session: return session.get(MARVEL_CSV).content.decode("utf-8") def load_data(): """Converts marvel.csv into a sequence of Character namedtuples as defined above""" content = _get_csv_data() reader = csv.DictReader(content.splitlines(), delimiter=",") for row in reader: name = re.sub(r"(.*?)\(.*", r"\1", row["name"]).strip() yield Character( pid=row["page_id"], name=name, sid=row["ID"], align=row["ALIGN"], sex=row["SEX"], appearances=row["APPEARANCES"], year=row["Year"], ) characters = list(load_data()) # start coding def most_popular_characters(characters=characters, top=5): """Get the most popular character by number of appearances, return top n characters (default 5) """ pop_char = [ (character.name, int(character.appearances)) for character in characters if character.appearances ][:top] return [character[0] for character in pop_char] def max_and_min_years_new_characters(characters=characters): """Get the year with most and least new characters introduced respectively, use either the 'FIRST APPEARANCE' or 'Year' column in the csv characters, or the 'year' attribute of the namedtuple, return a tuple of (max_year, min_year) """ new_char_years = Counter( character.year for character in characters if character.year ) return (new_char_years.most_common()[0][0], new_char_years.most_common()[-1][0]) def get_percentage_female_characters(characters=characters): """Get the percentage of female characters as percentage of all genders over all appearances. Ignore characters that don't have gender ('sex' attribue) set (in your characters data set you should only have Male, Female, Agender and Genderfluid Characters. Return the result rounded to 2 digits """ all_genders = Counter(character.sex for character in characters if character.sex) # print(all_genders) females = all_genders["Female Characters"] total = sum(all_genders.values()) return round((females / total) * 100, 2) print(get_percentage_female_characters())
import DialogTitle from "@mui/material/DialogTitle"; import Dialog from "@mui/material/Dialog"; import { Button } from "@mui/material"; import { useEffect, useState } from "react"; import Axios from "axios"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import moment from "moment"; function SimpleDialog(props) { const { onClose, id, vrsta, open } = props; const [info, setInfo] = useState([]); const handleClose = () => { onClose(); }; useEffect(() => { const fetchData = async () => { var string = ""; if (vrsta === "spa") { string = "/pregled/spa/" + id; } if (vrsta === "sport") { string = "/pregled/sport/" + id; } if (vrsta === "nocenje") { string = "/pregled/nocenje/" + id; } try { const res = await Axios.get(string); console.log(res.data); setInfo(res.data); } catch (err) { console.log(err); } }; fetchData(); }, []); var i = 0; return ( <Dialog onClose={handleClose} open={open}> <DialogTitle>Istorija</DialogTitle> <TableContainer component={Paper}> <Table sx={{ minWidth: 650 }} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Username</TableCell> <TableCell align="right">Ime korisnika</TableCell> <TableCell align="right">Prezime korisnika</TableCell> <TableCell align="right">Datum izdavanja racuna</TableCell> {vrsta === "nocenje" && ( <> <TableCell align="right">Datum dolaska</TableCell> <TableCell align="right">Datum odlaska</TableCell> </> )} </TableRow> </TableHead> <TableBody> {info.map((row) => ( <TableRow key={i++} sx={{ "&:last-child td, &:last-child th": { border: 0 } }} > <TableCell component="th" scope="row"> {row.USERNAME} </TableCell> <TableCell align="right">{row.IME_KOR}</TableCell> <TableCell align="right">{row.PREZIME_KOR}</TableCell> <TableCell align="right"> {moment(row.DATUM_IZD_RACUN).format("DD/MM/YYYY")}{" "} </TableCell> {vrsta === "nocenje" && ( <> <TableCell align="right"> {moment(row.DATUM_DOLASKA).format("DD/MM/YYYY")}{" "} </TableCell> <TableCell align="right"> {moment(row.DATUM_ODLASKA).format("DD/MM/YYYY")}{" "} </TableCell> </> )} </TableRow> ))} </TableBody> </Table> </TableContainer> <Button variant="text" onClick={handleClose}> Zatvori </Button> </Dialog> ); } export default SimpleDialog;
package com.yagod.workshopmongodb.resources; import com.yagod.workshopmongodb.domain.Post; import com.yagod.workshopmongodb.domain.User; import com.yagod.workshopmongodb.dto.UserDTO; import com.yagod.workshopmongodb.resources.util.URL; import com.yagod.workshopmongodb.services.PostService; import com.yagod.workshopmongodb.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @RestController @RequestMapping(value = "/posts/") public class PostResource { @Autowired private PostService service; @GetMapping(value = "/{id}") public ResponseEntity<Post> findById(@PathVariable String id){ Post obj = service.findById(id); return ResponseEntity.ok().body(obj); } @GetMapping(value = "/titlesearch") public ResponseEntity<List<Post>> findTitle(@RequestParam(value = "text", defaultValue = "") String text){ text = URL.decodeParam(text); List<Post> list = service.findByTitle(text); return ResponseEntity.ok().body(list); } }
<%@ page contentType="text/html" pageEncoding="UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="p" uri="/publisher-tags" %> <nav class="ym-hlist"> <ul> <li class="active"> <strong>Novo evento (LiveStats)</strong> </li> </ul> </nav> <s:form action="liveStats-save" cssClass="ym-form" onsubmit="checkPermanentLink();"> <s:hidden name="id"/> <s:fielderror cssStyle="color: red;"/> <div class="ym-fbox-text"> <label for="eventName">Nome do evento</label> <s:textfield name="eventName"/> <label for="description">Descrição</label> <s:textfield name="description"/> <label for="tags">Palavras chaves</label> <s:textarea name="tags" rows="2"/> <label for="code">Código LiveStats</label> <s:textarea name="code" rows="5"/> <label for="twitter">Twitter</label> <s:textfield name="twitter"/> <label for="adsZone">Zona de anúncio</label> <s:textfield name="adsZone"/> <label for="permanentLink">Link Permanent:</label> <s:hidden id="link" name="link" value="%{permanentLink}"/> <s:textfield id="permanentLink" name="permanentLink" /> <label for="skinName">Template</label> <s:hidden name="skinName"/> <s:if test="skinName != null && !skinName.isEmpty()"> <p:autocomplete name="skinId" display="skinName" url="/manager/ac-skin" /> </s:if> <s:else> <p:autocomplete name="skinId" url="/manager/ac-skin" /> </s:else> <label for="pollName">Enquete</label> <s:hidden name="pollQuestion"/> <s:if test="pollQuestion != null && !pollQuestion.isEmpty()"> <p:autocomplete name="pollId" display="pollQuestion" url="/manager/ac-poll" /> </s:if> <s:else> <p:autocomplete name="pollId" url="/manager/ac-poll" /> </s:else> <label class="categoryName">Categoria dos destaques:</label> <s:hidden name="categoryName"/> <s:if test="categoryName.equals('')"> <p:autocomplete name="categoryId" display="-vazio-" url="/manager/ac-category" initial="[{label:'Tatame',value: 1}]" /> </s:if> <s:else> <p:autocomplete name="categoryId" display="%{categoryName}" url="/manager/ac-category" initial="[{label:'Tatame',value: 1}]"/> </s:else> <label for="publishedAt">Data de publicação:</label> <s:textfield name="publishedAt" value="%{getText('date.format',{publishedAt})}" cssClass="publishedAt"/> <div class="ym-fbox-check check-box"> <label for="forumEnabled">Forum:</label> <s:checkbox name="forumEnabled" cssClass="forumEnabled"/> </div> <div class="ym-fbox-check check-box"> <label for="published">Publicado:</label> <s:checkbox id="published" name="published" cssClass="published"/> </div> <div class="ym-fbox-button"> <s:submit value="Enviar" align="left"/> </div> <s:if test="createdBy != null"> <p style="margin: 10px 0px">Criado por <s:property value="createdBy" /> em <s:property value="created"/></p> </s:if> <s:if test="lastModifiedBy != null"> <p style="margin: 10px 0px">Modificado por <s:property value="lastModifiedBy" /> em <s:property value="lastModified"/></p> </s:if> </div> </s:form> <script type="text/javascript"> function checkPermanentLink() { var name = $('input[name=name]').get(0).value; var link = $('#permanentLink').val(); if (name != undefined && name != null && name != "" && (link == undefined || link == null || link == "")) { $('#permanentLink').val(convertToPermanentLink(name)); } else if (link != undefined && link != null && link != "") { $('#permanentLink').val(convertToPermanentLink($('#permanentLink').val())); } } function convertToPermanentLink(text) { return text .replace(new RegExp(' - ', 'gi'), '/') .replace(new RegExp('[áàâÁÀÂãÃ]', 'gi'), 'a') .replace(new RegExp('[óòôÓÒÔõÕ]', 'gi'), 'o') .replace(new RegExp('[úùÚÙ]', 'gi'), 'u') .replace(new RegExp('[íìÍÌ]', 'gi'), 'i') .replace(new RegExp('[éèêÉÈÊ]', 'gi'), 'e') .replace(new RegExp('[çÇ]', 'gi'), 'c') .replace(new RegExp('[^a-zA-Z0-9/ -]', 'gi'), '') .trim() .replace(new RegExp(' ', 'gi'), '-') .toLowerCase(); } </script>
import { GlobalStyle } from '../../GlobalStyle'; import { Component } from 'react'; import { nanoid } from 'nanoid'; import { ContactsForm } from '../ContactsForm/ContactsForm'; import { ContactsList } from '../ContactsList/ContactsList'; import { Filter } from 'components/Filter/Filter'; import { Thumb } from './App.Styled'; export class App extends Component { state = { contacts: [ { id: 'id-1', name: 'Rosie Simpson', number: '459-12-56' }, { id: 'id-2', name: 'Hermione Kline', number: '443-89-12' }, { id: 'id-3', name: 'Eden Clements', number: '645-17-79' }, { id: 'id-4', name: 'Annie Copeland', number: '227-91-26' }, ], filter: '', }; componentDidMount() { const savedContacts = localStorage.getItem('contacts'); if (savedContacts !== null) { this.setState({ contacts: JSON.parse(savedContacts), }); } } componentDidUpdate(_, prevState) { if (prevState.contacts !== this.state.contacts) { localStorage.setItem('contacts', JSON.stringify(this.state.contacts)); } } addContact = (name, number) => { this.setState(prevState => ({ contacts: [...prevState.contacts, { id: nanoid(), name, number }], })); }; typeFilter = e => { this.setState({ filter: e.currentTarget.value }); }; getfilteredContacts = () => { return this.state.contacts.filter(contact => { return contact.name .toLowerCase() .includes(this.state.filter.toLocaleLowerCase()); }); }; deleteContact = contactId => { this.setState(prevState => ({ contacts: prevState.contacts.filter(contact => contact.id !== contactId), })); }; render() { return ( <Thumb> <h1>Phonebook</h1> <ContactsForm onSubmit={this.addContact} items={this.getfilteredContacts()} /> <h2>Contacts</h2> <Filter onType={this.typeFilter} /> {this.state.contacts.length > 0 && ( <ContactsList items={this.getfilteredContacts()} onDelete={this.deleteContact} /> )} <GlobalStyle /> </Thumb> ); } }
package server import ( "bytes" "context" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/dsha256/packer/internal/mock" "github.com/dsha256/packer/internal/packer" "github.com/golang/mock/gomock" "github.com/stretchr/testify/require" ) func TestSizesHandler_listSizes(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() testCases := []struct { name string method string buildStubs func(repo *mock.MockSizer) checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder) }{ { name: "200 on get", method: http.MethodGet, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().ListSizes().Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusOK, recorder.Code) }, }, } for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() newSizerSrvc := packer.NewSizerService(packer.SortedSizes) newPackerSrvc := packer.NewPacketsService(newSizerSrvc) server := NewServer(newSizerSrvc, newPackerSrvc) recorder := httptest.NewRecorder() url := "/api/v1/tables" req, err := http.NewRequest(tc.method, url, nil) require.NoError(t, err) server.listSizesHandler(recorder, req) tc.checkResponse(t, recorder) }) } } func TestSizesHandler_addSize(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() testCases := []struct { name string method string sizeToAdd int buildStubs func(repo *mock.MockSizer) checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder) }{ { name: "200 on POST - positive num", method: http.MethodGet, sizeToAdd: 100, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().AddSize(context.Background(), 0).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusOK, recorder.Code) }, }, { name: "422 on POST - 0", method: http.MethodGet, sizeToAdd: 0, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().AddSize(context.Background(), 1).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusUnprocessableEntity, recorder.Code) }, }, { name: "422 on POST - (-1)", method: http.MethodGet, sizeToAdd: 0, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().AddSize(context.Background(), 1).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusUnprocessableEntity, recorder.Code) }, }, } for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() newSizerSrvc := packer.NewSizerService(packer.SortedSizes) newPackerSrvc := packer.NewPacketsService(newSizerSrvc) server := NewServer(newSizerSrvc, newPackerSrvc) recorder := httptest.NewRecorder() url := "/api/v1/sizes" reqBody := map[string]int{"size": tc.sizeToAdd} var buf bytes.Buffer _ = json.NewEncoder(&buf).Encode(reqBody) req, err := http.NewRequest(tc.method, url, &buf) require.NoError(t, err) server.addSizeHandler(recorder, req) tc.checkResponse(t, recorder) }) } } func TestSizesHandler_putSizeHandler(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() testCases := []struct { name string method string sizesToAdd []int buildStubs func(repo *mock.MockSizer) checkResponse func(t *testing.T, recorder *httptest.ResponseRecorder) }{ { name: "200 on PUT - positive nums", method: http.MethodPut, sizesToAdd: []int{100, 200, 300}, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().PutSizes(context.Background(), []int{1, 2, 3}).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusOK, recorder.Code) }, }, { name: "422 on PUT - 0", method: http.MethodGet, sizesToAdd: []int{100, 0, 300}, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().AddSize(context.Background(), 1).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusUnprocessableEntity, recorder.Code) }, }, { name: "422 on PUT - (-1)", method: http.MethodGet, sizesToAdd: []int{100, -1, 300}, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().AddSize(context.Background(), 1).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusUnprocessableEntity, recorder.Code) }, }, { name: "400 on PUT - duplicated sizes", method: http.MethodGet, sizesToAdd: []int{100, 100, 300}, buildStubs: func(sizer *mock.MockSizer) { sizer.EXPECT().AddSize(context.Background(), 1).Times(1) }, checkResponse: func(t *testing.T, recorder *httptest.ResponseRecorder) { require.Equal(t, http.StatusBadRequest, recorder.Code) }, }, } for i := range testCases { tc := testCases[i] t.Run(tc.name, func(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() newSizerSrvc := packer.NewSizerService(packer.SortedSizes) newPackerSrvc := packer.NewPacketsService(newSizerSrvc) server := NewServer(newSizerSrvc, newPackerSrvc) recorder := httptest.NewRecorder() url := "/api/v1/sizes" reqBody := map[string][]int{"sizes": tc.sizesToAdd} var buf bytes.Buffer _ = json.NewEncoder(&buf).Encode(reqBody) req, err := http.NewRequest(tc.method, url, &buf) require.NoError(t, err) server.putSizesHandler(recorder, req) tc.checkResponse(t, recorder) }) } }
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import 'dart:math' as math; import '../barcode_format.dart'; import '../common/bit_matrix.dart'; import '../encode_hint.dart'; import '../writer.dart'; import 'decoder/error_correction_level.dart'; import 'encoder/encoder.dart'; import 'encoder/qrcode.dart'; /// This object renders a QR Code as a BitMatrix 2D array of greyscale values. /// /// @author dswitkin@google.com (Daniel Switkin) class QRCodeWriter implements Writer { static const int _quietZoneSize = 4; @override BitMatrix encode( String contents, BarcodeFormat format, int width, int height, [ EncodeHint? hints, ]) { if (contents.isEmpty) { throw ArgumentError('Found empty contents'); } if (format != BarcodeFormat.qrCode) { throw ArgumentError('Can only encode QR_CODE, but got $format'); } if (width < 0 || height < 0) { throw ArgumentError( 'Requested dimensions are too small: $width x $height', ); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; int quietZone = _quietZoneSize; if (hints != null) { if (hints.errorCorrectionLevel != null) { errorCorrectionLevel = hints.errorCorrectionLevel!; } else if (hints.errorCorrection != null) { errorCorrectionLevel = ErrorCorrectionLevel.values[hints.errorCorrection!]; } if (hints.margin != null) { quietZone = hints.margin!; } } final code = Encoder.encode(contents, errorCorrectionLevel, hints); return _renderResult(code, width, height, quietZone); } // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). static BitMatrix _renderResult( QRCode code, int width, int height, int quietZone, ) { final input = code.matrix; if (input == null) { throw StateError('ByteMatrix input is null'); } final inputWidth = input.width; final inputHeight = input.height; final qrWidth = inputWidth + (quietZone * 2); final qrHeight = inputHeight + (quietZone * 2); final outputWidth = math.max(width, qrWidth); final outputHeight = math.max(height, qrHeight); final multiple = math.min(outputWidth ~/ qrWidth, outputHeight ~/ qrHeight); // Padding includes both the quiet zone and the extra white pixels to accommodate the requested // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will // handle all the padding from 100x100 (the actual QR) up to 200x160. final leftPadding = (outputWidth - (inputWidth * multiple)) ~/ 2; final topPadding = (outputHeight - (inputHeight * multiple)) ~/ 2; final output = BitMatrix(outputWidth, outputHeight); for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) { // Write the contents of this row of the barcode for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (input.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } }
DROP DATABASE IF EXISTS EMPLEADOS_Join; CREATE DATABASE EMPLEADOS_Join; USE EMPLEADOS_Join; CREATE TABLE PUESTO( NUM_PUESTO INT, NOMB VARCHAR(20), SUELDO_HORA INT, PRIMARY KEY (NUM_PUESTO) ); CREATE TABLE DEPTO( NUM_DEPTO INT, NOMB VARCHAR(20), UBIC VARCHAR(30), PRIMARY KEY(NUM_DEPTO) ); CREATE TABLE EMPLEADO ( NUM_EMP INT, NOMB VARCHAR(20), NUM_JEFE INT, NUM_DEPTO INT, NUM_PUESTO INT, HORAS_CONTRATADAS INT, EDAD INT, PRIMARY KEY (NUM_EMP), FOREIGN KEY (NUM_DEPTO) REFERENCES DEPTO(NUM_DEPTO), FOREIGN KEY(NUM_PUESTO) REFERENCES PUESTO(NUM_PUESTO), FOREIGN KEY(NUM_JEFE) REFERENCES EMPLEADO(NUM_EMP) ); -- Insertar y verificar valores de tabla Puesto INSERT INTO PUESTO VALUES (1, 'GERENTE SISTEMAS', 100); INSERT INTO PUESTO VALUES (2, 'GERENTE INGENIERIA', 120); INSERT INTO PUESTO VALUES (3, 'GERENTE MKT', 130); INSERT INTO PUESTO VALUES (4, 'GERENTE FINANZAS', 140); INSERT INTO PUESTO VALUES (5, 'DESARROLLADOR', 120); INSERT INTO PUESTO VALUES (6, 'ADMON BD', 130); INSERT INTO PUESTO VALUES (7, 'ANALISTA', 110); INSERT INTO PUESTO VALUES (8, 'PROGRAMADOR', 110); INSERT INTO PUESTO VALUES (9, 'SUB GERENTE VTA', 120); SELECT * FROM PUESTO; -- Insertar y verificar valores de tabla Depto INSERT INTO DEPTO VALUES (1, 'DESARROLLO', 'PB'); INSERT INTO DEPTO VALUES (2, 'PRUEBAS', 'PB'); INSERT INTO DEPTO VALUES (3, 'SOPORTE', 'PB'); INSERT INTO DEPTO VALUES (4, 'IMPLEMENTACION', '1ER PISO'); INSERT INTO DEPTO VALUES (5, 'VENTAS', '2DO PISO'); SELECT * FROM DEPTO; -- Insertar y verificar valores de tabla Empleado, con case de valores nulos INSERT INTO EMPLEADO VALUES (1, 'JUAN', NULL, 1, 1, 10, 29); INSERT INTO EMPLEADO VALUES (2, 'OMAR', NULL, 2, 2, 10, 27); INSERT INTO EMPLEADO VALUES (3, 'RAUL', NULL, 3, 3, 12, 32); INSERT INTO EMPLEADO VALUES (4, 'PEDRO', NULL, 4, 4, 12, 32); INSERT INTO EMPLEADO VALUES (5, 'JOSE', 2, 4, 8, 9, 36); INSERT INTO EMPLEADO VALUES (6, 'CESAR', 1, 5, 7, 20, 40); INSERT INTO EMPLEADO VALUES (7, 'ANA', 1, 1, 6, 12, 21); INSERT INTO EMPLEADO VALUES (8, 'LUIS', 1, 1, 8, 10, 24); INSERT INTO EMPLEADO VALUES (9, 'BETTY', 3, 3, 6, 15, 30); INSERT INTO EMPLEADO VALUES (10, 'PATY', 3, 3, 6, 20, 39); INSERT INTO EMPLEADO VALUES (11, 'JUDITH', 1, 2, 5, 15, 28); SELECT NUM_EMP, NOMB, CASE WHEN NUM_JEFE IS NULL THEN 0 ELSE NUM_JEFE END AS NUM_JEFE, NUM_DEPTO, NUM_PUESTO, HORAS_CONTRATADAS, EDAD FROM EMPLEADO; -- Obtener el nombre del empleado, el depto donde trabaja y el puesto que tiene -- Paso 1 hacer el join entre empleado y depto ver bufer de datos el cual SELECT EMPLEADO.NUM_EMP, EMPLEADO.NOMB, CASE WHEN NUM_JEFE IS NULL THEN 0 ELSE NUM_JEFE END AS NUM_JEFE, EMPLEADO.NUM_DEPTO, EMPLEADO.NUM_PUESTO, EMPLEADO.HORAS_CONTRATADAS, EMPLEADO.EDAD, DEPTO.NUM_DEPTO, DEPTO.NOMB, DEPTO.UBIC FROM EMPLEADO, DEPTO WHERE EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO ORDER BY empleado.NUM_EMP; -- Paso 2 al buffer anterior hacerle el join con el puesto ver el nuevo buffer SELECT EMPLEADO.NUM_EMP, EMPLEADO.NOMB, CASE WHEN NUM_JEFE IS NULL THEN 0 ELSE NUM_JEFE END AS NUM_JEFE, EMPLEADO.NUM_DEPTO, EMPLEADO.NUM_PUESTO, EMPLEADO.HORAS_CONTRATADAS, EMPLEADO.EDAD, DEPTO.NUM_DEPTO, DEPTO.NOMB, DEPTO.UBIC, puesto.NUM_PUESTO, puesto.NOMB, puesto.SUELDO_HORA FROM EMPLEADO, DEPTO, PUESTO WHERE EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO AND EMPLEADO.NUM_PUESTO = PUESTO.NUM_PUESTO ORDER BY empleado.NUM_EMP; -- Paso 3 al buffer anterior hacer la proyección con lo que se solicito, ver el nuevo buffer SELECT EMPLEADO.NOMB, DEPTO.NOMB, PUESTO.NOMB FROM EMPLEADO, DEPTO, PUESTO WHERE EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO AND EMPLEADO.NUM_PUESTO = PUESTO.NUM_PUESTO; -- Paso 4 Ponemos los alias correspondientes SELECT EMPLEADO.NOMB Empleado, DEPTO.NOMB Departamento, PUESTO.NOMB Puesto FROM EMPLEADO, DEPTO, PUESTO WHERE EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO AND EMPLEADO.NUM_PUESTO = PUESTO.NUM_PUESTO; -- Paso 1 hacer el join entre empleado y depto ver bufer de datos el cual SELECT EMPLEADO.NUM_EMP, EMPLEADO.NOMB, CASE WHEN NUM_JEFE IS NULL THEN 0 ELSE NUM_JEFE END AS NUM_JEFE, EMPLEADO.NUM_DEPTO, EMPLEADO.NUM_PUESTO, EMPLEADO.HORAS_CONTRATADAS, EMPLEADO.EDAD, DEPTO.NUM_DEPTO, DEPTO.NOMB, DEPTO.UBIC FROM EMPLEADO JOIN DEPTO ON EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO ORDER BY empleado.NUM_EMP; -- Paso 2 al buffer anterior hacerle el join con el puesto ver el nuevo buffer SELECT EMPLEADO.NUM_EMP, EMPLEADO.NOMB, CASE WHEN NUM_JEFE IS NULL THEN 0 ELSE NUM_JEFE END AS NUM_JEFE, EMPLEADO.NUM_DEPTO, EMPLEADO.NUM_PUESTO, EMPLEADO.HORAS_CONTRATADAS, EMPLEADO.EDAD, DEPTO.NUM_DEPTO, DEPTO.NOMB, DEPTO.UBIC, puesto.NUM_PUESTO, puesto.NOMB, puesto.SUELDO_HORA FROM EMPLEADO JOIN DEPTO ON EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO JOIN puesto ON empleado.NUM_PUESTO = puesto.NUM_PUESTO ORDER BY empleado.NUM_EMP; -- Paso 3 al buffer anterior hacer la proyección con lo que se solicito, ver el nuevo buffer SELECT EMPLEADO.NOMB, DEPTO.NOMB, puesto.NOMB FROM EMPLEADO JOIN DEPTO ON EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO JOIN puesto ON empleado.NUM_PUESTO = puesto.NUM_PUESTO ORDER BY empleado.NUM_EMP; -- Paso 4 Ponemos los alias correspondientes SELECT EMPLEADO.NOMB AS "Empleado", DEPTO.NOMB AS "Departamento", puesto.NOMB AS "Puesto" FROM EMPLEADO JOIN DEPTO ON EMPLEADO.NUM_DEPTO = DEPTO.NUM_DEPTO JOIN puesto ON empleado.NUM_PUESTO = puesto.NUM_PUESTO ORDER BY empleado.NUM_EMP;
<?php /** * */ function game_pieces_install() { _game_pieces_running_game_add_default_fields(); _game_pieces_pattern_add_default_fields(); } /** * Implements hook_schema(). * * Defines the database tables used by this module. * Remember that the easiest way to create the code for hook_schema is with * the @link http://drupal.org/project/schema schema module @endlink * * @see hook_schema() * @ingroup dbtng_example */ function game_pieces_schema() { $schema = array(); $schema['piece'] = array( 'description' => 'Store base information for a piece.', 'fields' => array( 'id' => array( 'type' => 'serial', 'not null' => TRUE, 'description' => 'Primary Key: piece ID.', ), 'label' => array( 'description' => 'The label of the piece.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'type' => array( 'description' => 'The type (bundle) of this piece.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'moved' => array( 'description' => 'a boolean indicates if the piece had bean moved.', 'type' => 'int', 'size' => 'tiny', 'length' => 1, 'not null' => TRUE, 'default' => '0', ), 'uid' => array( 'description' => 'ID of participent that is assigned with this piece. if null assigned to all.', 'type' => 'int', 'not null' => FALSE, ), ), 'primary key' => array('id'), 'indexes' => array( 'name' => array('label'), ), ); $schema['piece_type'] = array( 'description' => 'Stores information about all defined piece types.', 'fields' => array( 'id' => array( 'type' => 'serial', 'not null' => TRUE, 'description' => 'Primary Key: Unique piece type ID.', ), 'symbol' => array( 'description' => 'The symbol of the piece.', 'type' => 'char', 'not null' => FALSE, 'default' => '', ), 'label' => array( 'description' => 'The human-readable name of this type.', 'type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', ), 'type' => array( 'description' => 'The machine-readable name of this type.', 'type' => 'varchar', 'length' => 32, 'not null' => TRUE, ), 'move_pattern' => array( 'description' => 'a pattern that makes the player move by specipic movement pattern', 'type' => 'varchar', 'length' => 32, 'not null' => FALSE, ), 'initiate_pattern' => array( 'description' => 'a pattern that allows the player to initiate another player by specipic pattern', 'type' => 'varchar', 'length' => 32, 'not null' => FALSE, ), 'description' => array( 'description' => 'A brief description of this piece type.', 'type' => 'text', 'not null' => TRUE, 'size' => 'medium', 'translatable' => TRUE, ), ) + entity_exportable_schema_fields(), 'primary key' => array('id'), 'unique keys' => array( 'type' => array('type'), ), ); return $schema; }
package za.ac.cput.domain; //Siphosethu Makhambeni // 221272976 //22/03/2024 //Contact.java public class Contact { private String phoneNumber; private String emailAddress; private String address; private Contact() { } private Contact(ContactBuilder builder) { this.phoneNumber = builder.phoneNumber; this.emailAddress = builder.emailAddress; this.address = builder.address; } public String getPhoneNumber() { return phoneNumber; } public String getEmailAddress() { return emailAddress; } public String getAddress() { return address; } @Override public String toString() { return "Contact{" + "phoneNumber='" + phoneNumber + '\'' + ", emailAddress='" + emailAddress + '\'' + ", address='" + address + '\'' + '}'; } public static class ContactBuilder { private String phoneNumber; private String emailAddress; private String address; public ContactBuilder setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; return this; } public ContactBuilder setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; return this; } public ContactBuilder setAddress(String address) { this.address = address; return this; } public Contact build() { return new Contact(this); } } }
--- lesson_id: mathontrack-numbers-natrual-numbers lesson_title: Natural Numbers lesson_description: Learn what Natural Numbers are. --- # Natural numbers ($ℕ$ or $N$) - Natural numbers are simply “counting” numbers. They are the numbers that a farmer may use to count the number of cows they have for example. - Natural numbers are denoted by the symbol $ℕ$, or simply N when writing (a bold capital $N$) - Natural numbers begin with 0 and continue by adding 1 to each successive term: $$ℕ_0= \{0, 1, 2, 3, 4, 5…\}$$ In this case, Natural numbers are denoted as $ℕ_0$ - Some definitions of natural numbers start with 1 and continue by adding 1 to each successive term: $$ℕ_1= \{1, 2, 3, 4, 5…\}$$ In this case, Natural numbers are denoted as $ℕ_1$
#encoding: utf8 import pytest import pprint import rejit.common from rejit.nfa import NFA from rejit.regex import Regex from tests.helper import accept_test_helper ppast = pprint.PrettyPrinter(indent=4) def assert_regex_parse_error(pattern): with pytest.raises(rejit.regex.RegexParseError): re = Regex(pattern) print('Did not raise RegexParseError') print('ast: {}'.format(re._ast)) print('description: {}'.format(re.get_matcher_description())) def assert_regex_description(ast, expected_description): result_description = Regex()._compile(ast).description print("ast:") ppast.pprint(ast) print("description:{description}, expected:{expected}, {ok}".format( description=result_description, expected=expected_description, ok='OK' if result_description == expected_description else 'FAILED')) assert result_description == expected_description def assert_regex_AST(pattern, expected_ast): result_ast = Regex()._parse(pattern) print("pattern:",pattern) print("result ast:") ppast.pprint(result_ast) print("expected ast:") ppast.pprint(expected_ast) print('OK' if result_ast == expected_ast else 'FAILED') assert result_ast == expected_ast def assert_regex_transform(ast, expected_trans_ast): trans_ast = Regex()._transform(ast) print("input ast:") ppast.pprint(ast) print("transformed ast:") ppast.pprint(trans_ast) print("expected ast:") ppast.pprint(expected_trans_ast) print('OK' if trans_ast == expected_trans_ast else 'FAILED') assert trans_ast == expected_trans_ast class TestRegexParsing: def test_empty_regex(self): pattern = '' expected_AST = ('empty',) expected_final_AST = expected_AST expected_NFA_description = '\\E' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_symbol_regex(self): for char in rejit.common.supported_chars: pattern = char expected_AST = ('symbol',char) expected_final_AST = expected_AST expected_NFA_description = char assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) for char in rejit.common.special_chars: pattern = "\\" + char expected_AST = ('symbol',char) expected_final_AST = expected_AST expected_NFA_description = "\\" + char assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_union_regex(self): pattern = 'a|b' expected_AST = ('union',[('symbol','a'),('symbol','b')]) expected_final_AST = expected_AST expected_NFA_description = '(a|b)' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) # test for bug #35 pattern = 'a|b|c' expected_AST = ('union',[('symbol','a'),('union',[('symbol','b'),('symbol','c')])]) expected_final_AST = ('union',[('symbol','a'),('symbol','b'),('symbol','c')]) expected_NFA_description = '(a|b|c)' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_kleene_star_regex(self): pattern = 'a*' expected_AST = ('kleene-star',('symbol','a')) expected_final_AST = expected_AST expected_NFA_description = '(a)*' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = ('(a*)*') expected_AST = ('kleene-star',('kleene-star',('symbol','a'))) expected_final_AST = ('kleene-star',('symbol','a')) expected_NFA_description = '(a)*' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_concat_regex(self): pattern = 'abcdef' expected_AST = ('concat',[('symbol','a'), ('concat',[('symbol','b'), ('concat',[('symbol','c'), ('concat',[('symbol','d'), ('concat',[('symbol','e'),('symbol','f')]) ]) ]) ]) ]) expected_final_AST = ('concat', [('symbol','a'), ('symbol','b'), ('symbol','c'), ('symbol','d'), ('symbol','e'),('symbol','f') ]) expected_NFA_description = 'abcdef' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_complex_regex(self): pattern = 'aa(bb|(cc)*)' expected_AST = ('concat',[('symbol','a'), ('concat',[('symbol','a'), ('union',[('concat',[('symbol','b'),('symbol','b')]), ('kleene-star',('concat',[('symbol','c'),('symbol','c')])) ]) ]) ]) expected_final_AST = ('concat', [ ('symbol','a'),('symbol','a'), ('union',[('concat',[('symbol','b'),('symbol','b')]), ('kleene-star',('concat',[('symbol','c'),('symbol','c')]))]) ]) expected_NFA_description = 'aa(bb|(cc)*)' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = 'aa.*bb.?(a|b)?' expected_AST = ('concat',[('symbol','a'), ('concat',[('symbol','a'), ('concat',[('kleene-star',('any',)), ('concat',[('symbol','b'), ('concat',[('symbol','b'), ('concat',[('zero-or-one',('any',)), ('zero-or-one',('union',[('symbol','a'),('symbol','b')]) ) ]) ]) ]) ]) ]) ]) expected_final_AST = ('concat', [ ('symbol','a'), ('symbol','a'), ('kleene-star',('any',)), ('symbol','b'), ('symbol','b'), ('zero-or-one',('any',)), ('zero-or-one',('union',[('symbol','a'),('symbol','b')])), ]) expected_NFA_description = 'aa(.)*bb(.)?((a|b))?' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = 'aa[x-z]*bb[0-0]+cc[]?' expected_AST = ('concat',[('symbol','a'), ('concat',[('symbol','a'), ('concat',[('kleene-star',('set',['x','y','z'],'[x-z]')), ('concat',[('symbol','b'), ('concat',[('symbol','b'), ('concat',[('kleene-plus',('set',['0'],'[0-0]')), ('concat',[('symbol','c'), ('concat',[('symbol','c'), ('zero-or-one',('set',[],'[]')) ]) ]) ]) ]) ]) ]) ]) ]) expected_final_AST = ('concat', [ ('symbol','a'), ('symbol','a'), ('kleene-star',('set',['x','y','z'],'[x-z]')), ('symbol','b'), ('symbol','b'), ('kleene-plus',('set',['0'],'[0-0]')), ('symbol','c'), ('symbol','c'), ('zero-or-one',('set',[],'[]')), ]) expected_NFA_description = 'aa([x-z])*bb([0-0])+cc([])?' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_one_or_zero_mult_regex(self): pattern = 'a?' expected_AST = ('zero-or-one',('symbol','a')) expected_final_AST = expected_AST expected_NFA_description = r'(a)?' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_charset_regex(self): pattern = '[abc]' expected_AST = ('set',['a','b','c'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[Xa-cY0-2Z]' expected_AST = ('set',['X','a','b','c','Y','0','1','2','Z'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[aa-bb]' expected_AST = ('set',['a','a','b','b'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[c-c]' expected_AST = ('set',['c'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[cc]' expected_AST = ('set',['c','c'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[z-a]' expected_AST = ('set',[],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[*+.<-?]' expected_AST = ('set',['*','+','.','<','=','>','?'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[[-]]' expected_AST = ('set',['[','\\',']'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '[---]' expected_AST = ('set',['-'],pattern) expected_final_AST = expected_AST expected_NFA_description = pattern assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) assert_regex_parse_error('[a-]') assert_regex_parse_error('[a-') assert_regex_parse_error('[abc') def test_negative_charset_regex(self): assert_regex_parse_error('[^abc]') def test_period_wildcard_regex(self): pattern = '.' expected_AST = ('any',) expected_final_AST = expected_AST expected_NFA_description = '.' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_kleene_plus_regex(self): pattern = 'a+' expected_AST = ('kleene-plus',('symbol','a')) expected_final_AST = expected_AST expected_NFA_description = '(a)+' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_grouping_regex(self): pattern = '(aa|bb)cc' expected_AST = ('concat',[ ('union',[ ('concat',[('symbol','a'),('symbol','a')]), ('concat',[('symbol','b'),('symbol','b')])]), ('concat',[('symbol','c'),('symbol','c')])] ) expected_final_AST = ('concat',[ ('union',[ ('concat',[('symbol','a'),('symbol','a')]), ('concat',[('symbol','b'),('symbol','b')])]), ('symbol','c'), ('symbol','c'), ]) expected_NFA_description = '(aa|bb)cc' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '(((a)))' expected_AST = ('symbol','a') expected_final_AST = expected_AST expected_NFA_description = 'a' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) pattern = '(((a)((b))))' expected_AST = ('concat',[('symbol','a'),('symbol','b')]) expected_final_AST = expected_AST expected_NFA_description = 'ab' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_invalid_use_of_special_char_regex(self): for char in rejit.common.special_chars.replace('.',''): assert_regex_parse_error(char) # test for bug #36 assert_regex_parse_error('a|b|') assert_regex_parse_error('abc\\') assert_regex_parse_error('a*?') assert_regex_parse_error('a**') assert_regex_parse_error('a*+') assert_regex_parse_error('(*a)') assert_regex_parse_error('(+a)') assert_regex_parse_error('(?a)') assert_regex_parse_error('a|*b') assert_regex_parse_error('a|+b') assert_regex_parse_error('a|?b') assert_regex_parse_error('|abc') assert_regex_parse_error('abc|') assert_regex_parse_error('a||b') assert_regex_parse_error('(|abc)') assert_regex_parse_error('(a||b)') assert_regex_parse_error('(abc|)') # test for bug #39 assert_regex_parse_error('a)') assert_regex_parse_error('a)aaa') assert_regex_parse_error('a)*?+[\\') assert_regex_parse_error('(a))') assert_regex_parse_error('(a)a)') assert_regex_parse_error('(a)a)a') assert_regex_parse_error('(a') assert_regex_parse_error('aaa(a') assert_regex_parse_error('((((') assert_regex_parse_error('((((aaaa') assert_regex_parse_error('a(a(a)a') assert_regex_parse_error('(abc|cde') def test_empty_set_regex(self): pattern = '[]' expected_AST = ('set',[],'[]') expected_final_AST = expected_AST expected_NFA_description = '[]' assert_regex_AST(pattern,expected_AST) assert_regex_transform(expected_AST,expected_final_AST) assert_regex_description(expected_final_AST,expected_NFA_description) def test_empty_group_regex(self): assert_regex_parse_error('()') class TestRegexASTtransform: def test_ast_flatten_noop(self): re = Regex() x = re._parse('a') xinline = re._flatten_nodes('concat',x) assert xinline == ('symbol','a') def test_ast_flatten_single(self): re = Regex() x = re._parse('ab') xinline = re._flatten_nodes('concat',x) assert xinline == ('concat',[('symbol','a'),('symbol','b')]) def test_ast_flatten_nested(self): re = Regex() x = re._parse('abc') xinline = re._flatten_nodes('concat',x) assert xinline == ('concat',[('symbol','a'),('symbol','b'),('symbol','c')]) x = re._parse('a*b+c?') xinline = re._flatten_nodes('concat',x) assert xinline == ('concat',[ ('kleene-star',('symbol','a')), ('kleene-plus',('symbol','b')), ('zero-or-one',('symbol','c')) ]) x = re._parse('a(bbb)+d') xinline = re._flatten_nodes('concat',x) assert xinline == ('concat',[('symbol','a'),('kleene-plus',('concat',[('symbol','b'),('symbol','b'),('symbol','b')])),('symbol','d')]) x = re._parse('a|b|c') xinline = re._flatten_nodes('union',x) assert xinline == ('union', [('symbol','a'),('symbol','b'),('symbol','c')]) x = re._parse('a|(b|c|d)|(ef|gh)') xinline = re._flatten_nodes('union',x) assert xinline == ('union', [ ('symbol','a'), ('symbol','b'), ('symbol','c'), ('symbol','d'), ('concat',[('symbol','e'),('symbol','f')]), ('concat',[('symbol','g'),('symbol','h')]), ]) nfa1 = re._compile(x) nfa2 = re._compile(xinline) assert nfa1.description == '(a|((b|(c|d))|(ef|gh)))' assert nfa2.description == '(a|b|c|d|ef|gh)' x = re._parse('a|x(b|c|d)|(ef|gh)') xinline = re._flatten_nodes('union',x) assert xinline == ('union', [ ('symbol','a'), ('concat', [ ('symbol', 'x'), ('union',[('symbol','b'),('symbol','c'),('symbol','d')]), ]), ('concat',[('symbol','e'),('symbol','f')]), ('concat',[('symbol','g'),('symbol','h')]), ]) def test_ast_flatten_full_tree(self): re = Regex() # really abstract syntax tree x = ('concat', [ ('concat', [ ('symbol','a'), ('concat',[ ('symbol','b'),('symbol','c')]) ]), ('concat', [ ('concat',[('symbol','d'),('symbol','e')]), ('symbol','f')]) ]) xinline = re._flatten_nodes('concat',x) assert xinline == ('concat', [ ('symbol','a'), ('symbol','b'), ('symbol','c'), ('symbol','d'), ('symbol','e'), ('symbol','f') ]) def test_ast_flatten_bug_44(self): re = Regex() # test for bug #44 x = ('xxxxx', [('symbol', 'a'), ('empty',)]) xinline = re._flatten_nodes('concat',x) assert xinline == x # test for bug #44 x = ('xxxxx', [('yyy', [('xxxxx',[])]), ('symbol', 'b')]) xinline = re._flatten_nodes('concat',x) assert xinline == x def test_ast_simplify_quant_noop(self): re = Regex() x = re._parse('a') xinline = re._simplify_quant(x) assert xinline == ('symbol','a') def test_ast_simplify_quant_single(self): re = Regex() x = re._parse('a*') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('a+') xinline = re._simplify_quant(x) assert xinline == ('kleene-plus',('symbol','a')) x = re._parse('a?') xinline = re._simplify_quant(x) assert xinline == ('zero-or-one',('symbol','a')) def test_ast_simplify_quant_nested(self): re = Regex() x = re._parse('(a+)+') xinline = re._simplify_quant(x) assert xinline == ('kleene-plus',('symbol','a')) x = re._parse('(a+)*') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a+)?') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a*)+') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a*)*') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a*)?') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a?)+') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a?)*') xinline = re._simplify_quant(x) assert xinline == ('kleene-star',('symbol','a')) x = re._parse('(a?)?') xinline = re._simplify_quant(x) assert xinline == ('zero-or-one',('symbol','a')) def test_ast_simplify_quant_nested_adv(self): re = Regex() x = re._parse('(([abc]*)?x+)*') xinline = re._simplify_quant(x) assert xinline == ('kleene-star', ('concat', [ ('kleene-star', ('set',['a','b','c'], '[abc]')), ('kleene-plus', ('symbol', 'x')), ]) ) x = re._parse('(a*|b+|c?)*') xinline = re._simplify_quant(x) assert xinline == ('kleene-star', ('union', [ ('kleene-star', ('symbol','a')), ('union', [ ('kleene-plus', ('symbol', 'b')), ('zero-or-one', ('symbol', 'c')), ]) ]) ) x = re._parse('(((((a*)*)+)+)?)?') xinline = re._simplify_quant(x) assert xinline == ('kleene-star', ('symbol', 'a')) class TestRegexOther: def test_empty_regex_checks(self): # test for but #63 re = Regex() assert re.pattern is None with pytest.raises(rejit.regex.RegexMatcherError): re.accept('') with pytest.raises(rejit.regex.RegexMatcherError): re.get_matcher_description() def test_DFA_compilation(self): re = Regex('a|b*') cases = [ ('a', True), ('a', True), ('', True), ('b', True), ('bbb', True), ('x', False), ('aaa', False), ('abb', False), ] accept_test_helper(re,cases) re.compile_to_DFA() accept_test_helper(re,cases) assert re._matcher_type == 'DFA' re = Regex() with pytest.raises(rejit.regex.RegexCompilationError): re.compile_to_DFA() def test_JIT_compilation(self): re = Regex('x(a|b)*x') cases = [ ('xx', True), ('xaaax', True), ('xbbbx', True), ('xabababx', True), ('xbbbaaax', True), ('', False), ('ababa', False), ('xxababxx', False), ('xaaa', False), ('bbbx', False), ('xxx', False), ('ccc', False), ] accept_test_helper(re,cases) assert re._matcher_type == 'NFA' # compile NFA -> DFA re.compile_to_DFA() accept_test_helper(re,cases) assert re._matcher_type == 'DFA' # compile DFA -> x86 re.compile_to_x86() accept_test_helper(re,cases) assert re._matcher_type == 'JIT' re = Regex('x(a|b)*x') accept_test_helper(re,cases) assert re._matcher_type == 'NFA' # compile NFA -> DFA -> x86 re.compile_to_x86() accept_test_helper(re,cases) assert re._matcher_type == 'JIT' # can't compile back to DFA with pytest.raises(rejit.regex.RegexCompilationError): re.compile_to_DFA() # can't compile a Regex without a matcher re = Regex() with pytest.raises(rejit.regex.RegexCompilationError): re.compile_to_x86()
<script lang="ts"> // import { unit } from "$lib/unit"; import { convertTemp } from "$lib/utilities/convertTemp"; import { toSentenceCase } from "$lib/utilities/toSentenceCase"; import WeatherIcon from "$lib/ui/WeatherIcon.svelte"; export let mode: "hourly" | "daily"; export let temp: { dt_txt: string; main: { temp: number; }; weather: Array<{ description: string; id: number; }>; }; $: date = new Date(temp.dt_txt); </script> <article class="forecast-item"> <time class="time" datetime={temp.dt_txt}> {#if mode === "hourly"} {date.toLocaleTimeString(undefined, { hour: "numeric", hour12: true, minute: "2-digit", })} {:else} {date.toLocaleDateString(undefined, { day: "numeric", month: "short", })} {/if} </time> <div class="weather-icon"> <WeatherIcon iconCode={temp.weather[0].id} /> </div> <div> <h3 class="temp"> </h3> <p class="descr">{toSentenceCase(temp.weather[0].description)}</p> </div> </article> <style lang="scss"> // @import '$lib/scss/variables.scss'; .forecast-item { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 1em; min-width: 10em; position: relative; scroll-snap-align: start; &:not(:last-child) { border-right: 1px solid transparent; &::after { content: ""; position: absolute; left: 100%; inset-block: 1em; width: 1px; background-color: hsl(0 0% 87%); } } } .time { font-style: italic; } .weather-icon { font-size: 3rem; } .temp { font-weight: 400; font-size: 24px; } </style>
import * as vlq from "vlq"; const merge = require('merge-source-map'); // // Maps a position in the generated file to to a position in the source file. // export interface IMapping { // // The line in the generated file (1-based). // genLine: number; // // The column in the generated file (0-based). // genColumn: number; // // The index of the source file. // sourceFileIndex: number; // // The line in the source file (1-based). // sourceLine: number; // // The column in the source file (0-based). // sourceColumn: number; // // The name that is mapped to. // nameIndex: number | undefined; } // // Parse a source mappings string and return the expanded result. // export function parseMappings(mappings: string): IMapping[] { const parsedMappings: IMapping[] = []; let genLine = 1; let sourceFile = 0; let sourceLine = 1; let sourceColumn = 0; let namesIndex = 0; for (const line of mappings.split(";")) { let genColumn = 0; for (const segment of line.split(",")) { if (segment.length > 0) { const decoded = vlq.decode(segment); if (decoded[0] !== undefined) { genColumn += decoded[0]; // I guess this is an index into the "sources" field of the source map. } if (decoded[1] !== undefined) { sourceFile += decoded[1]; } if (decoded[2] !== undefined) { sourceLine += decoded[2]; // A source line of 0 means just use the previous source line. } if (decoded[3] !== undefined) { sourceColumn += decoded[3]; } const hasName = decoded[4] !== undefined; if (hasName) { namesIndex += decoded[4]; } parsedMappings.push({ genLine: genLine, genColumn: genColumn, // This is 0-based. sourceFileIndex: sourceFile, sourceLine: sourceLine, // This is 1-based. sourceColumn: sourceColumn, // This is 0-based. nameIndex: hasName ? namesIndex : undefined, }); } } genLine += 1; } return parsedMappings; } // // Determines if two mappings are the same. // // Returns true if they are the same, otherwise false. // function mappingsAreSame(curMapping: IMapping, prevMapping: IMapping): boolean { if (curMapping.genLine !== prevMapping.genLine) { return false; } if (curMapping.genColumn !== prevMapping.genColumn) { return false; } if (curMapping.sourceFileIndex !== prevMapping.sourceFileIndex) { return false; } if (curMapping.sourceLine !== prevMapping.sourceLine) { return false; } if (curMapping.sourceColumn !== prevMapping.sourceColumn) { return false; } if (curMapping.nameIndex !== prevMapping.nameIndex) { return false; } return true; } // // Serialize source mappings to a string. // export function serializeMappings(mappings: IMapping[]): string { let output = ""; let previousGeneratedLine = 1; let previousGeneratedColumn = 0; let previousOriginalColumn = 0; let previousOriginalLine = 0; let previousNamesIndex = 0; let previousSource = 0; for (let mappingIndex = 0; mappingIndex < mappings.length; ++mappingIndex) { const mapping = mappings[mappingIndex]; if (mapping.genLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.genLine !== previousGeneratedLine) { output += ";"; previousGeneratedLine++; } } else if (mappingIndex > 0) { const prevMapping = mappings[mappingIndex - 1]; if (mappingsAreSame(mapping, prevMapping)) { continue; } output += ","; } const toEncode: number[] = []; const outputGenColumn = mapping.genColumn - previousGeneratedColumn; toEncode.push(outputGenColumn); previousGeneratedColumn = mapping.genColumn; const outputSourceFile = mapping.sourceFileIndex - previousSource; toEncode.push(outputSourceFile); previousSource = mapping.sourceFileIndex; // Lines are stored 0-based in SourceMap spec version 3 const outputSourceLine = mapping.sourceLine - 1 - previousOriginalLine; toEncode.push(outputSourceLine); previousOriginalLine = mapping.sourceLine - 1; const outputSourceColumn = mapping.sourceColumn - previousOriginalColumn; toEncode.push(outputSourceColumn); previousOriginalColumn = mapping.sourceColumn; if (mapping.nameIndex !== undefined) { const outputNamesIndex = mapping.nameIndex - previousNamesIndex; toEncode.push(outputNamesIndex); previousNamesIndex = mapping.nameIndex; } if (toEncode.length > 0) { output += vlq.encode(toEncode); } } return output; } // // Represents a position in a file. // export interface IFilePosition { // // The line in the file. // line: number; // // The column in the file. // column: number; } // // Represents a location in a source file. // export interface ISourceLocation { // // The source file that is referenced. // source: string; // // A name, if present. // name?: string; // // The position in the file. // position: IFilePosition; } // // Interface for interacting with a sourcemap. // export interface ISourceMap { // // Retrieves the source map data. // getData(): any; // // Gets the mappings that have been parsed from the source map data. // getMappings(): IMapping[]; // // Maps a generated file location to a source file location. // Returns undefined when no corresponding source location exists. // map(position: IFilePosition): ISourceLocation | undefined; } // // Class for interacting with a sourcemap. // export class SourceMap implements ISourceMap { // // The sourcemap data wrapped by this instance. // private sourceMapData: any; // // Parsed mappings from generated file to source file. // mappings: IMapping[]; constructor(sourceMapData: any) { this.sourceMapData = sourceMapData; this.mappings = parseMappings(sourceMapData.mappings || ""); } // // Retrieves the source map data. // getData(): any { return this.sourceMapData; } // // Gets the mappings that have been parsed from the source map data. // getMappings(): IMapping[] { return this.mappings; } // // Maps a generated file location to a source file location. // Returns undefined when no corresponding source location exists. // map(position: IFilePosition): ISourceLocation | undefined { const mapping = this.findMatchingMapping(position); if (mapping) { return this.computeMappingDetails(mapping); } return undefined; } /** * Return 0 <= i <= array.length such that !pred(array[i - 1]) && pred(array[i]). * * https://stackoverflow.com/a/41956372/25868 */ private binarySearch<T>(array: T[], pred: (el: T) => boolean): number { let lo = -1, hi = array.length; while (1 + lo < hi) { const mi = lo + ((hi - lo) >> 1); if (pred(array[mi])) { hi = mi; } else { lo = mi; } } return hi; } // // // Find a source mapping that matches the position in the generated file. // Original implementation: https://github.com/go-sourcemap/sourcemap/blob/180fcef48034918dd59a8920b0d1f5f12e4830de/consumer.go#L184 // private findMatchingMapping(position: IFilePosition): IMapping | undefined { let matchIndex = this.binarySearch(this.mappings, mapping => { if (mapping.genLine === position.line) { if (mapping.genColumn >= position.column) { return true; } } else if (mapping.genLine >= position.line) { return true; } return false; }); let match: IMapping | undefined; if (matchIndex >= this.mappings.length) { match = this.mappings[this.mappings.length-1]; if (match.genLine !== position.line) { return undefined; } } else { match = this.mappings[matchIndex]; // Fuzzy match. if (match.genLine > position.line || match.genColumn > position.column) { if (matchIndex === 0) { return undefined; } match = this.mappings[matchIndex - 1]; } } return match; } // // Computes mapping details returned to the caller. // private computeMappingDetails(mapping: IMapping): ISourceLocation { const sourceFile = this.sourceMapData.sources[mapping.sourceFileIndex]; const sourceFilePath = this.sourceMapData.sourceRoot ? this.sourceMapData.sourceRoot + "/" + sourceFile : sourceFile; return { source: sourceFilePath, name: mapping.nameIndex !== undefined ? this.sourceMapData.names[mapping.nameIndex] : undefined, position: { line: mapping.sourceLine, column: mapping.sourceColumn, }, }; } } // // Interface for generating a source map. // export interface ISourceMapGenerator { // // Get source files added to the source map. // getSources(): string[]; // // Get mappings already generated. // getMappings(): IMapping[]; // // Adds source mappings for a snippet of code to the source map. // addMappings(sourceFile: string, sourceCode: string, position: IFilePosition): void; // // Adds a single mapping to the source map. // addMapping(genPosition: IFilePosition, sourceLocation: ISourceLocation): void; // // Serializes the source map. // serialize(): any; } // // Computes the number of new lines in the code. // function determineNumNewLines(sourceCode: string): number { const newLines = sourceCode.match(/\n/g); return newLines ? newLines.length : 0; } // // Class for generating a source map. // export class SourceMapGenerator implements ISourceMapGenerator { // // Default fields for the the exported source map. // private sourceMapDefaults: any; // // Generated source mappings. // private mappings: IMapping[] = []; // // Source files that have been added. // private sources = new Map<string, number>(); // // The index of the next source file to be added to the source map. // private nextSourceFileIndex = 0; // // Names that have been added. // private names = new Map<string, number>(); // // The index of the next name to be added to the source map. // private nextNameIndex = 0; constructor(sourceMapDefaults?: any) { this.sourceMapDefaults = Object.assign({}, sourceMapDefaults); } // // Get source files added to the source map. // getSources(): string[] { return Array.from(this.sources.keys()); } // // Get mappings already generated. // getMappings(): IMapping[] { return this.mappings; } // // Adds source mappings for a snippet of code to the source map. // addMappings(sourceFile: string, sourceCode: string, position: IFilePosition): void { const numSourceLines = determineNumNewLines(sourceCode) + 1; for (let sourceLine = 1; sourceLine <= numSourceLines; sourceLine++) { this.addMapping( { line: position.line + sourceLine, column: position.column, }, { position: { line: sourceLine, column: 0, }, source: sourceFile, } ); } } // // Adds a single mapping to the source map. // addMapping(genPosition: IFilePosition, sourceLocation: ISourceLocation): void { let sourceFileIndex = this.sources.get(sourceLocation.source); if (sourceFileIndex === undefined) { sourceFileIndex = this.nextSourceFileIndex++ this.sources.set(sourceLocation.source, sourceFileIndex); } let namesIndex: number | undefined; if (sourceLocation.name) { namesIndex = this.names.get(sourceLocation.name); if (namesIndex === undefined) { namesIndex = this.nextNameIndex++ this.names.set(sourceLocation.name, namesIndex); } } this.mappings.push({ genLine: genPosition.line, genColumn: genPosition.column, sourceFileIndex: sourceFileIndex, sourceLine: sourceLocation.position.line, sourceColumn: sourceLocation.position.column, nameIndex: namesIndex, }); } // // Serializes the source map. // serialize(): any { return Object.assign( {}, this.sourceMapDefaults, { version: 3, names: Array.from(this.names.keys()), sources: Array.from(this.sources.keys()), mappings: serializeMappings(this.mappings), } ); }; } // // Merges two source maps. // export function mergeSourceMaps(sourceMapData1: any, sourceMapData2: any) { return merge(sourceMapData1, sourceMapData2); }
# Assignment 02 ## Task Idea Find the exit from an unknown labyrinth. ## Problem Description We start a journey through an unknown labyrinth. The labyrinth has many paths arranged on one level of a game board. The board is divided into square fields (locations) of the same size. Some paths are dead ends, and some introduce loops. Additionally, there is no direct access to the labyrinth. Exploration operations can be delegated to my software, but it will work in a multithreaded and asynchronous manner. An example labyrinth is shown in the image below: ![Labyrinth Image](labyrinth.png) The location placed in the bottom-left corner of the labyrinth has the position (row=0, col=0). ## Searching for the Exit When searching for the exit, follow these rules: - Do not explore the same labyrinth position multiple times. - Do not request exploration of positions that do not directly neighbor any previously explored positions. This refers to the immediate horizontal and vertical neighborhood (each position has four immediate neighbors). Exploring into the interior of walls is not allowed! - Explore the labyrinth in multiple places simultaneously. For example, if we know that we reached a certain position by going north and found out that it is adjacent to rooms to the south (the return path), east, and west, exploration orders for rooms to the east and west should be immediately triggered (if these rooms have not been explored yet). - In general, always delegate exploration orders to all positions that can be explored according to the previous points. ## Feedback Orders will be executed in the background, but the execution time is generally unknown. Later orders may finish earlier. Orders may even finish at the same time. Each order will be executed. Expect that each call to the `result` method of the `ResultListener` interface will be executed by a different thread. ## Defeat Reasons for failure: - Failure to find the exit. The search time will be limited, but the limit will be large enough for a correctly functioning program to find a solution. - Continuing the search after finding the exit. This should consider the "reaction time" associated with receiving and processing information about finding the exit. - Failure to adhere to the rules of searching for the exit, especially sequential work. - Failure to receive provided information. - Indicating an incorrect location in the labyrinth or outside it. - Reaching a "WALL" location. This should not happen. The exploration result contains information about allowed directions of movement—use this information! - Using CPU time when the program has nothing to do, i.e., when waiting for the results of orders. Unused threads must be put to sleep! ## Observer Since it is unknown when an order will be executed by my code, and there are no methods for "querying," the observer pattern must be used. The object receiving orders must be provided by you before the first order. Each order will receive a unique number. The observer will receive information about the specified location along with the order number, allowing the result to be associated with the order. ## Communication Your code communicates solely through the `Employer` interface. 1. First, I provide an object compatible with the `OrderInterface`. 2. Then, I execute the `start()` method in a separate thread, which receives the initial position and the directions in which the search for the exit can begin. The initial position is guaranteed to be of type `PASSAGE`. 3. Your code provides an object compatible with `ResultListener` using the `setResultListener` method. 4. Now, your program can delegate exploration orders (using the `order` method). 5. My program will, at any time, provide the result of an order. 6. The last steps are repeated until the exit is found. Finding the exit should conclude the `start()` method. ## Delivering the Solution Please provide the source code for the `ParallelEmployer` class. You can include your own methods and fields in the class. The class should implement the `Employer` interface. The solution file may contain other classes, but only the `ParallelEmployer` class can be public. Do not modify the code I provide. It will be used in the form it was shared during testing. Do not include the code I provide in the solutions. It will be available during testing. The programs will be tested using Java version 17. ## Appendix I added the `Location` record, which is used by the `Direction` enum. You can apply it in your solution if you wish. It's optional. ## Test result ![Test result](cute.png)
import { Route } from '@angular/router'; import { WelcomeComponent } from './welcome/welcome.component'; export const APP_ROUTES: Route[] = [ { path: '', component: WelcomeComponent, pathMatch: 'full', }, { path: 'about', loadComponent: () => import('./about/about.component').then((c) => c.AboutComponent), }, { path: 'dashboard', loadChildren: () => import('./dashboard/dashboard-routes').then((r) => r.DASHBOARD_ROUTES), }, ];
<!DOCTYPE html> <html lang="uk"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>WebStudio</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Oleo+Script&family=Raleway:wght@700&family=Roboto:ital,wght@0,400;0,500;0,700;0,900;1,400&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css" /> <link href="./css/styles.css" rel="stylesheet" type="text/css" /> </head> <body> <!-- Header section --> <header class="header section"> <div class="container header-container"> <nav class="header-nav"> <a class="header-logo link header-link" href=""> <span class="logo">Web</span>Studio</a > <ul class="header-list list"> <li class="header-item"> <a class="header-link current" href="./index.html">Студія</a> </li> <li class="header-item"> <a class="header-link" href="./portfolio.html">Портфоліо</a> </li> <li class="header-item"> <a class="header-link" href="">Контакти</a> </li> </ul> </nav> <ul class="header-contacts list"> <li class="header-contacts-list"> <a class="header-link link" href="mailto:info@devstudio.com"> <svg class="header-icon" width="16" height="12"> <use href="./іmages/icons.svg#envelope"></use> </svg> info@devstudio.com </a> </li> <li class="header-contacts-list"> <a class="header-link link" href="tel:+380961111111"> <svg class="header-icon" width="10" height="16"> <use href="./іmages/icons.svg#smartphone"></use> </svg> +38 096 111 11 11 </a> </li> </ul> </div> </header> <!-- Main section --> <main class="main"> <!--Hero--> <section class="hero section"> <div class="container"> <h1 class="hero-title">Ефективні рішення для вашого бізнесу</h1> <button type="button" class="button primary" data-modal-open> Замовити послугу </button> <!--Modal Window--> <div class="backdrop is-hidden" data-modal> <div class="modal"> <button class="modal-btn" type="button" data-modal-close> <svg class="modal-btn-icon" width="18" height="18"> <use href="./іmages/icons.svg#icon-close"></use> </svg> </button> </div> </div> </div> </section> <!--Advantage--> <section class="section advantage"> <div class="container"> <h2 class="section-title visually-hidden">Наші переваги</h2> <ul class="list advantage-list"> <li class="advantage-item"> <div class="advantage-icon"> <svg width="70" height="70"> <use href="./іmages/icons.svg#antenna"></use> </svg> </div> <h3 class="advantage-title title">Увага до деталей</h3> <p class="advantage-text"> Ідейні міркування, і навіть початок повсякденної роботи з формування позиції. </p> </li> <li class="advantage-item"> <div class="advantage-icon"> <svg width="70" height="70"> <use href="./іmages/icons.svg#clock"></use> </svg> </div> <h3 class="advantage-title title">Пунктуальність</h3> <p class="advantage-text"> Завдання організації, особливо рамки і місце навчання кадрів тягне у себе. </p> </li> <li class="advantage-item"> <div class="advantage-icon"> <svg width="70" height="70"> <use href="./іmages/icons.svg#diagram"></use> </svg> </div> <h3 class="advantage-title title">Планування</h3> <p class="advantage-text"> Так само консультація з широким активом значною мірою зумовлює. </p> </li> <li class="advantage-item"> <div class="advantage-icon"> <svg width="70" height="70"> <use href="./іmages/icons.svg#astronaut"></use> </svg> </div> <h3 class="advantage-title title">Сучасні технології</h3> <p class="advantage-text"> Значимість цих проблем настільки очевидна, що реалізація планових завдань. </p> </li> </ul> </div> </section> <!--What do we do--> <section class="section"> <div class="container"> <h2 class="section-title">Чим ми займаємося</h2> <ul class="list do-list"> <li class="do-img"> <img src="./іmages/box1.jpg" alt="Розробка сайтів" width="370" /> <div class="do-box"> <p class="do-text">Десктопні додатки</p> </div> </li> <li class="do-img"> <img src="./іmages/box2.jpg" alt="Розробка додатків" width="370" /> <div class="do-box"> <p class="do-text">Мобільні додатки</p> </div> </li> <li class="do-img"> <img src="./іmages/box3.jpg" alt="Веб-дизайн" width="370" /> <div class="do-box"> <p class="do-text">Дизайнерські рішення</p> </div> </li> </ul> </div> </section> <!--Team--> <section class="section team"> <div class="container"> <h2 class="section-title">Наша команда</h2> <ul class="list team-list"> <li class="team-img"> <img src="./іmages/img1.jpg" alt="Фото продакт дизайнера" width="270" /> <div class="team-caption"> <h3 class="title team-member">Ігорь Дем'яненко</h3> <p class="team-position">Product Designer</p> <ul class="socials list"> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка інстаграм" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#instagram"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="іконка твіттер" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#twitter"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Иконка фейсбук" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#facebook"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка лінкедін" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="team-img"> <img src="./іmages/img2.jpg" alt="Фото разробника" width="270" /> <div class="team-caption"> <h3 class="title team-member">Ольга Репіна</h3> <p class="team-position">Frontend Developer</p> <ul class="socials list"> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка інстаграм" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#instagram"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка твіттер" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#twitter"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка фейсбук" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#facebook"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка лінкедін" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="team-img"> <img src="./іmages/img3.jpg" alt="Фото маркетолога" width="270" /> <div class="team-caption"> <h3 class="title team-member">Микола Тарасов</h3> <p class="team-position">Marketing</p> <ul class="socials list"> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка інстаграм" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#instagram"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка твіттер" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#twitter"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка фейсбук" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#facebook"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка лінкедін" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#linkedin"></use> </svg> </a> </li> </ul> </div> </li> <li class="team-img"> <img src="./іmages/img4.jpg" alt="Фото веб-дизайнера" width="270" /> <div class="team-caption"> <h3 class="title team-member">Михайло Єрмаков</h3> <p class="team-position">UI Designer</p> <ul class="socials list"> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка інстаграм" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#instagram"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка твіттер" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#twitter"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка фейсбук" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#facebook"></use> </svg> </a> </li> <li class="socials-item"> <a class="link socials-link" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка лінкедін" > <svg class="socials-icon" width="20" height="20"> <use href="./іmages/icons.svg#linkedin"></use> </svg> </a> </li> </ul> </div> </li> </ul> </div> </section> <!--Clients--> <section class="section"> <div class="container"> <h2 class="section-title">Постійні клієнти</h2> <ul class="list clients"> <li class="clients-item"> <a class="clients-link link" href="" target="_blank " rel="noopener noreferrer" aria-label="перший логотип" > <svg class="clients-icon" width="106" height="60"> <use href="./іmages/icons.svg#logo-1"></use> </svg> </a> </li> <li class="clients-item"> <a class="clients-link link" href="" target="_blank " rel="noopener noreferrer" aria-label="другий логотип" > <svg class="clients-icon" width="106" height="60"> <use href="./іmages/icons.svg#logo-2"></use> </svg> </a> </li> <li class="clients-item"> <a class="clients-link link" href="" target="_blank " rel="noopener noreferrer" aria-label="третій логотип" > <svg class="clients-icon" width="106" height="60"> <use href="./іmages/icons.svg#logo-3"></use> </svg> </a> </li> <li class="clients-item"> <a class="clients-link link" href="" target="_blank " rel="noopener noreferrer" aria-label="четвертий логотип" > <svg class="clients-icon" width="106" height="60"> <use href="./іmages/icons.svg#logo-4"></use> </svg> </a> </li> <li class="clients-item"> <a class="clients-link link" href="" target="_blank " rel="noopener noreferrer" aria-label="п'ятий логотип" > <svg class="clients-icon" width="106" height="60"> <use href="./іmages/icons.svg#logo-5"></use> </svg> </a> </li> <li class="clients-item"> <a class="clients-link link" href="" target="_blank " rel="noopener noreferrer" aria-label="шостий логотип" > <svg class="clients-icon" width="106" height="60"> <use href="./іmages/icons.svg#logo-6"></use> </svg> </a> </li> </ul> </div> </section> </main> <!--Footer section --> <footer class="footer section"> <div class="container footer-container"> <div> <a class="footer-logo footer-link" href="" ><span class="logo">Web</span>Studio</a > <address class="footer-contacts"> <p class="footer-address">м. Київ, пр-т Лесі Українки, 26</p> <a class="footer-link" href="mailto:info@example.com" >info@example.com </a> <a class="footer-link" href="tel:+380991111111"> +38 099 111 11 11 </a> </address> </div> <div> <p class="footer-call">Приєднуйтесь</p> <ul class="list footer-list"> <li> <a class="link footer-socials" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка інстаграм" > <svg class="footer-icon" width="20" height="20"> <use href="./іmages/icons.svg#instagram"></use> </svg> </a> </li> <li class="socials-item"> <a class="link footer-socials" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка твиттер" > <svg class="footer-icon" width="20" height="20"> <use href="./іmages/icons.svg#twitter"></use> </svg> </a> </li> <li class="socials-item"> <a class="link footer-socials" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка фейсбук" > <svg class="footer-icon" width="20" height="20"> <use href="./іmages/icons.svg#facebook"></use> </svg> </a> </li> <li class="socials-item"> <a class="link footer-socials" href="" target="_blank " rel="noopener noreferrer" aria-label="Іконка лінкедін" > <svg class="footer-icon" width="20" height="20"> <use href="./іmages/icons.svg#linkedin"></use> </svg> </a> </li> </ul> </div> </div> </footer> <script src="./js/modal.js"></script> </body> </html> <!--<ul class="list"> <li> <a class="link" href="" target="_blank " rel="noopener noreferrer" aria-label="instagram" > <svg width="" height=""> <use href=""></use> </svg> </a> </li> <li></li> <li></li> <li></li> </ul>-->
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!-- c:out ; c:foreach; c:if --> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!-- form:form --> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <!-- formatting things like dates --> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="/webjars/bootstrap/4.5.0/css/bootstrap.min.css" /> <script src="/webjars/jquery/3.5.1/jquery.min.js"></script> <script src="/webjars/bootstrap/4.5.0/js/bootstrap.min.js"></script> </head> <body> <div class="container d-flex justify-content-between"> <div class="form-group"> <h1>Register!</h1> <p class="text-danger"><form:errors path="user.*"/></p> <form:form method="POST" action="/registration" modelAttribute="user"> <p> <form:label path="firstName">First Name:</form:label> <form:input type="text" path="firstName" class="form-control" /> </p> <p> <form:label path="lastName">Last Name:</form:label> <form:input type="text" path="lastName" class="form-control"/> </p> <p> <form:label path="email">Email:</form:label> <form:input type="email" path="email" class="form-control"/> </p> <p> <form:label path="password">Password:</form:label> <form:password path="password" class="form-control"/> </p> <p> <form:label path="passwordConfirmation">Password Confirmation:</form:label> <form:password path="passwordConfirmation" class="form-control"/> </p> <input type="submit" value="Register!" class="btn btn-primary" /> </form:form> </div> <div class="form-group"> <h1>Login</h1> <p class="text-danger"><c:out value="${error}" /></p> <form method="post" action="/login"> <p> <label for="email">Email</label> <input type="text" id="email" name="email" class="form-control"/> </p> <p> <label for="password">Password</label> <input type="password" id="password" name="password" class="form-control"/> </p> <input type="submit" value="Login!" class="btn btn-primary"/> </form> </div> </div> </body> </html>
import logging from logging.handlers import RotatingFileHandler import os basedir = os.path.abspath(os.path.dirname(__file__)) logs_dir = os.path.join(basedir, 'logs') if not os.path.exists(logs_dir): os.makedirs(logs_dir) # 创建一个日志实例 logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # 创建一个处理器,写入日志文件 file_handler = RotatingFileHandler(os.path.join(logs_dir, 'app.log'), maxBytes=10240, backupCount=10) file_formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') file_handler.setFormatter(file_formatter) file_handler.setLevel(logging.INFO) # 创建一个处理器,输出到控制台 stream_handler = logging.StreamHandler() stream_formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s') stream_handler.setFormatter(stream_formatter) stream_handler.setLevel(logging.DEBUG) # 将处理器添加到日志实例 logger.addHandler(file_handler) logger.addHandler(stream_handler)
package com.atguigu.gulimall.cart.vo; import lombok.Data; import java.math.BigDecimal; import java.util.List; /** * @author kLjSumi * @Date 2021/1/10 * * 购物车 */ public class Cart { private List<CartItem> items; private Integer countNum; //商品数量 private Integer countType; //商品类型数量 private BigDecimal totalAmount; //商品总价 private BigDecimal reduce = new BigDecimal("0"); //减免价格 public List<CartItem> getItems() { return items; } public void setItems(List<CartItem> items) { this.items = items; } public Integer getCountNum() { int count = 0; if (items!=null && items.size()>0) { for (CartItem item : items) { count+=item.getCount(); } } return count; } public Integer getCountType() { int count = 0; if (items!=null && items.size()>0) { for (CartItem item : items) { count+=1; } } return count; } public BigDecimal getTotalAmount() { BigDecimal amount = new BigDecimal("0"); if (items!=null && items.size()>0) { for (CartItem item : items) { BigDecimal totalPrice = item.getTotalPrice(); amount.add(totalPrice); } } amount.subtract(getReduce()); return amount; } public BigDecimal getReduce() { return reduce; } public void setReduce(BigDecimal reduce) { this.reduce = reduce; } }
package com.example.languagelegends.database import androidx.room.TypeConverter import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.io.ByteArrayOutputStream import android.graphics.Bitmap import android.graphics.BitmapFactory import com.example.languagelegends.features.Language /** * This class provides methods to convert between different data types. * It is used by Room to convert complex data types when persisting to and reading from the database. */ class Converters { private val gson = Gson() /** * Converts a list of Language objects to a JSON string. */ @TypeConverter fun fromLanguageList(value: MutableList<Language>?): String { return gson.toJson(value) } /** * Converts a JSON string to a list of Language objects. */ @TypeConverter fun toLanguageList(value: String): MutableList<Language>? { val type = object : TypeToken<MutableList<Language>>() {}.type return gson.fromJson(value, type) } /** * Converts a JSON string to a Language object. */ @TypeConverter fun fromLanguage(value: String): Language { val type = object : TypeToken<Language>() {}.type return Gson().fromJson(value, type) } /** * Converts a Language object to a JSON string. */ @TypeConverter fun languageToString(language: Language): String { return Gson().toJson(language) } /** * Converts a Bitmap object to a ByteArray. * The Bitmap is compressed to JPEG format. * The quality of the Bitmap is reduced if the size of the ByteArray exceeds 1MB. */ @TypeConverter fun fromBitmap(bitmap: Bitmap?): ByteArray? { val maxSize = 720 * 720 var quality = 70 val stream = ByteArrayOutputStream() bitmap?.compress(Bitmap.CompressFormat.JPEG, quality, stream) while (stream.toByteArray().size > maxSize) { stream.reset() quality -= 5 bitmap?.compress(Bitmap.CompressFormat.JPEG, quality, stream) } return stream.toByteArray() } /** * Converts a ByteArray to a Bitmap object. */ @TypeConverter fun toBitmap(byteArray: ByteArray?): Bitmap? { return BitmapFactory.decodeByteArray(byteArray, 0, byteArray?.size ?: 0) } }
from django.core.management import call_command from django.core.management.base import CommandError from gestion_client.models import User, Contrat, Client, Evenement from unittest.mock import patch, Mock from datetime import datetime, timedelta import pytest @pytest.fixture def custom_input(): return lambda _: "testpassword" @pytest.mark.django_db def test_update_evenement_successful(mocker, capsys): # Créer un collaborateur fictif pour le test collaborateur = User.objects.create( nom_complet="Collaborateur Test", username="testuser", password="testpassword", role="gestion" ) # Créer un client fictif pour le test client = Client.objects.create(nom_complet='Client Test', email='test@example.com') # Créer un commercial fictif pour le test commercial = User.objects.create_user(username='testcommercial', password='testpassword', nom_complet='Test Commercial', role='commercial') # Créer un contrat fictif pour le test contrat = Contrat.objects.create(client=client, commercial=commercial, montant_total='1000.00', montant_restant='800.00', statut='En cours') # Créer un support fictif pour le test support_user = User.objects.create(username='testsupport', role='support') evenement = Evenement.objects.create(contrat=contrat, nom='Test Evenement', date_debut='20220101', date_fin='20220105', support=support_user, lieu='Lieu test', nombre_participants=50, notes='Notes test') # Mock de la fonction getpass pour éviter les demandes de mot de passe réelles mocker.patch('getpass.getpass', return_value='testpassword') # Utilisation de patch pour simuler l'entrée utilisateur with patch('builtins.input', side_effect=custom_input): # Mock pour contourner la vérification de l'autorisation mocker.patch('gestion_client.permissions.get_user_role_from_token', return_value='gestion') # Mock de la fonction load_token pour retourner un token valide mocker.patch('gestion_client.permissions.load_token', return_value=('test_token', datetime.utcnow() + timedelta(days=1))) # Mock de la fonction validate_token pour retourner un utilisateur valide mocker.patch('gestion_client.permissions.validate_token', return_value=collaborateur) # Capture de la sortie standard pour vérification call_command('update_evenement', str(evenement.id), '--nom', 'Nouveau Nom evenement') # Vérification que le collaborateur a été modifié avec succès collaborateur.refresh_from_db() captured = capsys.readouterr() assert f"Événement avec l'ID {evenement.id} mis à jour avec succès." in captured.out @pytest.mark.django_db def test_update_evenement_permission_failure(mocker, capsys): # Créer un collaborateur fictif pour le test collaborateur = User.objects.create( nom_complet="Collaborateur Test", username="testuser", password="testpassword", role="commercial" ) # Créer un client fictif pour le test client = Client.objects.create(nom_complet='Client Test', email='test@example.com') # Créer un commercial fictif pour le test commercial = User.objects.create_user(username='testcommercial', password='testpassword', nom_complet='Test Commercial', role='commercial') # Créer un contrat fictif pour le test contrat = Contrat.objects.create(client=client, commercial=commercial, montant_total='1000.00', montant_restant='800.00', statut='En cours') # Créer un support fictif pour le test support_user = User.objects.create(username='testsupport', role='support') evenement = Evenement.objects.create(contrat=contrat, nom='Test Evenement', date_debut='20220101', date_fin='20220105', support=support_user, lieu='Lieu test', nombre_participants=50, notes='Notes test') # Mock de la fonction getpass pour éviter les demandes de mot de passe réelles mocker.patch('getpass.getpass', return_value='testpassword') # Utilisation de patch pour simuler l'entrée utilisateur with patch('builtins.input', side_effect=custom_input): # Mock pour contourner la vérification de l'autorisation mocker.patch('gestion_client.permissions.get_user_role_from_token', return_value='commercial') # Mock de la fonction load_token pour retourner un token valide mocker.patch('gestion_client.permissions.load_token', return_value=('test_token', datetime.utcnow() + timedelta(days=1))) # Mock de la fonction validate_token pour retourner un utilisateur valide mocker.patch('gestion_client.permissions.validate_token', return_value=collaborateur) # Capture de la sortie standard pour vérification with patch('sys.stderr', new_callable=Mock) as mock_stderr: # Création d'une instance de la commande try: # Capture de la sortie standard pour vérification call_command('update_evenement', str(evenement.id), '--nom', 'Nouveau Nom') except CommandError as ce: # Vérification du message d'erreur assert str(ce) == "Vous n'avez pas la permission d'effectuer cette action." @pytest.mark.django_db def test_update_evenement_not_found(mocker, capsys): # Créer un utilisateur fictif pour le test (rôle: 'gestion') user = User.objects.create_user(username='testuser', password='testpassword', nom_complet='Test User', role='gestion') # ID d'un evenement qui n'existe pas evenement_id = 999 # Mock de la fonction getpass pour éviter les demandes de mot de passe réelles mocker.patch('getpass.getpass', return_value='testpassword') # Utilisation de patch pour simuler l'entrée utilisateur with patch('builtins.input', side_effect=custom_input): # Mock pour contourner la vérification de l'autorisation mocker.patch('gestion_client.permissions.get_user_role_from_token', return_value='gestion') # Mock de la fonction load_token pour retourner un token valide mocker.patch('gestion_client.permissions.load_token', return_value=('test_token', datetime.utcnow() + timedelta(days=1))) # Mock de la fonction validate_token pour retourner un utilisateur valide mocker.patch('gestion_client.permissions.validate_token', return_value=user) # Capture de la sortie d'erreur standard pour vérification with patch('sys.stderr', new_callable=Mock) as mock_stderr: # Tentative de mise à jour d'un collaborateur qui n'existe pas try: call_command('update_evenement', str(evenement_id), '--nom', 'Nouveau evenement') except CommandError as ce: # Vérification du message d'erreur assert str(ce) == f"L'événement avec l'ID {evenement_id} n'existe pas."
import React from 'react' import { render } from 'react-dom' import { createStore } from 'redux' import { Provider, connect } from 'react-redux' import userReducer from 'core/lib/reducers/user' const LoginFormComponent = ({isLoggedIn, onLoginSubmit}) => { let input return <form onSubmit={e => { e.preventDefault() onLoginSubmit(input.value) input.value = '' }}> <input type='password' ref={node => { input = node }} /> <button type='submit'>Log in</button> <p>{ isLoggedIn ? 'Congratulations you have logged in' : 'You are not logged in' }</p> </form> } const LoginFormContainer = connect( state => ({ isLoggedIn: state.isLoggedIn }), dispatch => ({ onLoginSubmit: password => { dispatch({type: 'LOGIN', password}) } }) )(LoginFormComponent) const store = createStore(userReducer) render( <Provider store={store}> <LoginFormContainer /> </Provider>, document.getElementById('root') )
namespace Bookworm.Services.Data.Models.Books { using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Bookworm.Data.Common.Repositories; using Bookworm.Data.Models; using Bookworm.Services.Data.Contracts; using Bookworm.Services.Data.Contracts.Books; using Bookworm.Web.ViewModels.Books; using Bookworm.Web.ViewModels.Comments; using Microsoft.EntityFrameworkCore; public class RetrieveBooksService : IRetrieveBooksService { private readonly IDeletableEntityRepository<Book> bookRepository; private readonly IRepository<AuthorBook> authorsBooksRepository; private readonly IDeletableEntityRepository<Author> authorRepository; private readonly IDeletableEntityRepository<Publisher> publishersRepository; private readonly IDeletableEntityRepository<Comment> commentRepository; private readonly IRepository<Rating> ratingRepository; private readonly IRepository<Vote> voteRepository; private readonly ICategoriesService categoriesService; private readonly ILanguagesService languagesService; private readonly IRepository<FavoriteBook> favoriteBookRepository; public RetrieveBooksService( IDeletableEntityRepository<Book> bookRepository, IRepository<AuthorBook> authorsBooksRepository, IDeletableEntityRepository<Author> authorRepository, IDeletableEntityRepository<Publisher> publishersRepository, IDeletableEntityRepository<Comment> commentRepository, IRepository<Rating> ratingRepository, IRepository<Vote> voteRepository, ICategoriesService categoriesService, ILanguagesService languagesService, IRepository<FavoriteBook> favoriteBookRepository) { this.bookRepository = bookRepository; this.authorsBooksRepository = authorsBooksRepository; this.authorRepository = authorRepository; this.publishersRepository = publishersRepository; this.commentRepository = commentRepository; this.ratingRepository = ratingRepository; this.voteRepository = voteRepository; this.categoriesService = categoriesService; this.languagesService = languagesService; this.favoriteBookRepository = favoriteBookRepository; } public async Task<BookViewModel> GetBookWithIdAsync(string bookId, string userId = null) { Book book = await this.bookRepository .AllAsNoTracking() .FirstOrDefaultAsync(book => book.Id == bookId); string categoryName = await this.categoriesService.GetCategoryNameAsync(book.CategoryId); List<int> authorsIds = await this.authorsBooksRepository .AllAsNoTracking() .Where(x => x.BookId == bookId) .Select(x => x.AuthorId) .ToListAsync(); List<string> authors = await this.authorRepository .AllAsNoTracking() .Where(author => authorsIds.Contains(author.Id)) .Select(x => x.Name) .ToListAsync(); Publisher publisher = await this.publishersRepository .AllAsNoTracking() .FirstOrDefaultAsync(publisher => publisher.Id == book.PublisherId); string publisherName = publisher?.Name; string language = this.languagesService.GetLanguageName(book.LanguageId); double votesAvg = 0; int votesCount = this.ratingRepository.AllAsNoTracking().Where(x => x.BookId == bookId).Count(); if (votesCount > 0) { votesAvg = this.ratingRepository.AllAsNoTracking().Where(x => x.BookId == bookId).Average(x => x.Value); } BookViewModel model = new BookViewModel() { Id = book.Id, Title = book.Title, Description = book.Description, DownloadsCount = book.DownloadsCount, FileUrl = book.FileUrl, ImageUrl = book.ImageUrl, Language = language, PagesCount = book.PagesCount, Year = book.Year, Authors = authors, PublisherName = publisherName, CategoryName = categoryName, RatingsAvg = votesAvg, RatingsCount = votesCount, }; if (userId != null) { List<CommentViewModel> comments = await this.commentRepository .AllAsNoTracking() .Where(comment => comment.BookId == bookId) .Select(comment => new CommentViewModel() { Id = comment.Id, UserId = comment.UserId, Content = comment.Content, CreatedOn = comment.CreatedOn, UserUserName = comment.User.UserName, DownVotesCount = this.voteRepository .AllAsNoTracking() .Where(vote => vote.CommentId == comment.Id && vote.Value == VoteValue.DownVote) .Count(), UpVotesCount = this.voteRepository .AllAsNoTracking() .Where(vote => vote.CommentId == comment.Id && vote.Value == VoteValue.UpVote) .Count(), UserVote = (int)this.voteRepository .AllAsNoTracking() .FirstOrDefault(v => v.UserId == userId && v.CommentId == comment.Id).Value, }) .ToListAsync(); model.Comments = comments; bool isFavorite = await this.favoriteBookRepository .AllAsNoTracking() .AnyAsync(x => x.BookId == bookId && x.UserId == userId); model.IsFavorite = isFavorite; model.IsUserBook = book.UserId == userId; Rating rating = await this.ratingRepository .AllAsNoTracking() .FirstOrDefaultAsync(rating => rating.BookId == bookId && rating.UserId == userId); if (rating != null) { model.UserRating = rating.Value; } } return model; } public async Task<BookListingViewModel> GetBooksAsync(int categoryId, int page, int booksPerPage) { BookListingViewModel model = new BookListingViewModel() { CategoryName = await this.categoriesService.GetCategoryNameAsync(categoryId), Books = await this.bookRepository .AllAsNoTracking() .Where(x => x.CategoryId == categoryId && x.IsApproved) .Select(x => new BookViewModel() { Id = x.Id, Title = x.Title, ImageUrl = x.ImageUrl, }) .Skip((page - 1) * booksPerPage) .Take(booksPerPage) .OrderByDescending(x => x.Id) .ToListAsync(), PageNumber = page, BookCount = await this.bookRepository .AllAsNoTracking() .Where(x => x.CategoryId == categoryId && x.IsApproved) .CountAsync(), BooksPerPage = booksPerPage, }; return model; } public async Task<BookListingViewModel> GetUserBooksAsync(string userId, int page, int booksPerPage) { BookListingViewModel model = new BookListingViewModel() { Books = await this.bookRepository .AllAsNoTracking() .Where(x => x.UserId == userId) .OrderByDescending(x => x.CreatedOn) .Select(x => new BookViewModel() { Id = x.Id, Title = x.Title, ImageUrl = x.ImageUrl, }) .Skip((page - 1) * booksPerPage) .Take(booksPerPage) .OrderByDescending(x => x.Id) .ToListAsync(), PageNumber = page, BookCount = await this.bookRepository .AllAsNoTracking() .Where(x => x.UserId == userId) .CountAsync(), BooksPerPage = booksPerPage, }; return model; } public async Task<IList<BookViewModel>> GetPopularBooksAsync(int count) { List<BookViewModel> popularBooks = await this.bookRepository .AllAsNoTracking() .Where(x => x.IsApproved) .OrderByDescending(x => x.DownloadsCount) .Take(count) .Select(x => new BookViewModel() { Id = x.Id, ImageUrl = x.ImageUrl, }) .ToListAsync(); return popularBooks; } public async Task<IList<BookViewModel>> GetRecentBooksAsync(int count) { List<BookViewModel> recentBooks = await this.bookRepository .AllAsNoTracking() .Where(x => x.IsApproved) .OrderByDescending(x => x.CreatedOn) .Take(count) .Select(x => new BookViewModel() { Id = x.Id, ImageUrl = x.ImageUrl, }) .ToListAsync(); return recentBooks; } public async Task<List<BookViewModel>> GetUnapprovedBooksAsync() { List<BookViewModel> unapprovedBooks = await this.bookRepository .AllAsNoTracking() .Where(x => x.IsApproved == false) .Select(x => new BookViewModel() { Id = x.Id, UserId = x.UserId, Title = x.Title, }).ToListAsync(); return unapprovedBooks; } public async Task<int> GetUnapprovedBooksCountAsync() { int unapprovedBooksCount = await this.bookRepository .AllAsNoTracking() .Where(book => book.IsApproved == false) .CountAsync(); return unapprovedBooksCount; } public async Task<List<BookViewModel>> GetApprovedBooksAsync() { List<BookViewModel> approvedBooks = await this.bookRepository .AllAsNoTracking() .Where(book => book.IsApproved) .Select(book => new BookViewModel() { Id = book.Id, UserId = book.UserId, ImageUrl = book.ImageUrl, Title = book.Title, }).ToListAsync(); return approvedBooks; } public async Task<List<BookViewModel>> GetDeletedBooksAsync() { List<BookViewModel> deletedBooks = await this.bookRepository .AllAsNoTrackingWithDeleted() .Where(book => book.IsDeleted) .Select(book => new BookViewModel() { Id = book.Id, UserId = book.UserId, ImageUrl = book.ImageUrl, Title = book.Title, }).ToListAsync(); return deletedBooks; } } }
/* * GearBox Project: Peer-Reviewed Open-Source Libraries for Robotics * http://gearbox.sf.net/ * Copyright (c) 2004-2010 Alex Brooks * * This distribution is licensed to you under the terms described in * the LICENSE file included in this distribution. * */ #include <iostream> #include <cstring> #include <gbxutilacfr/gbxutilacfr.h> #include <gbxsickacfr/gbxiceutilacfr/gbxiceutilacfr.h> #include "driver.h" using namespace std; namespace gbxsickacfr { namespace { class NoRxMsgException : public std::exception { std::string message_; public: NoRxMsgException(const char *message) : message_(message) {} NoRxMsgException(const std::string &message) : message_(message) {} ~NoRxMsgException()throw(){} virtual const char* what() const throw() { return message_.c_str(); } }; class NackReceivedException : public std::exception { std::string message_; public: NackReceivedException(const char *message) : message_(message) {} NackReceivedException(const std::string &message) : message_(message) {} ~NackReceivedException()throw(){} virtual const char* what() const throw() { return message_.c_str(); } }; class RxMsgIsErrorException : public std::exception { std::string message_; public: RxMsgIsErrorException(const char *message) : message_(message) {} RxMsgIsErrorException(const std::string &message) : message_(message) {} ~RxMsgIsErrorException()throw(){} virtual const char* what() const throw() { return message_.c_str(); } }; } Config::Config() : baudRate(38400), minRange(0.0), maxRange(0.0), fieldOfView(0.0), startAngle(0.0), numberOfSamples(0) { } bool Config::isValid() const { // Don't bother verifying device, the user will find out soon enough when the Driver bitches. if ( !( baudRate == 9600 || baudRate == 19200 || baudRate == 38400 || baudRate == 500000 ) ) { return false; } if ( minRange < 0.0 ) return false; if ( maxRange <= 0.0 ) return false; if ( fieldOfView <= 0.0 || fieldOfView > DEG2RAD(360.0) ) return false; if ( startAngle <= DEG2RAD(-360.0) || startAngle > DEG2RAD(360.0) ) return false; if ( numberOfSamples <= 0 ) return false; return true; } std::string Config::toString() const { std::stringstream ss; ss << "Laser driver config: device="<<device<<", baudRate="<<baudRate<<", minr="<<minRange<<", maxr="<<maxRange<<", fov="<<RAD2DEG(fieldOfView)<<"deg, start="<<RAD2DEG(startAngle)<<"deg, num="<<numberOfSamples; return ss.str(); } bool Config::operator==( const Config & other ) { return (minRange==other.minRange && maxRange==other.maxRange && fieldOfView==other.fieldOfView && startAngle==other.startAngle && numberOfSamples==other.numberOfSamples); } bool Config::operator!=( const Config & other ) { return (minRange!=other.minRange || maxRange!=other.maxRange || fieldOfView!=other.fieldOfView || startAngle!=other.startAngle || numberOfSamples!=other.numberOfSamples); } Driver::Driver( const Config &config, gbxutilacfr::Tracer& tracer, gbxutilacfr::Status& status ) : config_(config), tracer_(tracer), status_(status) { if ( !config.isValid() ) { stringstream ss; ss << __func__ << "(): Invalid config: " << config.toString(); throw gbxutilacfr::Exception( ERROR_INFO, ss.str() ); } stringstream ssDebug; ssDebug << "Connecting to laser on serial port " << config_.device; tracer_.debug( ssDebug.str() ); const int MAX_TRIES=3; for ( int i=0; i < MAX_TRIES; i++ ) { stringstream tryString; tryString << "Connection attempt " << i+1 << " of " << MAX_TRIES << ": "; try { serialHandler_.reset(0); serialHandler_.reset( new SerialHandler( config_.device, tracer, status ) ); initLaser(); break; } catch ( const RxMsgIsErrorException &e ) { std::string errorLog = errorConditions(); stringstream ss; ss << e.what() << endl << "Laser error log: " << errorLog; if ( i == MAX_TRIES-1 ) throw RxMsgIsErrorException( ss.str() ); else tracer_.warning( tryString.str() + ss.str() ); } catch ( const std::exception &e ) { stringstream ss; ss << "during initLaser(): " << e.what(); tracer_.warning( tryString.str() + ss.str() ); if ( i == MAX_TRIES-1 ) throw; } } } bool Driver::waitForRxMsgType( uChar type, TimedLmsRxMsg &rxMsg, int maxWaitMs ) { gbxiceutilacfr::Timer waitTimer; while ( true ) { int ret = serialHandler_->getNextRxMsg( rxMsg, maxWaitMs ); if ( ret == 0 ) { // got rxMsg if ( rxMsg.msg->type == type ) return true; // Got a rxMsg, but not of the type we were expecting... // // In general, print out a warning message. // However, don't print out a warning if it's an ACK/NACK, because ACK/NACK don't // have checksums so they're likely to be found inside a failed-checksum message when a bit // gets flipped during transmission. if ( rxMsg.msg->type != ACK && rxMsg.msg->type != NACK ) { stringstream ss; ss << "Driver::waitForRxMsgType(): While waiting for " << cmdToString(type) << ", received unexpected rxMsg: " << toString(*(rxMsg.msg)); tracer_.warning( ss.str() ); } if ( waitTimer.elapsedMs() > maxWaitMs ) { // waited too long return false; } } else if ( ret == -1 ) { // timed out on buffer return false; } else { stringstream ss; ss << "Weird return code from getAndPopNext: " << ret; throw gbxutilacfr::Exception( ERROR_INFO, ss.str() ); } } } bool Driver::waitForAckOrNack( bool &receivedAck ) { const int maxWaitMs = 1000; gbxiceutilacfr::Timer waitTimer; while ( true ) { TimedLmsRxMsg timedRxMsg; int ret = serialHandler_->getNextRxMsg( timedRxMsg, maxWaitMs ); if ( ret == 0 ) { // got timedRxMsg if ( timedRxMsg.msg->type == ACK || timedRxMsg.msg->type == NACK ) { receivedAck = (timedRxMsg.msg->type == ACK); return true; } else { stringstream ss; ss << "Driver::waitForAckOrNack(): Received unexpected rxMsg: " << toString(*(timedRxMsg.msg)); tracer_.warning( ss.str() ); } double waitTimeSec = waitTimer.elapsedSec(); if ( waitTimeSec > maxWaitMs/1000.0 ) { return false; } } else if ( ret == -1 ) { tracer_.debug( "Driver: waitForAckOrNack(): timed out.", 3 ); return false; } else { stringstream ss; ss << "Weird return code from serialHandler_->getNextRxMsg: " << ret; throw gbxutilacfr::Exception( ERROR_INFO, ss.str() ); } } } LmsRxMsgPtr Driver::askLaserForStatusData() { constructStatusRequest( commandAndData_ ); TimedLmsRxMsg rxMsg = sendAndExpectRxMsg( commandAndData_ ); return rxMsg.msg; } LmsRxMsgPtr Driver::askLaserForConfigData() { constructConfigurationRequest( commandAndData_ ); try { TimedLmsRxMsg rxMsg = sendAndExpectRxMsg( commandAndData_ ); return rxMsg.msg; } catch ( NoRxMsgException &e ) { stringstream ss; ss << "While trying to askLaserForConfigData(): " << e.what(); throw NoRxMsgException( ss.str() ); } } uChar Driver::desiredMeasuredValueUnit() { if ( (int)(round(config_.maxRange)) == 80 ) { return MEASURED_VALUE_UNIT_CM; } else if ( (int)(round(config_.maxRange)) == 8 ) { return MEASURED_VALUE_UNIT_MM; } else { stringstream ss; ss << "Unknown linear resolution: " << config_.maxRange; throw gbxutilacfr::Exception( ERROR_INFO, ss.str() ); } } uint16_t Driver::desiredAngularResolution() { double angleIncrement = config_.fieldOfView / (config_.numberOfSamples-1); int angleIncrementInHundredthDegrees = (int)round(100.0 * angleIncrement*180.0/M_PI); assert( angleIncrementInHundredthDegrees == ANGULAR_RESOLUTION_1_0_DEG || angleIncrementInHundredthDegrees == ANGULAR_RESOLUTION_0_5_DEG || angleIncrementInHundredthDegrees == ANGULAR_RESOLUTION_0_25_DEG ); return (uint16_t)angleIncrementInHundredthDegrees; } bool Driver::isAsDesired( const LmsConfigurationData &lmsConfig ) { // This thing has a default constructor which will fill out most things return ( lmsConfig == desiredConfiguration() ); } LmsConfigurationData Driver::desiredConfiguration() { // Default constructor sets up reasonable defaults which we then modify LmsConfigurationData c; c.measuringMode = MEASURING_MODE_8m80m_REFLECTOR8LEVELS; c.measuredValueUnit = desiredMeasuredValueUnit(); // AlexB: It's not entirely clear, but from reading the SICK manual // it looks like perhaps setting availability to 0x01 may // help with dazzle (ie sunlight interfering with the laser). // I haven't had a chance to test it though, so I'm not game // to set it. cout<<"TRACE(driver.cpp): TODO: set availability?" << endl; // c.availability = 0x01; return c; } std::string Driver::errorConditions() { try { tracer_.debug( "Driver: Checking error conditions." ); constructRequestErrorMessage( commandAndData_ ); const bool ignoreErrorConditions = true; TimedLmsRxMsg errorRxMsg = sendAndExpectRxMsg( commandAndData_, ignoreErrorConditions ); return toString( *(errorRxMsg.msg) ); } catch ( std::exception &e ) { stringstream ss; ss << "Driver: Caught exception while getting error conditions: " << e.what(); tracer_.debug( ss.str() ); throw; } } void Driver::setBaudRate( int baudRate ) { // Tell the laser to switch constructRequestBaudRate( commandAndData_, baudRate ); sendAndExpectRxMsg( commandAndData_ ); // And switch myself serialHandler_->setBaudRate( config_.baudRate ); } int Driver::guessLaserBaudRate() { // Guess our current configuration first: maybe the laser driver was re-started. std::vector<int> baudRates; baudRates.push_back( config_.baudRate ); if ( config_.baudRate != 9600 ) baudRates.push_back( 9600 ); if ( config_.baudRate != 19200 ) baudRates.push_back( 19200 ); if ( config_.baudRate != 38400 ) baudRates.push_back( 38400 ); if ( config_.baudRate != 500000 ) baudRates.push_back( 500000 ); for ( size_t baudRateI=0; baudRateI < baudRates.size(); baudRateI++ ) { stringstream ss; ss << "Driver: Trying to connect at " << baudRates[baudRateI] << " baud."; tracer_.info( ss.str() ); // Switch my local serial port serialHandler_->setBaudRate( baudRates[baudRateI] ); try { stringstream ss; ss <<"Driver: Trying to get laser status with baudrate " << baudRates[baudRateI]; tracer_.debug( ss.str() ); askLaserForStatusData(); return baudRates[baudRateI]; } catch ( const NoRxMsgException &e ) { stringstream ss; ss << "Driver::guessLaserBaudRate(): failed: " << e.what(); tracer_.debug( ss.str() ); } } // end loop over baud rates throw gbxutilacfr::Exception( ERROR_INFO, "Is the laser connected and powered on? Failed to detect laser baud rate." ); } void Driver::initLaser() { int currentBaudRate = guessLaserBaudRate(); tracer_.debug( "Driver: Guessed the baud rate!" ); // // Turn continuous mode off // tracer_.debug("Driver: Turning continuous mode off"); constructRequestMeasuredOnRequestMode( commandAndData_ ); sendAndExpectRxMsg( commandAndData_ ); // // Set Desired BaudRate // tracer_.debug("Driver: Telling the laser to switch to the desired baud rate"); if ( currentBaudRate != config_.baudRate ) { setBaudRate( config_.baudRate ); } // Gather info about the SICK stringstream ssInfo; ssInfo << "Laser info prior to initialisation:" << endl; // // Make note of error log // ssInfo << errorConditions() << endl; // // Check operating data counters // tracer_.debug("Driver: Checking operating data counters"); constructRequestOperatingDataCounter( commandAndData_ ); TimedLmsRxMsg counterRxMsg = sendAndExpectRxMsg( commandAndData_ ); ssInfo << "OperatingDataCounter: " << toString(counterRxMsg.msg) << endl; // // Get status // tracer_.debug("Driver: Checking status"); LmsRxMsgPtr statusRxMsg = askLaserForStatusData(); LmsStatusRxMsgData *statusRxMsgData = dynamic_cast<LmsStatusRxMsgData*>(statusRxMsg->data.get()); assert( statusRxMsgData != NULL ); ssInfo << "Status: " << statusRxMsgData->toString() << endl; LmsRxMsgPtr configRxMsg = askLaserForConfigData(); LmsConfigurationData *lmsConfig = dynamic_cast<LmsConfigurationData*>(configRxMsg->data.get()); assert( lmsConfig != NULL ); ssInfo << "Config: " << configRxMsg->data->toString() << endl; tracer_.info( ssInfo.str() ); // // Enter installation mode // constructRequestInstallationMode( commandAndData_ ); sendAndExpectRxMsg( commandAndData_ ); // // Configure the thing if we have to // if ( !isAsDesired( *lmsConfig ) ) { tracer_.info( "Driver: Have to reconfigure the laser..." ); constructConfigurationCommand( desiredConfiguration(), commandAndData_ ); TimedLmsRxMsg configCmdRxMsg = sendAndExpectRxMsg( commandAndData_ ); LmsConfigurationRxMsgData *configCmdRxMsgData = dynamic_cast<LmsConfigurationRxMsgData*>(configCmdRxMsg.msg->data.get()); if ( !isAsDesired( configCmdRxMsgData->config ) ) { stringstream ss; ss << "Error configuring SICK: Config after configuration not what we expect. Asked for: " << desiredConfiguration().toString() << endl << "got: " << configCmdRxMsgData->toString(); throw gbxutilacfr::Exception( ERROR_INFO, ss.str() ); } } // // Configure the angular resolution // const uint16_t desiredScanningAngle = 180; constructSwitchVariant( desiredScanningAngle, desiredAngularResolution(), commandAndData_ ); TimedLmsRxMsg angRxMsg = sendAndExpectRxMsg( commandAndData_ ); LmsSwitchVariantRxMsgData *angRxMsgData = dynamic_cast<LmsSwitchVariantRxMsgData*>(angRxMsg.msg->data.get()); assert( angRxMsgData != NULL ); if ( !( angRxMsgData->scanningAngle == desiredScanningAngle && angRxMsgData->angularResolution == desiredAngularResolution() ) ) { stringstream ss; ss << "Error configuring SICK variant: Variant after configuration not what we expect: " << angRxMsgData->toString(); throw gbxutilacfr::Exception( ERROR_INFO, ss.str() ); } // // Start continuous mode // constructRequestContinuousMode( commandAndData_ ); TimedLmsRxMsg contRxMsg = sendAndExpectRxMsg( commandAndData_ ); tracer_.info( "Driver: enabled continuous mode, laser is running." ); } TimedLmsRxMsg Driver::sendAndExpectRxMsg( const std::vector<uChar> &commandAndData, bool ignoreErrorConditions ) { constructTelegram( telegramBuffer_, commandAndData ); assert( commandAndData.size()>0 && "constructTelegram should give telegram with non-zero size." ); const uChar command = commandAndData[0]; stringstream ss; ss << "Driver: requesting send "<<cmdToString(command)<<endl<<" telegram: " << toHexString(telegramBuffer_); tracer_.debug( ss.str(), 3 ); serialHandler_->send( telegramBuffer_ ); bool isAck; bool receivedAckOrNack = waitForAckOrNack( isAck ); if ( !receivedAckOrNack ) { throw NoRxMsgException( "No ACK/NACK to command "+cmdToString(command) ); } if ( !isAck ) { throw NackReceivedException( "Received NACK for command "+cmdToString(command) ); } int timeoutMs = 1000; if ( command == CMD_CONFIGURE_LMS ) { // This takes a long time to complete timeoutMs = 15000; } TimedLmsRxMsg rxMsg; bool received = waitForRxMsgType( ack(command), rxMsg, timeoutMs ); if ( !received ) { throw NoRxMsgException( "No rxMsg to command "+cmdToString(command) ); } if ( !ignoreErrorConditions && rxMsg.msg->isError() ) { throw RxMsgIsErrorException( "RxMsg contains an error condition: "+toString(rxMsg.msg) ); } if ( rxMsg.msg->isWarn() ) { stringstream ss; tracer_.warning( "RxMsg contains warning: "+toString(rxMsg.msg) ); } return rxMsg; } void Driver::read( Data &data ) { TimedLmsRxMsg rxMsg; // This timeout is greater than the scan inter-arrival time for all baudrates. const int timeoutMs = 1000; bool received = waitForRxMsgType( ACK_REQUEST_MEASURED_VALUES, rxMsg, timeoutMs ); if ( !received ) { throw gbxutilacfr::Exception( ERROR_INFO, "No scan received." ); } LmsMeasurementData *measuredData = (LmsMeasurementData*)rxMsg.msg->data.get(); if ( rxMsg.msg->isError() ) { std::string errorLog = errorConditions(); stringstream ss; ss << "Scan data indicates errors: " << toString(rxMsg.msg) << endl << "Laser error log: " << errorLog; throw RxMsgIsErrorException( ss.str() ); } else if ( rxMsg.msg->isWarn() ) { data.haveWarnings = true; stringstream ss; ss << "Scan data indicates warnings: " << toString(rxMsg.msg); data.warnings = ss.str(); } memcpy( &(data.ranges[0]), &(measuredData->ranges[0]), measuredData->ranges.size()*sizeof(float) ); memcpy( &(data.intensities[0]), &(measuredData->intensities[0]), measuredData->intensities.size()*sizeof(unsigned char) ); data.timeStampSec = rxMsg.timeStampSec; data.timeStampUsec = rxMsg.timeStampUsec; } } // namespace
function me() { return "Hola, soy 👨‍💻"; } // Pueden ser usadas como argumentos de función const greet = (fn) => console.log(fn()); greet(me); // 2. Pueden ser devueltas function makeGreeter() { return me; // ^ Estamos devolviendo una función! } // Podemos asignar el resultado a una variable y luego llamarlo, porque es una función const greeter = makeGreeter(); greeter(); // Podemos ejecutarlo directamente makeGreeter()(); // 3. Pueden ser asignadas como variables const Person = { greet: me, }; Person.greet();
require 'rails_helper' describe 'Usuário edita um pedido' do it 'e não é o dono' do # Arrange gabriel = User.create!(name: 'Gabriel', email: 'gabriel@gmail.com', password: 'password') joao = User.create!(name: 'João', email: 'joao@gmail.com', password: 'password') warehouse = Warehouse.create!(name: 'Guarulhos Aeroporto', code: 'GRU', city: 'Guarulhos', area:60_000, address: 'Rua do aeroporto, 3102', cep: '31412', description: 'Galpão localizado no aeroporto de Guarulhos' ) supplier = Supplier.create!(corporate_name: 'Razer Eletronics', brand_name: 'Razer', registration_number: '131341', full_address: 'Wall Street, 341', city: 'New York', state: 'NY', email: 'razer@gmail.com') supplier_2 = Supplier.create!(corporate_name: "Logitech LTDA", brand_name: "Logitech", registration_number: '43132531', full_address: "Av Brasil, 1231", city: "São Paulo", state: "SP", email: "logi@tech.com" ) supplier_3 = Supplier.create!(corporate_name: "Red Dragon Eletronics", brand_name: "RedDragon", registration_number: '03132531', full_address: "China Town, 1231", city: "Nova Iorque", state: "NY", email: "red@dragon.com" ) order = Order.create!(user: gabriel, warehouse: warehouse, supplier: supplier, estimated_delivery_date: Date.tomorrow) # Act login_as(joao) patch(order_path(order), params:{ order: {supplier_Id: 3} }) # Assert expect(response).to redirect_to(root_path) end end
import { ActivityType, ButtonBuilder, ButtonStyle, Client, REST, Routes, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, } from 'discord.js'; import {schedule} from 'node-cron'; import {commandHash, commandList, presenceCmds, wikiCmd} from '../commands'; import {config} from '../config'; import {getData, mappedNames} from '../api-wrapper'; import { compareData, dbData, loadWikiFiles, logger, updateMessages, } from '../handlers'; // bot client token, for use with discord API const BOT_TOKEN = config.BOT_TOKEN; const PERSISTENT_MESSAGE_INTERVAL = config.PERSISTENT_MESSAGE_INTERVAL; const API_UPDATE_INTERVAL = config.API_UPDATE_INTERVAL; const STATUS_UPDATE_INTERVAL = config.STATUS_UPDATE_INTERVAL; const DB_DATA_INTERVAL = config.DB_DATA_INTERVAL; const COMPARE_INTERVAL = config.COMPARE_INTERVAL; const VERSION = config.VERSION; const onReady = async (client: Client) => { if (!client.user) throw Error('Client not initialised'); const clientId = client.user.id; const serverCount = (await client.guilds.fetch()).size; const rest = new REST().setToken(BOT_TOKEN); logger.info( `[v${VERSION}] Serving ${serverCount} servers as ${client.user?.tag}`, { type: 'startup', } ); // two non-constant value for timing functions let start = Date.now(); let time = ''; // register commands as global discord slash commands const commandData = commandList.map(command => command.data.toJSON()); await rest.put(Routes.applicationCommands(clientId), { body: commandData, }); logger.info(`Commands loaded: ${Object.keys(commandHash).join(', ')}`, { type: 'startup', }); time = `${Date.now() - start}ms`; logger.info(`Loaded ${commandData.length} commands in ${time}`, { type: 'startup', }); start = Date.now(); // get api data on startup await getData().then(data => { mappedNames.planets = data.Planets.map(x => x.name); mappedNames.campaignPlanets = data.Campaigns.map(x => x.planetName); }); // retrieve encounters and load them as autocomplete suggestions time = `${Date.now() - start}ms`; logger.info(`Loaded ${mappedNames.planets.length} planets in ${time}`, { type: 'startup', }); // load wiki pages const wiki = loadWikiFiles('./wiki'); wikiCmd.buttons = wiki.categories.map(c => { const {directory, display_name, content, emoji, thumbnail, image} = c; const button = new ButtonBuilder() .setCustomId(directory) .setLabel(display_name) .setStyle(ButtonStyle.Secondary); if (emoji) button.setEmoji(emoji); return button; }); wikiCmd.dirSelect = wiki.categories.reduce( (acc, c) => { acc[c.directory] = new StringSelectMenuBuilder() .setCustomId(c.directory) .setPlaceholder('Select a page from this category...') .addOptions( wiki.pages .filter(page => page.page.startsWith(c.directory)) .map(page => { const option = new StringSelectMenuOptionBuilder() .setLabel(page.title) .setValue(page.page); if (page.description) option.setDescription(page.description); if (page.emoji) option.setEmoji(page.emoji); return option; }) ); return acc; }, {} as Record<string, StringSelectMenuBuilder> ); wikiCmd.pages = wiki.pages; wikiCmd.categories = wiki.categories; time = `${Date.now() - start}ms`; logger.info(`Loaded ${wiki.pages.length} wiki pages in ${time}`, { type: 'startup', }); // cron schedule to update messages schedule(PERSISTENT_MESSAGE_INTERVAL, () => updateMessages()); // cron schedule to insert new api data into db schedule(DB_DATA_INTERVAL, () => dbData()); // cron schedule to update api data every 10 seconds schedule(API_UPDATE_INTERVAL, () => { getData().then(data => { mappedNames.planets = data.Planets.map(x => x.name); mappedNames.campaignPlanets = data.Campaigns.map(x => x.planetName); }); }); // cron schedule to compare api data schedule(COMPARE_INTERVAL, () => compareData()); // cron schedule to update presence every 3 seconds schedule(STATUS_UPDATE_INTERVAL, () => { if (client.user) { if (client.user.presence.activities[0]) { const prev = client.user.presence.activities[0].name; client.user.setActivity(presenceCmds.shift() as string, { type: ActivityType.Listening, }); presenceCmds.push(prev); } else client.user.setActivity(presenceCmds.shift() as string, { type: ActivityType.Listening, }); } }); }; export {onReady};
// Copyright 2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // PopupManager is a library to facilitate integration with OpenID // // [Note: that was OpenID 1.0, now (year 2020) since long gone, // but the open-popup code here, still works fine. /KajMagnus] // // identity providers (OP)s that support a pop-up authentication interface. // To create a popup window, you first construct a popupOpener customized // for your site and a particular identity provider, E.g.: // // var googleOpener = popupManager.createOpener(openidParams); // // where 'openidParams' are customized for Google in this instance. // (typically you just change the openidpoint, the version number // (the openid.ns parameter) and the extensions based on what // the OP supports. // OpenID libraries can often discover these properties // automatically from the location of an XRD document. // // Then, you can either directly call // googleOpener.popup(width, height), where 'width' and 'height' are your choices // for popup size, or you can display a button 'Sign in with Google' and set the //..'onclick' handler of the button to googleOpener.popup() var popupManager = {}; // Library constants // COULD_OPTIMIZE SMALLER_BUNDLE remove more unneeded stuff /kajmagnus popupManager.constants = { 'darkCover' : 'popupManager_darkCover_div', 'darkCoverStyle' : ['position:absolute;', 'top:0px;', 'left:0px;', 'padding-right:0px;', 'padding-bottom:0px;', 'background-color:#000000;', 'opacity:0.5;', //standard-compliant browsers // SMALLER_BUNDLE DO_AFTER 2021-01 remove this backw compat stuff? // Was probably IE 7 or 8 or sth like that. '-moz-opacity:0.5;', // old Mozilla 'filter:alpha(opacity=0.5);', // IE 'z-index:10000;', 'width:100%;', 'height:100%;' ].join('') }; // Computes the size of the window contents. Returns a pair of // coordinates [width, height] which can be [0, 0] if it was not possible // to compute the values. popupManager.getWindowInnerSize = function() { var width = 0; var height = 0; var elem = null; if ('innerWidth' in window) { // For non-IE width = window.innerWidth; height = window.innerHeight; } else { // For IE, // SMALLER_BUNDLE DO_AFTER 2021-01 remove this? Was probably IE 7 or 8 or sth like that. if (('BackCompat' === window.document.compatMode) && ('body' in window.document)) { elem = window.document.body; } else if ('documentElement' in window.document) { elem = window.document.documentElement; } if (elem !== null) { width = elem.offsetWidth; height = elem.offsetHeight; } } return [width, height]; }; // Computes the coordinates of the parent window. // Gets the coordinates of the parent frame popupManager.getParentCoords = function() { var width = 0; var height = 0; if ('screenLeft' in window) { // IE-compatible variants // SMALLER_BUNDLE DO_AFTER 2021-01 remove this? Was probably IE 7 or 8 or sth like that. width = window.screenLeft; height = window.screenTop; } else if ('screenX' in window) { // Firefox-compatible width = window.screenX; height = window.screenY; } return [width, height]; }; // Computes the coordinates of the new window, so as to center it // over the parent frame popupManager.getCenteredCoords = function(width, height) { var parentSize = this.getWindowInnerSize(); var parentPos = this.getParentCoords(); var xPos = parentPos[0] + Math.max(0, Math.floor((parentSize[0] - width) / 2)); var yPos = parentPos[1] + Math.max(0, Math.floor((parentSize[1] - height) / 2)); return [xPos, yPos]; }; // A utility class, implements an onOpenHandler that darkens the screen // by overlaying it with a semi-transparent black layer. To use, ensure that // no screen element has a z-index at or above 10000. // This layer will be suppressed automatically after the screen closes. // // Note: If you want to perform other operations before opening the popup, but // also would like the screen to darken, you can define a custom handler // as such: // var myOnOpenHandler = function(inputs) { // .. do something // popupManager.darkenScreen(); // .. something else // }; // Then you pass myOnOpenHandler as input to the opener, as in: // var openidParams = {}; // openidParams.onOpenHandler = myOnOpenHandler; // ... other customizations // var myOpener = popupManager.createOpener(openidParams); popupManager.darkenScreen = function() { var darkCover = window.document.getElementById(window.popupManager.constants['darkCover']); if (!darkCover) { darkCover = window.document.createElement('div'); darkCover['id'] = window.popupManager.constants['darkCover']; darkCover.setAttribute('style', window.popupManager.constants['darkCoverStyle']); window.document.body.appendChild(darkCover); } darkCover.style.visibility = 'visible'; };
<template> <div> <button @click="isShow = !isShow">显示/隐藏</button> <!-- 如果transition指定了name属性,那么样式内的动画名字需要修改为:(name)-leave-active --> <!-- 添加一个appear属性,可以使得进入页面时就具有动画效果 --> <transition> <h1 v-show="isShow">你好</h1> </transition> </div> </template> <script> export default { name: "Test", data() { return { isShow: true, }; }, }; </script> <style scoped> h1 { background-color: orange; } .v-enter-active { animation: trans 1s; } .v-leave-active { animation: trans 1s reverse; } @keyframes trans { from { transform: translateX(-100%); } to { transform: translateX(0px); } } </style>
#pragma once #include "Parsing/IParserValue.h" #include "Parsing/TokenPos.h" #include "Utils/ClassUtils.h" #include <string> enum class SimpleParserValueType { // Meta tokens INVALID, END_OF_FILE, NEW_LINE, // Character sequences CHARACTER, MULTI_CHARACTER, // Generic token types INTEGER, FLOATING_POINT, STRING, IDENTIFIER, // End MAX }; class SimpleParserValue final : public IParserValue { public: TokenPos m_pos; SimpleParserValueType m_type; size_t m_hash; bool m_has_sign_prefix; union ValueType { char char_value; int int_value; int multi_character_sequence_id; double double_value; std::string* string_value; } m_value; static SimpleParserValue Invalid(TokenPos pos); static SimpleParserValue EndOfFile(TokenPos pos); static SimpleParserValue NewLine(TokenPos pos); static SimpleParserValue Character(TokenPos pos, char c); static SimpleParserValue MultiCharacter(TokenPos pos, int multiCharacterSequenceId); static SimpleParserValue Integer(TokenPos pos, int value); static SimpleParserValue Integer(TokenPos pos, int value, bool hasSignPrefix); static SimpleParserValue FloatingPoint(TokenPos pos, double value); static SimpleParserValue FloatingPoint(TokenPos pos, double value, bool hasSignPrefix); static SimpleParserValue String(TokenPos pos, std::string* stringValue); static SimpleParserValue Identifier(TokenPos pos, std::string* identifier); private: SimpleParserValue(TokenPos pos, SimpleParserValueType type); public: ~SimpleParserValue() override; SimpleParserValue(const SimpleParserValue& other) = delete; SimpleParserValue(SimpleParserValue&& other) noexcept; SimpleParserValue& operator=(const SimpleParserValue& other) = delete; SimpleParserValue& operator=(SimpleParserValue&& other) noexcept; _NODISCARD bool IsEof() const override; _NODISCARD const TokenPos& GetPos() const override; _NODISCARD char CharacterValue() const; _NODISCARD int MultiCharacterValue() const; _NODISCARD int IntegerValue() const; _NODISCARD double FloatingPointValue() const; _NODISCARD std::string& StringValue() const; _NODISCARD std::string& IdentifierValue() const; _NODISCARD size_t IdentifierHash() const; };
<?php namespace Plugins\PageBuilder\Addons\Tenants\Common; use App\Helpers\LanguageHelper; use App\Helpers\SanitizeInput; use Plugins\PageBuilder\Fields\Image; use Plugins\PageBuilder\Fields\Repeater; use Plugins\PageBuilder\Fields\Select; use Plugins\PageBuilder\Fields\Text; use Plugins\PageBuilder\Helpers\RepeaterField; use Plugins\PageBuilder\PageBuilderBase; use function __; class KeyFeatureStyleTwo extends PageBuilderBase { public function preview_image() { return 'Tenant/common/key-feature-02.png'; } public function admin_render() { $output = $this->admin_form_before(); $output .= $this->admin_form_start(); $output .= $this->default_fields(); $widget_saved_values = $this->get_settings(); $output .= $this->admin_language_tab(); //have to start language tab from here on $output .= $this->admin_language_tab_start(); $all_languages = LanguageHelper::all_languages(); foreach ($all_languages as $key => $lang) { $output .= $this->admin_language_tab_content_start([ 'class' => $key == 0 ? 'tab-pane fade show active' : 'tab-pane fade', 'id' => "nav-home-" . $lang->slug ]); $output .= Text::get([ 'name' => 'title_'.$lang->slug, 'label' => __('Title'), 'value' => $widget_saved_values['title_'.$lang->slug] ?? null, ]); $output .= $this->admin_language_tab_content_end(); } $output .= $this->admin_language_tab_end(); //have to end language tab $output .= Image::get([ 'name' => 'bg_image', 'label' => __('Background Image'), 'value' => $widget_saved_values['bg_image'] ?? null, ]); //repeater $output .= Repeater::get([ 'multi_lang' => true, 'settings' => $widget_saved_values, 'id' => 'key_feature_one', 'fields' => [ [ 'type' => RepeaterField::TEXT, 'name' => 'repeater_title', 'label' => __('Title') ], [ 'type' => RepeaterField::TEXT, 'name' => 'repeater_number', 'label' => __('Number') ], ] ]); // add padding option $output .= $this->padding_fields($widget_saved_values); $output .= $this->admin_form_submit_button(); $output .= $this->admin_form_end(); $output .= $this->admin_form_after(); return $output; } public function frontend_render() { $user_lang = LanguageHelper::default_slug(); $padding_top = SanitizeInput::esc_html($this->setting_item('padding_top')); $padding_bottom = SanitizeInput::esc_html($this->setting_item('padding_bottom')); $title = $this->setting_item('title_'.$user_lang); $bg_image = $this->setting_item('bg_image'); $repeater_data = $this->setting_item('key_feature_one'); $data = [ 'padding_top'=> $padding_top, 'padding_bottom'=> $padding_bottom, 'repeater_data'=> $repeater_data, 'title'=> $title, 'bg_image'=> $bg_image, ]; return self::renderView('tenant.common.key-feature-two',$data); } public function enable(): bool { return !is_null(tenant()); } public function addon_title() { return __('Key Feature (02)'); } }
<div class="private-form-wrapper"> <!-- <div class="sign-card"> --> <h2 class="detail-form-title">Activity Update Form</h2> <form class="item-create" [formGroup]="form" (ngSubmit)="onSubmit()"> <div class="form-row-one-item-start"> <div class="activityTitle"> <label for="activityTitle">Activity title: *</label> <input class="activity-create" type="text" placeholder="activity title" id="activityTitle" formControlName="activityTitle" required> <div *ngIf="f.activityTitle.invalid && (f.activityTitle.dirty || f.activityTitle.touched)" class="activity-input-error"> activity title cannot be empty </div> </div> </div> <div class="form-row-one-item-start"> <div> <label for="activityDescription">Activity description:</label> <textarea placeholder="activity description" id="activityDescription" formControlName="activityDescription"></textarea> </div> </div> <div class="form-row-more-items-center"> <div> <label for="activityStatus">Status: *</label> <select id="activityStatus" formControlName="activityStatus"> <option *ngFor="let item of activityStatusEnum" value="{{item}}">{{item}}</option> </select> </div> <div> <label for="activityPriority">Priority: *</label> <select id="activityPriority" formControlName="activityPriority"> <option *ngFor="let item of activityPriorityEnum" value="{{item}}">{{item}}</option> </select> </div> <div> <label for="activityCategory">Category:</label> <input type="text" placeholder="activity category" id="activityCategory" formControlName="activityCategory"> </div> </div> <div class="form-row-more-items-center"> <div> <label for="activityStartDate">Start date: *</label> <input type="date" placeholder="start date" id="activityStartDate" formControlName="activityStartDate" required> </div> <div> <label for="activityStartTime">Start time:</label> <input type="time" placeholder="start time" id="activityStartTime" formControlName="activityStartTime"> </div> <div> <label for="activityLengthTotal">Length total [hh:min]:</label> <input type="time" placeholder="length total" id="activityLengthTotal" formControlName="activityLengthTotal"> </div> <div> <label for="activityLengthAction">Length action [hh:min]:</label> <input type="time" placeholder="length action" id="activityLengthAction" formControlName="activityLengthAction"> </div> <div> <label for="activityAveragePace">Average pace [min:ss]:</label> <input type="time" placeholder="[min:sec]" id="activityAveragePace" formControlName="activityAveragePace"> <!-- : --> <!-- <input type="number" placeholder="[sec]" id="activityAveragePaceSec" min="0" max="59" formControlName="activityAveragePaceSec"> --> </div> </div> <div class="form-row-more-items-center"> <div> <label for="activityPlace">Place:</label> <input type="text" placeholder="place" id="activityPlace" formControlName="activityPlace"> </div> <div> <label for="activityShoes">Shoes:</label> <input type="text" placeholder="shoes" id="activityShoes" formControlName="activityShoes"> </div> <div> <label for="activitySources">Sources:</label> <input type="text" placeholder="sources" id="activitySources" formControlName="activitySources"> </div> </div> <div class="form-row-one-item-start"> <div> <label for="activityNote">Note:</label> <textarea placeholder="activity note" id="activityNote" formControlName="activityNote"></textarea> </div> </div> <div class="form-row-button"> <button class="update-ok" type="submit" [disabled]="!form.valid">Update</button> <button class="private-cancel" type="button" (click)="backToList()">Cancel</button> </div> </form> </div>
import { useState } from "react"; const Checkbox = ({ label, storageKey }) => { const [checked, setChecked] = useState( localStorage.getItem(storageKey) === "true" ); const handleChange = () => { // setChecked(!checked); // localStorage.setItem(storageKey, !checked); // localStorage.setItem("SplashScreen", "disabled"); const newValue = !checked; setChecked(newValue); localStorage.setItem(storageKey, newValue); if (newValue) { localStorage.setItem("SplashScreen", "disabled"); } else { localStorage.removeItem("SplashScreen"); } }; return ( <div className="checkbox"> <style> {` .checkbox { position: absolute; z-index: 10; right: 32px; bottom: 22px; display: flex; justify-content: center; align-items: center; } `} </style> <input type="checkbox" checked={checked} onChange={handleChange} /> <label>{label}</label> </div> ); }; export default Checkbox;
<doctype html> <html> <head> <meta charset='utf-8'> </head> <body> Markdown: <br> <textarea id='e_in' style='width: 100%; height: 50vh;'> &lt;!-- Output copied to clipboard! --&gt; # WGSL 2021-00-00 Minutes ### Example 1 * lorem ## H2 ### [Example 2](example.com) * ipsum ### Example [5](example.com/5) (stuff) * dolor ## H2 Example [3](example.com/3) * sit amet </textarea> <br>Override URL: <input type=url id=e_link_url style='width: 50%'></input> <br>Override Title: <input type=text id=e_link_title style='width: 50%'></input> <br><button id='e_extract'>Extract</button> <hr> <div id='e_out'></div> <script> 'use strict'; function count_char_repeats(str, c) { let i = 0; while (str[i] == c) { i += 1; } return i; } { if (count_char_repeats('### hi', '#') != 3) throw 3; } function MdSection(title) { this.title = title; this.h_level = count_char_repeats(title || '', '#'); this.children = []; this.add_child = child => { child.parent = this; this.children.push(child); }; } function md_to_tree(text) { const lines = text.split('\n'); const root = new MdSection(null); let cur_sec = root; while (lines.length) { const line = lines.shift(); const h_level = count_char_repeats(line, '#'); if (!h_level) { cur_sec.children.push(line); continue; } const new_sec = new MdSection(line); const parent_h_level = new_sec.h_level - 1; while (cur_sec.h_level > parent_h_level) { cur_sec = cur_sec.parent; } //while (cur_sec.h_level < parent_h_level) { // const dummy = new MdSection('#'.repeat(cur_sec.h_level + 1)); // dummy.title = undefined; // cur_sec.add_child(dummy); // cur_sec = dummy; //} cur_sec.add_child(new_sec); cur_sec = new_sec; } return root; } function* range(n) { for (let i = 0; i < n; i++) { yield i; } } function trimPrefix(str, prefix) { if (str.startsWith(prefix)) { str = str.slice(prefix.length); } return str; } function withoutPrefix(str, prefix) { const ret = trimPrefix(str, prefix); if (ret == str) throw {str, prefix}; return ret; } const RE_DATE = /\d\d\d\d-\d\d-\d\d/; function find_date(str) { const match = str.match(RE_DATE) || []; return match; } if (find_date('# WGSL 2021-04-13 Minutes') != '2021-04-13') throw 'find_date'; function to_github_general_url_slug(text) { let parts = text.split(/ +/); parts = parts.map(s => { s = s.toLowerCase(); s = [].filter.call(s, c => c.match(/[0-9A-Za-z-_()\/]/)); // Filter character set. s = s.join(''); return s; }); return parts.join('-'); } function to_github_page_slug(text) { let ret = to_github_general_url_slug(text); ret = ret.replaceAll(/[()\/]/g, '-'); return ret; } function to_github_anchor_slug(text) { let ret = to_github_general_url_slug(text); ret = ret.replaceAll(/[()\/]/g, ''); return ret; } { const title = '[wgsl] Proposal: Remove pointer out parameters from modf, frexp · Issue #1480 · gpuweb/gpuweb'; const expected = 'wgsl-proposal-remove-pointer-out-parameters-from-modf-frexp--issue-1480--gpuwebgpuweb'; const was = to_github_anchor_slug(title); if (was != expected) throw was; } { const title = 'Triage the issues without milestones (timebox 15m).'; const expected = 'triage-the-issues-without-milestones-timebox-15m'; const was = to_github_anchor_slug(title); if (was != expected) throw was; } { const title = 'GPU Web meeting 2022-08-02/03 APAC-timed'; const expected = 'gpu-web-meeting-2022-08-02-03-apac-timed'; const was = to_github_page_slug(title); if (was != expected) throw was; } const RE_URL = /\[(.*)\]\((.*?)\)/g; function section_desc(node) { let issue_url; let slug; if (node.title) { if (!node.title.startsWith('#')) throw node.title; const section_title = node.title.replace(/#+ /, ''); const found = Array.from(section_title.matchAll(RE_URL)); issue_url = (found[0] || [])[2]; const title_text = section_title.replaceAll(RE_URL, '$1'); slug = to_github_anchor_slug(title_text); } // - // A section's `children` contain, zero or more string children, followed // by zero or more subsection children. let content = []; let subsections = []; for (const child of node.children) { if (child.h_level) { // section subsections.push(child); } else { if (subsections.length) throw node; content.push(child); } } content = content.join('\n'); content = content.replace(/^\n+/, ''); content = content.replace(/\n+$/, ''); // - const ret = { issue_url, slug, content, subsections, }; if (!ret.content) delete ret.content; if (!ret.subsections.length) delete ret.subsections; return ret; } // - // Tests { const content = `\ * DM: Do we want to spend innovation budget on anonymous structs here? * BC: Previously there were concerns about having to have a named struct to return here, but now with type inference, we could return anonymous structs here. Not necessarily proposing userland anonymous structs, and if we decided to name them in the future, we could name them. * DM: Some complexity, new types for these builtins.`; const h3_section = { title: '### [[wgsl] Proposal: Remove pointer out parameters from modf, frexp · Issue #1480 · gpuweb/gpuweb](https://github.com/gpuweb/gpuweb/issues/1480)', h_level: 3, children: content.split('\n'), }; const expected = { issue_url: 'https://github.com/gpuweb/gpuweb/issues/1480', slug: 'wgsl-proposal-remove-pointer-out-parameters-from-modf-frexp--issue-1480--gpuwebgpuweb', content: content.trim(), }; const was = section_desc(h3_section); if (JSON.stringify(expected) != JSON.stringify(was)) throw {was, expected}; } // - function make_details(desc) { return `\ <details><summary><a href="${e_link_url.value}#${desc.slug}">${e_link_title.value}</a></summary> ${desc.content} </details>`; } function extract_minutes() { const text = e_in.value; const tree = md_to_tree(text); console.log('tree', tree); const first_titled = (() => { for (const x of tree.children) { if (x.title) return x; } throw tree.children; })(); console.assert(first_titled.title.startsWith('# ')); const page_title = first_titled.title.slice(2); const page_slug = to_github_page_slug(page_title); const wiki_url = `https://github.com/gpuweb/gpuweb/wiki/${page_slug}`; if (!e_link_url.value) { e_link_url.value = wiki_url; } if (!e_link_title.value) { e_link_title.value = page_title; } while (e_out.firstChild) { e_out.removeChild(e_out.firstChild); } function per_section_node(cur) { if (cur.h_level === undefined) return; // A string, not a section: Don't recurse. const section = section_desc(cur); console.log(section); if (section.content) { const details = make_details(section); e_out.appendChild(document.createElement('br')); const out = e_out.appendChild(document.createElement('div')); let e_section_title; if (section.issue_url) { e_section_title = out.appendChild(document.createElement('a')); e_section_title.href = section.issue_url; } else { e_section_title = out.appendChild(document.createElement('span')); } e_section_title.textContent = cur.title; out.appendChild(document.createElement('br')); const e_details = out.appendChild(document.createElement('pre')); e_details.style.border = '1px solid black'; e_details.textContent = details; } // - if (section.subsections) { for (const sub of section.subsections) { per_section_node(sub); } } } per_section_node(tree); } e_extract.addEventListener('click', extract_minutes, false); </script> </body> </html>
<?php class Centurion_Test_PHPUnit_ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase { public function __construct($name = NULL, array $data = array(), $dataName = '') { if (null == $this->bootstrap) { // Assign and instantiate in one step: $this->bootstrap = new Centurion_Application( APPLICATION_ENV, Centurion_Config_Directory::loadConfig(APPLICATION_PATH . '/configs/', APPLICATION_ENV, true) ); } parent::__construct($name, $data, $dataName); } /** * Retrieve front controller instance * * @return Zend_Controller_Front */ public function getFrontController() { if (null === $this->_frontController) { $this->_frontController = Centurion_Controller_Front::getInstance(); } return $this->_frontController; } public function tearDown() { global $application; Centurion_Controller_Front::getInstance()->resetInstance(); $this->resetRequest(); $this->resetResponse(); $this->request->setPost(array()); $this->request->setQuery(array()); Centurion_Signal::unregister(); Centurion_Auth::getInstance()->clearIdentity(); Centurion_Loader_PluginLoader::cleanCache(); return $application->getBootstrap()->bootstrap('cachemanager'); } public function logInAsAdmin() { $user = Centurion_Db::getSingleton('auth/user')->findOneById(1); if ($user == null) { throw new PHPUnit_Framework_Exception('Can not log as admin. User does not exists'); } Centurion_Auth::getInstance()->clearIdentity(); Centurion_Auth::getInstance()->getStorage()->write($user); } public function logInAsAnnonymous() { $user = Centurion_Db::getSingleton('auth/user')->findOneById(2); if ($user == null) { throw new PHPUnit_Framework_Exception('Can not log as annonymous. User does not exists'); } Centurion_Auth::getInstance()->clearIdentity(); Centurion_Auth::getInstance()->getStorage()->write($user); } public function is404($url) { $this->resetResponse(); $this->resetRequest(); try { $this->dispatch($url); $exceptions = $this->getResponse()->getException(); if (!isset($exceptions[0]) || 404 !== $exceptions[0]->getCode()) { return false; } } catch (Centurion_Controller_Action_Exception $e) { if ($e->getCode() !== 404) { return false; } } return true; } public function is200($url) { $this->resetResponse(); $this->resetRequest(); try { $this->dispatch($url); if ($this->getResponse()->getHttpResponseCode() != 200) { return false; } } catch (Centurion_Controller_Action_Exception $e) { return false; } return true; } public function assert200($url) { if (!$this->is200($url)) { $this->fail('The action not raised the 200 code'); } } public function assertNot200($url) { if ($this->is200($url)) { $this->fail('The action raised the 200 code. It should not'); } } public function assert404($url) { if (!$this->is404($url)) { $this->fail('The action not raised the 404 exception'); } } public function assertNot404($url) { if ($this->is404($url)) { $this->fail('The action raised 404 exception. It should not.'); } } }
const express = require('express') const router = express.Router() const createError = require('http-errors') const User = require('../models/user') const { authSchema, loginSchema } = require('../helpers/validationSchema') const { signAccessToken, signRefreshToken, verifyRefreshToken, verifyAccessToken } = require('../helpers/jwtHelper') router.get('/profile', verifyAccessToken, async (req, res, next) => { try { const user = await User.findById(req.user.id).select('-password') if (!user) { throw createError.NotFound('User not found') } res.send(user) } catch (error) { next(error) } }) router.post('/register', async (req, res, next) => { try { const result = await authSchema.validateAsync(req.body) const doesExist = await User.findOne({ email: result.email.toLowerCase().trim() }) if (doesExist) throw createError.Conflict(`${result.email} is already registered`) const user = new User(result) const savedUser = await user.save() const accessToken = await signAccessToken(savedUser.id) const refreshToken = await signRefreshToken(savedUser.id) res.send({ accessToken, refreshToken }) } catch (error) { if (error.isJoi === true) { return next(createError.BadRequest(error.message)) } next(error) } }) router.post('/login', async (req, res, next) => { try { const result = await loginSchema.validateAsync(req.body) const user = await User.findOne({ email: result.email.toLowerCase().trim() }) if (!user) { throw createError.NotFound('User not registered') } const isMatchPassword = await user.isValidPassword(result.password) if (!isMatchPassword) { throw createError.Unauthorized('Username/Password not valid.') } const accessToken = await signAccessToken(user.id, user.role) const refreshToken = await signRefreshToken(user.id) res.send({ accessToken, refreshToken }) } catch (error) { if (error.isJoi === true) { return next(createError.BadRequest(error.message)) } next(error) } }) router.post('/refresh-token', async (req, res, next) => { try { const { refreshToken } = req.body if (!refreshToken) { throw createError.BadRequest('Refresh token missing') } const userId = await verifyRefreshToken(refreshToken) const accessToken = await signAccessToken(userId) const refToken = await signRefreshToken(userId) res.send({ accessToken: accessToken, refreshToken: refToken }) } catch (error) { if (error.name === 'TokenExpiredError') { return next(createError.BadRequest('Refresh token expired')) } next(error) } }) module.exports = router
/* Assignment operator assigns a value to its left operand based on the value of its right operand. All of them are binary operators. left operand (operator) right operand = -> simple assignment += -> addition assignment -= -> subtraction assignment *= -> multiplication assignment /= -> division assignment %= -> modulo/remainder assignment **= -> exponentiation assignment ??= -> nullish coalescing assignment */ // = -> simple assignment const a = 2; let b = 4; b = 5; // += -> addition assignment console.log(b); b = b + 4; console.log(b); b += 4; // b = b + 4 => b = 9 + 4 => b = 13 console.log(b); // -= -> subtraction assignment b -= 8; console.log(b); // *= -> multiplication assignment b *= 8; console.log(b); // /= -> division assignment b /= 10; console.log(b); // %= -> modulo/remainder assignment b %= 10; console.log(b); // **= -> exponentiation assignment b **= 2; console.log(b); // value this returns -> assigned value console.log((b /= 8)); console.log(b); // ??= -> nullish coalescing assignment
import React, { DetailedHTMLProps, forwardRef, ButtonHTMLAttributes, } from "react"; const Button = forwardRef< HTMLButtonElement, DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement> >(({ className, children, ...rest }, ref) => { return ( <button className={`bg-blue-600 rounded px-4 py-2 text-white font-bold hover:bg-blue-500 focus:bg-blue-400 transition-colors disabled:bg-gray-500 w-full ${className}`} ref={ref} {...rest} > {children} </button> ); }); export default Button;
package com.tangzq.common; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.Properties; /** * Properties文件載入工具類. 可載入多個properties檔, 相同的屬性在最後載入的檔中的值將會覆蓋之前的值,但以System的Property優先. * @author tangzhiqiang */ public class PropertiesLoader { private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class); private static ResourceLoader resourceLoader = new DefaultResourceLoader(); private final Properties properties; public PropertiesLoader(String... resourcesPaths) { properties = loadProperties(resourcesPaths); } public Properties getProperties() { return properties; } /** * 取出Property,但以System的Property優先,取不到返回空字串. * * @param key * @return */ private String getValue(String key) { String systemProperty = System.getProperty(key); if (systemProperty != null) { return systemProperty; } if (properties.containsKey(key)) { return properties.getProperty(key); } return ""; } /** * 取出String類型的Property,但以System的Property優先,如果都為Null則拋出異常. * * @param key * @return */ public String getProperty(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return value; } /** * 取出String類型的Property,但以System的Property優先.如果都為Null則返回Default值. * * @param key * @param defaultValue * @return */ public String getProperty(String key, String defaultValue) { String value = getValue(key); return value != null ? value : defaultValue; } /** * 取出Integer類型的Property,但以System的Property優先.如果都為Null或內容錯誤則拋出異常. * * @param key * @return */ public Integer getInteger(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Integer.valueOf(value); } /** * 取出Integer類型的Property,但以System的Property優先.如果都為Null則返回Default值,如果內容錯誤則拋出異常 * * @param key * @param defaultValue * @return */ public Integer getInteger(String key, Integer defaultValue) { String value = getValue(key); return value != null ? Integer.valueOf(value) : defaultValue; } /** * 取出Double類型的Property,但以System的Property優先.如果都為Null或內容錯誤則拋出異常. * * @param key * @return */ public Double getDouble(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Double.valueOf(value); } /** * 取出Double類型的Property,但以System的Property優先.如果都為Null則返回Default值,如果內容錯誤則拋出異常 */ public Double getDouble(String key, Integer defaultValue) { String value = getValue(key); return value != null ? Double.valueOf(value) : defaultValue; } /** * 取出Boolean類型的Property,但以System的Property優先.如果都為Null拋出異常,如果內容不是true/false則返回false. * * @param key * @return */ public Boolean getBoolean(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Boolean.valueOf(value); } /** * 取出Boolean類型的Property,但以System的Property優先.如果都為Null則返回Default值,如果內容不為true/false則返回false. * * @param key * @param defaultValue * @return */ public Boolean getBoolean(String key, boolean defaultValue) { String value = getValue(key); return value != null ? Boolean.valueOf(value) : defaultValue; } /** * 載入多個檔, 檔路徑使用Spring Resource格式. * * @param resourcesPaths * @return */ private Properties loadProperties(String... resourcesPaths) { Properties props = new Properties(); for (String location : resourcesPaths) { logger.debug("Loading properties file from:" + location); InputStream is = null; try { Resource resource = resourceLoader.getResource(location); is = resource.getInputStream(); props.load(is); } catch (IOException ex) { logger.info("Could not load properties from path:" + location + ", " + ex.getMessage()); } finally { IOUtils.closeQuietly(is); } } return props; } }