text
stringlengths
184
4.48M
type kind = | ProhibitedModuleOpen({line: int, prohibitedModuleName: ModuleName.t}) | ProhibitedModuleInclude({line: int, prohibitedModuleName: ModuleName.t}) | ProhibitedModuleAssign({line: int, prohibitedModuleName: ModuleName.t}) | ProhibitedModuleUsage({line: int, prohibitedModuleName: ModuleName.t}) | InvalidStdlibParentDirName({stdlibParentDirName: string}) type t = {path: string, kind: kind} let make = (~path, ~kind) => { {path, kind} } let getLink = lintIssue => switch lintIssue.kind { | InvalidStdlibParentDirName(_) => lintIssue.path | ProhibitedModuleOpen({line}) | ProhibitedModuleInclude({line}) | ProhibitedModuleAssign({line}) | ProhibitedModuleUsage({line}) => `${lintIssue.path}:${line->Int.toString}` } let getMessage = lintIssue => switch lintIssue.kind { | InvalidStdlibParentDirName({stdlibParentDirName}) => `The "${stdlibParentDirName}" is an invalid directory name for custom standary library related files. Put the files to the directory with the name "stdlib" to make it easier to find them.` | ProhibitedModuleOpen({prohibitedModuleName}) => `Found "${prohibitedModuleName->ModuleName.toString}" module open.` | ProhibitedModuleInclude({prohibitedModuleName}) => `Found "${prohibitedModuleName->ModuleName.toString}" module include.` | ProhibitedModuleUsage({prohibitedModuleName}) | ProhibitedModuleAssign({prohibitedModuleName}) => `Found "${prohibitedModuleName->ModuleName.toString}" module usage.` }
// // JAlert.swift // JAlert // // Created by 장효원 on 2022/01/02. // import UIKit public class JAlert: UIView { // MARK: Public Proerties (You can customize Alert View!) public weak var delegate: JAlertDelegate? // delegate public var appearType: AppearType = .default public var disappearType: DisappearType = .default public var cornerRadius: CGFloat = 8.0 public var textAlignment: NSTextAlignment = .center public var alertBackgroundColor: UIColor = .white public var animationWithDuration:CGFloat = 0.3 public var titleColor:UIColor = UIColor(red: 5.0/255.0, green: 0, blue: 153.0/255.0, alpha: 1.0) public var messageColor:UIColor = UIColor(red: 5.0/255.0, green: 0, blue: 153.0/255.0, alpha: 1.0) public var actionButtonColor:UIColor = UIColor.black public var cancelButtonColor:UIColor = UIColor.black public var isUseBackgroundView = true public var isUseSeparator = true public var isAnimation = true public var titleSideMargin: CGFloat = 20.0 public var titleTopMargin: CGFloat = 20.0 public var titleToMessageSpacing: CGFloat = 20.0 public var messageSideMargin: CGFloat = 20.0 public var messageBottomMargin: CGFloat = 20.0 // MARK: Private Properties private var alertType: AlertType = .default private var backgroundView: UIView! private var alertView: UIView! private var titleLabel: UILabel! private var messageLabel: UILabel! private var textView: UITextView! private var title: String? private var message: String? private var viewWidth: CGFloat = 0 private var viewHeight: CGFloat = 0 private var buttonTitle: String? private var buttonTitles: [String] = ["OK", "Cancel"] private var buttons: [UIButton] = [] private var buttonHeight: CGFloat = 44.0 private var actionButtonIndex = 0 private var onActionClicked: (() -> Void)? private var onCancelClicked: (() -> Void)? private let kDefaultWidth: CGFloat = 270.0 private let kDefaultHeight: CGFloat = 144.0 private let kDefaultCornerRadius: CGFloat = 8.0 // MARK: Initialization required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public init(title: String? = nil, message: String? = nil, alertType: AlertType = .default) { super.init(frame: CGRect(x: 0, y: 0, width: kDefaultWidth, height: kDefaultHeight)) setup(title: title, message: message, alertType: alertType) } private func show(in view: UIView) { frame = CGRect(origin: .zero, size: UIScreen.main.bounds.size) backgroundView.frame = CGRect(origin: .zero, size: UIScreen.main.bounds.size) addButtonToAlertView() setupElemetsFrame() view.addSubview(self) view.bringSubviewToFront(self) } } //Public function extension JAlert { public func setButton(actionName:String, cancelName:String? = nil, onActionClicked: (() -> Void)? = nil, onCancelClicked: (() -> Void)? = nil) { if cancelName != nil { buttonTitles = [actionName, cancelName!] } else { buttonTitles = [actionName] } self.onActionClicked = onActionClicked self.onCancelClicked = onCancelClicked } /* TODO: new function is waiting public func setActionButtonFont(font:UIFont) { } public func setCancelButtonFont(font:UIFont) { } public func setALLButtonFont(font:UIFont, containActionAndCancel:Bool = true) { } */ public func show() { if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) { show(in: window) } } } extension JAlert { private func setup(title: String? = nil, message: String? = nil, alertType: AlertType) { self.title = title self.message = message self.alertType = alertType setupDefaultValue() setupElements() NotificationCenter.default.addObserver(self, selector: #selector(deviceDidRotate(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) } private func setupDefaultValue() { clipsToBounds = true viewWidth = kDefaultWidth viewHeight = kDefaultHeight cornerRadius = kDefaultCornerRadius } private func setupElements() { backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)) alertView = UIView(frame: .zero) titleLabel = UILabel(frame: .zero) messageLabel = UILabel(frame: .zero) textView = UITextView(frame: .zero) addSubview(backgroundView) addSubview(alertView) addSubview(textView) if title != nil { titleLabel.text = title titleLabel.textAlignment = textAlignment titleLabel.textColor = titleColor alertView.addSubview(titleLabel) } if message != nil && alertType != .submit { messageLabel.text = message messageLabel.textAlignment = textAlignment messageLabel.textColor = messageColor alertView.addSubview(messageLabel) } if alertType == .submit { textView.layer.borderColor = UIColor.black.cgColor textView.layer.borderWidth = 0.5 alertView.addSubview(textView) } } private func addButtonToAlertView() { for buttonTitle in buttonTitles { let button = UIButton(type: .custom) button.setTitle(buttonTitle, for: .normal) buttons.append(button) alertView.addSubview(button) } setButtonProperties() } private func setButtonProperties() { var i = 0 for button in buttons { button.tag = i button.backgroundColor = .clear button.setTitleColor(.black, for: .normal) if button.tag == actionButtonIndex { button.setTitleColor(actionButtonColor, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17) } else { button.setTitleColor(cancelButtonColor, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 17) } button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside) i += 1 } } private func setupElemetsFrame() { self.isHiddenJAlert(status: true) if title != nil { titleLabel.frame = CGRect(x: 0, y: 0, width: viewWidth - titleSideMargin*2, height: 0) labelHeightToFit(titleLabel) titleLabel.center = CGPoint(x: viewWidth/2, y: titleTopMargin + titleLabel.frame.size.height/2) } if message != nil && alertType != .submit { messageLabel.frame = CGRect(x: 0, y: 0, width: viewWidth - messageSideMargin*2, height: 0) labelHeightToFit(messageLabel) messageLabel.center = CGPoint(x: viewWidth/2, y: titleTopMargin + titleLabel.frame.size.height + titleToMessageSpacing + messageLabel.frame.size.height/2) } if alertType == .submit { textView.frame = CGRect(x: 0, y: 0, width: viewWidth - messageSideMargin*2 - 10, height: 150) textView.center = CGPoint(x: viewWidth/2, y: titleTopMargin + titleLabel.frame.size.height + titleToMessageSpacing + textView.frame.size.height/2) } setupButtonView() updateAlertViewFrame() setupAnimation() } private func setupButtonView() { switch alertType { case .default: let topPartHeight = titleTopMargin + titleLabel.frame.size.height + titleToMessageSpacing + messageLabel.frame.size.height + messageBottomMargin viewHeight = topPartHeight + buttonHeight let button = buttons.first! button.frame = CGRect(x: 0, y: viewHeight-buttonHeight, width: viewWidth, height: buttonHeight) if isUseSeparator { let lineView = UIView(frame: CGRect(x: 0, y: button.frame.origin.y, width: viewWidth, height: 0.5)) lineView.backgroundColor = .black alertView.addSubview(lineView) } case .confirm: let topPartHeight = titleTopMargin + titleLabel.frame.size.height + titleToMessageSpacing + messageLabel.frame.size.height + messageBottomMargin viewHeight = topPartHeight + buttonHeight let leftButton = buttons[0] let rightButton = buttons[1] leftButton.frame = CGRect(x: 0, y: viewHeight-buttonHeight, width: viewWidth/2, height: buttonHeight) rightButton.frame = CGRect(x: viewWidth/2, y: viewHeight-buttonHeight, width: viewWidth/2, height: buttonHeight) if isUseSeparator { let horLine = UIView(frame: CGRect(x: 0, y: leftButton.frame.origin.y, width: viewWidth, height: 0.5)) horLine.backgroundColor = .black self.alertView.addSubview(horLine) let verLine = UIView(frame: CGRect(x: viewWidth/2, y: leftButton.frame.origin.y, width: 0.5, height: leftButton.frame.size.height)) verLine.backgroundColor = .black self.alertView.addSubview(verLine) } case .submit: let topPartHeight = titleTopMargin + titleLabel.frame.size.height + titleToMessageSpacing + textView.frame.size.height + messageBottomMargin viewHeight = topPartHeight + buttonHeight let leftButton = buttons[0] let rightButton = buttons[1] leftButton.frame = CGRect(x: 0, y: viewHeight-buttonHeight, width: viewWidth/2, height: buttonHeight) rightButton.frame = CGRect(x: viewWidth/2, y: viewHeight-buttonHeight, width: viewWidth/2, height: buttonHeight) if isUseSeparator { let horLine = UIView(frame: CGRect(x: 0, y: leftButton.frame.origin.y, width: viewWidth, height: 0.5)) horLine.backgroundColor = .black self.alertView.addSubview(horLine) let verLine = UIView(frame: CGRect(x: viewWidth/2, y: leftButton.frame.origin.y, width: 0.5, height: leftButton.frame.size.height)) verLine.backgroundColor = .black self.alertView.addSubview(verLine) } } } private func updateAlertViewFrame() { alertView.frame = CGRect(x: (backgroundView.frame.size.width - viewWidth)/2, y: (backgroundView.frame.size.height - viewHeight)/2, width: viewWidth, height: viewHeight) alertView.backgroundColor = alertBackgroundColor alertView.layer.cornerRadius = CGFloat(cornerRadius) } private func setupAnimation(){ self.isHiddenJAlert(status: false) //Add animation Type if isAnimation { showAppearAnimation() } } private func showAppearAnimation() { switch appearType { case .scale: self.alertView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) UIView.animate(withDuration: animationWithDuration, animations: { self.alertView.transform = CGAffineTransform.identity }) case .default: self.isHiddenJAlert(status: true) UIView.animate(withDuration: animationWithDuration, animations: { self.isHiddenJAlert(status: false) }) } } private func closeAnimation(completion:@escaping () -> Void) { switch disappearType { case .scale: self.alertView.transform = CGAffineTransform.identity UIView.animate(withDuration: animationWithDuration, animations: { self.alertView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3) self.isHiddenJAlert(status: true) }, completion: { _ in completion() }) case .default: UIView.animate(withDuration: animationWithDuration, animations: { self.isHiddenJAlert(status: true) }, completion: { _ in completion() }) } } private func isHiddenJAlert(status:Bool){ if status { self.backgroundView.alpha = 0 self.alertView.alpha = 0 } else { if isUseBackgroundView { backgroundView.backgroundColor = .black backgroundView.alpha = 0.5 } else { backgroundView.alpha = 0 } self.alertView.alpha = 1 } } private func close() { if self.isAnimation { closeAnimation { self.removeFromSuperview() } } else { self.removeFromSuperview() } self.isHiddenJAlert(status: true) } } // @objc extension JAlert { @objc private func deviceDidRotate(_ aNotifitation: NSNotification) -> Void { show() } @objc private func buttonClicked(_ button: UIButton) { close() let buttonIndex = button.tag delegate?.alertView?(self, clickedButtonAtIndex: buttonIndex) if buttonIndex == actionButtonIndex { onActionClicked?() } else { onCancelClicked?() } } } @objc public protocol JAlertDelegate : NSObjectProtocol { @objc optional func alertView(_ alertView: JAlert, clickedButtonAtIndex buttonIndex: Int) } //Utils Function extension JAlert { private func labelHeightToFit(_ label: UILabel) { let maxWidth = label.frame.size.width let maxHeight = CGFloat.greatestFiniteMagnitude let rect = label.attributedText?.boundingRect( with: CGSize(width: maxWidth, height: maxHeight), options: .usesLineFragmentOrigin, context: nil) label.frame.size.height = rect!.size.height } }
import { Button } from "@/components/ui/button" import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" import { Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, } from "@/components/ui/sheet" import { CaretSortIcon } from "@radix-ui/react-icons" import { MoreHorizontal } from "lucide-react" export const columns = [ { accessorKey: "image", header: ({ column }) => { return ( <Button className="" variant="ghost" size="sm" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Image <CaretSortIcon className="ml-2 h-4 w-4" /> </Button> ) }, cell: ({ row }) => ( <div style={{ backgroundImage: `url("${row.getValue('image')}")`, backgroundRepeat: 'no-repeat', backgroundSize: 'cover' }} className="bg-gray-200 rounded-full w-12 h-12 border-2 mx-2"> </div> ), }, { accessorKey: "title", header: ({ column }) => { return ( <Button className="-mx-3" variant="ghost" size="sm" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Nom du produit <CaretSortIcon className="ml-2 h-4 w-4" /> </Button> ) }, cell: ({ row }) => ( <div className="overflow-hidden"> <p className="text-xs line-clamp-2">{row.getValue('title')}</p> </div> ), }, { accessorKey: "category", header: ({ column }) => { return ( <Button className="-mx-3" variant="ghost" size="sm" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Categorie du produit <CaretSortIcon className="ml-2 h-4 w-4" /> </Button> ) }, }, { accessorKey: "description", header: ({ column }) => { return ( <div className="-mx-3"> <Button size="sm" variant="ghost" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Description <CaretSortIcon className="ml-2 h-4 w-4" /> </Button> </div> ) }, cell: ({ row }) => ( <div className="bg-white w-fit border rounded-md px-2 py-1 overflow-hidden"> <p className="text-xs line-clamp-3">{row.getValue('description')}</p> </div> ), }, { accessorKey: "rating.rate", header: ({ column }) => { return ( <Button className="-mx-2" variant="ghost" size="sm" onClick={() => column.toggleSorting(column.getIsSorted() === "asc")} > Note du produit <CaretSortIcon className="ml-2 h-4 w-4" /> </Button> ) }, cell: ({ row }) => ( <p className="bg-white w-fit border rounded-md px-2 text-xs font-extrabold text-orange-700 py-1 text-dark">{row.original.rating.rate}</p> ), }, { accessorKey: "price", header: () => <div className="">Prix</div>, cell: ({ row }) => { const amount = parseFloat(row.getValue("price")) const formatted = new Intl.NumberFormat('fr', { style: 'currency', currency: 'XOF' }).format(amount) return <div className="font-medium">{formatted}</div> }, }, { id: "actions", header: 'Action', cell: ({ row }) => { const payment = row.original return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" className="h-8 w-8 p-0"> <MoreHorizontal className="h-4 w-4" /> </Button> </DropdownMenuTrigger> <DropdownMenuContent align="end"> <DropdownMenuLabel>Actions</DropdownMenuLabel> <DropdownMenuItem onSelect={(e) => e.preventDefault()} onClick={() => navigator.clipboard.writeText(payment.id)} > <Sheet> <SheetTrigger asChild> <h1>voir le produit</h1> </SheetTrigger> <SheetContent> <SheetHeader> <SheetTitle>Ajouter un produit</SheetTitle> <SheetDescription> Make changes to your profile here. Click save when you're done. </SheetDescription> </SheetHeader> <div className="grid gap-4 py-4"> </div> <SheetFooter> <SheetClose asChild> <Button type="submit">Enregistrer</Button> </SheetClose> </SheetFooter> </SheetContent> </Sheet> </DropdownMenuItem> <DropdownMenuSeparator /> <DropdownMenuItem onSelect={(e) => e.preventDefault()}> <Sheet> <SheetTrigger asChild> <h1>Modifier le produit</h1> </SheetTrigger> <SheetContent> <SheetHeader> <SheetTitle>Modification du produit</SheetTitle> <SheetDescription> Make changes to your profile here. Click save when you're done. </SheetDescription> </SheetHeader> <div className="grid gap-4 py-4"> </div> <SheetFooter> <SheetClose asChild> <Button type="submit" className="bg-orange-500">Modifier le produit</Button> </SheetClose> </SheetFooter> </SheetContent> </Sheet> </DropdownMenuItem> <DropdownMenuItem onSelect={(e) => e.preventDefault()}> <Dialog> <DialogTrigger>Supprimer le produit</DialogTrigger> <DialogContent> <DialogHeader> <DialogTitle>Êtes-vous absolument sûr ?</DialogTitle> <DialogDescription> Cette action ne peut être annulée. Cette action supprimera définitivement cet element. </DialogDescription> </DialogHeader> <DialogFooter> <Button variant='destructive'>Oui, supprimer</Button> </DialogFooter> </DialogContent> </Dialog> </DropdownMenuItem> </DropdownMenuContent> </DropdownMenu> ) }, }, ]
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Redirect } from 'react-router'; import { connect } from 'react-redux'; import Input from '../components/Input'; import TextArea from '../components/TextArea'; import Button from '../components/Button'; import { btnWork } from '../redux/actions/action'; class ProfessionalForm extends Component { constructor() { super(); this.state = { curriculo: '', cargo: '', descricao: '', redirect: false, }; this.handleChange = this.handleChange.bind(this); this.redirectLink = this.redirectLink.bind(this); } handleChange({ target }) { const { name, value } = target; this.setState({ [name]: value }); } redirectLink(state) { const { handleClick } = this.props; handleClick(state); this.setState({ redirect: true }); } render() { const { curriculo, cargo, descricao, redirect } = this.state; return ( <> { redirect && <Redirect to="/formdisplay" /> } <fieldset> <TextArea label="Resumo do currículo: " value={ curriculo } name="curriculo" maxLength="1000" onChange={ this.handleChange } required /> <Input label="Cargo:" name="cargo" type="text" value={ cargo } onChange={ this.handleChange } required /> <TextArea label="Descrição do cargo: " name="descricao" maxLength="500" onChange={ this.handleChange } value={ descricao } required /> <Button label="enviar" onClick={ () => this.redirectLink(this.state) } /> </fieldset> </> ); } } const mapDispatchToProps = (dispatch) => ({ handleClick: (state) => dispatch(btnWork(state)), }); ProfessionalForm.propTypes = { handleClick: PropTypes.func.isRequired, }; export default connect(null, mapDispatchToProps)(ProfessionalForm);
package com.ichop.core.areas.reaction.repository; import com.ichop.core.EntityFactory; import com.ichop.core.areas.reaction.domain.entities.ReactionType; import com.ichop.core.areas.reaction.domain.entities.ThreadReaction; import com.ichop.core.areas.reaction.repositories.ThreadReactionRepository; import com.ichop.core.areas.thread.domain.entities.Thread; import com.ichop.core.areas.thread.repositories.ThreadRepository; import com.ichop.core.areas.user.domain.entities.User; import com.ichop.core.areas.user.repositories.UserRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @DataJpaTest @ActiveProfiles("test") public class ThreadReactionRepositoryTests { @Autowired private ThreadReactionRepository threadReactionRepository; @Autowired private ThreadRepository threadRepository; @Autowired private UserRepository userRepository; private EntityFactory entityFactory; @Before public void setUp() { this.entityFactory = new EntityFactory(); } @Test public void getUserTotalReactions_withUserNotHavingReactions_shouldReturn0(){ User user = this.userRepository.save(this.entityFactory.createUser()); Thread thread = this.entityFactory.createThread(); thread.setCreator(user); this.threadRepository.save(thread); int result = this.threadReactionRepository.getUserTotalReactions(user); assertEquals(result,0); } @Test public void getUserTotalReactions_withUserHavingAReaction_shouldReturn1(){ User user = this.userRepository.save(this.entityFactory.createUser()); Thread thread = this.entityFactory.createThread(); thread.setCreator(user); this.threadRepository.save(thread); ThreadReaction threadReaction = this.entityFactory.createThreadReaction(user,thread); this.threadReactionRepository.save(threadReaction); int result = this.threadReactionRepository.getUserTotalReactions(user); assertEquals(result,1); } @Test public void getUserTotalReactionsWithReactionTypeLike_withUserHavingAReaction_shouldReturn1(){ User user = this.userRepository.save(this.entityFactory.createUser()); Thread thread = this.entityFactory.createThread(); thread.setCreator(user); this.threadRepository.save(thread); ThreadReaction threadReaction = this.entityFactory.createThreadReaction(user,thread, ReactionType.LIKE); this.threadReactionRepository.save(threadReaction); int result = this.threadReactionRepository.getUserTotalReactions(user,ReactionType.LIKE); assertEquals(result,1); } @Test public void getUserTotalReactionsWithReactionTypeDislike_withUserHavingAReaction_shouldReturn1(){ User user = this.userRepository.save(this.entityFactory.createUser()); Thread thread = this.entityFactory.createThread(); thread.setCreator(user); this.threadRepository.save(thread); ThreadReaction threadReaction = this.entityFactory.createThreadReaction(user,thread, ReactionType.DISLIKE); this.threadReactionRepository.save(threadReaction); int result = this.threadReactionRepository.getUserTotalReactions(user,ReactionType.DISLIKE); assertEquals(result,1); } @Test public void isUserReactedAtThatThread_withUserReactedAtThatThread_shouldReturnTrue() { User user = this.userRepository.save(this.entityFactory.createUser()); Thread thread = this.entityFactory.createThread(); thread.setCreator(user); this.threadRepository.save(thread); ThreadReaction threadReaction = this.entityFactory.createThreadReaction(user, thread); this.threadReactionRepository.save(threadReaction); boolean result = this.threadReactionRepository.isUserReactedAtThatThread(user,thread); assertTrue(result); } @Test public void isUserReactedAtThatThread_withUserNotReactedAtThatThread_shouldReturnFalse() { User user = this.userRepository.save(this.entityFactory.createUser()); Thread thread = this.entityFactory.createThread(); thread.setCreator(user); this.threadRepository.save(thread); boolean result = this.threadReactionRepository.isUserReactedAtThatThread(user,thread); assertFalse(result); } }
/** * 内部模块,防止命名冲突,组织代码 * 命名空间内的东西属于模块内部,外部无法访问,如果要访问需要export导出 * */ namespace B { interface Animal { name: string; eat(str: string): void } export class Dog implements Animal { name: string constructor(name: string) { this.name = name } eat() { console.log(`${this.name}吃粮食`); } } function foo() { } } var dog = new B.Dog("狼狗") dog.eat()
use context essentials2021 include gdrive-sheets include shared-gdrive( "dcic-2021", "1wyQZj_L0qqV9Ekgr9au6RX2iqt2Ga8Ep") include data-source ssid = "1RYN0i4Zx_UETVuYacgaGfnFcv4l9zd9toQTTdkQkj7g" kWh-wealthy-consumer-data = load-table: komponent, energi source: load-spreadsheet(ssid).sheet-by-name("kWh", true) sanitize energi using string-sanitizer end kWh-wealthy-consumer-data distance-travelled-per-day = 30 #km distance-per-unit-of-fuel = 10 #km/L energy-per-unit-of-fuel = 10 #kWh som oppgitt i formelen energy-per-day = ( distance-travelled-per-day / distance-per-unit-of-fuel ) * energy-per-unit-of-fuel # Oppgave a: # lest og studert. # Oppgave b: fun energi-to-number(str :: String) -> Number: doc: ```changes string value to number value``` cases(Option) string-to-number(str): | some(a) => a | none => energy-per-day end where: energi-to-number("") is energy-per-day energi-to-number("48") is 48 end # Oppgave c: fixed-energi = transform-column(kWh-wealthy-consumer-data, "energi", energi-to-number) # Oppgave d: summer = sum(fixed-energi, "energi") table-summert = table: komponent :: String, energi :: Number row: "Totalt energiforbruk", summer end new-row = get-row(table-summert, 0) add-row(fixed-energi, new-row) # Oppgave e: bar-chart(fixed-energi, "komponent", "energi")
"""Base classes for typing and sequential optimization procedure encoding. Members are explicitly re-exported in pyprobound. """ from __future__ import annotations import abc import collections import functools import logging import time from collections.abc import Callable, Iterator from typing import Any, Literal, NamedTuple, TypeVar, cast import torch from torch import Tensor from typing_extensions import override from . import __version__ from .utils import clear_cache logger = logging.getLogger(__name__) ComponentT = TypeVar("ComponentT", bound="Component") class Call(NamedTuple): """A function to be called during optimization. Run as `getattr(cmpt, fun)(**kwargs)`. Attributes: cmpt: The component to be called. fun: The name of the function to be called. kwargs: Any keyword arguments that will be passed to the function. """ cmpt: Component fun: str kwargs: dict[str, Any] class Step(NamedTuple): """A series of calls performed in a single step before re-optimizing. Attributes: calls: The calls that will be performed together before re-optimizing. greedy: Whether to repeat the calls each time the loss improves. """ calls: list[Call] greedy: bool = False class BindingOptim(NamedTuple): """The sequential optimization steps taken to fit a Binding component. Attributes: ancestry: A set of tuples where each successive component is a child component of the previous component, from the root to the Binding component to be optimized; one Binding can occur multiple times. steps: The sequential optimization steps to fit a Binding component. """ ancestry: set[tuple[Component, ...]] steps: list[Step] def merge_binding_optim(self) -> None: """Merge all redundant steps and redundant calls in a step.""" # Merge unfreezes call_to_step: dict[ tuple[str, str, frozenset[tuple[str, Any]]], int ] = {} for step_idx, step in enumerate(self.steps): dropped_call_indices: set[int] = set() for call_idx, call in enumerate(step.calls): if call.fun in ("unfreeze", "activity_heuristic", "freeze"): key = ( type(call.cmpt).__name__, call.fun, frozenset(call.kwargs.items()), ) if call.fun == "activity_heuristic": key = ("", call.fun, frozenset()) if key[-1] == frozenset([("parameter", "spacing")]): key = ( "PSAM", call.fun, frozenset([("parameter", "monomer")]), ) if key not in call_to_step: call_to_step[key] = step_idx else: if call not in self.steps[call_to_step[key]].calls: self.steps[call_to_step[key]].calls.append(call) if step_idx != call_to_step[key]: dropped_call_indices.add(call_idx) # Remove redundant calls calls = { (call.cmpt, call.fun, frozenset(call.kwargs.items())): None for call_idx, call in enumerate(step.calls) if call_idx not in dropped_call_indices } step.calls[:] = [ Call(cmpt, fun, dict(kwargs)) for (cmpt, fun, kwargs) in calls ] # Remove redundant or empty steps calls_set: set[ frozenset[tuple[Component, str, frozenset[tuple[str, Any]]]] ] = set() dropped_step_indices: set[int] = set() for step_idx, step in enumerate(self.steps): calls_set_key = frozenset( (call.cmpt, call.fun, frozenset(call.kwargs.items())) for call in step.calls ) if len(calls_set_key) == 0 or calls_set_key in calls_set: dropped_step_indices.add(step_idx) else: calls_set.add(calls_set_key) self.steps[:] = [ step for step_idx, step in enumerate(self.steps) if step_idx not in dropped_step_indices ] # Move 'unfreeze all' to the end try: idx = self.steps.index( Step( [ Call( next(iter(self.ancestry))[0], "unfreeze", {"parameter": "all"}, ) ] ) ) step = self.steps.pop(idx) self.steps.append(step) except ValueError: pass class Component(torch.nn.Module, abc.ABC): """Module that serves as a component in PyProBound. Includes functions for loading from a checkpoint, freezing or unfreezing parameters, and defining sequential optimization procedures. Attributes: unfreezable: All possible values that can be passed to unfreeze(). _cache_fun: The name of a function in the module's child components that will be cached to avoid recomputation. _blocking: A mapping from the name of the cached function to the parent components waiting on that function's output. _caches: A mapping from the name of the cached function to a tuple of two optional elements, the input pointer and the output cache. """ unfreezable = Literal["all"] _cache_fun = "forward" def __init__(self, name: str = "") -> None: super().__init__() self.name = name self._blocking: dict[str, set[Component]] = collections.defaultdict( set ) self._caches: dict[str, tuple[int | None, Tensor | None]] = {} @override def __str__(self) -> str: return f"{self.name}{self.__class__.__name__}" @override def __repr__(self) -> str: return self.__str__() def save( self, checkpoint: torch.serialization.FILE_LIKE, flank_lengths: tuple[tuple[int, int], ...] = tuple(), ) -> None: """Saves the model to a file with "state_dict" and "metadata" fields. Args: checkpoint: The file where the model will be checkpointed to. flank_lengths: The (left_flank_length, right_flank_length) of each table represented by the model, written to the metadata field. """ metadata = { "time": time.asctime(), "version": __version__, "flank_lengths": flank_lengths, } state_dict = self.state_dict() torch.save( {"state_dict": state_dict, "metadata": metadata}, checkpoint ) def reload_from_state_dict(self, state_dict: dict[str, Any]) -> None: """Loads the model from a state dict. Args: state_dict: The state dict, usually returned by self.state_dict(). """ def get_attr(obj: Any, names: list[str]) -> Any: if len(names) == 1: return getattr(obj, names[0]) return get_attr(getattr(obj, names[0]), names[1:]) def set_attr(obj: Any, names: list[str], val: Any) -> None: if len(names) == 1: setattr(obj, names[0], val) else: set_attr(getattr(obj, names[0]), names[1:], val) # Update symmetry buffers for key in list(state_dict.keys()): if "symmetry" not in key: continue checkpoint_param = state_dict[key] submod_names = key.split(".") set_attr(self, submod_names, checkpoint_param) # Reshape convolution matrices for module in self.modules(): if hasattr(module, "update_params") and callable( module.update_params ): module.update_params() # Reshape remaining tensors for key in list(state_dict.keys()): checkpoint_param = state_dict[key] submod_names = key.split(".") try: self_attr = get_attr(self, submod_names) except AttributeError: continue if self_attr.shape != checkpoint_param.shape: if isinstance(self_attr, torch.nn.Parameter): checkpoint_param = torch.nn.Parameter( checkpoint_param, requires_grad=self_attr.requires_grad ) set_attr(self, submod_names, checkpoint_param) self.load_state_dict(state_dict, strict=False) def reload( self, checkpoint: torch.serialization.FILE_LIKE ) -> dict[str, Any]: """Loads the model from a checkpoint file. Args: checkpoint: The file where the model state_dict was written to. Returns: The metadata field of the checkpoint file. """ checkpoint_state: dict[str, Any] = torch.load(checkpoint) checkpoint_state_dict: dict[str, Any] = checkpoint_state["state_dict"] d = {} for key, val in checkpoint_state_dict.items(): d[key.replace("flat_log_spacing", "log_spacing")] = val checkpoint_state_dict.update(d) self.reload_from_state_dict(checkpoint_state_dict) return cast(dict[str, Any], checkpoint_state["metadata"]) @abc.abstractmethod def components(self) -> Iterator[Component]: """Iterator of child components.""" def max_embedding_size(self) -> int: """The maximum number of bytes needed to encode a sequence. Used for splitting calculations to avoid GPU limits on tensor sizes. """ max_sizes = [i.max_embedding_size() for i in self.components()] return max(max_sizes + [1]) def freeze(self) -> None: """Turns off gradient calculation for all parameters.""" for p in self.parameters(): p.requires_grad_(False) def unfreeze(self, parameter: unfreezable = "all") -> None: """Turns on gradient calculation for the specified parameter. Args: parameter: Parameter to be unfrozen, defaults to all parameters. """ if parameter == "all": for cmpt in self.components(): cmpt.unfreeze("all") else: raise ValueError( f"{type(self).__name__} cannot unfreeze parameter {parameter}" ) def check_length_consistency(self) -> None: """Checks that input lengths of Binding components are consistent. Raises: RuntimeError: There is an input mismatch between components. """ bindings = {m for m in self.modules() if isinstance(m, Binding)} for binding in bindings: binding.check_length_consistency() def optim_procedure( self, ancestry: tuple[Component, ...] | None = None, current_order: dict[tuple[Spec, ...], BindingOptim] | None = None, ) -> dict[tuple[Spec, ...], BindingOptim]: """The sequential optimization procedure for all Binding components. The optimization procedure is generated recursively through iteration over the child components of each module. All Binding components with the same specification returned from `key()` are trained jointly. Args: ancestry: The parent components from the root for which the procedure is being generated to the current component. current_order: Mapping of Binding component specifications to the sequential optimization procedure for those Binding components. Returns: The `current_order` updated with the optimization of the current component's children. """ if ancestry is None: ancestry = tuple() if current_order is None: current_order = {} for cmpt in self.components(): current_order = cmpt.optim_procedure( ancestry + (self,), current_order ) return current_order def _apply_block( self, component: Component | None = None, cache_fun: str | None = None ) -> None: """Directs the storage of intermediate results to avoid recomputation. Args: component: The parent component applying a block. cache_fun: The function whose output will be cached. """ if component is not None and cache_fun is not None: logger.info( "Applying block of %s on %s.%s", component, self, cache_fun ) self._blocking[cache_fun].add(component) logger.debug("%s._blocking=%s", self, self._blocking) for cmpt in self.components(): # pylint: disable-next=protected-access cmpt._apply_block(self, self._cache_fun) def _release_block( self, component: Component | None = None, cache_fun: str | None = None ) -> None: """Releases intermediate results, called after output has been used. Args: component: The parent component releasing the block. cache_fun: The function whose output will be released. """ if component is not None and cache_fun is not None: logger.info( "Releasing block of %s on %s.%s", component, self, cache_fun ) self._blocking[cache_fun].discard(component) logger.debug("%s._blocking=%s", self, self._blocking) if len(self._blocking[cache_fun]) == 0: logger.info("Clearing cache of %s.%s", self, cache_fun) self._caches[cache_fun] = (None, None) logger.debug("%s._caches=%s", self, self._caches) clear_cache() for cmpt in self.components(): # pylint: disable-next=protected-access cmpt._release_block(self, self._cache_fun) class Transform(Component): """Component that applies a transformation to a tensor. Includes improved typing and caching outputs to avoid recomputation for transformations that appear multiple times in a loss module. See https://github.com/pytorch/pytorch/issues/45414 for typing information. """ @override @abc.abstractmethod def forward(self, seqs: Tensor) -> Tensor: """A transformation applied to a sequence tensor.""" @override def __call__(self, seqs: Tensor) -> Tensor: return cast(Tensor, super().__call__(seqs)) @classmethod def cache( cls, fun: Callable[[ComponentT, Tensor], Tensor] ) -> Callable[[ComponentT, Tensor], Tensor]: """Decorator for a function to cache its output. The decorator must be applied to every function call whose output will be used in the cached function - generally all forward definitions. """ @functools.wraps(fun) def cache_decorator(self: ComponentT, seqs: Tensor) -> Tensor: # pylint: disable=protected-access data_ptr = seqs.data_ptr() logger.info("Calling %s.%s(%s)", self, fun.__name__, data_ptr) logger.debug("%s._caches=%s", self, self._caches) ptr, output = self._caches.get(fun.__name__, (None, None)) if output is not None: if ptr != data_ptr: raise RuntimeError( "Cached input pointer does not match current input" ) logger.info("Returning cache of %s.%s", self, fun.__name__) return output self._apply_block() logger.info("Calculating output of %s.%s", self, fun.__name__) output = fun(self, seqs) self._release_block() if len(self._blocking[fun.__name__]) > 0: logger.info("Caching output of %s.%s", self, fun.__name__) self._caches[fun.__name__] = (data_ptr, output) logger.debug("%s._caches=%s", self, self._caches) # pylint: enable=protected-access return output return cache_decorator class Spec(Component): """A component that stores experiment-independent parameters. The forward implementation should be left to the experiment-specific implementation (either a Layer or Cooperativity component). """ @override def components(self) -> Iterator[Component]: return iter(()) def update_binding_optim( self, binding_optim: BindingOptim ) -> BindingOptim: """Updates a BindingOptim with the specification's optimization steps. Args: binding_optim: The parent BindingOptim to be updated. Returns: The updated BindingOptim. """ return binding_optim class Binding(Transform, abc.ABC): """Abstract base class for binding modes and binding cooperativity. Each Binding component links a specification storing experiment-independent parameters with the matching experiment and its specific parameters. """ @abc.abstractmethod def key(self) -> tuple[Spec, ...]: """The specification of a Binding component. All Binding components with the same specification will be optimized together in the sequential optimization procedure. """ @abc.abstractmethod def expected_sequence(self) -> Tensor: """Uninformative prior of input, used for calculating expectations.""" def expected_log_score(self) -> float: """Calculates the expected log score.""" with torch.inference_mode(): training = self.training self.eval() out = self(self.expected_sequence()) self.train(training) return out.item() @abc.abstractmethod def score_windows(self, seqs: Tensor) -> Tensor: r"""Calculates the score of each window before summing over them. Args: seqs: A sequence tensor of shape :math:`(\text{minibatch},\text{length})` or :math:`(\text{minibatch},\text{in_channels},\text{length})`. Returns: A tensor with the score of each window. """
using System.ComponentModel.DataAnnotations; namespace WebApplication6.Models { public class EmployeeModel { [Key] public int Empid { get; set; } [Required(ErrorMessage ="Enter Employee Name")] [Display(Name ="Employee Name")] public string Empname { get; set; } [Required(ErrorMessage = "Enter Email")] [Display(Name = "Email")] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Required(ErrorMessage = "Enter Employee Age")] [Display(Name = "Age")] [Range(20,50)] public int Age { get; set; } [Required(ErrorMessage = "Enter Employee Salary")] [Display(Name = "Salary")] public int Salary { get; set; } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>LayOut</title> <style> .bar{ width:100%; height:50px; border:1px solid; } li{ list-style: none; } .bar a{ display: inline-block; float:right; text-align:center; color:white; line-height: 50px; cursor:pointer; } .bar a.list-icon{ width:50px; height:50px; background:red; } .bar a.grid-icon{ width:50px; height:50px; background:blue; } ul.grid{ width:570px; margin:0 auto; text-align:left; } ul.grid li{ padding:2px; float:left; } ul.grid li img{ width:280px; height:280px; display: block; border:none; } ul.list{ width:500px; margin:0 auto; text-align: left; } ul.list li{ border-bottom:1px solid #ddd; padding:10px; overflow: hidden; } ul.list li img{ width:120px; height:120px; float:left; border:none; } ul.list li p{ margin-left: 135px; font-weight: bold; color:#6e7a7f; } </style> </head> <body> <div id="main" v-cloak> <div class="bar"> <a class="grid-icon" v-bind:class="{ 'active': layout == 'grid'}" v-on:click="layout = 'grid'">grid</a> <a class="list-icon" v-bind:class="{ 'active': layout == 'list'}" v-on:click="layout = 'list'">list</a> </div> <ul v-if="layout == 'grid'" class="grid"> <li v-for="item in items"> <a v-bind:href="item.url" target="_blank"><img v-bind:src="item.image.large" /></a> </li> </ul> <ul v-if="layout == 'list'" class="list"> <li v-for="item in items"> <a v-bind:href="item.url" target="_blank"><img v-bind:src="item.image.small" /></a> <p>{{item.title}}</p> </li> </ul> </div> </body> <script src="https://cdn.bootcss.com/vue/2.5.13/vue.min.js"></script> <script> var demo = new Vue({ el: '#main', data: { layout: 'grid', items: [{ "title": "What You Need To Know About CSS Variables", "url": "http://tutorialzine.com/2016/03/what-you-need-to-know-about-css-variables/", "image": { "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/03/css-variables.jpg", "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/03/css-variables-150x150.jpg" } }, { "title": "Freebie: 4 Great Looking Pricing Tables", "url": "http://tutorialzine.com/2016/02/freebie-4-great-looking-pricing-tables/", "image": { "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/great-looking-pricing-tables.jpg", "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/great-looking-pricing-tables-150x150.jpg" } }, { "title": "20 Interesting JavaScript and CSS Libraries for February 2016", "url": "http://tutorialzine.com/2016/02/20-interesting-javascript-and-css-libraries-for-february-2016/", "image": { "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/interesting-resources-february.jpg", "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/interesting-resources-february-150x150.jpg" } }, { "title": "Quick Tip: The Easiest Way To Make Responsive Headers", "url": "http://tutorialzine.com/2016/02/quick-tip-easiest-way-to-make-responsive-headers/", "image": { "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/quick-tip-responsive-headers.png", "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/02/quick-tip-responsive-headers-150x150.png" } }, { "title": "Learn SQL In 20 Minutes", "url": "http://tutorialzine.com/2016/01/learn-sql-in-20-minutes/", "image": { "large": "http://cdn.tutorialzine.com/wp-content/uploads/2016/01/learn-sql-20-minutes.png", "small": "http://cdn.tutorialzine.com/wp-content/uploads/2016/01/learn-sql-20-minutes-150x150.png" } }, { "title": "Creating Your First Desktop App With HTML, JS and Electron", "url": "http://tutorialzine.com/2015/12/creating-your-first-desktop-app-with-html-js-and-electron/", "image": { "large": "http://cdn.tutorialzine.com/wp-content/uploads/2015/12/creating-your-first-desktop-app-with-electron.png", "small": "http://cdn.tutorialzine.com/wp-content/uploads/2015/12/creating-your-first-desktop-app-with-electron-150x150.png" } }] } }); </script> </html>
import React, {useState, useEffect} from "react"; const ProfileStatusWithHooks = (props) => { let [editMode, setEditMode] = useState(false) let [status, setStatus] = useState(props.status) useEffect( () => { setStatus(props.status) }, [props.status]) const activateEditMode = () => { setEditMode(true) } const deactivateEditMode = () => { setEditMode(false) props.updateStatus(status) } const onChangeStatus = (e) => { setStatus(e.currentTarget.value) } return <div> {!editMode && <div> <span onDoubleClick={activateEditMode}>{props.status || '-----'}</span> </div>} {editMode && <div> <input onChange={onChangeStatus} onBlur={deactivateEditMode} autoFocus={true} value={status}/> </div>} </div> } export default ProfileStatusWithHooks;
import SwiftUI struct TictactoeView: View { @StateObject private var viewModel = GameViewModel() var body: some View { ZStack { ThemeListView().vectorView LazyVGrid(columns: viewModel.columns) { ForEach(0..<9) { i in ZStack { RoundedRectangle(cornerRadius: 25) .fill(viewModel.mainColor) .frame(width: 100, height: 100) Image(systemName: viewModel.moves[i]?.indicator ?? "") .resizable() .frame(width: 40, height: 40) .foregroundStyle(viewModel.gradientColor) } .onTapGesture { viewModel.playerMove(for: i) } } .navigationTitle("TicTacToe") } .navigationBarItems(trailing: Button(action: { viewModel.resetGame() }, label: { Image(systemName: "arrow.clockwise").imageScale(.large) })) } .padding(5) .disabled(viewModel.isGameboardDisabled) .alert(item: $viewModel.alertItem, content: { alertItem in Alert(title: alertItem.title, message: alertItem.message, dismissButton: .default(alertItem.buttonTitle, action: {viewModel.resetGame()} )) }) .background(Color(red: 233.0/255, green: 233.0/255, blue: 233.0/255).ignoresSafeArea()) } } enum Player { case human, computer } struct Move { let player: Player let boardIndex: Int var indicator: String { return player == .human ? "xmark" : "circle" } } struct TictactoeView_Preview: PreviewProvider { static var previews: some View { TictactoeView() } }
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) import os import spack.util.spack_json as sjson from spack import * def sanitize_environments(*args): for env in args: for var in ( "PATH", "CET_PLUGIN_PATH", "LDSHARED", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "LIBRARY_PATH", "CMAKE_PREFIX_PATH", "ROOT_INCLUDE_PATH", ): env.prune_duplicate_paths(var) env.deprioritize_system_paths(var) class Nurandom(CMakePackage): """Random number generator interfaces to art.""" homepage = "https://cdcvs.fnal.gov/redmine/projects/nurandom" git_base = "https://github.com/NuSoftHEP/nurandom.git" url = "https://github.com/NuSoftHEP/nurandom/archive/refs/tags/v1_07_06.tar.gz" list_url = "https://api.github.com/repos/NuSoftHEP/nurandom/tags" version("1.10.02", sha256="9010dc663d08ee3c7451a7c423f2350a77fe98f3de8bfd4cbd9a5bdcb67c6114") version("1.10.01", sha256="6f491b2b71f009f6e42caa259672763c4344cdfc0dffedaaa48cee7e58298ec7") version("1.08.00", sha256="f7ffa502bf2088ac1a9b974e6c57b8cc6d0ba07730174ea0f45b89810bc04411") version("1.07.06", sha256="85a6b595bd1b6b2873ebc726e0d4031570dc12897632cdb7d2a8fb5c16954cb5") version("mwm1", tag="mwm1", git=git_base, get_full_repo=True) version( "develop", commit="feb2c214ffec9dd2e9a1b3c7e02f2315f3ec9666", git=git_base, get_full_repo=True, ) def url_for_version(self, version): url = "https://github.com/NuSoftHEP/{0}/archive/v{1}.tar.gz" return url.format(self.name, version.underscored) def fetch_remote_versions(self, concurrency=None): return dict( map( lambda v: (v.dotted, self.url_for_version(v)), [ Version(d["name"][1:]) for d in sjson.load( spack.util.web.read_from_url( self.list_url, accept_content_type="application/json" )[2] ) if d["name"].startswith("v") ], ) ) variant( "cxxstd", default="17", values=("14", "17", "20"), multi=False, description="Use the specified C++ standard when building.", ) # Build-only dependencies. depends_on("cetmodules", type="build") depends_on("cetbuildtools", type="build") depends_on("art") depends_on("art-root-io") depends_on("cetlib") depends_on("cetlib-except") depends_on("clhep") patch("cetmodules2.patch", when="@develop") patch("v1_07_06.patch", when="@1.07.06") def cmake_args(self): # Set CMake args. args = ["-DCMAKE_CXX_STANDARD={0}".format(self.spec.variants["cxxstd"].value)] return args def setup_build_environment(self, spack_env): # Binaries. spack_env.prepend_path("PATH", os.path.join(self.build_directory, "bin")) # Ensure we can find plugin libraries. spack_env.prepend_path("CET_PLUGIN_PATH", os.path.join(self.build_directory, "lib")) spack_env.prepend_path("CET_PLUGIN_PATH", self.prefix.lib) # Ensure Root can find headers for autoparsing. for d in self.spec.traverse( root=False, cover="nodes", order="post", deptype=("link"), direction="children" ): spack_env.prepend_path("ROOT_INCLUDE_PATH", str(self.spec[d.name].prefix.include)) # Perl modules. spack_env.prepend_path("PERL5LIB", os.path.join(self.build_directory, "perllib")) # Cleaup. sanitize_environments(spack_env) def setup_run_environment(self, run_env): # Ensure we can find plugin libraries. run_env.prepend_path("CET_PLUGIN_PATH", self.prefix.lib) # Ensure Root can find headers for autoparsing. for d in self.spec.traverse( root=False, cover="nodes", order="post", deptype=("link"), direction="children" ): run_env.prepend_path("ROOT_INCLUDE_PATH", str(self.spec[d.name].prefix.include)) run_env.prepend_path("ROOT_INCLUDE_PATH", self.prefix.include) # Perl modules. run_env.prepend_path("PERL5LIB", os.path.join(self.prefix, "perllib")) # Cleaup. sanitize_environments(run_env) def setup_dependent_build_environment(self, spack_env, dependent_spec): # Binaries. spack_env.prepend_path("PATH", self.prefix.bin) # Ensure we can find plugin libraries. spack_env.prepend_path("CET_PLUGIN_PATH", self.prefix.lib) # Ensure Root can find headers for autoparsing. spack_env.prepend_path("ROOT_INCLUDE_PATH", self.prefix.include) # Perl modules. spack_env.prepend_path("PERL5LIB", os.path.join(self.prefix, "perllib")) # Cleanup. sanitize_environments(spack_env) def setup_dependent_run_environment(self, run_env, dependent_spec): # Binaries. run_env.prepend_path("PATH", self.prefix.bin) # Ensure we can find plugin libraries. run_env.prepend_path("CET_PLUGIN_PATH", self.prefix.lib) # Ensure Root can find headers for autoparsing. run_env.prepend_path("ROOT_INCLUDE_PATH", self.prefix.include) # Perl modules. run_env.prepend_path("PERL5LIB", os.path.join(self.prefix, "perllib")) # Cleanup. sanitize_environments(run_env)
* This file holds all of the character specific data for your class, as * well as some shop related data for buying items and utility * the appropriate ACS file. * * many of the files below need to bare the name of the * class they are associated with in order to properly work. actor Blake : ClassBase { Player.displayname "Blake" player.startitem "IsBlake" player.startitem "BusterPower", 1000 player.startitem "SetupShop" player.startitem "LoadShopInventory" player.startitem "RoundSignatureGive" player.startitem "Blake_ClassSet" states { Spawn: HMEG A 0 HMEG B 1 HMEG A 1 Goto Spawn+2 See: HMEG BCDE 5 Goto Spawn Missile: HMEG F 5 HMEG G 4 goto Spawn } } Actor IsBlake : Once{} * The Following constants dictate the maximum number of * "charges" one can have on each ability at any given time, * These constants are used for the shop item and a few scripts Const int Cap_BombSlide = 1; Const int Cap_BombLay = 2; Const int Cap_BlakeOut = 1; * This constant is relevant for Signature abilities that * rely on kills to recharge, it determines how many kills * you need to gain a new charge on that round Const int Blake_SigKillCap = 2; * The [Class]starterset is given to you the first * time you spawn into the game, typically this gives you * the Zapper and a single charge to your signature ability actor BlakeStarterSet : CustomInventory { states { Pickup: TNT1 A 0 A_GiveInventory("Zapper",1) TNT1 A 0 ACS_NamedExecuteAlways("GiveSignatureCharge",0,Cap_BombSlide) TNT1 A 0 Done: TNT1 A 0 stop } } * The [Class]_Melee is what gives you your melee weapon, while * all classes use the same pool of guns, they can bring their * own melee weapon, though they can only differ in appearance actor Blake_Melee : CustomInventory { states { Pickup: TNT1 A 0 A_GiveInventory("BlakeMelee",1) TNT1 A 0 Done: TNT1 A 0 stop } } * The [Class}_ClassSet is given to the class every time * they spawn and respawn, it contains necessary inventory * items and scripts they need to initialize everytime * this class comes into play. generally the following * are required: * * Ability[1-3]_ChargeFlag : identifies that this ability * uses individual charges * Ability[1-3]_ResourceFlag : identifies that this ability * uses a gradual resource * AbilityChargeCap_[1-3] : Defines the max number of * Charges this ability is able to have * UseAbility[1-3]_[Class] : The name of the custominventories * That initiate that given ability when triggered. * SignatureKillRecharge : A flag that states this class * Recharges their signature ability through kills. * SignatureKillCap : Establishes how many kills are * needed to regain a new charge of your signature. * actor Blake_ClassSet : CustomInventory { states { Pickup: TNT1 A 0 A_GiveInventory("UseAbility1_Blake",1) TNT1 A 0 A_GiveInventory("Ability1_ChargeFlag",1) TNT1 A 0 A_GiveInventory("AbilityChargeCap_1",Cap_BombSlide) TNT1 A 0 A_GiveInventory("SignatureKillRecharge",1) TNT1 A 0 A_GiveInventory("SignatureKillCap",Blake_SigKillCap) //== TNT1 A 0 A_GiveInventory("UseAbility2_Blake",1) TNT1 A 0 A_GiveInventory("Ability2_ChargeFlag",1) TNT1 A 0 A_GiveInventory("AbilityChargeCap_2",Cap_BombLay) //== TNT1 A 0 A_GiveInventory("UseAbility3_Blake",1) TNT1 A 0 A_GiveInventory("Ability3_ChargeFlag",1) TNT1 A 0 A_GiveInventory("AbilityChargeCap_3",Cap_BlakeOut) TNT1 A 0 Done: TNT1 A 0 stop } } * These are actors that handle the function of the * Class's specific shop for purchasing their abilities, * the [Class}_ClassShop supplies the function actors * needed to perform the purchase, and the Cost_[AbilityName] * constants are used to set the price of a given ability * in the shop. actor Blake_ClassShop : CustomInventory { states { Pickup: TNT1 A 0 A_GiveInventory("BuyBlakeOut",1) TNT1 A 0 A_GiveInventory("BuyBombLay",1) TNT1 A 0 A_GiveInventory("BuyBlakeOut",1) stop } } Const int Cost_BombSlide = 150; Const int Cost_BombLay = 250; Const int Cost_BlakeOut = 350; actor BuyBombSlide : BuyThing { states { Use1: TNT1 A 0 A_JumpIf(CallACS("CashCheck",Cost_BombSlide),"Use2") goto NoMoney CostPay: TNT1 A 0 ACS_NamedExecuteWithResult("CashPay",Cost_BombSlide) goto BuySuccess //=== Use2: TNT1 A 0 A_JumpIfInventory("AbilityCharge_1",Cap_BombSlide,"FullCapacity") TNT1 A 0 A_GiveInventory("AbilityCharge_1",1) TNT1 A 0 ACS_NamedExecuteAlways("Write_Inventory",0) goto CostPay } } actor BuyBombLay : BuyThing { states { Use1: TNT1 A 0 A_JumpIf(CallACS("CashCheck",Cost_BombLay),"Use2") goto NoMoney CostPay: TNT1 A 0 ACS_NamedExecuteWithResult("CashPay",Cost_BombLay) goto BuySuccess //=== Use2: TNT1 A 0 A_JumpIfInventory("AbilityCharge_2",Cap_BombLay,"FullCapacity") TNT1 A 0 A_GiveInventory("AbilityCharge_2",1) TNT1 A 0 ACS_NamedExecuteAlways("Write_Inventory",0) goto CostPay } } actor BuyBlakeOut : BuyThing { states { Use1: TNT1 A 0 A_JumpIf(CallACS("CashCheck",Cost_BlakeOut),"Use2") goto NoMoney CostPay: TNT1 A 0 ACS_NamedExecuteWithResult("CashPay",Cost_BlakeOut) goto BuySuccess //=== Use2: TNT1 A 0 A_JumpIfInventory("AbilityCharge_3",Cap_BlakeOut,"FullCapacity") TNT1 A 0 A_GiveInventory("AbilityCharge_3",1) TNT1 A 0 ACS_NamedExecuteAlways("Write_Inventory",0) goto CostPay } }
import "./styles.css"; import { useContext, useRef } from "react"; import coinData from "../../contexts/coinData"; function Popup() { let { state, dispatch } = useContext(coinData); let selected = state.selected let inputValue = state.inputValue function getMaxValue() { if (selected === "buy") { return state.wallet !== 0 ? state.wallet / state.currentSelected.price : 0; } else { let foundCount = state.currentHoldingArr.find((e) => { if (e.coinName === state.currentSelected.coinName) { return e.count; } return e }); return foundCount ? foundCount.count : 0; } } let ref = useRef(); return ( <div className="pop-up"> {state.currentSelected === null ? ( "" ) : ( <> <div className="header"> <h4> {selected === "sell" ? "Sell" : "Buy"} {state.currentSelected.coinName} </h4> <h4 onClick={() => { dispatch({ type: "popUp-toggle" }) ref.current.value = ''; dispatch({ type: 'update-selected', payload: 'buy' }) }} style={{ cursor: "pointer" }}> ☓ </h4> </div> <p>Current Price:${state.currentSelected.price}</p> <div className="input-container"> <input ref={ref} type="number" name="input" id="input" onChange={() => dispatch({ type: 'update-inputValue', payload: ref.current.value })} required /> {inputValue !== undefined ? <p>You will {selected === 'buy' ? 'Pay' : 'Receive'} {state.currentSelected.price * inputValue}</p> : ''} <label htmlFor="input" onClick={() => { ref.current.value = getMaxValue(); dispatch({ type: 'update-inputValue', payload: ref.current.value }) }} > Max {getMaxValue()} </label> </div> <div className="buy-sell"> <div> <input type="radio" name="radio-btn" id="btn1" checked={selected === "buy" ? true : false} onClick={() => { dispatch({ type: 'update-selected', payload: 'buy' }) }} /> <label htmlFor="btn1">Buy</label> </div> <div> <input type="radio" name="radio-btn" id="btn2" checked={selected === "buy" ? false : true} onClick={() => { dispatch({ type: 'update-selected', payload: 'sell' }) }} /> <label htmlFor="btn2">Sell</label> </div> </div> <button style={{ opacity: (inputValue <= getMaxValue() && 0 !== getMaxValue()) ? '1' : '0.5' }} onClick={() => { if (((state.transactionArr.find((ele) => ele.coinName === state.currentSelected.coinName) && inputValue <= getMaxValue()) || (selected === "buy" && state.wallet >= inputValue * state.currentSelected.price)) && getMaxValue() !== 0) { dispatch({ type: selected, payload: { coinName: state.currentSelected.coinName, price: state.currentSelected.price, time: new Date().toLocaleString(), count: inputValue, typeofTransaction: selected } }); dispatch({ type: "popUp-toggle" }); } ref.current.value = ''; }} > {selected === "sell" ? "SELL" : "BUY"} </button> </> )} </div> ); } export default Popup;
package HashTab; import java.util.Scanner; public class HashTabDemo { public static void main(String[] args) { //创建一个哈希表 HashTab hashTab = new HashTab(7); String key = ""; Scanner scanner = new Scanner(System.in); while (true){ System.out.println("add: 添加雇员"); System.out.println("list: 显示雇员"); System.out.println("find: 查找雇员"); System.out.println("del:删除雇员"); System.out.println("exit: 退出系统"); key = scanner.next(); switch (key){ case "add": System.out.println("输入id"); int id = scanner.nextInt(); System.out.println("输入名字"); String name = scanner.next(); Emp emp = new Emp(id,name); hashTab.add(emp); break; case "list": hashTab.list(); break; case "find": System.out.println("请输入要查找的id"); id = scanner.nextInt(); hashTab.findEmpById(id); break; case "del": System.out.println("请输入要删除的id"); id = scanner.nextInt(); hashTab.delEmp(id); break; case "exit": scanner.close(); System.exit(0); default: break; } } } } //创建哈希表 管理多条链表 class HashTab{ private EmpLinkedList[] empLinkedListArray; private int size;//表示有多少条链表 //构造器 public HashTab(int size){ this.size = size; empLinkedListArray=new EmpLinkedList[size]; for (int i = 0; i < size; i++) { empLinkedListArray[i] = new EmpLinkedList(); } } //添加员工 public void add(Emp emp){ //根据员工id 得到员工应该添加到哪条链表 int empLinkedListNO = hashFun(emp.id); //将emp 添加到对应链表中 empLinkedListArray[empLinkedListNO].add(emp); } //查找 public void findEmpById(int id){ //使用散列函数确定哪条链表查找 int empLinkedListNO = hashFun(id); Emp emp = empLinkedListArray[empLinkedListNO].findEmpById(id); if (emp != null){ //找到 System.out.printf("在第%d条链表中找到 雇员 id = id = %d\n",(empLinkedListNO+1),id); }else { System.out.println("未找到"); } } //遍历所有的链表 数组加链表==》哈希表 public void list(){ for (int i = 0;i<size;i++){ empLinkedListArray[i].list(i); } } public void delEmp(int id){ int empLinkedListNo = hashFun(id); empLinkedListArray[empLinkedListNo].del(id); } //编写散列函数 取模法 public int hashFun(int id){ return id % size; } } class Emp{ public int id; public String name; public Emp next;//next 默认为空 public Emp(int id, String name) { super(); this.id = id; this.name = name; } } //创建EmpLinkedList,表示链表 class EmpLinkedList{ //头指针执行第一个Emp 链表的head 指向第一个Emp private Emp head;//默认null //添加雇员到链表 假定添加雇员 到链表最后 public void add(Emp emp){ if (head == null){ head = emp; return; } //如果不是第一个雇员 借助辅助指针 Emp curEmp = head; while (true){ if (curEmp.next == null){ break;//链表到最后 } curEmp = curEmp.next;//后移 } //退出时直接将emp 加入链表 curEmp.next=emp; } //遍历链表 public void list(int no){ if (head == null){ System.out.println("第"+(no+1)+"链表为空"); return; } System.out.print("第"+(no+1)+"链表信息为:"); Emp curEmp = head;//辅助指针 while (true){ System.out.printf("=> id=%d name=%s\t",curEmp.id,curEmp.name); if (curEmp.next == null){ break; } curEmp = curEmp.next;//后移遍历 } System.out.println(); } //根据id查找雇员 找到返回Emp 没有 返回null public Emp findEmpById(int id){ //先判断链表是否为空 if (head == null){ System.out.println("链表为空"); return null; } //辅助指针 Emp curEmp = head; while (true){ if (curEmp.id == id){ break;//找到 } if (curEmp.next == null){ //说明遍历当前链表没有找到该员工 curEmp = null; break; } curEmp = curEmp.next;//后移 } return curEmp; } //删除输入的id对应的雇员信息 public void del(int id){ if(head==null){ System.out.println("链表为空,无法删除"); return; } if (head.id==id){ if(head.next==null){ head=null; }else { head = head.next; } return; } Emp curEmp = head; boolean flag = false; while (true){ if(curEmp.next==null){ break; } if (curEmp.next.id==id){ flag=true; break; } curEmp = curEmp.next; } if (flag){ curEmp.next = curEmp.next.next; }else { System.out.println("要删除的节点不存在"); } } }
package com.mycompany.myapp.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.*; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A Customer. */ @Entity @Table(name = "customer") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @SuppressWarnings("common-java:DuplicatedBlocks") public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator") @SequenceGenerator(name = "sequenceGenerator") @Column(name = "id") private Long id; @OneToOne @JoinColumn(unique = true) private User user; @OneToMany(mappedBy = "customer") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @JsonIgnoreProperties(value = { "commandItems", "customer", "address" }, allowSetters = true) private Set<Command> commands = new HashSet<>(); @OneToMany(mappedBy = "customer") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @JsonIgnoreProperties(value = { "commands", "customer" }, allowSetters = true) private Set<Address> addresses = new HashSet<>(); // jhipster-needle-entity-add-field - JHipster will add fields here public Long getId() { return this.id; } public Customer id(Long id) { this.setId(id); return this; } public void setId(Long id) { this.id = id; } public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } public Customer user(User user) { this.setUser(user); return this; } public Set<Command> getCommands() { return this.commands; } public void setCommands(Set<Command> commands) { if (this.commands != null) { this.commands.forEach(i -> i.setCustomer(null)); } if (commands != null) { commands.forEach(i -> i.setCustomer(this)); } this.commands = commands; } public Customer commands(Set<Command> commands) { this.setCommands(commands); return this; } public Customer addCommands(Command command) { this.commands.add(command); command.setCustomer(this); return this; } public Customer removeCommands(Command command) { this.commands.remove(command); command.setCustomer(null); return this; } public Set<Address> getAddresses() { return this.addresses; } public void setAddresses(Set<Address> addresses) { if (this.addresses != null) { this.addresses.forEach(i -> i.setCustomer(null)); } if (addresses != null) { addresses.forEach(i -> i.setCustomer(this)); } this.addresses = addresses; } public Customer addresses(Set<Address> addresses) { this.setAddresses(addresses); return this; } public Customer addAddresses(Address address) { this.addresses.add(address); address.setCustomer(this); return this; } public Customer removeAddresses(Address address) { this.addresses.remove(address); address.setCustomer(null); return this; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Customer)) { return false; } return id != null && id.equals(((Customer) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Customer{" + "id=" + getId() + "}"; } }
---json { "description": "boldness is a typographic effect that sets the font weight. It defines the width of a character outlines relative to its height. It's also known as strongness.", "page_id": "dd0i74454dynry3c00imf", "title": "How to set the Boldness (Font Weight \/ Strong)" } --- ====== ComboStrap Styling - Boldness (Font Weight) ====== ===== About ===== ''boldness'' is a [[docs:content:typo|typographic effect]] that sets the [[docs:styling:font|font]] weight. It defines the width of a character outlines relative to its height. ===== Syntax ===== ==== Double Star ==== With the ''double star'', you can set quickly the font weight (boldness) to the value ''bold'' Example: <webcode name="Default" frameborder="0"> * Input <code dw> This text is a **bold text**. </code> * Output: </webcode> \\ \\ <note warning> You cannot use this syntax with only space before it on a line because it will be seen as a [[:docs:lists:list|list element]]. </note> ==== Name or numerical Value ==== You can also set a precise value with the [[docs:content:typo|typographic attribute]] ''boldness'' that accepts a name or a numerical value. The following names are supported and any numerical value. ^ Name ^ Numerical values ^ | ''Thin'' | 100 | | ''Extra-light'' | 200 | | ''Light'' | 300 | | ''Normal'' | 400 | | ''Medium'' | 500 | | ''Semi-bold'' | 600 | | ''Bold'' | 700 | | ''Extra-bold'' | 800 | | ''Black'' | 900 | | ''Extra-black'' | 950 | Example with the [[docs:content:itext|itext component]] <webcode name="Default" frameborder="0"> * Input <code dw> This text is a <itext boldness="black">black text</itext> </code> * Output: </webcode> ==== Superlatif (More or less than) ==== You can also set a superlatif that is set according to the ''boldness'' of the parent. We accepts the following values: * ''bolder'': bolder than the parent * ''lighter'': lighter than the parent Example with the [[docs:block:text|text component]] <webcode name="Default" frameborder="0"> * Input <code dw> <text boldness="light"> This text is a <itext boldness="bolder">bolder text</itext> </text> </code> * Output: </webcode>
import { ChangeDetectorRef, Component, ElementRef, Injectable, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { MatDatepicker } from '@angular/material/datepicker'; import { WsLoading } from '@elements/ws-loading/ws-loading'; import { Phase } from '@objects/phase'; import { Moment } from 'moment'; import * as moment from 'moment'; import _ from 'lodash'; import { interval, Subject, Subscription, timer } from 'rxjs'; import { environment } from '@environments/environment'; import * as braintree from 'braintree-web'; import { ViewChild } from '@angular/core'; import { WsToastService } from '@elements/ws-toast/ws-toast.service'; import { AuthAdvertisementContributorService } from '@services/http/auth-store/contributor/auth-advertisement-contributor.service'; import { finalize, switchMap, takeUntil } from 'rxjs/operators'; import { NativeDateAdapter, DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '@angular/material/core'; import { URLValidator } from '@validations/url.validator'; import { SharedStoreService } from '@services/shared/shared-store.service'; import { DocumentHelper } from '@helpers/documenthelper/document.helper'; import { AdsConfiguration } from '@objects/server-configuration'; import { Store } from '@objects/store'; import { HttpClient } from '@angular/common/http'; import { UploadHelper } from '@helpers/uploadhelper/upload.helper'; import { AuthOnSellingCategoryContributorService } from '@services/http/auth-store/contributor/auth-on-selling-category-contributor.service'; @Injectable() export class CustomDateAdapter extends NativeDateAdapter { getFirstDayOfWeek(): number { return 1; } } @Component({ selector: 'app-advertising', templateUrl: './advertising.component.html', styleUrls: ['./advertising.component.scss'], providers: [{provide: DateAdapter, useClass: CustomDateAdapter }, { provide: MAT_DATE_LOCALE, useValue: 'en-GB' }] }) export class AdvertisingComponent implements OnInit { store: Store; advertisings = []; loading: WsLoading = new WsLoading(); analysisLoading: WsLoading = new WsLoading(); editingAdsLoading: WsLoading = new WsLoading(); submitLoading: WsLoading = new WsLoading(); isModifyAdvertisingModalOpened: boolean; isAdvertisementModalOpened: boolean; isDisplayAdvertisementExample: boolean; isAdvertisingPolicyOpened: boolean; isEditAdvertisementOpened: boolean; isAdsFree: boolean = false; phase: Phase<number> = new Phase(0, 4); selectedAdvertisement; minDate = new Date; isAcceptAgreement: boolean; isAdvertisementEnabledModalOpened: boolean; isAdvertisementDisabledModalOpened: boolean; confirmationLoading: WsLoading = new WsLoading(); configLoading: WsLoading = new WsLoading(); paymentLoading: WsLoading = new WsLoading(); adsConfiguration: AdsConfiguration; configuration = this.getConfiguration(); maxWidth: number = 800; week: number = 0; totalAmount: number = 0; environment = environment; today: Date = new Date; availableAdvertisementsDates = {}; advertisingPolicy = ''; REFRESH_ADVERTISEMENT_INTERVAL = 2 * 60 * 1000; exampleImages = []; private ngUnsubscribe: Subject<any> = new Subject(); @ViewChild('picker') datepicker: MatDatepicker<any>; @ViewChild('submit', {static: false}) submit: ElementRef; dateFilter = (d: Date | null): boolean => { const day = (d || new Date()).getDay(); let isBetweenDates = true; if (this.isAdsFree) { // Only available for 1 week if it is free advertisement isBetweenDates = moment(d || new Date()) < moment(this.configuration.startDate).add(8, 'days'); } if (this.configuration.startDate) { const date = moment(d || new Date()).subtract(6, 'days').format('YYYY/MM/DD'); return day === 0 && this.availableAdvertisementsDates[date] > 0 && d > new Date(this.configuration.startDate) && isBetweenDates; } else { const date = moment(d || new Date()).format('YYYY/MM/DD'); return day === 1 && this.availableAdvertisementsDates[date] > 0; } } constructor(private ref: ChangeDetectorRef, private http: HttpClient, private uploadHelper: UploadHelper, private sharedStoreService: SharedStoreService, private authOnSellingCategoryContributorService: AuthOnSellingCategoryContributorService, private authAdvertisementContributorService: AuthAdvertisementContributorService) { this.sharedStoreService.store.pipe(takeUntil(this.ngUnsubscribe)) .subscribe(result => { if (result) { DocumentHelper.setWindowTitleWithWonderScale('Advertising - ' + result.name); this.store = result; } }) } ngOnInit(): void { this.getAdvertisements(true); this.refreshAdvertisements(); this.minDate = moment().startOf('isoWeek').add(1, 'week').toDate(); } getNumberOfPublishedItems() { this.authOnSellingCategoryContributorService.getNumberOfPublishedItems().pipe(takeUntil(this.ngUnsubscribe)).subscribe(result => { this.store.numberOfPublishedItems = result['result']; }); } createBraintreeClient() { this.ref.detectChanges(); this.paymentLoading.start(); braintree.client.create({ authorization: environment.BRAINTREE_AUTHORIZATION }, (clientErr, clientInstance) => { if (clientErr) { return; } var options = { client: clientInstance, styles: { input: { 'font-size': '14px' }, 'input.invalid': { color: 'red' }, 'input.valid': { color: 'green' } }, fields: { cardholderName: { selector: '#cardholder-name', placeholder: 'John Doe' }, number: { selector: '#card-number', placeholder: '4111 1111 1111 1111' }, cvv: { selector: '#cvv', placeholder: '123' }, expirationDate: { selector: '#expiration-date', placeholder: '10/' + (new Date().getFullYear() + 3) } } } this.createHostedFields(options); }); } createHostedFields(options) { braintree.hostedFields.create(options, (hostedFieldsErr, hostedFieldsInstance) => { if (hostedFieldsErr) { // WsToastService.toastSubject.next({ content: hostedFieldsErr.message, type: 'danger'}); console.error(hostedFieldsErr); return; } if (this.submit.nativeElement) { this.submit.nativeElement.addEventListener('click', (event) => { event.preventDefault(); this.submit.nativeElement.disabled = true; hostedFieldsInstance.tokenize((tokenizeErr, payload) => { if (tokenizeErr) { this.submit.nativeElement.disabled = false; WsToastService.toastSubject.next({ content: tokenizeErr.message, type: 'danger'}); return; } this.placeorder(payload); }); }, false); this.paymentLoading.stop(); } }); } placeorder(payload) { let obj = { ...this.configuration, amount: this.totalAmount, isAdsFree: this.isAdsFree }; if (payload) { obj['paymentMethodNonce'] = payload.nonce; } this.submitLoading.start(); this.authAdvertisementContributorService.addAdvertisement(obj).pipe(takeUntil((this.ngUnsubscribe)), finalize(() => { if (this.submit?.nativeElement) { this.submit.nativeElement.disabled = false; } this.submitLoading.stop(); })).subscribe(result => { if (result && result['result']) { this.isModifyAdvertisingModalOpened = false; this.getAdvertisements(); WsToastService.toastSubject.next({ content: 'Wait for the approval.<br/>It will take 1-2 days.<br/>Payment will not be proceed until it is approved.', type: 'success'}); } else if (result && !result['result'] && result['message']) { WsToastService.toastSubject.next({ content: result['message'], type: 'danger'}); } else { WsToastService.toastSubject.next({ content: 'The selected date is full, kindly select other date.', type: 'danger'}); } }, err => { WsToastService.toastSubject.next({ content: err.error, type: 'danger'}); }); } editAdvertisement() { this.submitLoading.start(); this.authAdvertisementContributorService.editAdvertisement(this.configuration).pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.submitLoading.stop())).subscribe(result => { if (result && result['result']) { this.isEditAdvertisementOpened = false; this.getAdvertisements(); WsToastService.toastSubject.next({ content: 'Wait for the approval.<br/>It will take 1-2 days.<br/>Payment will not be proceed until it is approved.', type: 'success'}); } else if (result && !result['result'] && result['message']) { WsToastService.toastSubject.next({ content: result['message'], type: 'danger'}); } else { WsToastService.toastSubject.next({ content: 'Server Error!<br/>Kindly contact the admin!', type: 'danger' }); } }, err => { WsToastService.toastSubject.next({ content: err.error, type: 'danger' }); }); } getAvailableAdvertisements() { let obj = { type: this.configuration.type, timezone: new Date().getTimezoneOffset() } this.authAdvertisementContributorService.getAvailableAdvertisementDates(obj).pipe(takeUntil(this.ngUnsubscribe)).subscribe(result => { this.availableAdvertisementsDates = result['result']; }); } getAdvertisementAmount() { let advertisementAmount = 0; switch (this.configuration.type) { case 'pop-out': advertisementAmount = this.adsConfiguration.advertisementPopOutAmount * (100 - this.adsConfiguration?.advertisementDiscountPercentage) / 100; break; case 'large': advertisementAmount = this.adsConfiguration.advertisementBannerLargeAmount * (100 - this.adsConfiguration?.advertisementDiscountPercentage) / 100; break; case 'medium': advertisementAmount = this.adsConfiguration.advertisementBannerMediumAmount * (100 - this.adsConfiguration?.advertisementDiscountPercentage) / 100; break; case 'small': advertisementAmount = this.adsConfiguration.advertisementBannerSmallAmount * (100 - this.adsConfiguration?.advertisementDiscountPercentage) / 100; break; case 'square': advertisementAmount = this.adsConfiguration.advertisementBannerSquareAmount * (100 - this.adsConfiguration?.advertisementDiscountPercentage) / 100; break; } advertisementAmount *= this.week; if (this.isAdsFree) { advertisementAmount = 0; } this.configuration.adsAmount = advertisementAmount; if (this.configuration.type === 'pop-out' || this.configuration.type === 'square' || this.configuration.type === 'large') { if (!this.isAdsFree && this.configuration.isFbPromoting) { advertisementAmount += this.adsConfiguration.advertisementBannerFBAmount; this.configuration.fbAmount = this.adsConfiguration.advertisementBannerFBAmount; } if (!this.isAdsFree && this.configuration.isInstaPromoting) { advertisementAmount += this.adsConfiguration.advertisementBannerInstaAmount; this.configuration.instaAmount = this.adsConfiguration.advertisementBannerInstaAmount; } } return advertisementAmount; } openAdvertisingModal() { this.phase.reset(); this.maxWidth = 800; this.isModifyAdvertisingModalOpened = true; this.isAcceptAgreement = false; this.isAdsFree = false; this.configuration = this.getConfiguration(); this.getAdvertisementConfiguration(); this.getNumberOfPublishedItems(); } onImageChange(event) { for (let item of event) { const result = this.uploadHelper.validate(item.file, true, environment.MAX_IMAGE_SIZE_IN_MB); if (result.result) { this.configuration.imageUrl = item.base64; this.configuration.image = item.base64.replace(/^data:image\/\w+;base64,/, ''); } else { WsToastService.toastSubject.next({ content: result.error, type: 'danger' }); } } } getConfiguration() { return { type: '', store: null, isFbPromoting: false, isInstaPromoting: false, pageClickedType: 'local', imageUrl: '', image: null, url: '', description: '', startDate: null, endDate: null, reason: undefined, fbAmount: null, instaAmount: null, adsAmount: null } } getAdvertisementConfiguration() { this.configLoading.start(); this.authAdvertisementContributorService.getAdvertisementConfiguration().pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.configLoading.stop())).subscribe(result => { this.adsConfiguration = result['result']; if (!this.adsConfiguration.isEnabledFreeAdvertisement || !this.adsConfiguration.isFreeAvailable) { this.phase.setStep(1); } }); } getAdvertisements(isLoading=false) { if (isLoading) { this.loading.start(); } this.authAdvertisementContributorService.getAdvertisements().pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.loading.stop())).subscribe(result => { this.advertisings = this.updateIsRunning(result?.['result']); }); } updateIsRunning(advertisings) { for (let advertising of advertisings) { if (advertising?.status === 'approved' && new Date(advertising?.startDate).getTime() < this.today.getTime() && new Date(advertising?.endDate).getTime() > this.today.getTime() ) { advertising.status = 'in_progress'; } else if (advertising?.status === 'approved' && new Date(advertising?.endDate).getTime() < this.today.getTime() ) { advertising.status = 'finished'; } } return advertisings; } prevStartDate prevEndDate openDatePicker() { this.prevStartDate = this.configuration.startDate; this.prevEndDate = this.configuration.endDate; this.configuration.startDate = null; this.configuration.endDate = null; this.datepicker.open(); } startDateChange() { this.datepicker.close(); if (this.isEditAdvertisementOpened) { this.configuration.endDate = moment(this.configuration.startDate).add(this.week, 'week').subtract(1, 'day').toDate(); } else { _.delay(() => { this.datepicker.open(); }, 100); } } openStartAdvertisingModal() { this.isAdvertisementEnabledModalOpened = true; } openStopAdvertisingModal() { this.isAdvertisementDisabledModalOpened = true; } stopAdvertising() { this.submitLoading.start(); this.authAdvertisementContributorService.stopAdvertising(this.selectedAdvertisement._id).pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.submitLoading.stop())).subscribe(result => { if (result['result']) { this.selectedAdvertisement.isEnabled = true; WsToastService.toastSubject.next({ content: 'Advertisement is stopped advertising!', type: 'success'}); this.getAdvertisements(); this.isAdvertisementDisabledModalOpened = false; } }); } startAdvertising() { this.submitLoading.start(); this.authAdvertisementContributorService.startAdvertising(this.selectedAdvertisement._id).pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.submitLoading.stop())).subscribe(result => { if (result['result']) { this.selectedAdvertisement.isEnabled = true; WsToastService.toastSubject.next({ content: 'Advertisement is started advertising!', type: 'success'}); this.getAdvertisements(); this.isAdvertisementEnabledModalOpened = false; } }); } closeDatePicker() { if (!this.configuration.startDate && this.prevStartDate) { this.configuration.startDate = this.prevStartDate; } if (this.isEditAdvertisementOpened && this.configuration.startDate && !this.configuration.endDate && this.prevEndDate) { this.configuration.endDate = this.prevEndDate; } } refreshAdvertisementsInterval: Subscription; refreshAdvertisements() { if (this.refreshAdvertisementsInterval) { this.refreshAdvertisementsInterval.unsubscribe(); } this.refreshAdvertisementsInterval = interval(this.REFRESH_ADVERTISEMENT_INTERVAL).pipe(switchMap(() => { return this.authAdvertisementContributorService.getAdvertisements(); }), takeUntil(this.ngUnsubscribe)).subscribe(result => { this.advertisings = this.updateIsRunning(result?.['result']); }); } chosenDayHandler(normalizedDay: Moment, datepicker:MatDatepicker<Moment>, date) { const ctrlValue = date.value; ctrlValue.date(normalizedDay.date()); ctrlValue.month(normalizedDay.month()); ctrlValue.year(normalizedDay.year()); date.setValue(ctrlValue); datepicker.close(); } nextToAdsConfig(type) { if (this.isAdsFree) { if (!this.store?.isPublished) { WsToastService.toastSubject.next({ content: 'Store is not published yet!', type: 'danger'}); return; } if (this.store?.numberOfPublishedItems === 0) { WsToastService.toastSubject.next({ content: 'At least 1 product should be displayed publicly!', type: 'danger'}); return; } } this.week = 0; this.configuration.type = type; this.configuration.imageUrl = ''; this.configuration.store = { username: this.store.username }; if (this.configuration.type === 'medium') { this.maxWidth = 1180; } else { this.maxWidth = 800; } window.scrollTo({top: 0}); this.phase.next(); if (this.adsConfiguration.isEnabledFreeAdvertisement && (this.configuration.type === 'pop-out' || this.configuration.type === 'square' || this.configuration.type === 'large')) { this.configuration.isFbPromoting = true; this.configuration.isInstaPromoting = true; } this.getAvailableAdvertisements(); } previousToAdsType() { this.maxWidth = 800; this.configuration = this.getConfiguration(); this.phase.previous(); } previousToAdsFreePaidType() { this.maxWidth = 800; this.phase.previous(); } showConfirmation() { if (!this.configuration.type) { WsToastService.toastSubject.next({content: 'Please select an advertisement type!', type: 'danger'}); return; } else if (!this.configuration.imageUrl) { WsToastService.toastSubject.next({content: 'Please upload an advertising image!', type: 'danger'}); return; } else if (!this.configuration.startDate) { WsToastService.toastSubject.next({content: 'Please select start week!', type: 'danger'}); return; } else if (!this.configuration.endDate) { WsToastService.toastSubject.next({content: 'Please select end week!', type: 'danger'}); return; } else if (this.configuration.pageClickedType === 'custom' && (!this.configuration.url || !this.configuration.url.trim())) { WsToastService.toastSubject.next({content: 'Please enter page url after clicking!', type: 'danger'}); return; } else if (this.configuration.pageClickedType === 'custom' && !URLValidator.validate(this.configuration.url)) { WsToastService.toastSubject.next({content: 'Please enter a valid page url!', type: 'danger'}); return; } else if (this.week <= 0) { WsToastService.toastSubject.next({content: 'Please enter a valid date range!', type: 'danger'}); return; } else if (this.configuration.pageClickedType === 'local' && !this.store?.isPublished) { WsToastService.toastSubject.next({content: 'Please publish your store if you want to advertise your page!', type: 'danger'}); return; } this.totalAmount = this.getAdvertisementAmount(); this.phase.next(); this.confirmationLoading.start(); _.delay(() => { this.confirmationLoading.stop(); this.configuration = {...this.configuration}; if (!this.isAdsFree) { this.createBraintreeClient(); } }, 1000); } onEditAdsModalClicked(advertisement) { this.isEditAdvertisementOpened = true; this.selectedAdvertisement = null; this.configuration = null; this.editingAdsLoading.start(); this.paymentLoading.start(); this.getAdvertisementConfiguration(); this.authAdvertisementContributorService.getAdvertisement(advertisement._id).pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.editingAdsLoading.stop())).subscribe(result => { this.selectedAdvertisement = result['result']; this.configuration = this.selectedAdvertisement; this.isAdsFree = this.selectedAdvertisement.isAdsFree; this.calculateWeek(); this.totalAmount = this.selectedAdvertisement.amount; this.getAvailableAdvertisements(); if (this.selectedAdvertisement?.status === 'rejected' && this.selectedAdvertisement?.reason === 'payment-error') { _.delay(() => { this.createBraintreeClient(); }, 1000); } }); } onEditAdsClicked(advertisement) { this.submitLoading.start(); this.authAdvertisementContributorService.editAdvertisement(advertisement).pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.submitLoading.stop())).subscribe(result => { if (result && result['result']) { this.isEditAdvertisementOpened = false; this.getAdvertisements(); WsToastService.toastSubject.next({ content: 'Wait for the approval.<br/>It will take 1-2 days.<br/>Payment will not be proceed until it is approved.', type: 'success'}); } }, err => { WsToastService.toastSubject.next({ content: err.error, type: 'danger'}); }); } onViewAdsClicked(advertisement) { this.isAdvertisementModalOpened = true; this.analysisLoading.start(); this.selectedAdvertisement = null; this.authAdvertisementContributorService.getAdvertisement(advertisement._id).pipe(takeUntil(this.ngUnsubscribe), finalize(() => this.analysisLoading.stop())).subscribe(result => { this.selectedAdvertisement = result['result']; if (this.selectedAdvertisement) { this.selectedAdvertisement = this.updateIsRunning([this.selectedAdvertisement])[0]; } }); } onAdvertisementTypeClicked(type) { this.isAdsFree = type === 'free'; this.phase.next(); } onImageExampleClicked(event, images=[]) { event.stopPropagation(); if (images.length) { this.isDisplayAdvertisementExample = true; this.exampleImages = images; } } calculateWeek() { this.week = moment(this.configuration.endDate).diff(moment(this.configuration.startDate), 'weeks') + 1; } onViewAdsClosed() { this.isAdvertisementModalOpened = false; this.selectedAdvertisement = null; } viewTermAndCondition() { this.isAdvertisingPolicyOpened = true; this.http.get('/assets/text/advertisingPolicy.txt', { responseType: 'text' }).pipe( takeUntil(this.ngUnsubscribe)).subscribe((result: string) => { this.advertisingPolicy = result; }) } ngOnDestroy(): void { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); } }
package gbw.sdu.msd.backend.controllers; import gbw.sdu.msd.backend.dtos.*; import gbw.sdu.msd.backend.models.Group; import gbw.sdu.msd.backend.models.User; import gbw.sdu.msd.backend.services.Auth; import gbw.sdu.msd.backend.services.IGroupRegistry; import gbw.sdu.msd.backend.services.IUserRegistry; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(path="/api/v1/groups") public class GroupController { private final IUserRegistry userRegistry; private final IGroupRegistry groupRegistry; private final Auth auth; @Autowired public GroupController(IUserRegistry users, IGroupRegistry groups, Auth auth){ this.userRegistry = users; this.groupRegistry = groups; this.auth = auth; } /** * Checks if the user is the admin of said group or not */ @ApiResponses(value = { @ApiResponse(responseCode = "404", description = "No such user or no such group"), @ApiResponse(responseCode = "200", description = "Success") }) @GetMapping(path = "/{groupId}/is-admin/{userId}") public @ResponseBody ResponseEntity<Boolean> checkAdmin(@PathVariable Integer groupId, @PathVariable Integer userId){ User user = userRegistry.get(userId); Group group = groupRegistry.get(groupId); if(user == null || group == null){ return ResponseEntity.notFound().build(); } return ResponseEntity.ok(user.id() == group.admin().id()); } /** * Adds a user to an existing group * @return Adds a user to an existing group */ @PostMapping(path="{groupId}/add-user/{userId}") public @ResponseBody ResponseEntity<Boolean> joinGroup(@PathVariable Integer userId, @PathVariable int groupId){ User user = userRegistry.get(userId); if(user == null){ return ResponseEntity.notFound().build(); } if(!groupRegistry.addUser(groupId,user)){ return ResponseEntity.badRequest().build(); } return ResponseEntity.ok(true); } /** * Creates a new group * @return Creates a new group */ @ApiResponses(value = { @ApiResponse(responseCode = "404", description = "No such user - A user that doesn't exist can't be admin."), @ApiResponse(responseCode = "200", description = "Success") }) @PostMapping(path="/create") public @ResponseBody ResponseEntity<GroupDTO> create(@RequestBody CreateGroupDTO dto){ User admin = userRegistry.get(dto.idOfAdmin()); if(admin == null){ return ResponseEntity.notFound().build(); } Group group = groupRegistry.create(dto, admin); return ResponseEntity.ok(GroupDTO.of(group)); } /** * Update the group information to be xxx, admin only. * Returns the full updated information of the group. */ @ApiResponses(value = { @ApiResponse(responseCode = "400", description = "Invalid values to be updated"), @ApiResponse(responseCode = "401", description = "Unauthorized, acting user is not admin"), @ApiResponse(responseCode = "404", description = "No such group or no such acting user") }) @PostMapping(path="/{groupId}/update") public @ResponseBody ResponseEntity<GroupDTO> updateGroup(@PathVariable Integer groupId, @RequestBody UpdateGroupDTO dto){ User actingUser = userRegistry.get(dto.idOfActingUser()); Group group = groupRegistry.get(groupId); if(actingUser == null || group == null){ return ResponseEntity.notFound().build(); } if(actingUser.id() != group.admin().id()){ return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } if(dto.updatedColor() < 0 || dto.updatedDescription() == null || dto.updatedDescription().isBlank() || dto.updatedTitle() == null || dto.updatedTitle().isBlank()){ return ResponseEntity.badRequest().build(); } Group updatedGroup = groupRegistry.update(groupId, dto); return ResponseEntity.ok(GroupDTO.of(updatedGroup)); } /** * Adds a user to a group. URI example: /api/v1/groups/join?groupId=1&userId=1 * @param groupId id of group * @param userId id of user * @return Adds a user to a group. URI example: /api/v1/groups/join?groupId=1&userId=1 */ @ApiResponses(value = { @ApiResponse(responseCode = "404", description = "No such user or no such group"), @ApiResponse(responseCode = "400", description = "Missing groupId or userId"), @ApiResponse(responseCode = "200", description = "Success") }) @PostMapping(path="/join") public @ResponseBody ResponseEntity<GroupDTO> linkJoin(@RequestParam Integer groupId, @RequestParam Integer userId){ if(groupId == null || userId == null){ return ResponseEntity.badRequest().build(); } User user = userRegistry.get(userId); if(user == null){ return ResponseEntity.notFound().build(); } if(!groupRegistry.addUser(groupId, user)){ return ResponseEntity.notFound().build(); } return ResponseEntity.ok(GroupDTO.of(groupRegistry.get(groupId))); } /** * Get the activities for the group. * Optionally, you can use the query param "amount" to limit the... amount. */ @ApiResponses(value = { @ApiResponse(responseCode = "404", description = "No such group"), @ApiResponse(responseCode = "200", description = "Success") }) @GetMapping(path = "/{groupId}/activities") public @ResponseBody ResponseEntity<List<GroupActivityDTO>> getActivities(@PathVariable Integer groupId, @RequestParam(required = false) Integer amount){ Group group = groupRegistry.get(groupId); if(group == null){ return ResponseEntity.notFound().build(); } if(amount == null){ amount = -1; } return ResponseEntity.ok(groupRegistry.activitiesOf(groupId, amount)); } /** * Removes the user from the group if the acting user is authorized to do so * @param userInQuestion id of user to be removed * @param groupId id of group * @param actingUser Credentials of the user performing this action * @return Removes the user from the group if the acting user is authorized to do so */ @ApiResponses(value = { @ApiResponse(responseCode = "401", description = "Unauthorized"), @ApiResponse(responseCode = "400", description = "Invalid acting user"), @ApiResponse(responseCode = "200", description = "Success") }) @PostMapping(path= "/{groupId}/remove-user/{userInQuestion}") public @ResponseBody ResponseEntity<Boolean> removeUser(@PathVariable Integer userInQuestion, @PathVariable Integer groupId, @RequestBody UserCredentialsDTO actingUser){ if(actingUser == null || groupId == null){ return ResponseEntity.notFound().build(); } User maybeAdmin = userRegistry.get(actingUser); if(maybeAdmin == null){ System.out.println("User not found"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); }else if(!auth.mayDeleteUsersFrom(maybeAdmin.id(), userInQuestion, groupId)){ System.out.println("User not authorized: " + maybeAdmin); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } if(userInQuestion == null){ return ResponseEntity.notFound().build(); } User user = userRegistry.get(userInQuestion); if(user == null){ return ResponseEntity.notFound().build(); } if(!groupRegistry.removeUser(groupId, user)){ return ResponseEntity.notFound().build(); } return ResponseEntity.ok(true); } /** * The information about that group * @param groupId id of group * @return The information about that group */ @ApiResponses(value = { @ApiResponse(responseCode = "404", description = "No such group"), @ApiResponse(responseCode = "400", description = "Missing group id"), @ApiResponse(responseCode = "200", description = "Success") }) @GetMapping(path = "/{groupId}") public @ResponseBody ResponseEntity<GroupDTO> getGroup(@PathVariable Integer groupId){ if(groupId == null){ return ResponseEntity.badRequest().build(); } Group group = groupRegistry.get(groupId); if(group == null){ return ResponseEntity.notFound().build(); } return ResponseEntity.ok(GroupDTO.of(group)); } /** * Deletes a given group if the acting user is authorized to do so * @param groupId group to delete * @param credentials of the user trying to delete said group * @return true on success */ @ApiResponses(value = { @ApiResponse(responseCode = "401", description = "Unauthorized"), @ApiResponse(responseCode = "400", description = "Invalid acting user"), @ApiResponse(responseCode = "200", description = "Success") }) @PostMapping(path="/{groupId}/delete") public @ResponseBody ResponseEntity<Boolean> deleteGroup(@PathVariable Integer groupId, @RequestBody UserCredentialsDTO credentials){ User user = userRegistry.get(credentials); if(user == null) { return ResponseEntity.badRequest().build(); } if(!auth.mayDeleteGroup(user.id(),groupId)) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } return ResponseEntity.ok(groupRegistry.delete(groupId)); } }
<div class="row"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <div class="page-header"> <h4 class="page-title">Classe</h4> <ul class="breadcrumbs"> <li class="nav-home"> <p > <i class="fa fa-school"></i> </p> </li> <li class="separator"> <i class="flaticon-right-arrow"></i> </li> <li class="nav-item"> <p >Classe</p> </li> <li class="separator"> <i class="flaticon-right-arrow"></i> </li> <li class="nav-item"> <p >Ajouter Une Classe</p> </li> </ul> </div> <h3 class="box-title"> <i class="icon-arrow-right" ></i>Inserer Une Classe <i class="fa fa-school" ></i></h3> </div> <div class="ml-md-auto py-4 py-md-2"> <a href="" routerLink="/default/lister_classe" class="btn btn-primary btn-round"> <i class="fa fa-plus fa-fw"></i>Liste Classe</a> </div> <form [formGroup]="loginForm" (ngSubmit)="Enregistrer()"> <div class="form-row"> <div class="form-group col-md-4"> <div class="form-group form-group-default"> <label>Code Classe</label> <input id="Name" [ngClass]="{ 'is-invalid': submitted && f.codeclasse.errors }" formControlName="codeclasse" type="text" class="form-control" placeholder="Code Classe Svp"> <div *ngIf="submitted && f.codeclasse.errors" class="invalid-feedback"> <div *ngIf="f.codeclasse.errors.required">Code Classe est Obligatoire</div> </div> </div> </div> <div class="form-group col-md-4"> <div class="form-group form-group-default"> <label>Libelle De La Classe</label> <input id="Name" [ngClass]="{ 'is-invalid': submitted && f.libelleclasse.errors }" formControlName="libelleclasse" type="text" class="form-control" placeholder="Libelle Classe Svp"> <div *ngIf="submitted && f.libelleclasse.errors" class="invalid-feedback"> <div *ngIf="f.libelleclasse.errors.required">Libelle Classe est Obligatoire</div> </div> </div> </div> <div class="form-group col-md-4"> <div class="form-group form-group-default" > <select class="form-control input-border-bottom" id="selectFloatingLabel" formControlName="niveaux" [ngClass]="{ 'is-invalid': submitted && f.niveaux.errors }"> <option value="">&nbsp;</option> <option *ngFor=" let niv of allniv " value="{{niv.id}}"> {{niv.libelleniveau}} </option> <div *ngIf="submitted && f.niveaux.errors" class="invalid-feedback"> <div *ngIf="f.niveaux.errors.required">Le Niveau est Obligatoire</div> </div> </select> <label for="selectFloatingLabel" class="placeholder">...Choisissez Un Niveau</label> </div> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <div class="form-group form-group-default" > <select class="form-control input-border-bottom" id="selectFloatingLabel" formControlName="series" > <option value="">&nbsp;</option> <option *ngFor=" let ser of allser " value="{{ser.id}}"> {{ser.libelleserie}} </option> </select> <label for="selectFloatingLabel" class="placeholder">...La Serie Est Facultative...</label> </div> </div> <div class="form-group col-md-4"> <div class="form-group form-group-default"> <label>Montant D'inscription</label> <input id="Name" [ngClass]="{ 'is-invalid': submitted && f.montantIns.errors }" formControlName="montantIns" type="text" class="form-control" placeholder="Montant d'inscription de la Classe Svp"> <div *ngIf="submitted && f.montantIns.errors" class="invalid-feedback"> <div *ngIf="f.montantIns.errors.required">Veuillez Donner Le Montant D'inscription</div> </div> </div> </div> <div class="form-group col-md-4"> <div class="form-group form-group-default"> <label>Montant Mensuele</label> <input id="Name" [ngClass]="{ 'is-invalid': submitted && f.montantMens.errors }" formControlName="montantMens" type="text" class="form-control" placeholder="Montant Mensuele de la Classe Svp"> <div *ngIf="submitted && f.montantMens.errors" class="invalid-feedback"> <div *ngIf="f.montantMens.errors.required">Veuillez Donner Le Montant Mensuele</div> </div> </div> </div> </div> <div class="form-row"> <div class="form-group col-md-4"> <div class="form-group form-group-default"> <button [disabled]="loading" class="btn btn-primary" > <span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"> </span> Submit </button> </div> </div> </div> </form> </div> </div> </div>
/** Estrutura inicial para um jogo de labirinto versão: 0.1 (Felski) versão final: Felipe Luz */ #include <iostream> #include <windows.h> #include <conio.h> #include <unistd.h> #include "conmanip.h" #include "gameHelper.h" #include<fstream> #include <vector> #include <string> #include <algorithm> #include <sstream> using namespace conmanip; using namespace std; typedef pair<string, int> PlayerScore; void finishMenu(COORD &coord, int moveCount, string playerName); void pauseMenu(COORD &coord, string playerName, history oldHistory); void startMenu(COORD &coord, string playerName); void setFontSize(int a, int b) { HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); PCONSOLE_FONT_INFOEX lpConsoleCurrentFontEx = new CONSOLE_FONT_INFOEX(); lpConsoleCurrentFontEx->cbSize = sizeof(CONSOLE_FONT_INFOEX); GetCurrentConsoleFontEx(hStdOut, 0, lpConsoleCurrentFontEx); lpConsoleCurrentFontEx->dwFontSize.X = a; lpConsoleCurrentFontEx->dwFontSize.Y = b; lpConsoleCurrentFontEx->FontWeight = 1000; SetCurrentConsoleFontEx(hStdOut, 0, lpConsoleCurrentFontEx); } void setup(COORD &coord) { ///ALERTA: NAO MODIFICAR O TRECHO DE CODIGO, A SEGUIR. //INICIO: COMANDOS PARA QUE O CURSOR NAO FIQUE PISCANDO NA TELA HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO cursorInfo; GetConsoleCursorInfo(out, &cursorInfo); cursorInfo.bVisible = false; // set the cursor visibility SetConsoleCursorInfo(out, &cursorInfo); setFontSize(25, 25); console_out_context ctxout; console_out conout(ctxout); conout.settitle("Sokoban - Felipe Luz"); //FIM: COMANDOS PARA QUE O CURSOR N�O FIQUE PISCANDO NA TELA //INICIO: COMANDOS PARA REPOSICIONAR O CURSOR NO IN�CIO DA TELA short int CX=0, CY=0; coord.X = CX; coord.Y = CY; //FIM: COMANDOS PARA REPOSICIONAR O CURSOR NO IN�CIO DA TELA ///ALERTA: NAO MODIFICAR O TRECHO DE CODIGO, ACIMA. } bool sortScores(const PlayerScore &a, const PlayerScore &b) { return (a.second < b.second); } void saveScore(string mapName, string playerName, int moveCount) { vector<PlayerScore> scores; string path = SCORES_FOLDER + mapName + SCORES_EXTENSION; ifstream file(path); string line, name; int moves; if (file.is_open()) { while (getline(file, line)) { stringstream ss(line); getline(ss, name, ','); ss >> moves; scores.push_back(make_pair(name, moves)); } } file.close(); scores.push_back(make_pair(playerName, moveCount)); sort(scores.begin(), scores.end(), sortScores); ofstream outputFile(path); if (outputFile.is_open()) { for (const auto& score : scores) { outputFile << score.first << "," << score.second << "\n"; } } outputFile.close(); } void clearMoves() { ofstream file("moves.csv"); file.close(); } void gameV2(COORD &coord, assets assets, history history) { printMap(coord, assets.map); printHoles(coord, assets.holes, assets.boxCount); printPlayer(coord, assets.player); printBoxes(coord, assets.boxes, assets.boxCount); if(checkComplete(assets.boxes, assets.holes, assets.boxCount)) { saveScore(assets.mapName, assets.playerName, assets.moveCount); finishMenu(coord, assets.moveCount, assets.playerName); return; } char input = getInput(); if(input == 27) pauseMenu(coord, assets.playerName, history); assets = move(input, assets, history); gameV2(coord, assets, history); } assets readMapFileV2( assets pAssets, string mapName ) { ifstream stream; string mapPath = MAPS_FOLDER + mapName + MAP_EXTENSION; int currBox = 0; int currHole = 0; stream.open(mapPath); if (stream.is_open()){ stream>>pAssets.player.x; stream>>pAssets.player.y; for(int i=0; i<10; i++){ for(int j=0; j<10; j++){ int cell; stream >> cell; if(cell == 2) { pAssets.boxes[currBox] = {.x = j, .y = i}; currBox++; } else if(cell == 3) { pAssets.holes[currHole] = {.x = j, .y = i}; currHole++; } else if(cell == 4) { pAssets.holes[currHole] = {.x = j, .y = i}; pAssets.boxes[currBox] = {.x = j, .y = i}; currBox++; currHole++; } if(cell == 1) { pAssets.map[i][j] = cell; } else { pAssets.map[i][j] = 0; } } } } stream.close(); pAssets.boxCount = currBox; return pAssets; } void loadMap(COORD &coord, string mapName, string playerName) { assets assets; history history; assets.init(); assets.moveCount = 0; assets.mapName = mapName; assets.playerName = playerName; assets = readMapFileV2(assets, mapName); history.assets.push_back(assets); clear(); gameV2(coord, assets, history); } void finishMenu(COORD &coord, int moveCount, string playerName) { Sleep(2000); //2 sec printFinishMenu(moveCount); char input = getInput(); if(input == 'r' || input == 27) { startMenu(coord, playerName); exit(0); } finishMenu(coord, moveCount, playerName); } void selectMap(COORD &coord, string playerName) { clearMoves(); printSelectMapMenu(); char input = getInput(); string map = "map"; switch (input) { case 'r': case 27: return; case '0': case '1': case '2': loadMap(coord, map.append(1, input), playerName); break; default: selectMap(coord, playerName); } } void pauseMenu(COORD &coord, string playerName, history oldHistory) { printPauseMenu(); char input = getInput(); if(input == 'f' || input == 27) exit(0); if(input == 'n') selectMap(coord, playerName); else if(input == 's') about(); else if( input == 'v') { clear(); int step = 0; cout << "Voce deu " << oldHistory.assets.back().moveCount << " passos, quantos movimentos quer voltar? " << endl; cin >> step; if( step >= oldHistory.assets.back().moveCount) { history newHistory; newHistory.assets.push_back(oldHistory.assets[0]); return gameV2(coord, oldHistory.assets[0], newHistory); } for (int i = 0; i < step; i++) oldHistory.assets.pop_back(); return gameV2(coord, oldHistory.assets.back(), oldHistory); } else if( input == 'c') return; pauseMenu(coord, playerName, oldHistory); } void startMenu(COORD &coord, string playerName) { printStartMenu(); char input = getInput(); if(input == 'f' || input == 27) return; if(input == 'n') selectMap(coord, playerName); else if(input == 's') about(); startMenu(coord, playerName); } int main() { clearMoves(); string playerName; cout << "Entre seu nome: "; cin >> playerName; COORD coord; setup(coord); startMenu(coord, playerName); return 0; }
/* eslint-disable react/jsx-props-no-spreading */ // React import React, { useEffect, useRef, forwardRef, useState } from "react"; // Libraries import PropTypes from "prop-types"; import { Form, Button, Icon, Select } from "semantic-ui-react"; import { isEmpty, omit } from "lodash"; // Styles import styles from "./styles.module.css"; const Input = forwardRef((props, ref) => { const { isPassword = false, name, value, className, icon, disabled, rounded, onChange, onKeyPress, dropdown, fluid = true, big, } = props; const input = useRef(null); const [type, setType] = useState(isPassword ? "password" : "text"); const [passwordIcon, setPasswordIcon] = useState("eye slash"); useEffect(() => { if (rounded && isEmpty(value)) { (ref || input).current.style.removeProperty("border-top-left-radius"); (ref || input).current.style.removeProperty("border-bottom-left-radius"); (ref || input).current.style.removeProperty("border-top-right-radius"); (ref || input).current.style.removeProperty("border-bottom-right-radius"); (ref || input).current.style.removeProperty("border-right"); (ref || input).current.style.setProperty("border-radius", "1rem", "important"); } if (rounded && !isEmpty(value)) { (ref || input).current.style.removeProperty("border-radius"); (ref || input).current.style.setProperty("border-top-left-radius", "1rem", "important"); (ref || input).current.style.setProperty("border-bottom-left-radius", "1rem", "important"); (ref || input).current.style.setProperty("border-top-right-radius", "0", "important"); (ref || input).current.style.setProperty("border-bottom-right-radius", "0", "important"); (ref || input).current.style.setProperty("border-right", "0", "important"); } if (!isEmpty(dropdown)) { (ref || input).current.style.setProperty("border-top-left-radius", "0", "important"); (ref || input).current.style.setProperty("border-bottom-left-radius", "0", "important"); (ref || input).current.style.setProperty("border-left-color", "transparent", "important"); } if (big) { (ref || input).current.style.removeProperty("flex-wrap"); (ref || input).current.style.setProperty("height", "2.4rem", "important"); (ref || input).current.style.setProperty("font-size", "1.2rem", "important"); } }, [rounded, value, dropdown, ref]); const handleEnter = (e) => { const { key } = e; if (key === "Enter") { e.preventDefault(); } }; const handleToggle = () => { const toggle = type === "password"; const typeVal = toggle ? "text" : "password"; const iconVal = toggle ? "eye" : "eye slash"; setType(typeVal); setPasswordIcon(iconVal); }; const clearInput = (e) => { const data = { name, value: "" }; onChange({ ...e, target: data }, data); }; const validProps = omit(props, [ "ref", "icon", "children", "onKeyPress", "name", "value", "onChange", "disabled", "className", "rounded", "isPassword", ]); return ( <Form.Input {...validProps} className={`${styles.input} ${className}`} disabled={disabled} onChange={onChange} name={name} value={value} type={type} {...(isEmpty(dropdown) ? { iconPosition: "left" } : {})} autoComplete="off" fluid={fluid} onKeyPress={onKeyPress || handleEnter} action> {!isEmpty(dropdown) && <Select labeled {...dropdown} />} {isEmpty(dropdown) && (!isEmpty(icon) || isPassword) && ( <Icon name={isPassword ? "lock" : icon} /> )} <input ref={ref || input} /> {!isEmpty(value) && !disabled && ( <Button className={rounded ? styles.clearRoundedIconLast : styles.clearIconLast} icon="cancel" onClick={clearInput} /> )} {isPassword && ( <Button className={styles.clearIconLast} icon={passwordIcon} onClick={handleToggle} /> )} </Form.Input> ); }); Input.propTypes = { onChange: PropTypes.func, onKeyPress: PropTypes.func, name: PropTypes.string, value: PropTypes.string, className: PropTypes.string, disabled: PropTypes.bool, icon: PropTypes.string, children: PropTypes.node, rounded: PropTypes.bool, dropdown: PropTypes.object, fluid: PropTypes.bool, big: PropTypes.bool, isPassword: PropTypes.bool, }; export default Input;
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package logika; import db.DBBroker; import domen.Poruka; import domen.User; import java.net.Socket; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Danilo */ public class Kontroler { DBBroker db; private static Kontroler instance; private HashMap<String, Socket> mapaUlogovanih; private Kontroler() { mapaUlogovanih = new HashMap<>(); db = new DBBroker(); } public static Kontroler getInstance() { if (instance == null) { instance = new Kontroler(); } return instance; } public User ulogujKorisnika(User user, Socket socket) { db.otovoriKonekciju(); User ulogovani = null; try { ulogovani = db.vratiUlogovanog(user); db.commit(); if (ulogovani != null) { mapaUlogovanih.put(ulogovani.getUsername(), socket); } } catch (SQLException ex) { db.rollback(); Logger.getLogger(Kontroler.class.getName()).log(Level.SEVERE, null, ex); } db.zatvoriKonekciju(); return ulogovani; } public ArrayList<String> vratiUlogovane() { ArrayList<String> lista = new ArrayList<>(); for (Map.Entry<String, Socket> entry : mapaUlogovanih.entrySet()) { String key = entry.getKey(); Socket val = entry.getValue(); lista.add(key); } return lista; } public HashMap<String, Socket> getMapaUlogovanih() { return mapaUlogovanih; } public boolean sacuvajPoruku(Poruka poruka) { boolean uspesno = false; db.otovoriKonekciju(); try { db.sacuvajPoruku(poruka); db.commit(); uspesno = true; } catch (SQLException ex) { db.rollback(); Logger.getLogger(Kontroler.class.getName()).log(Level.SEVERE, null, ex); } db.zatvoriKonekciju(); return uspesno; } public ArrayList<Poruka> vratPrimljenePorukeZaKorisnika(User korisnik) { ArrayList<Poruka> listaPoruka = new ArrayList<>(); db.otovoriKonekciju(); try { listaPoruka = db.vratiPrimljenePoruke(korisnik); db.commit(); } catch (SQLException ex) { db.rollback(); Logger.getLogger(Kontroler.class.getName()).log(Level.SEVERE, null, ex); } db.zatvoriKonekciju(); return listaPoruka; } public ArrayList<Poruka> vratPoslatePorukeZaKorisnika(User k) { ArrayList<Poruka> listaPoruka = new ArrayList<>(); db.otovoriKonekciju(); try { listaPoruka = db.vratiPoslatePoruke(k); db.commit(); } catch (SQLException ex) { db.rollback(); Logger.getLogger(Kontroler.class.getName()).log(Level.SEVERE, null, ex); } db.zatvoriKonekciju(); return listaPoruka; } public ArrayList<User> vratiKorisnikeIUlogovane() { ArrayList<User> listaUsera = new ArrayList<>(); db.otovoriKonekciju(); try { listaUsera = db.vratiKorisnike(); db.commit(); } catch (SQLException ex) { db.rollback(); Logger.getLogger(Kontroler.class.getName()).log(Level.SEVERE, null, ex); } db.zatvoriKonekciju(); for (User user : listaUsera) { if (mapaUlogovanih.containsKey(user.getUsername())) { user.setAktivan(true); } } return listaUsera; } }
from typing import TYPE_CHECKING from pyconnectwise.endpoints.base.connectwise_endpoint import ConnectWiseEndpoint from pyconnectwise.interfaces import IPostable from pyconnectwise.models.manage import Calendar from pyconnectwise.types import JSON, ConnectWiseManageRequestParams if TYPE_CHECKING: from pyconnectwise.clients.connectwise_client import ConnectWiseClient class ScheduleCalendarsIdCopyEndpoint(ConnectWiseEndpoint, IPostable[Calendar, ConnectWiseManageRequestParams]): def __init__(self, client: "ConnectWiseClient", parent_endpoint: ConnectWiseEndpoint = None) -> None: ConnectWiseEndpoint.__init__(self, client, "copy", parent_endpoint=parent_endpoint) IPostable.__init__(self, Calendar) def post(self, data: JSON | None = None, params: ConnectWiseManageRequestParams | None = None) -> Calendar: """ Performs a POST request against the /schedule/calendars/{id}/copy endpoint. Parameters: data (dict[str, Any]): The data to send in the request body. params (dict[str, int | str]): The parameters to send in the request query string. Returns: Calendar: The parsed response data. """ return self._parse_one(Calendar, super()._make_request("POST", data=data, params=params).json())
//1. print the number 5 to the console console.log(5); //2. Print your name to the console console.log("Marina"); //3. Store your age as a variable called "myAge" var myAge = 34; //4. Print to the console how old you will be in 5 years console.log(myAge + 5); //5. Store your favorite food as a variable called "myFavoriteFood" var myFavoriteFood = "Pasta"; //6. Publish your favorite food to `index.html` using `document.write()` document.write(myFavoriteFood); //7. Print the remainder of 14 / 3 to the console console.log(14 % 3); //8. Print the remainder of 829 / 13 to the console console.log(829 % 13); //9. Create a for loop that counts from 0 to 130 by 3s for(var i = 0; i < 130; i+=3){document.write(i+"<br>"); } //10. Create a for loop that counts from 3 to 17 by 2s for(var i = 3; i < 17; i+=2) {document.write(i+"<br>"); } //11. Create a for loop that counts from 100 to 3 by -1 for(var i = 100; i>3; i-=) {document.write(i+"<br>"); } //12. Create a for loop that counts from 1 to 100 by 1s for(var i = 1; i<100; i++) {document.write(i+"<br>"); } //13. Create a for loop that counts from 1 to 100, but instead of printing `i` prints `fizz` if the number is divisible by 5 for(var i = 1; i<100; i++) if (i % 5 ===0) {document.write("fizz" +"<br>");} else { document.write(i + "<br>"); } //14. Create a for loop that counts from 1 to 100, but instead of printing `i` prints `buzz` if the number is divisible by 3 for(var i = 1; i<100; i++) if (i % 3 ===0) {document.write("buzz" +"<br>");} else { document.write(i + "<br>"); } //15. Create a for loop that counts from 1 to 100, but instead of printing `i` prints `fizzbuzz` if the number is divisible by 15 for(var i = 1; i<100; i++) if (i % 15 ===0) {document.write("fizzbuzz" +"<br>");} else { document.write(i + "<br>"); } //EXTRA CREDIT: Fizzbuzz for(var i = 1; i<100; i++) if (i % 15 ===0) {document.write("fizzbuzz" +"<br>");} else if (i % 5 ===0) {document.write("fizz" + "<br>");} else if ( i % 3 ===0){ document.write("buzz"+"<br>"); }else{ document.write(i+"<br>"); } /* The "Fizz-Buzz test" is an interview question designed to help filter out the 99.5% of programming job candidates who can't seem to program their way out of a wet paper bag. The text of the programming assignment is as follows: "Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”." Hint: Use your last three loops and if/then/else statements. You can learn about those here https://www.w3schools.com/js/js_if_else.asp */
// Script assets have changed for v2.3.0 see // https://help.yoyogames.com/hc/en-us/articles/360005277377 for more information enum TURNS { AMBER, LILLESKUTT } function turnsToName(varEnum) { switch(varEnum) { case TURNS.AMBER : return "Amber"; break; case TURNS.LILLESKUTT : return "LilleSkutt"; break; } } enum PHASES { choosing, attackMiss, attackHit, start, switchingPokemon, win, riddle, MOVE_ANIMATION, waitForAttack, waitForSwitching, statusAilment, pokeball } function phasesToName(varEnum) { switch(varEnum) { case PHASES.choosing : return "choosing"; break; case PHASES.attackHit : return "attackHit"; break; case PHASES.attackMiss : return "attackMiss"; break; case PHASES.start : return "start"; break; case PHASES.switchingPokemon : return "switchingPokemon"; break; case PHASES.win : return "win"; break; case PHASES.riddle : return "riddle"; break; case PHASES.MOVE_ANIMATION : return "MOVE_ANIMATION"; break; case PHASES.waitForAttack : return "waitForAttack"; break; case PHASES.waitForSwitching : return "waitForSwitching"; break; case PHASES.statusAilment : return "statusAilment"; break; case PHASES.pokeball : return "pokeball"; break; } } enum ELEMENTS { fire, water, grass, rock, bug, ghost, psychic, earth, dragon, normal, } function elementsToName(varEnum) { switch(varEnum) { case ELEMENTS.fire : return "fire"; break; case ELEMENTS.water : return "water"; break; case ELEMENTS.grass : return "grass"; break; case ELEMENTS.rock : return "rock"; break; case ELEMENTS.bug : return "bug"; break; case ELEMENTS.ghost : return "ghost"; break; case ELEMENTS.psychic : return "psychic"; break; case ELEMENTS.earth : return "earth"; break; case ELEMENTS.dragon : return "dragon"; break; case ELEMENTS.normal : return "normal"; break } } enum PLAYERS { Nils, Ida, Jonathan } function playersToName(varEnum) { switch(varEnum) { case PLAYERS.Nils : return "Nils"; break; case PLAYERS.Ida : return "Ida"; break; case PLAYERS.Jonathan : return "Jonathan"; break; } } enum MOVES { BUBBLE, EMBER, VINE_WHIP, GROWL, TAIL_WHIP, DEFENCE_CURL, PSY_CUTTER, SLEEP, LEER, ROCK_THROW, TACKLE } function movesToName(varEnum) { switch(varEnum) { case MOVES.BUBBLE : return "bubble"; break; case MOVES.EMBER : return "ember"; break; case MOVES.VINE_WHIP : return "vine whip"; break; case MOVES.GROWL : return "growl"; break; case MOVES.TAIL_WHIP : return "tail whip"; break; case MOVES.DEFENCE_CURL : return "defence curl"; break; case MOVES.PSY_CUTTER : return "psy cutter"; break; case MOVES.SLEEP : return "sleep"; break; case MOVES.LEER : return "leer"; break; case MOVES.ROCK_THROW : return "rock throw"; break; case MOVES.TACKLE : return "tackle"; break; } } enum AILMENTS { SLEEPING, REGENING } function ailmentsToName (varEnum) { switch(varEnum) { case AILMENTS.SLEEPING : return "sleeping"; break; case AILMENTS.REGENING : return "regening"; break; } }
package krimselis.dto; import lombok.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import java.time.LocalDateTime; @Setter @Getter @NoArgsConstructor @AllArgsConstructor @Builder public class CommentDto { private Long id; @NotEmpty private String name; @NotEmpty(message = "Email should not be empty or null") @Email private String email; @NotEmpty(message = "Message body should not be empty") private String content; private LocalDateTime createdOn; private LocalDateTime updatedOn; }
// // Created by Kalen Suen on 2023/10/22. // #include <iostream> #include "cmath" using namespace std; struct Point { int x; int y; }; struct PointDouble { double x; double y; }; double min(double a, double b, double c, double d) { return min(min(a, b), min(c, d)); } double distance(Point a, Point b) { double dis = sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2)); return dis; } bool onSegment(Point p, Point q, Point r) { if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false; } bool onSegment(PointDouble p, Point q, Point r) { if (q.x <= max(p.x, (double) r.x) && q.x >= min(p.x, (double) r.x) && q.y <= max(p.y, (double) r.y) && q.y >= min(p.y, (double) r.y)) return true; return false; } PointDouble ptProjection2line(Point pt0, Point pt1, Point pt2) { double xp = pt0.x; double yp = pt0.y; double xp1 = pt1.x; double yp1 = pt1.y; double xp2 = pt2.x; double yp2 = pt2.y; double xm = ((xp2 - xp1) * (xp - xp1) + (yp2 - yp1) * (yp - yp1)) / (pow(xp2 - xp1, 2) + pow(yp2 - yp1, 2)) * (xp2 - xp1) + xp1; double ym = ((xp2 - xp1) * (xp - xp1) + (yp2 - yp1) * (yp - yp1)) / (pow(xp2 - xp1, 2) + pow(yp2 - yp1, 2)) * (yp2 - yp1) + yp1; PointDouble ptm{xm, ym}; return ptm; } double distancePt2Seg(Point a, Point pt0, Point pt1) { int detY01 = pt0.y - pt1.y; int detX01 = pt0.x - pt1.x; int det01 = pt0.x * pt1.y - pt0.y * pt1.x; double dis; dis = onSegment(ptProjection2line(a, pt0, pt1), pt0, pt1) ? abs(a.x * detY01 - a.y * detX01 + det01) / sqrt(pow(detY01, 2) + pow(detX01, 2)) : min(distance(a, pt0), distance(a, pt1)); return dis; } int orientation(Point p, Point q, Point r) { int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; return (val > 0) ? 1 : 2; } bool doIntersect(Point p1, Point q1, Point p2, Point q2) { int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); if (o1 != o2 && o3 != o4) return true; if (o1 == 0 && onSegment(p1, p2, q1)) return true; if (o2 == 0 && onSegment(p1, q2, q1)) return true; if (o3 == 0 && onSegment(p2, p1, q2)) return true; if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; } PointDouble calIntersection(Point p0, Point p1, Point p2, Point p3) { int detY01 = p0.y - p1.y; int detY23 = p2.y - p3.y; int detX01 = p0.x - p1.x; int detX23 = p2.x - p3.x; int det01 = p0.x * p1.y - p0.y * p1.x; int det23 = p2.x * p3.y - p3.x * p2.y; int det = -detY01 * detX23 + detY23 * detX01; PointDouble intersection{}; intersection.x = ((double) det01 * detX23 - detX01 * det23) / det; intersection.y = -((double) detY01 * det23 - detY23 * det01) / det; return intersection; } double calDistance(Point p0, Point p1, Point p2, Point p3) { double dis; if (doIntersect(p0, p1, p2, p3)) { dis = 0; } else { dis = min(distancePt2Seg(p0, p2, p3), distancePt2Seg(p1, p2, p3), distancePt2Seg(p2, p0, p1), distancePt2Seg(p3, p0, p1)); } return dis; } int main() { int q; cin >> q; for (int i = 0; i < q; ++i) { Point p0, p1, p2, p3; cin >> p0.x >> p0.y >> p1.x >> p1.y >> p2.x >> p2.y >> p3.x >> p3.y; double dis = calDistance(p0, p1, p2, p3); printf("%.10lf\n", dis); } return 0; }
import { createAsyncThunk } from '@reduxjs/toolkit'; import CosmeticsService from '../../services/CosmeticsService'; import { IError } from '../../models/IError'; import { ICosmetic } from '../../models/ICosmetic'; import { setPageCosmetics } from './cosmeticsSlice'; export const fetchCosmetics = createAsyncThunk<ICosmetic[], undefined, { rejectValue: IError }>( 'cosmetics/fetchAll', async (_, thunkAPI) => { const response = await CosmeticsService.fetchCosmetics(); if ('error' in response.data.data) { const error = response.data.data as IError; return thunkAPI.rejectWithValue(error); } thunkAPI.dispatch(setPageCosmetics(response.data.data as ICosmetic[])); return response.data.data as ICosmetic[]; }, ); export const fetchCosmetic = createAsyncThunk<ICosmetic, string | undefined, { rejectValue: IError }>( 'cosmetics/fetchOne', async (cosmeticID: string | undefined, thunkAPI) => { const response = await CosmeticsService.fetchCosmetic(cosmeticID); if ('error' in response.data.data) { const error = response.data.data as IError; return thunkAPI.rejectWithValue(error); } return response.data.data as ICosmetic; }, ); export const fetchCosmeticByName = createAsyncThunk<ICosmetic[], string | undefined, { rejectValue: IError }>( 'cosmetics/fetchByName', async (cosmeticName: string | undefined, thunkAPI) => { const response = await CosmeticsService.fetchCosmeticByName(cosmeticName); if ('error' in response.data.data) { const error = response.data.data as IError; return thunkAPI.rejectWithValue(error); } return response.data.data as ICosmetic[]; }, );
using Microsoft.EntityFrameworkCore; using Midterm_Project_Nashtech.Domain.Entities; namespace Midterm_Project_Nashtech.Infrastructure.Data { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<User> User { get; set; } public DbSet<Category> Category { get; set; } public DbSet<BorrowingRequest> BorrowingRequest { get; set; } public DbSet<BorrowingRequestDetails> RequestsDetails { get; set; } public DbSet<Book> Book { get; set;} public DbSet<BookCategories> BookCategories { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //Relative 1-n modelBuilder.Entity<BorrowingRequest>() .HasOne(e => e.Requestor) .WithMany(e => e.BorrowingRequests) .HasForeignKey(e => e.RequestorId) .IsRequired(); //Relative 1-n modelBuilder.Entity<BorrowingRequest>() .HasMany(e => e.RequestDetails) .WithOne(e => e.BorrowingRequest) .HasForeignKey(e => e.RequestId) .IsRequired(); //Relative 1-n modelBuilder.Entity<Book>() .HasMany(e => e.RequestsDetails) .WithOne(e => e.Book) .HasForeignKey(e => e.BookId) .IsRequired(); //Relative n-n modelBuilder.Entity<BookCategories>() .HasKey(bc => new { bc.BookId, bc.CategoryId }); modelBuilder.Entity<BookCategories>() .HasOne(e => e.Book) .WithMany(e => e.BookCategories) .HasForeignKey(e => e.BookId); modelBuilder.Entity<BookCategories>() .HasOne(e => e.Category) .WithMany(e => e.BookCategories) .HasForeignKey(e => e.CategoryId); } } }
import { ApiProperty, OmitType, PickType } from '@nestjs/swagger'; import { ProfileImg } from '../util/image.schema'; export class TutorReqDto { @ApiProperty() _id: String; @ApiProperty() firstName: String; @ApiProperty() lastName: String; @ApiProperty() readonly email: String; @ApiProperty() citizenID: ProfileImg; @ApiProperty() transcription: ProfileImg; @ApiProperty() timeStamp: Date; @ApiProperty() citizenID64: String; @ApiProperty() transcription64: String; } export class CreateTutorReq extends PickType(TutorReqDto, [ 'email', 'citizenID64', 'transcription64', ] as const) {} export class ShowTutorReq extends OmitType(TutorReqDto, [ 'citizenID64', 'transcription64', ] as const) {}
import { DynamicModule } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { ENV_FILE_PATH } from '../constants/env-file-path'; import { PackageEntity } from '../entities/package.enttiy'; import { PackageModule } from './package.module'; import { TrainerEntity } from '../entities/trainer.entity'; export class AppModule { static forRoot(settings): DynamicModule { return { module: AppModule, imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: ENV_FILE_PATH }), TypeOrmModule.forRootAsync({ imports: [ConfigModule], useFactory: (configService: ConfigService) => ({ type: 'mysql', host: configService.get('DATABASE_HOST'), port: configService.get<number>('DATABASE_PORT'), username: configService.get('DATABASE_USER'), password: configService.get('DATABASE_PASSWORD'), database: configService.get('DATABASE_NAME'), entities: [ PackageEntity, TrainerEntity, ], }), inject: [ConfigService], }), PackageModule, ], }; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Subida de Imágenes</title> <link rel="stylesheet" type="text/css" href="static/css/main.css"> <link rel="shortcut icon" href="static\imgs\favicon.ico"> </head> <body> <div id="image-uploader"> <h1>Subida de Imágenes</h1> <form method="post" enctype="multipart/form-data"> {{ form.hidden_tag() }} {{ form.csrf_token }} {{ form.imagenes.label }} {{ form.imagenes(multiple="multiple") }} <input type="submit" value="Subir Imagen"> </form> <label for="opciones">Selecciona una opción:</label> <select id="opciones" name="opciones"> <option value="opcion1" selected>U-Net</option> <option value="opcion2">W-Net</option> <option value="opcion3">clustering</option> </select> </div> <a href="{{ url_for('archivos') }}">Mis archivos</a> <a href="{{ url_for('orthomap') }}">Ortomapas</a> <div class="gallery" id="image-container"> {% if uploaded_images %} {% for image in uploaded_images.keys() %} <div class="image-container" data-instance="{{ loop.index }}"> {% if image %} <h2>Imagen Original</h2> <img src="{{ os.path.join('/', image) }}" alt="Original Image"> <!--button type="button" onclick="procesarImagen('{{ image|e }}')">Procesar Imagen</button--> <form class="miFormulario"> <input type="hidden" class="rutaImagen" value="{{image}}"> <button type="button" onclick=" procesarImagen('{{ loop.index }}')">Procesar Imagen</button> </form> <div class="Imagen_procesada"style="display: none;"> <h2>Imagen Procesada</h2> <img class="processed-image" alt="Processed Image"> <form class="processed-form" method="get"> <button type="submit">Descargar Imagen Procesada</button> </form> </div> {% endif %} </div> {% endfor %} {% endif %} </div> <script> function procesarImagen(instance) { console.log("asdaksjdnasdj") console.log(instance) var rutaImagen = document.querySelector('.image-container[data-instance="' + instance + '"] .rutaImagen').value; var boton = document.querySelector('.image-container[data-instance="' + instance + '"] button'); var selectElement = document.getElementById("opciones"); var selectedValue = selectElement.value; console.log(boton) boton.disabled = true; boton.classList.add('loading'); console.log(selectedValue) // Actualizar el atributo src de la imagen original // Acceder al valor del campo rutaImagen fetch('/process/', { method: 'POST', //body: rutaImagen, body: JSON.stringify({ opcionSeleccionada: selectedValue, imagen: rutaImagen }), headers: { //'X-CSRF-Token': obtenerCSRFToken(), 'Content-Type': 'application/json', } }) .then(response => response.text()) .then(data => { datosRespuesta = data; //console.log(data); document.querySelector('.image-container[data-instance="' + instance + '"] .processed-image').src = "/" + datosRespuesta; document.querySelector('.image-container[data-instance="' + instance + '"] .processed-form').action = "\/" + "download/" + datosRespuesta; document.querySelector('.image-container[data-instance="' + instance + '"] .Imagen_procesada').style.display = "block"; boton.disabled = false; boton.classList.remove('loading'); }) .catch(error => { console.error('Error en la solicitud fetch:', error); }); } </script> </body> </html>
#We often want to use a for loop to search through a list for some value items_on_sale = ["blue_shirt", "striped_socks", "knit_dress", "red_headband", "dinosaur_onesie"] # we want to check if the item with ID "knit_dress" is on sale: for item in items_on_sale: if item == "knit_dress": print("Knit Dress is on sale!") #But what if items_on_sale had 1000 items after "knit_dress"? #What if it had 100,000 items after "knit_dress"? #You can stop a for loop from inside the loop by using break. #When the program hits a break statement, control returns to the code #outside of the for loop. For example print("---------------------------") items_on_sale = ["blue_shirt", "striped_socks", "knit_dress", "red_headband", "dinosaur_onesie"] print("Checking the sale list!") for item in items_on_sale: print(item) if item == "knit_dress": break print("End of search!")
import React from 'react'; import NextLink from 'next/link'; import classNames from 'classnames'; type LinkProps = { href?: string; children: React.ReactNode; className?: string; variant?: 'primary' | 'secondary'; external?: boolean; underlined?: boolean; size?: 'sm' | 'base'; onClick?: () => void; }; const Link: React.FC<LinkProps> = ({ href, children, className, external = false, underlined = false, variant = 'primary', size = 'base', onClick, }) => { const isPrimary = variant === 'primary'; const styles = classNames( `border-none bg-transparent text-blueN300 p-0 font-bodyText text-${size}`, className, { underline: underlined }, { 'text-blueN300': isPrimary, 'text-grayN500 hover:text-blueN300': !isPrimary, 'font-bold': !isPrimary, } ); if (href && !external) { return ( <NextLink href={href}> <a className={styles} onClick={onClick}> {children} </a> </NextLink> ); } else if (href && external) { return ( <a rel="noreferrer" href={href} className={styles} target="_blank" onClick={onClick} > {children} </a> ); } return ( <button className={styles} onClick={onClick}> {children} </button> ); }; export default Link;
import "./Card.css"; import data from "../../data.json"; import { timeSpan } from "../../timespanStore"; import { useStore } from "@nanostores/react"; import PropTypes from "prop-types"; const timeSpans = { daily: "Yesterday", weekly: "Last Week", monthly: "Last Month", }; const Card = (props) => { const $timeSpan = useStore(timeSpan); return ( <div class="card"> <div class="banner" style={{ backgroundColor: props.bannerColor }}> <img class="banner__icon" src={props.icon} /> </div> <div class="data-card"> <h2 class="data-card__title">{data[props.index].title}</h2> <button class="data-card__ellipsis"> <img src={"svg/icon-ellipsis.svg"} /> </button> <h1 class="data-card__hours">{`${ data[props.index].timeframes[$timeSpan].current }hrs`}</h1> <h3 class="data-card__previous">{`${timeSpans[$timeSpan]} - ${ data[props.index].timeframes[$timeSpan].previous }hrs`}</h3> </div> </div> ); }; Card.defaultProps = { index: 0, icon: "svg/icon-work.svg", bannerColor: "hsl(15, 100%, 70%)", }; Card.propTypes = { index: PropTypes.number.isRequired, icon: PropTypes.string.isRequired, bannerColor: PropTypes.string.isRequired, }; export default Card;
<div class="gradient-creator"> <div class="gradient-creator__gradient-container"> <p class="gradient-creator__gradient-string">{{gradientString}}</p> <div class="gradient-creator__gradient" [ngStyle]="{'background-image': gradientString}"> <button (click)="addColor()" class="gradient-creator__button gradient-creator__button--add-color" title="add color"> <i class="fa fa-plus" aria-hidden="true"></i> </button> </div> </div> <div class="gradient-creator__options"> <div class="gradient-creator__angle"> <p class="gradient-creator__heading">angle</p> <input class="rgb-slider__number" type="range" min="0" max="360" (ngModelChange)="setAngle($event)" [formControl]="control" [(ngModel)]="angle"> </div> <div class="gradient-creator__colorlist"> <p class="gradient-creator__heading">Colors</p> <div class="gradient-creator__color" *ngFor="let color of colorList; let i = index"> <div class="gradient-creator__color-heading"> <p class="gradient-creator__color-name">{{RGBtoString(color)}}</p> <div class="gradient-creator__color-preview" [ngStyle]="{'background-color': RGBtoString(color)}"> </div> <button (click)="deleteColor(i)" title="delete color" class="gradient-creator__button" [disabled]="isOnlyOneColor()"> <i class="fa fa-times" aria-hidden="true"></i> </button> <button (click)="toggleSlidersVisibility(i)" title="toggle slider" class="gradient-creator__button gradient-creator__button--slider-toggle"> <i class="fa" [ngClass]="{'fa-angle-down': !visibilityArray[i], 'fa-angle-up': visibilityArray[i]}" aria-hidden="true"></i> </button> </div> <div class="gradient-creator__slider-container" [ngClass]="{'gradient-creator__slider-container--hidden': !visibilityArray[i] }"> <app-rgb-slider *ngFor="let item of rgbToArray(color); trackBy: trackByFn" [colorTupple]="item" (sliderChange)="handleChange($event, i)"></app-rgb-slider> </div> </div> </div> </div> </div>
<!DOCTYPE html> <html> <head> <title>Web assignment 1</title> <link rel="stylesheet" type="text/css" href="cssFile.css"> </head> <body> <div id="header"> <img id = "img" src="me.jpeg" alt="a picture of me"> <h1>Assg.1: CSS, JavaScript, and Forms</h1> <p>Brought to you by: <br> <b><u>Georges Abi Khalil</u></b></p> </div> <div id="nav"> <div id='drop-menu'> <ul> <li><a href="index.html"><span>Home</span></a></li> <li><a href="index.html"><span>About Me</span></a></li> <li class='active has-sub'><a href='#'><span>Courses</span></a> <ul> <li><a href='#'><span>CP1</span></a></li> <li class='last'><a href='#'><span>CP2</span></a></li> <li class='last'><a href='#'><span>CP3</span></a></li> <li class='last'><a href='#'><span>Computer organization</span></a></li> <li class='last'><a href='#'><span>Web programming</span></a></li> <li class='last'><a href='#'><span>Database</span></a></li> <li class='last'><a href='#'><span>Operating systems</span></a></li> </ul> </li> <li><a href="form.html"><span>Guest Book</span></a></li> </li> </ul> </li> </ul> </div> </div> </div> <div id="section"> <form onsubmit="return func();" name="myForm"> First name:<br><input type="text" name="firstname" id="fn"><br> Last name:<br><input type="text" name="lastname" id="ln"><br> Comments:<br><textarea name="message" rows="10" cols="30"></textarea><br> <input type="submit" value="Submit"> </form> <script> function func() { var first, last; first= document.getElementById("fn").value; last= document.getElementById("ln").value; if(first == null || first == "") { alert("first name is missing."); return false; } if(last == null || last == "") { alert("last name is missing."); return false; } } </script> </div> <div id="footer"> CSC 443, Assg 1, Fall 2015 </div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>🖥 Geek Ark</title> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="./main.css" /> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <main> <div class="arrow left-arrow">&#8249;</div> <section class="glass"> <div class="dashboard"> <div> <a href="index.html"> <img class="avatar" src="default_picture.jpg" alt="Avatar" style="border-radius: 50%; margin-top: 25px; margin-bottom: 10px;" /> <h3 id= "userName" >Alessia Rossi</h3> <div class="specialities-container"> <p>Web & Mobile Development</p> </div> </a> </div> <div class="links"> <a href="education.html"> <div class="link"> <img src="./images/education.png" width="40px" alt="" /> <h2>Education</h2> </div> </a> <a href="skills.html"> <div class="link"> <img src="./images/skills.png" width="40px" alt="" /> <h2>Skills</h2> </div> </a> <a href="experience.html"> <div class="link"> <img src="./images/experience.png" width="37px" alt="" /> <h3>Experience</h3> </div> </a> <a href="projects.html"> <div class="link"> <img src="./images/projects.png" width="37px" alt="" /> <h2>Projects</h2> </div> </a> </div> <div class="social"> <a href="https://facebook.com/k.choubari/"> <img src="./images/facebook.png" alt="" width="20px" /> </a> <a href="https://instagram.com/choubari_/"> <img src="./images/instagram.png" alt="" width="20px" /> </a> <a href="https://twitter.com/choubari_"> <img src="./images/twitter.png" alt="" width="20px" /> </a> <a href="https://github.com/choubari/"> <img src="./images/github.png" alt="" width="20px" /> </a> <a href="https://www.linkedin.com/in/kawtar-choubari-2226b0150/"> <img src="./images/linkedin.png" alt="" width="20px" /> </a> </div> </div> <div class="carditems"> <h1 class="userName">Hello World &#x1F44B !</h1> <br> <p id="bio"></a></p> <br> <p></p> <br> <p class="gradient-par">I'm currently looking for a summer internship on Web and/or Mobile development (from June to August 2023).</p> <br> <a href="https://drive.google.com/file/d/1NAfTZ_1FknrnCiSsQp9eKtZSka-f9QDV/view?usp=sharing" target="_blank"> <div class="glassbutton"> <p>Connect With me</p> </div> </a> </div> </section> <div class="arrow right-arrow">&#8250;</div> <!-- Add right arrow here --> </main> <div class="circle1"></div> <div class="circle2"></div> <script> const airtableApiKey = 'keyI8Sg86PWf1ocNE'; const airtableBaseId = 'appXGjV0zt5ytIrEe'; const tableName = 'Freelancers'; let currentRecordIndex = 0; const fetchAirtableData = async (recordIndex) => { try { const response = await axios.get(`https://api.airtable.com/v0/${airtableBaseId}/${tableName}`, { headers: { 'Authorization': `Bearer ${airtableApiKey}` } }); const record = response.data.records[recordIndex]; const userName = record.fields['Freelancer Name']; const bio = record.fields['Bio']; const pictureUrl = record.fields['Picture'][0].url; const serviceSpecialities = record.fields['Service specialities']; document.querySelector("h3").innerText = userName; const bioElement = document.querySelector(".carditems p"); if (bioElement) { bioElement.innerText = bio; } else { document.querySelector(".carditems").innerHTML = `<p>${bio}</p>`; } const avatarImage = document.querySelector(".avatar"); if (avatarImage) { avatarImage.src = pictureUrl; } const serviceSpecialitiesElement = document.querySelector(".specialities"); if (serviceSpecialitiesElement) { serviceSpecialitiesElement.innerText = serviceSpecialities; } else { document.querySelector(".specialities-container").innerHTML = `<p class="specialities">${serviceSpecialities}</p>`; } } catch (error) { console.error('Error fetching data:', error); } }; fetchAirtableData(currentRecordIndex); document.querySelector(".right-arrow").addEventListener("click", () => { currentRecordIndex++; fetchAirtableData(currentRecordIndex); }); document.querySelector(".left-arrow").addEventListener("click", () => { if (currentRecordIndex > 0) { currentRecordIndex--; fetchAirtableData(currentRecordIndex); } }); </script> </body> <script src="./airtable-data.js"></script> </html>
import React, { useState, useEffect } from 'react'; import PostList from './components/PostList'; import OpenedPost from './components/OpenedPost'; import NewPost from './components/NewPost'; import NewUser from './components/NewUser'; import EditUser from './components/EditUser'; import EditPost from './components/EditPost'; import NavBar from './components/NavBar'; import UserList from './components/UserList'; import OpenedUser from './components/OpenedUser'; import SignUp from './components/SignUp'; import LogIn from './components/LogIn'; import ResetPass from './components/ResetPass'; import ConfirmPass from './components/ConfirmPass'; import axios from 'axios' import { AuthContext } from './context' import './styles/style.css'; import avatar from './img/avatars/lufy.jpg' const { BrowserRouter, Routes, Route } = require('react-router-dom'); function App() { const [token, setToken] = useState(':token'); const [posts, setPosts] = useState([]); const [currentUser, setCurrentUser] = useState([]); const [section, setSection] = useState('Posts'); useEffect(() => { async function getPosts() { const response = await axios.get(`http://localhost:5000/api/posts/${token}`); setPosts(response.data); } async function getCurrentUser() { const response = await axios.get(`http://localhost:5000/api/users/get/current/${token}`); setCurrentUser(response.data); } getPosts(); getCurrentUser(); if (localStorage.getItem('auth') == null) { setToken(':token') } else { setToken(localStorage.getItem('auth')) } }, [token, posts]) return ( <div className="App"> <AuthContext.Provider value={{ token, setToken }}> <BrowserRouter> <NavBar id={currentUser.id} avatar={avatar} currentSection={section} setCurrentSection={setSection} login={currentUser.length === 0 ? 'guest' : currentUser.login} /> <Routes> <Route path='/' element={<PostList posts={posts} />} /> <Route path='/post/:id' element={<OpenedPost />} /> <Route path='/post/new/:token' element={<NewPost />} /> <Route path='/post/edit/:id' element={<EditPost />} /> <Route path='/users' element={<UserList setCurrentSection={setSection} />} /> <Route path='/users/:id' element={<OpenedUser setCurrentSection={setSection} />} /> <Route path='/users/new/:token' element={<NewUser />} /> <Route path='/users/edit/:token' element={<EditUser />} /> <Route path='/signup' element={<SignUp setCurrentSection={setSection} />} /> <Route path='/login' element={<LogIn setCurrentSection={setSection} />} /> <Route path='/reset_password' element={<ResetPass setCurrentSection={setSection} />} /> <Route path='/confirm_password/:token' element={<ConfirmPass />} /> </Routes> </BrowserRouter> </AuthContext.Provider> </div> ); } export default App;
package task2; /** * * @author ASUS */ public class Rectangle extends Shape{ private double width; private double length; public Rectangle(){ this.length=1.0; this.width=1.0; } public Rectangle(double width,double length){ this.length=length; this.width=width; } public Rectangle(double width,double length,String color,boolean filled){ super(color,filled); this.length=length; this.width=width; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getArea(){ return getLength()*getLength(); } public double getPerimeter(){ return (2*getWidth())+(2*getLength()); } public String toString(){ return "A Rectangle with width = "+getWidth()+" and length = "+getLength()+",which is a subclass of "+super.toString(); } }
use super::{super::utils::*, YEAR}; pub struct Solver {} impl DaySolver<i32> for Solver { fn part_one_driver(&self, input: &str) -> i32 { fn is_nice_string(s: &str) -> bool { let does_not_have_blacklisted_substrings = !(s.contains("ab") || s.contains("cd") || s.contains("pq") || s.contains("xy")); let num_vowels = s .chars() .filter(|c| match c { 'a' | 'e' | 'i' | 'o' | 'u' => true, _ => false, }) .count(); let has_double = 'has_double_check: { for i in 1..s.chars().count() { if s.chars().nth(i).unwrap() == s.chars().nth(i - 1).unwrap() { break 'has_double_check true; } } false }; does_not_have_blacklisted_substrings && num_vowels >= 3 && has_double } input.lines().filter(|line| is_nice_string(line)).count() as i32 } fn part_two_driver(&self, input: &str) -> i32 { fn is_nice_string(s: &str) -> bool { let mut pairs = Vec::new(); for index in 1..s.chars().count() { let a = s.chars().nth(index - 1).unwrap(); let b = s.chars().nth(index).unwrap(); // Store indices so we can check that they don't overlap pairs.push((index - 1, index, (a, b))); } let has_non_overlapping_pairs = 'found: { for i in 0..pairs.len() { for j in (i + 1)..pairs.len() { if pairs[i].2 == pairs[j].2 && pairs[i].1 != pairs[j].0 { break 'found true; } } } false }; let has_sandwiched_letter = 'found: { for i in 1..s.chars().count() - 1 { let prev = s.chars().nth(i - 1).unwrap(); let me = s.chars().nth(i).unwrap(); let next = s.chars().nth(i + 1).unwrap(); if me != prev && prev == next { break 'found true; } } false }; has_non_overlapping_pairs && has_sandwiched_letter } input.lines().filter(|line| is_nice_string(line)).count() as i32 } fn read_input(&self) -> String { read_input(YEAR, 5) } } #[cfg(test)] mod tests { use super::*; #[test] fn part_one_works() { let solver = Solver {}; let cases = vec![ ("ugknbfddgicrmopn", 1), ("aaa", 1), ("jchzalrnumimnmhp", 0), ("haegwjzuvuyypxyu", 0), ("dvszwmarrgswjxmb", 0), ]; for case in cases { assert_eq!(solver.part_one_driver(case.0), case.1, "input = {}", case.0); } assert_eq!(solver.part_one(), 258); } #[test] fn part_two_works() { let solver = Solver {}; let cases = vec![ ("qjhvhtzxzqqjkmpb", 1), ("xxyxx", 1), ("uurcxstgmygtbstg", 0), ("ieodomkazucvgmuy", 0), ]; for case in cases { assert_eq!(solver.part_two_driver(case.0), case.1, "input = {}", case.0); } assert_eq!(solver.part_two(), 53); } }
<template> <v-app-bar flat color="black"> <!-- --> <v-app-bar-nav-icon class="hidden-lg-and-up" @click="drawer = !drawer" ></v-app-bar-nav-icon> <v-toolbar-title class="ml-10">Wellcome {{ userName }} </v-toolbar-title> <div> <v-btn :to="{ name: 'purchases' }" class="hidden-md-and-down text-capitalize" >your purchases <v-icon class="ml-2">mdi-cash-multiple</v-icon> </v-btn> <v-btn class="hidden-md-and-down mr-10" v-if="isloggedIn" @click="handleSignOut()" >LogOut <v-icon>mdi-exit-to-app</v-icon> </v-btn> </div> </v-app-bar> <v-navigation-drawer color="black" v-model="drawer"> <v-list> <v-list-item> <v-icon>mdi-view-dashboard</v-icon> <v-btn variant="text" class="text-capitalize">navigation list</v-btn> </v-list-item> <v-list-item class="mt-5"> <v-icon>mdi-cash-multiple</v-icon> <v-btn variant="text" :to="{ name: 'purchases' }" class="text-capitalize" >your purchases </v-btn> </v-list-item> <v-list-item class="mt-5"> <v-icon>mdi-exit-to-app</v-icon> <v-btn variant="text" class="mr-10" v-if="isloggedIn" @click="handleSignOut()" >LogOut </v-btn> </v-list-item> </v-list> </v-navigation-drawer> </template> <script> import { mapMutations, mapState } from "vuex"; export default { name: "headerPage", data() { return { drawer: false, userName: localStorage.getItem("user-name"), }; }, mounted() {}, computed: { ...mapState(["isloggedIn"]), }, methods: { ...mapMutations(["handleSignOut", "logOut"]), }, }; </script>
package org.example; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; public class DataContainer { ArrayList<String> timeStrings; ArrayList<String> orderedVariableNames; Hashtable<String, ArrayList<Double>> data; int numberOfSamples = 0; public DataContainer(String csvFileName) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader(csvFileName)); orderedVariableNames = new ArrayList<String>(); timeStrings = new ArrayList<String>(); data = new Hashtable<String, ArrayList<Double>>(); String line; line = bufferedReader.readLine(); String[] tokens = line.split(","); int numberOfVariables = 0; for (int i = 1; i < tokens.length; i++) { orderedVariableNames.add(tokens[i]); data.put(tokens[i], new ArrayList<Double>()); numberOfVariables++; } while ((line = bufferedReader.readLine()) != null) { String[] values = line.split(","); for (int i = 0; i < numberOfVariables + 1; i++) { if (i == 0) { timeStrings.add(values[i]); } else { data.get(orderedVariableNames.get(i - 1)).add(Double.parseDouble(values[i])); } } } bufferedReader.close(); numberOfSamples = timeStrings.size(); } public int getNumberOfSamples() { return numberOfSamples; } public int getNumberOfVariables() { return data.size(); } public String[] getTimeStrings() { return timeStrings.toArray(new String[numberOfSamples]); } public Date[] getDates() throws ParseException { Date[] dates = new Date[numberOfSamples]; DateFormat format = new SimpleDateFormat("yyyy-MM-d HH:mm:ss"); for (int i = 0; i < numberOfSamples; i++) { dates[i] = format.parse(timeStrings.get(i)); } return dates; } public String[] getAvailableVariables() { return orderedVariableNames.toArray(new String[getNumberOfVariables()]); } public Double[] getData(String variableName) { return data.get(variableName).toArray(new Double[numberOfSamples]); } public void addData(String variableName, double[] values) { if (values.length != getNumberOfSamples()) { throw new RuntimeException(variableName + " has " + values.length + " samples instead of " + getNumberOfSamples()); } if (data.containsKey(variableName)) { throw new RuntimeException(variableName + " already exists"); } orderedVariableNames.add(variableName); ArrayList<Double> newValues = new ArrayList<Double>(); for (double value : values) { newValues.add(value); } data.put(variableName, newValues); } public void addData(String variableName, Double[] values) { double[] primitiveValues = new double[values.length]; for (int i = 0; i < values.length; i++) { primitiveValues[i] = values[i]; } addData(variableName, primitiveValues); } public String toString() { String string = getNumberOfVariables() + " variables: "; String firstRow = "["; String lastRow = "["; for (String variableName : getAvailableVariables()) { string += variableName + ", "; Double[] values = getData(variableName); firstRow += values[0] + ", "; lastRow += values[numberOfSamples - 1] + ", "; } string += "\n number of data: " + numberOfSamples + "\n"; string += getTimeStrings()[0] + ": " + firstRow + "]\n...\n" + getTimeStrings()[numberOfSamples - 1] + ": " + lastRow + "]\n"; return string; } }
import React, { useState, useEffect } from 'react'; const ImageSlider = ({ images, messages }) => { const [currentIndex, setCurrentIndex] = useState(0); const showNext = () => { setCurrentIndex((currentIndex + 1) % images.length); }; const showPrevious = () => { setCurrentIndex((currentIndex - 1 + images.length) % images.length); }; const buttonStyle = { position: 'absolute', top: '50%', transform: 'translateY(-50%)', backgroundColor: '#fff', border: '5px solid #ddd', padding: '8px 16px', borderRadius: '50px', cursor: 'pointer', outline: 'none', }; const messageStyle = { color: 'black', fontSize: '30px', fontWeight: 'bold', }; useEffect(() => { // You can add any additional logic or side effects here // when currentIndex changes (e.g., updating messages). }, [currentIndex]); return ( <div style={{ position: 'relative', overflow: 'hidden', textAlign: 'center' }}> <img src={images[currentIndex]} alt={`Slide ${currentIndex + 1}`} style={{ width: '20%', height: 'auto' }} /> <p style = {messageStyle} >{messages[currentIndex]}</p> <button style={{ ...buttonStyle, left: '10px' }} onClick={showPrevious}> Previous </button> <button style={{ ...buttonStyle, right: '10px' }} onClick={showNext}> Next </button> </div> ); }; export default ImageSlider;
import { type Infer, instance, nullable, integer, assign, number, object, string, any, } from "superstruct"; import { unique, albumBase, trackBase, artistBase, playlistBase, } from "@amadeus-music/protocol"; import { primary, crr, ordered, index, type Database } from "crstore"; import type { Struct } from "superstruct"; const id = integer; const boolean = integer as () => Struct<0 | 1, null>; const tracks = assign(unique(trackBase), object({ album: id() })); crr(tracks); index(tracks, "album"); primary(tracks, "id"); const albums = unique(albumBase); crr(albums); primary(albums, "id"); const artists = assign(unique(artistBase), object({ following: boolean() })); crr(artists); primary(artists, "id"); const attribution = object({ album: id(), artist: id(), }); crr(attribution); index(attribution, "artist"); primary(attribution, "album", "artist"); const sources = object({ source: string(), owner: id(), primary: boolean(), }); crr(sources); primary(sources, "owner", "source"); const assets = object({ art: string(), thumbnail: nullable(string()), owner: id(), primary: boolean(), }); crr(assets); primary(assets, "owner", "art"); const playlists = assign(unique(playlistBase), object({ order: string() })); crr(playlists); primary(playlists, "id"); ordered(playlists, "order"); index(playlists, "order", "id"); const library = object({ id: id(), playlist: id(), track: id(), date: integer(), order: string(), }); crr(library); primary(library, "id"); index(library, "date"); index(library, "track"); index(library, "playlist"); index(library, "order", "id"); ordered(library, "order", "playlist"); const playback = object({ id: id(), device: instance(Uint8Array), track: id(), order: string(), temp: any(), }); crr(playback); primary(playback, "id"); index(playback, "device"); index(playback, "order", "id"); ordered(playback, "order", "device"); const devices = object({ id: instance(Uint8Array), playback: id(), direction: integer(), infinite: integer(), progress: number(), repeat: integer(), }); crr(devices); primary(devices, "id"); const settings = object({ key: string(), value: string(), }); crr(settings); index(settings, "value"); primary(settings, "key"); const history = object({ query: string(), date: integer(), }); crr(history); index(history, "date"); primary(history, "query"); type Views = { queue: { id: number; device: Uint8Array; track: number; position: number }; }; export type Schema = Infer<typeof schema> & Views; export type DB = Database<Schema>; export const schema = object({ tracks, albums, attribution, artists, sources, assets, library, playlists, playback, devices, settings, history, });
<img width="800" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/3dacb9f8-5466-48d3-a81b-c689ed2e9978"/> # Gangwon-Pet-Trip <br> > **강원 펫 트립** <br> ## 1️⃣ 목적 & 구성 <br> > - 반려동물과 함께 강원도를 여행하고자 하는 이용자들에게 각 여행지의 위치와 정보 제공 > - [강원도 반려동물 동반관광 API시스템](https://www.pettravel.kr/petapi/api) 에서 제공하는 API를 활용 > - 데이터를 JSON 파일로 재가공 ### - 페이지 구성 ``` <App> <Header /> <Main /> <MainBanner /> <MainMap /> <Map /> <KeywordRecommend /> <CardSlide /> <ListCard /> <Hospital /> <City /> <FoodCate /> <CateCardSlide /> <ListCard /> <ExperienceCate /> <CateCardSlide /> <ListCard /> <HotelCate /> <CateCardSlide /> <ListCard /> <Category /> <CateList /> <ListCard /> <Pagination /> <Detail /> <DetailInfoList /> <DetailIntro /> <DetailPrice /> <DetailCaution /> <RecommendPlace /> <Footer /> ``` <br> ## 2️⃣ 프로젝트 역할 <br> > - 김현우 : 기획, 디자인(100%), 개발(100%) > - [오정석](https://github.com/jeong0214) : 기획 <br> ## 3️⃣ 프로젝트 사용 툴 ### Communication >![Slack](https://img.shields.io/badge/Slack-4A154B?style=for-the-badge&logo=Slack&logoColor=white) >![Notion](https://img.shields.io/badge/Notion-000000?style=for-the-badge&logo=Notion&logoColor=white) ### Environment > <img src="https://img.shields.io/badge/Figma-F24E1E?style=for-the-badge&logo=figma&logoColor=white"/> >![Visual Studio Code](https://img.shields.io/badge/Visual%20Studio%20Code-007ACC?style=for-the-badge&logo=Visual%20Studio%20Code&logoColor=white) >![Git](https://img.shields.io/badge/Git-F05032?style=for-the-badge&logo=Git&logoColor=white) >![Github](https://img.shields.io/badge/GitHub-181717?style=for-the-badge&logo=GitHub&logoColor=white) ### Development > <img src="https://img.shields.io/badge/React-61DAFB?style=for-the-badge&logo=react&logoColor=white"/> > <img src="https://img.shields.io/badge/javascript-F7DF1E?style=for-the-badge&logo=javascript&logoColor=black"> <br> ## 4️⃣ 기획 & 설계 시안 <br> > - [약식기획서 (figjam)](https://www.figma.com/file/zP3ONk3pY9sfOYamSRjl0N/with-my-pet?type=whiteboard&t=GIJbVjxciEZG0fYb-1) > - [설계 시안 (figma)](https://www.figma.com/file/1JIeWlzenjTkxptlkc70tX/Project4-Gangwon-Pet-Trip?type=design&node-id=0%3A1&t=GIJbVjxciEZG0fYb-1) <br> ## 5️⃣ 이슈 히스토리 <br> > 1. 빈 데이터와 오류가 생기는 데이터들이 있어 API 활용 단계에서 JS코드를 활용해 API의 데이터들을 JSON파일로 재가공했습니다. > <img src="https://user-images.githubusercontent.com/119498531/235096445-11dcdfa4-146d-4220-ae78-ba2a094eee92.png"> ```const https = require("https"); const querystring = require("querystring"); const fs = require("fs"); const baseUrl = "https://www.pettravel.kr/api/detailSeqPart.do"; const allData = []; for (let i = 1; i <= 5; i++) { // PC01 ~ PC05 for (let j = 1; j <= 500; j++) { // contentNum 1 ~ 500 const queryParams = querystring.stringify({ partCode: "PC" + i.toString().padStart(2, "0"), contentNum: j, }); const url = `${baseUrl}?${queryParams}`; https .get(url, (res) => { let data = ""; res.on("data", (chunk) => { data += chunk; }); res.on("end", () => { const jsonData = JSON.parse(data); if (jsonData.length > 0 && jsonData[0].errorCode !== "ERR_03") { allData.push(...jsonData); } if (i === 5 && j === 500) { const fileName = "allData.json"; fs.writeFile(fileName, JSON.stringify(allData), (err) => { if (err) { console.error(err); } else { console.log(`All data saved to file ${fileName}`); } }); } }); }) .on("error", (err) => { console.log("Error: " + err.message); }); } } ``` <br> <br> > 2. 기존 클릭시 클릭을 제외한 모든 요소에 'on'클래스를 제거하고 클릭한 요소에만 'on'클래스를 붙여 <br> > css요소를 추가하거나 기능이 구현되는 것을 document.qurearySelect로 불러와 forEach문을 활용했지만<br> > react에서 개발할때는 제한이 있음을 느꼈습니다. map함수로 만든 요소에 클릭할 시 useState의 setSelectedAreaLink에 <br> > 배열값을 넣고 className에 selectedAreaLink의 값이 넣은 배열의 값과 같다면 'on'클래스가 붙게 하는 방법을 활용했습니다. ``` {areaNames.map((name, i) => ( <Link to="#" key={i} className={`${areaClass[i]} ${ selectedAreaLink === areaNames[i] ? "on" : "" }`} onClick={() => { setSelectedAreaLink(areaNames[i]); }} > <i className="fa-solid fa-location-dot mapPin"></i> <span>{name}</span> </Link> ))} ``` <br> <br> > 3. 데이터 필터링을 하기위해 filter함수를 사용했지만 부정의 의미인 "!" 를 사용했지만 작동하지 않았습니다.<br> > "!" 가 "===" 보다 연산자 순위가 높은것을 확인하고 괄호로 처리해준다음 "!"를 붙여줬습니다. ``` let selectedCityData = list.filter( (item) => item.resultList.areaName.includes(selectedCity) && !(item.resultList.partName === "동물병원") ); ``` <br> <br> > 4. 페이지 내에서 select요소로 지역을 변경하면 useState의 변수뿐만 아니라 url자체도 바뀌지 않았습니다.<br> > 해결 방법으로 useEffect와 window.history.replaceState를 활용했습니다. ``` useEffect(() => { window.history.replaceState("", "", `/city/${selectedCity}`); }, [selectedCity]); ``` <br> <br> > 5. 이전 페이지에서 useParams로 가져온 카테코리명에 따라 배너의 이미지의 url이 바뀌어야했는데<br> > css에서 넣는 방식과 동일하게 작성했더니 작동되는 배경의 주소와 변수로 집어넣은 주소가 console창에 찍히는게<br> > 다르다는것을 확인했습니다. css에서 작성한 주소가 아니기 때문에 경로 앞에 ${process.env.PUBLIC_URL}를 붙여주고<br> > styled-component를 install하여 사용했습니다. ``` let categoryUrl = categoryName === "food" ? `${process.env.PUBLIC_URL}/img/categoryBg1.jpg` : categoryName === "experience" ? `${process.env.PUBLIC_URL}/img/categoryBg2.jpg` : categoryName === "hotel" ? `${process.env.PUBLIC_URL}/img/categoryBg3.jpg` : ""; let BannerTitle = styled.section` background-image: url(${categoryUrl}); `; ``` <br> ## 6️⃣ 화면구성 📺 <br> > - 메인화면 > <img width="350" alt="image" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/c9acf737-5132-443b-b59c-8692939b83d0"> <br> <br> > - 검색모달 > <img width="350" alt="image" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/737f2775-7cbc-4c64-8af5-d618ad17f2cc"> <br> <br> > - 지역 페이지 > <img width="350" alt="image" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/c6205568-60e8-4bf6-b318-4ab0692300fd"> <br> <br> > - 카테고리 페이지 > <img width="350" alt="image" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/bb9a785c-95e1-4a66-bca0-2db76e4cc61a"> <br> <br> > - 디테일 페이지 > <img width="350" alt="image" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/47478fad-d11a-42bb-810e-6e0925dbee71"> <br> <br> > - 병원 지도 페이지 > <img width="350" alt="image" src="https://github.com/KHW1025/Gangwon-Pet-Trip/assets/119498531/da8ac140-5d64-4f52-9887-374c7520ff96">
# -*- coding: utf-8 -*- # Amara, universalsubtitles.org # # Copyright (C) 2013 Participatory Culture Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see # http://www.gnu.org/licenses/agpl-3.0.html. import datetime from django.test import TestCase from babelsubs.storage import SubtitleLine, SubtitleSet from apps.auth.models import CustomUser as User from apps.teams.models import Team, TeamVideo from apps.subtitles import pipeline from apps.subtitles.models import SubtitleLanguage, SubtitleVersion from apps.videos.models import Video, VIDEO_TYPE_BRIGHTCOVE from apps.videos.types import video_type_registrar, VideoTypeError from apps.videos.types.base import VideoType, VideoTypeRegistrar from apps.videos.types.bliptv import BlipTvVideoType from apps.videos.types.brigthcove import BrightcoveVideoType from apps.videos.types.dailymotion import DailymotionVideoType from apps.videos.types.flv import FLVVideoType from apps.videos.types.htmlfive import HtmlFiveVideoType from apps.videos.types.kaltura import KalturaVideoType from apps.videos.types.mp3 import Mp3VideoType from apps.videos.types.vimeo import VimeoVideoType from apps.videos.types.youtube import ( YoutubeVideoType, _prepare_subtitle_data_for_version, add_credit, should_add_credit ) from utils import test_utils class YoutubeVideoTypeTest(TestCase): fixtures = ['test.json'] def setUp(self): self.vt = YoutubeVideoType self.data = [{ 'url': 'http://www.youtube.com/watch#!v=UOtJUmiUZ08&feature=featured&videos=Qf8YDn9mbGs', 'video_id': 'UOtJUmiUZ08' },{ 'url': 'http://www.youtube.com/v/6Z5msRdai-Q', 'video_id': '6Z5msRdai-Q' },{ 'url': 'http://www.youtube.com/watch?v=woobL2yAxD4', 'video_id': 'woobL2yAxD4' },{ 'url': 'http://www.youtube.com/watch?v=woobL2yAxD4&amp;playnext=1&amp;videos=9ikUhlPnCT0&amp;feature=featured', 'video_id': 'woobL2yAxD4' }] self.shorter_url = "http://youtu.be/HaAVZ2yXDBo" def test_create_kwars(self): vt = self.vt('http://www.youtube.com/watch?v=woobL2yAxD4') kwargs = vt.create_kwars() self.assertEqual(kwargs, {'videoid': 'woobL2yAxD4'}) def test_set_values(self): youtbe_url = 'http://www.youtube.com/watch?v=_ShmidkrcY0' video, created = Video.get_or_create_for_url(youtbe_url) vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.videoid, '_ShmidkrcY0') self.assertTrue(video.title) self.assertEqual(video.duration, 79) self.assertTrue(video.thumbnail) def test_matches_video_url(self): for item in self.data: self.assertTrue(self.vt.matches_video_url(item['url'])) self.assertFalse(self.vt.matches_video_url('http://some-other-url.com')) self.assertFalse(self.vt.matches_video_url('')) self.assertFalse(self.vt.matches_video_url('http://youtube.com/')) self.assertFalse(self.vt.matches_video_url('http://youtube.com/some-video/')) self.assertTrue(self.vt.matches_video_url(self.shorter_url)) def test_get_video_id(self): for item in self.data: self.failUnlessEqual(item['video_id'], self.vt._get_video_id(item['url'])) def test_shorter_format(self): vt = self.vt(self.shorter_url) self.assertTrue(vt) self.assertEqual(vt.video_id , self.shorter_url.split("/")[-1]) def test_data_prep(self): video = Video.objects.all()[0] subs = [ (0, 1000, 'Hi'), (2000, 3000, 'How are you?'), ] new_sv = pipeline.add_subtitles(video, 'en', subs) content, t, code = _prepare_subtitle_data_for_version(new_sv) srt = "1\r\n00:00:00,000 --> 00:00:01,000\r\nHi\r\n\r\n2\r\n00:00:02,000 --> 00:00:03,000\r\nHow are you?\r\n\r\n3\r\n00:01:52,000 --> 00:01:55,000\r\nSubtitles by the Amara.org community\r\n" self.assertEquals(srt, content) self.assertEquals('', t) self.assertEquals('en', code) class HtmlFiveVideoTypeTest(TestCase): def setUp(self): self.vt = HtmlFiveVideoType def test_type(self): url = 'http://someurl.com/video.ogv?val=should&val1=be#removed' clean_url = 'http://someurl.com/video.ogv' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.url, clean_url) self.assertEqual(self.vt.video_url(vu), vu.url) self.assertTrue(self.vt.matches_video_url(url)) self.assertTrue(self.vt.matches_video_url('http://someurl.com/video.ogg')) self.assertTrue(self.vt.matches_video_url('http://someurl.com/video.mp4')) self.assertTrue(self.vt.matches_video_url('http://someurl.com/video.m4v')) self.assertTrue(self.vt.matches_video_url('http://someurl.com/video.webm')) self.assertFalse(self.vt.matches_video_url('http://someurl.ogv')) self.assertFalse(self.vt.matches_video_url('')) #for this is other type self.assertFalse(self.vt.matches_video_url('http://someurl.com/video.flv')) self.assertFalse(self.vt.matches_video_url('http://someurl.com/ogv.video')) class Mp3VideoTypeTest(TestCase): def setUp(self): self.vt = Mp3VideoType def test_type(self): url = 'http://someurl.com/audio.mp3?val=should&val1=be#removed' clean_url = 'http://someurl.com/audio.mp3' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.url, clean_url) self.assertEqual(self.vt.video_url(vu), vu.url) self.assertTrue(self.vt.matches_video_url(url)) self.assertTrue(self.vt.matches_video_url('http://someurl.com/audio.mp3')) self.assertFalse(self.vt.matches_video_url('http://someurl.com/mp3.audio')) class BlipTvVideoTypeTest(TestCase): def setUp(self): self.vt = BlipTvVideoType def test_type(self): url = 'http://blip.tv/day9tv/day-9-daily-438-p3-build-orders-made-easy-newbie-tuesday-6066868' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() # this is the id used to embed videos self.assertEqual(vu.videoid, 'hdljgvKmGAI') self.assertTrue(video.title) self.assertTrue(video.thumbnail) self.assertTrue(vu.url) self.assertTrue(self.vt.matches_video_url(url)) self.assertTrue(self.vt.matches_video_url('http://blip.tv/day9tv/day-9-daily-438-p3-build-orders-made-easy-newbie-tuesday-6066868')) self.assertFalse(self.vt.matches_video_url('http://blip.tv')) self.assertFalse(self.vt.matches_video_url('')) def test_video_title(self): url = 'http://blip.tv/day9tv/day-9-daily-100-my-life-of-starcraft-3505715' video, created = Video.get_or_create_for_url(url) #really this should be jsut not failed self.assertTrue(video.get_absolute_url()) def test_creating(self): # this test is for ticket: https://www.pivotaltracker.com/story/show/12996607 url = 'http://blip.tv/day9tv/day-9-daily-1-flash-vs-hero-3515432' video, created = Video.get_or_create_for_url(url) class DailymotionVideoTypeTest(TestCase): def setUp(self): self.vt = DailymotionVideoType def test_type(self): url = 'http://www.dailymotion.com/video/x7u2ww_juliette-drums_lifestyle#hp-b-l' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.videoid, 'x7u2ww') self.assertTrue(video.title) self.assertTrue(video.thumbnail) self.assertEqual(vu.url, 'http://dailymotion.com/video/x7u2ww') self.assertTrue(self.vt.video_url(vu)) self.assertTrue(self.vt.matches_video_url(url)) self.assertFalse(self.vt.matches_video_url('')) self.assertFalse(self.vt.matches_video_url('http://www.dailymotion.com')) def test_type1(self): url = u'http://www.dailymotion.com/video/edit/xjhzgb_projet-de-maison-des-services-a-fauquembergues_news' vt = self.vt(url) try: vt.get_metadata(vt.videoid) self.fail('This link should return wrong response') except VideoTypeError: pass class FLVVideoTypeTest(TestCase): def setUp(self): self.vt = FLVVideoType def test_type(self): url = 'http://someurl.com/video.flv?val=should&val1=be#removed' clean_url = 'http://someurl.com/video.flv' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.url, clean_url) self.assertEqual(self.vt.video_url(vu), vu.url) self.assertTrue(self.vt.matches_video_url(url)) self.assertFalse(self.vt.matches_video_url('http://someurl.flv')) self.assertFalse(self.vt.matches_video_url('')) self.assertFalse(self.vt.matches_video_url('http://someurl.com/flv.video')) def test_blip_type(self): url = 'http://blip.tv/file/get/Coldguy-SpineBreakersLiveAWizardOfEarthsea210.FLV' video, created = Video.get_or_create_for_url(url) video_url = video.videourl_set.all()[0] self.assertEqual(self.vt.abbreviation, video_url.type) class VimeoVideoTypeTest(TestCase): def setUp(self): self.vt = VimeoVideoType def test_type(self): url = 'http://vimeo.com/15786066?some_param=111' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.videoid, '15786066') self.assertTrue(self.vt.video_url(vu)) self.assertTrue(self.vt.matches_video_url(url)) self.assertFalse(self.vt.matches_video_url('http://vimeo.com')) self.assertFalse(self.vt.matches_video_url('')) def test1(self): #For this video Vimeo API returns response with strance error #But we can get data from this response. See vidscraper.sites.vimeo.get_shortmem #So if this test is failed - maybe API was just fixed and other response is returned # FIXME: restablish when vimeo api is back! return url = u'http://vimeo.com/22070806' video, created = Video.get_or_create_for_url(url) self.assertNotEqual(video.title, '') self.assertNotEqual(video.description, '') vu = video.videourl_set.all()[:1].get() self.assertEqual(vu.videoid, '22070806') self.assertTrue(self.vt.video_url(vu)) class VideoTypeRegistrarTest(TestCase): def test_base(self): registrar = VideoTypeRegistrar() class MockupVideoType(VideoType): abbreviation = 'mockup' name = 'MockUp' registrar.register(MockupVideoType) self.assertEqual(registrar[MockupVideoType.abbreviation], MockupVideoType) self.assertEqual(registrar.choices[-1], (MockupVideoType.abbreviation, MockupVideoType.name)) def test_video_type_for_url(self): type = video_type_registrar.video_type_for_url('some url') self.assertEqual(type, None) type = video_type_registrar.video_type_for_url('http://youtube.com/v=UOtJUmiUZ08') self.assertTrue(isinstance(type, YoutubeVideoType)) return self.assertRaises(VideoTypeError, video_type_registrar.video_type_for_url, 'http://youtube.com/v=100500') class BrightcoveVideoTypeTest(TestCase): def setUp(self): self.vt = BrightcoveVideoType def test_type(self): url = 'http://link.brightcove.com/services/player/bcpid955357260001?bckey=AQ~~,AAAA3ijeRPk~,jc2SmUL6QMyqTwfTFhUbWr3dg6Oi980j&bctid=956115196001' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.all()[:1].get() self.assertTrue(vu.type == VIDEO_TYPE_BRIGHTCOVE == BrightcoveVideoType.abbreviation) self.assertTrue(self.vt.video_url(vu)) self.assertTrue(self.vt.matches_video_url(url)) def test_redirection(self): url = 'http://bcove.me/7fa5828z' vt = video_type_registrar.video_type_for_url(url) self.assertTrue(vt) self.assertEqual(vt.video_id, '956115196001') class CreditTest(TestCase): def setUp(self): original_video , created = Video.get_or_create_for_url("http://www.example.com/original.mp4") original_video.duration = 10 original_video.save() self.original_video = original_video self.language = SubtitleLanguage.objects.create( video=original_video, language_code='en', is_forked=True) self.version = pipeline.add_subtitles( self.original_video, self.language.language_code, [], created=datetime.datetime.now(), ) def _sub_list_to_sv(self, subs): sublines = [] for sub in subs: sublines.append(SubtitleLine( sub['start'], sub['end'], sub['text'], {}, )) user = User.objects.all()[0] new_sv = pipeline.add_subtitles( self.original_video, self.language.language_code, sublines, author=user, ) return new_sv def _subs_to_sset(self, subs): sset = SubtitleSet(self.language.language_code) for s in subs: sset.append_subtitle(*s) return sset def test_last_sub_not_synced(self): subs = [SubtitleLine( 2 * 1000, None, 'text', {}, )] last_sub = subs[-1] self.assertEquals(last_sub.end_time, None) subs = add_credit(self.version, self._subs_to_sset(subs)) self.assertEquals(last_sub.text, subs[-1].text) def test_straight_up_video(self): subs = [SubtitleLine( 2 * 1000, 3 * 1000, 'text', {}, )] subs = add_credit(self.version, self._subs_to_sset(subs)) last_sub = subs[-1] self.assertEquals(last_sub.text, "Subtitles by the Amara.org community") self.assertEquals(last_sub.start_time, 7000) self.assertEquals(last_sub.end_time, 10 * 1000) def test_only_a_second_left(self): subs = [SubtitleLine( 2 * 1000, 9 * 1000, 'text', {}, )] subs = add_credit(self.version, self._subs_to_sset(subs)) last_sub = subs[-1] self.assertEquals(last_sub.text, "Subtitles by the Amara.org community") self.assertEquals(last_sub.start_time, 9000) self.assertEquals(last_sub.end_time, 10 * 1000) def test_no_space_left(self): self.original_video.duration = 10 self.original_video.save() subs = [SubtitleLine( 2 * 1000, 10 * 1000, 'text', {}, )] subs = add_credit(self.version, self._subs_to_sset(subs)) self.assertEquals(len(subs), 1) last_sub = subs[-1] self.assertEquals(last_sub.text, 'text') def test_should_add_credit(self): sv = SubtitleVersion.objects.filter( subtitle_language__video__teamvideo__isnull=True)[0] self.assertTrue(should_add_credit(sv)) video = sv.subtitle_language.video team, created = Team.objects.get_or_create(name='name', slug='slug') user = User.objects.all()[0] TeamVideo.objects.create(video=video, team=team, added_by=user) sv = SubtitleVersion.objects.filter( subtitle_language__video__teamvideo__isnull=False)[0] self.assertFalse(should_add_credit(sv)) class KalturaVideoTypeTest(TestCase): def test_type(self): url = 'http://cdnbakmi.kaltura.com/p/1492321/sp/149232100/serveFlavor/entryId/1_zr7niumr/flavorId/1_djpnqf7y/name/a.mp4' video, created = Video.get_or_create_for_url(url) vu = video.videourl_set.get() self.assertEquals(vu.type, 'K') self.assertEquals(vu.kaltura_id(), '1_zr7niumr')
#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc.hpp> #include <vector> class TrackerData { public: int thres, ratio_green, size_open, size_close, size_blur, ratio_blue; TrackerData(int thres_, int ratio1, int ratio2, int size1, int size2, int size3) { thres = thres_; ratio_green = ratio_green; ratio_blue = ratio2; size_open = size1; size_close = size2; size_blur = size3; } }; void Onchange_thres(int value, void* data) { TrackerData &user_data = *(TrackerData*)data; user_data.thres = value; } void Onchange_ratio_green(int value, void* data) { TrackerData &user_data = *(TrackerData*)data; user_data.ratio_green = value; } void Onchange_ratio_blue(int value, void* data) { TrackerData &user_data = *(TrackerData*)data; user_data.ratio_blue = value; } void Onchange_size_open(int value, void* data) { TrackerData &user_data = *(TrackerData*)data; user_data.size_open = value; } void Onchange_size_close(int value, void* data) { TrackerData &user_data = *(TrackerData*)data; user_data.size_close = value; } void Onchange_size_blur(int value, void* data) { TrackerData &user_data = *(TrackerData*)data; if (value % 2 == 0) value += 1; user_data.size_blur = value; } int main() { cv::Mat apple = cv::imread("../apple.png"); assert(apple.channels() == 3); cv::Mat result; int thres = 110, ratio_green = 958, ratio_blue = 565, size_open = 17, size_close = 3, size_blur = 7; TrackerData data = TrackerData(thres, ratio_green, ratio_blue, size_open, size_close, size_blur); cv::namedWindow("result"); cv::createTrackbar("thres", "result", &thres, 200, Onchange_thres, &data); cv::createTrackbar("ratio_green", "result", &ratio_green, 2000, Onchange_ratio_green, &data); cv::createTrackbar("ratio_blue", "result", &ratio_blue, 1000, Onchange_ratio_blue, &data); cv::createTrackbar("size_open", "result", &size_open, 50, Onchange_size_open, &data); cv::createTrackbar("size_close", "result", &size_close, 50, Onchange_size_close, &data); cv::createTrackbar("size_blur", "result", &size_blur, 50, Onchange_size_blur, &data); while(true) { cv::Mat channels[3]; cv::split(apple, channels); channels[2] -= channels[1] * 1.0 * data.ratio_green / 1000 + 1.0 * channels[0] * data.ratio_blue / 1000; cv::threshold(channels[2], result, 1.0 * data.thres / 10, 255, cv::THRESH_BINARY); cv::Mat kernel_open = cv::getStructuringElement(cv::MORPH_ELLIPSE, {data.size_open, data.size_open}); cv::morphologyEx(result, result, cv::MORPH_OPEN, kernel_open); cv::Mat kernel_close = cv::getStructuringElement(cv::MORPH_ELLIPSE, {data.size_close, data.size_close}); cv::morphologyEx(result, result, cv::MORPH_CLOSE, kernel_close); cv::medianBlur(result, result, data.size_blur); // cv::imshow("result", result); // cv::waitKey(0); std::vector< std::vector<cv::Point> > contours; std::vector< cv::Vec4i > hierachy; cv::Mat contour_result = apple.clone(); cv::findContours(result, contours, hierachy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE); int max_contour_id = std::max_element(contours.begin(), contours.end(), [](const std::vector<cv::Point> &c1, const std::vector<cv::Point> &c2) { return cv::contourArea(c1) < cv::contourArea(c2); }) - contours.begin(); cv::drawContours(contour_result, contours, max_contour_id, {220, 220, 220}, 1); cv::rectangle(contour_result, cv::boundingRect(contours[max_contour_id]),{220, 220, 220}, 2); cv::imshow("contour", contour_result); cv::waitKey(0); } return 0; }
package edu.study.module.springbootrabbitmq.demo; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * 测试使用:RabbitMQ 简单工作模式(hello world) * <pre> * 1.创建链接工厂; * 2.创建链接Connection * 3.通过链接获取通道Channel * 4.通过创建交换机,声明队列,绑定关系,路由key,发送消息,和接受消息; * 5.准备消息内容 * 6.发送消息给队列queue * 7.关闭链接 * 8.关闭通道 * </pre> * * @author zl * @create 2021-08-16 11:06 */ public class RabbitmqDemoProductor { public static void main(String[] args) { // 1. 创建链接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("192.168.174.156"); connectionFactory.setPort(5672); connectionFactory.setUsername("admin"); connectionFactory.setPassword("admin"); connectionFactory.setConnectionTimeout(6000); connectionFactory.setVirtualHost("/"); // 2.创建链接 Connection connection = null; Channel channel = null; try { connection = connectionFactory.newConnection("生产者"); channel = connection.createChannel(); String queueName = "queue1"; /** * 队列声明信息 * 1.队列名称 * 2.是否要持久化durable=false,所谓持久化消息是否存盘,如果false,非持久化true是否持久化?非持久化会存盘嘛?会存盘,但是会随着rabbitmq服务的关闭而丢失 * 3.排他性,是否是独占队列 * 4.是否自动删除,随着最后一个消息完毕消息以后是否吧队列自动删除 * 5.携带附属参数 */ channel.queueDeclare(queueName, false, false,false,null); String message = "hello world"; channel.basicPublish("", queueName, MessageProperties.PERSISTENT_BASIC, message.getBytes()); System.out.println("消息发送成功。。。"); } catch (Exception e) { e.printStackTrace(); } finally { // 关闭通道 if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } catch (TimeoutException e) { e.printStackTrace(); } } // 关闭链接 if (connection != null && connection.isOpen()) { try { connection.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
import React, { useState } from "react"; import { useNavigate } from "react-router-dom"; import axios from "axios"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; import { MDBContainer, MDBRow, MDBCol, MDBCard, MDBCardBody, MDBInput, } from "mdb-react-ui-kit"; import "../../styles/NewSubmit.css"; const NewSubmit = () => { const [otp, setOTP] = useState(""); const [password, setPassword] = useState(""); const navigate = useNavigate(); // Handle fomr submit const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios.post( `${process.env.REACT_APP_API}/api/v1/auth/submit-otp`, { otp: otp, password: password, } ); console.log(response); if (response && response.data.success) { toast.success("Password updated Successfully"); navigate("/login"); } else { toast.error(response.data.message); } } catch (error) { toast.error("Something went wrong"); } }; return ( <> <MDBContainer fluid className="p-4 background-radial-gradient overflow-hidden" > <MDBRow className="justify-content-center align-items-center" style={{ minHeight: "100vh" }} > <MDBCol md="6" className="text-center text-md-start d-flex flex-column justify-content-center" > <h1 className="my-5 display-3 fw-bold ls-tight px-3" style={{ color: "hsl(218, 81%, 95%)" }} > The best offer <br /> <span style={{ color: "hsl(218, 81%, 75%)" }}> for your business </span> </h1> <p className="px-3" style={{ color: "hsl(218, 81%, 85%)" }}> Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet, itaque accusantium odio, soluta, corrupti aliquam quibusdam tempora at cupiditate quis eum maiores libero veritatis? Dicta facilis sint aliquid ipsum atque? </p> </MDBCol> <MDBCol md="6" className="position-relative"> <div id="radius-shape-7" className="position-absolute rounded-circle shadow-5-strong" ></div> <div id="radius-shape-8" className="position-absolute shadow-5-strong" ></div> <MDBCard className="my-5 bg-glass"> <MDBCardBody className="p-5"> <MDBInput value={otp} onChange={(e) => setOTP(e.target.value)} placeholder="Enter OTP" wrapperClass="mb-3" label="OTP" id="form2" type="text" /> <MDBInput value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Enter Your New Password" wrapperClass="mb-3" label="New Password" id="form2" type="password" /> <button type="button" className="btn btn-primary w-100 mb-4" style={{ maxWidth: "600px", margin: "0 auto" }} onClick={handleSubmit} > Reset Password </button> </MDBCardBody> </MDBCard> </MDBCol> </MDBRow> </MDBContainer> <ToastContainer position="top-center" theme="dark" autoClose={1000} /> </> ); }; export default NewSubmit;
const OPTIONS = ["Internship", "Pabau", "Employment", "Career"]; let optionsState = OPTIONS.map((option) => ({ name: option, checked: false })); function mountOption(option) { const { name, checked } = option; const checkboxContainer = document.getElementById("checkboxContainer"); const divWrapper = document.createElement("div"); divWrapper.setAttribute("id", `div-${name}`); const input = document.createElement("input"); input.setAttribute("type", "checkbox"); input.setAttribute("id", `input-${name}`); input.setAttribute("value", name); input.checked = checked; const label = document.createElement("label"); label.innerText = name; divWrapper.appendChild(input); divWrapper.appendChild(label); checkboxContainer.appendChild(divWrapper); } function mountOptions(opsState) { for (const option of opsState) { mountOption(option); } } function clearOptions() { const checkboxContainer = document.getElementById("checkboxContainer"); let child = checkboxContainer.lastElementChild; while (child) { checkboxContainer.removeChild(child); child = checkboxContainer.lastElementChild; } } function shuffleOptions() { let shuffledOptions = optionsState .map((value) => ({ ...value, sort: Math.random(), })) .sort((a, b) => a.sort - b.sort) .map(({ name, checked }) => ({ name, checked })); shuffledOptions = shuffledOptions.map((option) => { const { name, checked } = option; const input = document.getElementById(`input-${name}`); const isChecked = input?.checked; return { name, checked: isChecked, }; }); optionsState = shuffledOptions; const checkboxContainer = document.getElementById("checkboxContainer"); clearOptions(); mountOptions(optionsState); } function changeValues() { const checkboxContainer = document.getElementById("checkboxContainer"); checkboxContainer.childNodes; for (const node of checkboxContainer.childNodes) { const input = node.childNodes[0]; input.checked = Math.random() > 0.5; } } function showSelectedValues() { const selectedValues = document.getElementById("selectedValues"); const checkboxContainer = document.getElementById("checkboxContainer"); const nodes = checkboxContainer.childNodes; let textToShow = "Selected values: "; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; const input = node.childNodes[0]; const label = node.childNodes[1].innerText; if (input.checked) { textToShow += `${label}, `; } } if (textToShow) { textToShow = textToShow.slice(0, -2); } selectedValues.innerText = textToShow; } document.addEventListener("DOMContentLoaded", function () { mountOptions(optionsState); shuffleBtn.addEventListener("click", shuffleOptions); changeBtn.addEventListener("click", changeValues); showBtn.addEventListener("click", showSelectedValues); });
#pragma once #include "Component.h" #include "Auxiliar/Generics/Drawable.h" #include <vector> #include <memory> class EmitterInstance; class ParticleEmitter; class ResourceParticleSystem; class ComponentParticleSystem : public Component, public Drawable { public: ComponentParticleSystem(const bool active, GameObject* owner); ComponentParticleSystem(const ComponentParticleSystem& toCopy, GameObject* parent); ~ComponentParticleSystem() override; void Play(); void Pause(); void Stop(); void Update(); void Reset(); void Draw() const override; void Render(); void SaveConfig(); bool IsEmittersEmpty() const; bool IsPlaying() const; bool IsFinished() const; std::vector<EmitterInstance*> GetEmitters() const; bool GetPlayAtStart() const; const std::shared_ptr<ResourceParticleSystem>& GetResource() const; void SetResource(const std::shared_ptr<ResourceParticleSystem> resource); void SetEmitters(const std::vector<EmitterInstance*> emitters); void SetPlayAtStart(bool playAtStart); void CheckEmitterInstances(bool forceRecalculate); void RemoveEmitter(int pos); private: void InternalSave(Json& meta) override; void InternalLoad(const Json& meta) override; void CreateEmitterInstance(); void CreateEmitterInstance(ParticleEmitter* emitter); void AddEmitterInstance(EmitterInstance* emitter); void ClearEmitters(); void InitEmitterInstances(); std::vector<EmitterInstance*> emitters; std::shared_ptr<ResourceParticleSystem> resource; bool playAtStart; bool isPlaying; bool pause; }; inline bool ComponentParticleSystem::IsEmittersEmpty() const { return emitters.empty(); } inline bool ComponentParticleSystem::IsPlaying() const { return isPlaying; } inline const std::shared_ptr<ResourceParticleSystem>& ComponentParticleSystem::GetResource() const { return resource; } inline void ComponentParticleSystem::SetEmitters(const std::vector<EmitterInstance*> emitters) { this->emitters = emitters; } inline void ComponentParticleSystem::SetPlayAtStart(bool playAtStart) { this->playAtStart = playAtStart; } inline std::vector<EmitterInstance*> ComponentParticleSystem::GetEmitters() const { return emitters; } inline bool ComponentParticleSystem::GetPlayAtStart() const { return playAtStart; }
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, Davinder Pal <[email protected]> from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = """ module: aws_secretsmanager_info short_description: Get Information about AWS Secrets Manager. description: - Get Information about AWS Secrets Manager. - U(https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_Operations.html) version_added: 0.0.9 options: describe_secret: description: - do you want to get details of secret for given I(id)? required: false type: bool list_secrets: description: - do you want to get of secrets? required: false type: bool author: - "Davinder Pal (@116davinder) <[email protected]>" extends_documentation_fragment: - amazon.aws.ec2 - amazon.aws.aws requirements: - boto3 - botocore """ EXAMPLES = """ - name: "get details of secret" aws_secretsmanager_info: describe_secret: true id: 'secret_id' - name: "get list of secrets" aws_secretsmanager_info: list_secrets: true """ RETURN = """ secret: description: details of secret. returned: when `describe_secret` is defined and success. type: dict secrets: description: get of secrets. returned: when `list_secrets` is defined and success. type: list """ try: from botocore.exceptions import BotoCoreError, ClientError except ImportError: pass # Handled by AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.core import AnsibleAWSModule from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AWSRetry from ansible_collections.community.missing_collection.plugins.module_utils.aws_response_parser import aws_response_list_parser from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict def _secretsmanager(client, module): try: if module.params['describe_secret']: if client.can_paginate('describe_secret'): paginator = client.get_paginator('describe_secret') return paginator.paginate( SecretId=module.params['id'] ), True else: return client.describe_secret( SecretId=module.params['id'] ), False elif module.params['list_secrets']: if client.can_paginate('list_secrets'): paginator = client.get_paginator('list_secrets') return paginator.paginate(), True else: return client.list_secrets(), False else: return None, False except (BotoCoreError, ClientError) as e: module.fail_json_aws(e, msg='Failed to fetch AWS Secrets Manager details') def main(): argument_spec = dict( id=dict(required=False, aliases=['secret_id']), describe_secret=dict(required=False, type=bool), list_secrets=dict(required=False, type=bool), ) module = AnsibleAWSModule( argument_spec=argument_spec, required_if=( ('describe_secret', True, ['id']), ), mutually_exclusive=[ ( 'describe_secret', 'list_secrets', ) ], ) client = module.client('secretsmanager', retry_decorator=AWSRetry.exponential_backoff()) it, paginate = _secretsmanager(client, module) if module.params['describe_secret']: module.exit_json(secret=camel_dict_to_snake_dict(it)) elif module.params['list_secrets']: module.exit_json(secrets=aws_response_list_parser(paginate, it, 'SecretList')) else: module.fail_json("unknown options are passed") if __name__ == '__main__': main()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: zzq # @Date: 2021-07-02 # @Describe: 衢州衢江区公共资源交易网 import re import math import json import scrapy import urllib from urllib import parse from lxml import etree from scrapy.spiders import Spider from spider_pro.items import NoticesItem, FileItem from spider_pro import constans as const from spider_pro.utils import get_accurate_pub_time, judge_dst_time_in_interval, remove_specific_element, file_notout_time class MySpider(Spider): name = "ZJ_city_3357_qujiangqu_spider" area_id = "3357" area_province = "浙江-衢州市衢江区公共资源交易服务平台" allowed_domains = ['qjq.gov.cn'] domain_url = "www.qjq.gov.cn" count_url = "http://www.qjq.gov.cn/module/jpage/dataproxy.jsp?startrecord={}&endrecord={}&perpage=15" # data_url = "https://www.hzctc.cn/afficheshow/Home?" # flie_url = "https://www.hzctc.cn:20001/UService/DownloadAndShow.aspx?dirtype=3&filepath=" page_size = "10" # 招标公告 list_notice_category_num = ["1229425417", "1229505851", "1229425421", "1229425427", "1229425430"] # 招标变更 list_alteration_category_num = ["1229425420", "1229425424"] # 中标预告 list_win_advance_notice_num = ["002001004"] # 中标公告 list_win_notice_category_num = ["1229425418", "1229425422", "1229425419", "1229425423", "1229425428", "1229425431"] # 其他公告 list_other_notice = ["1229425429", "1229425432", "1229425433", "1229425434"] list_all_category_num = list_notice_category_num + list_alteration_category_num \ + list_win_advance_notice_num + list_win_notice_category_num + list_other_notice def __init__(self, *args, **kwargs): super(MySpider, self).__init__() self.r_dict = {"col": "1", "appid": "1", "webid": "2759", "sourceContentType": "1", "unitid": "4467411", "webname": "衢州市衢江区政府", "path": "/", "permissiontype": "0"} if kwargs.get("sdt") and kwargs.get("edt"): self.enable_incr = True self.sdt_time = kwargs.get("sdt") self.edt_time = kwargs.get("edt") else: self.enable_incr = False cookies_str = 'JSESSIONID=59DAAEF31B1B3B2CA853309DE982258F; SERVERID=a6d2b4ba439275d89aa9b072a5b72803|1625213840|1625210738' # 将cookies_str转换为cookies_dict self.cookies_dict = {i.split('=')[0]: i.split('=')[1] for i in cookies_str.split('; ')} def start_requests(self): if self.enable_incr: callback_url = self.extract_data_urls else: callback_url = self.parse_urls for item in self.list_all_category_num: temp_dict = self.r_dict | {"columnid": "{}".format(item)} yield scrapy.FormRequest(self.count_url.format("1", "15"), formdata=temp_dict, priority=2, cookies=self.cookies_dict, callback=callback_url, meta={"afficheType": str(item)}) def extract_data_urls(self, response): temp_list = response.xpath("recordset//record") category_num = response.meta["afficheType"] ttlrow = response.xpath("totalrecord/text()").get() startrecord = 1 endrecord = 15 count_num = 0 for item in temp_list: title_name = re.findall("title='(.*?)'", item.get())[0] info_url = re.findall("href='(.*?)'", item.get())[0] pub_time = re.findall("&gt;(\d+\-\d+\-\d+)&lt;", item.get())[0] x, y, z = judge_dst_time_in_interval(pub_time, self.sdt_time, self.edt_time) if x: count_num += 1 yield scrapy.Request(url=info_url, callback=self.parse_item, dont_filter=True, priority=10, meta={"category_num": category_num, "pub_time": pub_time, "title_name": title_name}) if count_num >= len(temp_list): startrecord += 15 endrecord += 15 if endrecord <= int(ttlrow): temp_dict = self.r_dict | {"columnid": "{}".format(category_num)} yield scrapy.FormRequest(self.count_url.format(str(startrecord), str(endrecord)), formdata=temp_dict, dont_filter=True, callback=self.parse_data_urls, priority=8, cookies=self.cookies_dict, meta={"afficheType": category_num}) def parse_urls(self, response): try: startrecord = 1 endrecord = 15 afficheType = response.meta["afficheType"] ttlrow = response.xpath("totalrecord/text()").get() if int(ttlrow) < 15: pages = 1 endrecord = int(ttlrow) else: pages = int(ttlrow) // 15 self.logger.info(f"本次获取总条数为:{ttlrow},共有{pages}页") for page in range(1, pages+1): if page > 1: startrecord += 15 endrecord += 15 if endrecord > int(ttlrow): endrecord = int(ttlrow) temp_dict = self.r_dict | {"columnid": "{}".format(afficheType)} yield scrapy.FormRequest(self.count_url.format(str(startrecord), str(endrecord)), formdata=temp_dict, dont_filter=True, callback=self.parse_data_urls, priority=8, cookies=self.cookies_dict, meta={"afficheType": afficheType}) except Exception as e: self.logger.error(f"初始总页数提取错误 {response.meta=} {e} {response.url=}") def parse_data_urls(self, response): try: temp_list = response.xpath("recordset//record") category_num = response.meta["afficheType"] for item in temp_list: title_name = re.findall("title='(.*?)'", item.get())[0] info_url = re.findall("href='(.*?)'", item.get())[0] pub_time = re.findall("&gt;(\d+\-\d+\-\d+)&lt;", item.get())[0] # info_url = "http://ggzy.qz.gov.cn/jyxx/002001/002001001/20171023/72a05665-7405-46bc-a8a2-289f88ceb225.html" yield scrapy.Request(url=info_url, callback=self.parse_item, dont_filter=True, priority=10, meta={ "category_num": category_num, "pub_time": pub_time, "title_name":title_name}) except Exception as e: self.logger.error(f"发起数据请求失败 {e} {response.url=}") def parse_item(self, response): if response.status == 200: origin = response.url print(origin) category_num = response.meta.get("category_num", "") title_name = response.meta.get("title_name", "") pub_time = response.meta.get("pub_time", "") info_source = self.area_province content = response.xpath("//table[@id='c']").get() if not content: content = response.xpath("//div[@class='box_wzy_ys']").get() if not content: content = response.xpath("//div[@class='template-preview-wrap']").get() # _, content = remove_specific_element(content, 'td', 'class', 'bt-heise', index=0) _, contents = remove_specific_element(content, 'div', 'id', 'share-2', index=0) _, content = remove_specific_element(contents, 'div', 'class', 'main-fl-gn bt-padding-right-20 bt-padding-left-20', index=0) content = re.sub("浏览次数:", "", content) files_path = {} if file_notout_time(pub_time): if file_list := re.findall("""附件:<a href="(.*)"><strong>""", content): file_suffix = file_list[0].split(".")[1] file_url = self.domain_url + file_list[0] file_name = "附件下载." + file_suffix files_path[file_name] = file_url if category_num in self.list_notice_category_num: notice_type = const.TYPE_ZB_NOTICE elif category_num in self.list_alteration_category_num: notice_type = const.TYPE_ZB_ALTERATION elif category_num in self.list_win_notice_category_num: notice_type = const.TYPE_WIN_NOTICE elif category_num in self.list_win_advance_notice_num: notice_type = const.TYPE_WIN_ADVANCE_NOTICE elif category_num in self.list_other_notice: notice_type = const.TYPE_OTHERS_NOTICE else: notice_type = const.TYPE_UNKNOWN_NOTICE if re.search(r"单一来源|询价|竞争性谈判|竞争性磋商|招标公告", title_name): notice_type = const.TYPE_ZB_NOTICE elif re.search(r"候选人|中标公示", title_name): notice_type = const.TYPE_WIN_ADVANCE_NOTICE elif re.search(r"终止|中止|流标|废标|异常", title_name): notice_type = const.TYPE_ZB_ABNORMAL elif re.search(r"变更|更正|澄清|修正|补充|取消|延期", title_name): notice_type = const.TYPE_ZB_ALTERATION if category_num in ["1229425427", "1229425428", "1229425429", "1229425430", "1229425431", "1229425432"]: classifyShow = "政府采购" elif category_num in ["1229425433", "1229425434"]: classifyShow = "其他交易" else: classifyShow = "工程建设" notice_item = NoticesItem() notice_item["origin"] = origin notice_item["title_name"] = title_name notice_item["pub_time"] = pub_time notice_item["info_source"] = info_source notice_item["is_have_file"] = const.TYPE_HAVE_FILE if files_path else const.TYPE_NOT_HAVE_FILE notice_item["files_path"] = "" if not files_path else files_path notice_item["notice_type"] = notice_type notice_item["content"] = content notice_item["area_id"] = self.area_id notice_item["category"] = classifyShow # print(type(files_path)) # print(notice_item) # # TODO 产品要求推送,故注释 # # if not is_clean: # # notice_item['is_clean'] = const.TYPE_CLEAN_NOT_DONE yield notice_item if __name__ == "__main__": from scrapy import cmdline cmdline.execute("scrapy crawl ZJ_city_3357_qujiangqu_spider -a sdt=2021-08-25 -a edt=2021-08-30".split(" ")) # cmdline.execute("scrapy crawl ZJ_city_3357_qujiangqu_spider".split(" "))
import React, { useEffect, useState, useCallback } from 'react'; import { redirect } from 'react-router-dom'; import { Helmet } from 'react-helmet'; import { Container, Box, Flex, useColorModeValue } from '@chakra-ui/react'; import Particles from 'react-particles'; import { loadFull } from 'tsparticles'; // if you are going to use `loadFull`, install the "tsparticles" package too. // import { loadSlim } from 'tsparticles-slim'; // if you are going to use `loadSlim`, install the "tsparticles-slim" package too. import { Hero } from './components/Hero/Intro.jsx'; import { AboutMe } from './components/AboutMe/AboutMe.jsx'; import { Skills } from './components/SkillBars/progress.jsx'; import { Projects } from './components/MyWork/projects.jsx'; import { Timeline } from './components/Timeline.jsx'; import { Navbar } from './components/Navbar/Navbar.jsx'; import { Loading } from './Loading.jsx'; const Back = () => { const particlesInit = useCallback(async engine => { // you can initiate the tsParticles instance (engine) here, adding custom shapes or presets // this loads the tsparticles package bundle, it's the easiest method for getting everything ready // starting from v2 you can add only the features you need reducing the bundle size await loadFull(engine); }, []); const particlesLoaded = useCallback(async container => { await container; }, []); return ( <Box position={'relative'}> <Box bg={useColorModeValue('whiteAlpha.700', 'blackAlpha.600')} w="100%" minH={['calc(100vh)', 'calc(100vh)']} position={'absolute'} zIndex={3} ></Box> <Container backgroundColor="white" maxHeight="100vh" display="flex" flexDirection="column" fontSize="calc(10px + 2vmin)" color="black" textAlign="center" alignItems="center" justifyContent="center" position={'absolute'} > <Particles id="tsparticles" options={{ background: { color: { value: useColorModeValue('#fff', '#000'), }, }, fpsLimit: 120, interactivity: { detect_on: 'window', events: { onClick: { enable: true, mode: 'push', }, onHover: { enable: true, mode: 'grab', }, resize: true, }, modes: { grab: { distance: 150, line_linked: { opacity: 1, }, }, bubble: { distance: 400, size: 40, duration: 2, opacity: 8, speed: 1, }, repulse: { distance: 200, duration: 0.4, }, push: { particles_nb: 4, }, remove: { particles_nb: 2, }, }, }, particles: { color: { value: useColorModeValue('#000', '#fff'), }, links: { color: useColorModeValue('#000', '#fff'), distance: 150, enable: true, opacity: 0.5, width: 1, }, move: { direction: 'none', enable: true, outModes: { default: 'bounce', }, random: false, speed: 1, straight: false, bounce: true, attract: { enable: false, rotateX: 600, rotateY: 1200, }, }, number: { density: { enable: true, area: 800, }, value: 130, }, opacity: { value: 0.5, }, shape: { type: 'circle', stroke: { width: 3, color: '#fff', }, polygon: { nb_sides: 5, }, image: { src: 'git.svg', width: 100, height: 100, }, }, size: { value: { min: 1, max: 5 }, }, }, detectRetina: true, }} init={particlesInit} loaded={particlesLoaded} /> </Container> </Box> ); }; export const Home = () => { return [ <Container maxW="100vw" px={0}> <Loading /> <Navbar /> <Helmet> <meta charSet="utf-8" /> <title>Home | Avani Sharma</title> <link rel="canonical" href="http://avani.dev/home" /> <meta name="description" content="Avani Sharma - Machine Learning Engineer | Software Engineer" /> </Helmet> <Back /> <Hero /> <AboutMe /> <Skills /> <Projects /> <Timeline /> </Container>, ]; };
# frozen_string_literal: true class User < ApplicationRecord include Recoverable include Rememberable enum role: { basic: 0, moderator: 1, admin: 2 }, _suffix: :role attr_accessor :old_password, :skip_all_password has_secure_password validations: false validate :password_presence validates :password, confirmation: true, allow_blank: true validate :password_complexity validate :correct_old_password, on: :update, if: -> { password.present? && !skip_all_password } validates :email, presence: true, uniqueness: true, 'valid_email_2/email': { mx: true } validates :role, presence: true before_save :set_gravatar_hash, if: :email_changed? has_many :questions, dependent: :destroy has_many :answers, dependent: :destroy has_many :comments, dependent: :destroy def author?(obj) obj.user == self end def guest? false end private def set_gravatar_hash return if email.blank? hash = Digest::MD5.hexdigest email.strip.downcase self.gravatar_hash = hash end def digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def correct_old_password return if BCrypt::Password.new(password_digest_was).is_password?(old_password) errors.add :old_password, 'is incorrect' end def password_complexity # Regexp extracted from https://stackoverflow.com/questions/19605150/regex-for-password-must-contain-at-least-eight-characters-at-least-one-number-a return if password.blank? || password =~ /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,70}$/ msg = 'complexity requirement not met. Length should be 8-70 characters' \ 'and include: 1 uppercase, 1 lowercase, 1 digit and 1 special character' errors.add :password, msg end def password_presence errors.add(:password, :blank) if password_digest.blank? end end
import { ChatBubble } from './chatBubble'; import type { OperationsNeedingAttentionItem } from './conversationItem'; import { OperationsNeedingAttentionOnUserAction } from './conversationItem'; import type { OperationInfoItemProps } from './flowDiffPreview'; import { OperationItemsList } from './flowDiffPreview'; import type { IFontIconProps } from '@fluentui/react'; import { FontIcon, getTheme } from '@fluentui/react'; import React from 'react'; import { useIntl } from 'react-intl'; type OperationsNeedingAttentionMessageProps = { item: OperationsNeedingAttentionItem; }; export const OperationsNeedingAttentionMessage: React.FC<OperationsNeedingAttentionMessageProps> = ({ item }) => { const intl = useIntl(); const intlText = { allRequiredParametersAreSetMessage: intl.formatMessage({ defaultMessage: 'All required parameters are set', description: 'Chatbot message letting user know that required parameters are set.', }), savingDescription: intl.formatMessage({ defaultMessage: 'To save this workflow, finish setting up this action:', description: 'Chatbot message telling user to set up action in order to save the workflow', }), editingDescription: intl.formatMessage({ defaultMessage: 'To get this workflow ready, finish setting up this action:', description: 'Chatbot message telling user to set up action in order to get the workflow ready', }), savingDescription_plural: intl.formatMessage({ defaultMessage: 'To save this workflow, finish setting up these actions:', description: 'Chatbot message telling user to set up actions in order to save the workflow', }), editingDescription_plural: intl.formatMessage({ defaultMessage: 'To get this workflow ready, finish setting up these actions:', description: 'Chatbot message telling user to set up actions in order to get the workflow ready', }), }; if (item.operationsNeedingAttention.length === 0) { return <AllOperationsFixedStatus message={intlText.allRequiredParametersAreSetMessage} />; } const description = item.userAction === OperationsNeedingAttentionOnUserAction.saving ? item.operationsNeedingAttention.length > 1 ? intlText.savingDescription_plural : intlText.savingDescription : item.operationsNeedingAttention.length > 1 ? intlText.editingDescription_plural : intlText.editingDescription; const operations = item.operationsNeedingAttention.map((info: any) => { const disabled = false; const isComplete = true; const statusIcon = disabled ? disabledIconProps : isComplete ? noAttentionIconProps : needAttentionIconProps; const operationProps: OperationInfoItemProps & { isComplete: boolean } = { info, isComplete, disabled, statusIcon, // TODO: add onClick selectOperationInDesigner(info.operationName) }; return operationProps; }); // TODO: add check for operations that are either disabled or complete return ( <div> <ChatBubble key={item.id} isUserMessage={false} isAIGenerated={true} date={item.date} selectedReaction={item.reaction}> <div className={'msla-operationsneedattention-description'}>{description}</div> <OperationItemsList operations={operations} className={'msla-operationsneedattention-list'} /> </ChatBubble> </div> ); }; const AllOperationsFixedStatus: React.FC<{ message: string }> = ({ message }) => { return ( <div className={'msla-operationsfixedstatus-root'}> <span className={'msla-operationsfixedstatus-status'}> <FontIcon iconName="Completed" className={'msla-operationsfixedstatus-icon'} /> <span className={'msla-operationsfixedstatus-text'}>{message}</span> </span> </div> ); }; const needAttentionIconProps: IFontIconProps = { iconName: 'Error', style: { color: getTheme().semanticColors.errorIcon }, }; const noAttentionIconProps: IFontIconProps = { iconName: 'Connected', style: { color: getTheme().semanticColors.successIcon }, }; const disabledIconProps: IFontIconProps = { iconName: 'Connected', style: { color: getTheme().semanticColors.inputIconDisabled }, };
/* eslint-disable no-unused-vars */ import React, { useEffect, useState } from "react"; import { useLazyQuery, useSubscription } from "@apollo/client"; import { makeStyles } from "@material-ui/core/styles"; import { Box, Button, Typography, Grid, Paper, List, ListItem, ListItemIcon, ListItemText, Avatar, Divider, InputBase, InputAdornment, } from "@material-ui/core"; import Search from "@material-ui/icons/Search"; import Connections from "./Connections"; import ChatBox from "./ChatBox"; import cookies from "js-cookie"; import { useRouter } from "next/router"; import { useSelector, useDispatch } from "react-redux"; import { setChats, addChat } from "../redux/chatsReducer"; import { GET_CHATS, NEW_MESSAGE } from "../Apollo/queries"; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, width: "100%", }, headerMessage: { padding: "0.3em", }, friendsDiv: { // paddingLeft: "1em", // paddingRight: "1em", backgroundColor: "white", height: "100%", borderRight: "1px solid #e0e0e0", overflowY: "scroll", scrollbarWidth: "none" /* Firefox */, "&::-webkit-scrollbar": { display: "none", } /* Chrome */, }, container: { height: "80vh", width: "100%", }, chatArea: { height: "100%", overflowY: "auto", width: "100%", }, appbar: { height: "4em", }, textfield: { height: "3rem", width: "100%", border: "2px solid #32506D", paddingLeft: "5px", paddingRight: "0.5em", }, })); const Messaging = () => { const classes = useStyles(); const router = useRouter(); const dispatch = useDispatch(); const [user, setUser] = useState({}); const selectedUser = useSelector((state) => state.chats.selectedUser); useEffect(() => { const localUser = JSON.parse(localStorage.getItem("sosha_user")); const token = cookies.get("sosha_token"); if (!token) { router.push("/login?previousPage=/messaging"); } setUser(localUser); }, []); const [getChats, { data, loading, error }] = useLazyQuery(GET_CHATS, { onError: () => { console.log("error", error); }, onCompleted: () => { dispatch(setChats(data.chats)); }, }); const { data: newMessageData, error: newMessageError } = useSubscription( NEW_MESSAGE, { variables: { friendshipId: selectedUser?.friend.id }, } ); useEffect(() => { if (newMessageData && selectedUser) { dispatch(addChat(newMessageData.newChat)); } }, [newMessageError, newMessageData]); useEffect(() => { if (selectedUser !== null) { getChats({ variables: { friendshipId: selectedUser?.friend.id } }); } }, [selectedUser]); return ( <div className={classes.root}> <Grid style={{ width: "100%", minWidth: "100%" }} container> <Grid item xs={12} className={classes.headerMessage}> <Typography color="primary" variant="h5"> Chats </Typography> </Grid> </Grid> <Grid component={Paper} className={classes.container} container> <Grid className={classes.friendsDiv} item xs={12} sm={3}> <List> <ListItem button key={user?.id}> <ListItemIcon> <Avatar alt="Remy Sharp" src={user?.imgUrl} /> </ListItemIcon> <ListItemText style={{ fontWeight: "bold" }} color="primary" // primary={`${user?.firstName} ${user?.lastName}`} > <Typography style={{ fontWeight: 600 }} color="primary" variant="body2" >{`${user?.firstName} ${user?.lastName}`}</Typography> </ListItemText> </ListItem> </List> <Divider /> <Grid item xs={12} style={{ padding: "10px" }}> <InputBase className={classes.textfield} id="input-with-icon-textfield" placeholder="Search for friends" style={{ borderRadius: "2rem" }} startAdornment={ <InputAdornment> <Search color="primary" style={{ height: "1em", width: "1em" }} /> </InputAdornment> } /> </Grid> <Divider /> <Connections /> </Grid> <Grid className={classes.chatArea} item sm={9}> <ChatBox /> </Grid> </Grid> </div> ); }; export default Messaging;
#pragma once #include "GPipeline.h" #include "Object3D.h" #include "ConstBuff.h" #include "Shader.h" #include "MyDebugCamera.h" #include "Square.h" #include "Controller.h" #include <memory> #include "Model.h" /// <summary> /// ゴール作成クラス /// </summary> class Goal { public: Goal(); ~Goal(); /// <summary> /// 初期化 /// </summary> /// <param name="dx_"></param> /// <param name="shader"></param> /// <param name="pipeline_"></param> void Initialize(MyDirectX* dx_, Shader shader, GPipeline* pipeline_); /// <summary> /// 描画 /// </summary> /// <param name="tex"></param> void Draw(size_t tex); /// <summary> /// 更新 /// </summary> /// <param name="matView"></param> /// <param name="matProjection"></param> void Update(Matrix matView, Matrix matProjection); /// <summary> /// 箱同士の判定(collisionManager作成後削除) /// </summary> /// <param name="model"></param> /// <returns></returns> bool BoxCollision(Model model); /// <summary> /// リセット /// </summary> void Reset(); /// <summary> /// posをセット /// </summary> void SetPos(Vector3D pos); //ゴール用モデル Model goal_; };
import React, { useEffect, useState } from "react"; import Drawer from "../Drawer"; import { CloseIcon } from "../Icons"; import toast from "react-hot-toast"; import Input from "../Input"; import CustomDropdown from "../Dropdown"; import { TaskPriorityList, TaskStatusList } from "../../constants/consts"; import Button from "../Button"; import ErrorMessage from "../ErrorMessage"; import useEditTask from "../../hook/useTask/useEditTask"; interface CreateTaskProps { isEditTaskDrawerOpen: boolean; taskToEdit: any; setIsEditTaskDrawerOpen: (isOpen: boolean) => void; } const EditTask = ({ isEditTaskDrawerOpen, taskToEdit, setIsEditTaskDrawerOpen, }: CreateTaskProps) => { const { editTaskData, editTaskErrors, onEditTask, resetCreateTaskData, selectedPriority, selectedStatus, setEditTaskData, setEditTaskErrors, setSelectedPriority, setSelectedStatus, } = useEditTask({ isEditTaskDrawerOpen, setIsEditTaskDrawerOpen, }); useEffect(() => { setEditTaskData({ taskName: taskToEdit.taskName, description: taskToEdit.description, status: taskToEdit.status, priority: taskToEdit.priority, }); setSelectedStatus(taskToEdit.status); setSelectedPriority(taskToEdit.priority); }, [taskToEdit]); return ( <Drawer className="px-3" setShowSidebar={setIsEditTaskDrawerOpen} showSidebar={isEditTaskDrawerOpen} > <div className="flex gap-10 flex-col pl-4 h-full mt-3"> <div className="flex justify-between w-full items-center mt-3"> <h1 className="text-xl font-semibold ">Edit Task</h1> <div className="" onClick={() => { resetCreateTaskData(); }} > <CloseIcon className="h-8 cursor-pointer" /> </div> </div> <form className="flex flex-col gap-3 justify-between h-full " onSubmit={(e) => { e.preventDefault(); }} > <div className="flex flex-col gap-6"> <Input isRequired={true} error={editTaskErrors.taskname} value={editTaskData.taskName} label="Task name" placeholder="task name" onChange={(e) => setEditTaskData({ ...editTaskData, taskName: e.target.value, }) } /> <div> <label className="mb-2 font-semibold text-md"> Task description </label> <textarea placeholder="task description" value={editTaskData.description} onChange={(e) => setEditTaskData({ ...editTaskData, description: e.target.value, }) } className="w-full border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 p-3 border-gray-400" /> {editTaskErrors.description && ( <ErrorMessage message={editTaskErrors.description} /> )} </div> <div className=" grid grid-cols-2 gap-3"> <CustomDropdown error={editTaskErrors.status} label="Status" selectedOption={selectedStatus} setSelectedOption={setSelectedStatus} isRequired={true} defaultOption="Select Status" options={TaskStatusList} onSelect={(e) => { setEditTaskData({ ...editTaskData, status: e.value }); }} /> <CustomDropdown error={editTaskErrors.priority} defaultOption="Select Priority" selectedOption={selectedPriority} setSelectedOption={setSelectedPriority} label="Priority" options={TaskPriorityList} onSelect={(e) => setEditTaskData({ ...editTaskData, priority: e.value }) } /> </div> </div> <div className="flex gap-3 mb-10"> <Button onClick={onEditTask}>Edit Task</Button> <Button onClick={resetCreateTaskData}>Cancel</Button> </div> </form> </div> </Drawer> ); }; export default EditTask;
'use client' import React, { useEffect, useState } from 'react'; import { Vehicle } from '@/types/db/Vehicle' import { DataTable } from './components/data-table' import { columns } from './components/columns' import { db } from '@/lib/db/db'; export default function Vehicles() { const [data, setData] = useState<Vehicle[]>([]); const [reload, setReload] = useState(false); useEffect(() => { async function fetchData() { const vehicles = await db.vehicles.fetch.all(); if (vehicles) { setData(vehicles); // Sort vehicles by status = available, then by registration vehicles.sort((a, b) => { if (a.status === "Available" && b.status !== "Available") return -1; if (a.status !== "Available" && b.status === "Available") return 1; if (a.registration < b.registration) return -1; if (a.registration > b.registration) return 1; return 0; }); } } fetchData(); }, [reload]); const refreshData = () => setReload(prev => !prev); return ( <div className="flex flex-col w-full justify-start gap-4 mx-auto p-4 max-w-[1400px]"> <div className="inline-flex justify-between"> <h1 className="text-foreground font-bold text-3xl my-auto">Vehicles</h1> </div> <DataTable columns={columns(refreshData)} data={data} refreshData={refreshData} /> </div> ) }
import Database from "../Database/index.js"; function ModuleRoutes(app) { app.get("/api/courses/:cid/modules", (req, res) => { const{cid} = req.params; const modules = Database.modules. filter((m) => m.course === cid); res.send(modules); }); app.post("/api/courses/:cid/modules", (req, res) => { const { cid } = req.params; const module = {...req.body, course: cid}; const courseModules = Database.modules.filter((m) => m.course === cid); const idNumbers = courseModules.map(m => { const match = m._id.match(/\d+$/); return match ? parseInt(match[0]) : 0; }); const highestIdNumber = Math.max(...idNumbers, 0); const newIdNumber = highestIdNumber + 1; const newId = `M${newIdNumber.toString().padStart(3, '0')}`; const newModule = {...module, _id: newId}; Database.modules.push(newModule); res.send(newModule); }); app.delete("/api/modules/:mid", (req, res) => { const { mid } = req.params; Database.modules = Database.modules.filter((m) => m._id !== mid); res.sendStatus(200); }); app.put("/api/modules/:mid", (req, res) => { const { mid } = req.params; console.log(mid); const moduleIndex = Database.modules.findIndex( (m) => m._id === mid); if (moduleIndex === -1) { return res.status(404).send('Module not found'); } Database.modules[moduleIndex] = { ...Database.modules[moduleIndex], ...req.body }; res.sendStatus(204); }); } export default ModuleRoutes;
package com.example.corporate.api.entity; import jakarta.persistence.*; import java.util.Objects; @Entity @Table(name = "partnership_table") public class Partnership { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "partner_id") private Long id; @Column(name = "partner_name") private String name; @Column(name = "partnership_start_year") private Integer partnerStartYear; @Column(name = "partnership_type") private String partner_type; @Column(name = "partnership_status") private String partner_status; @ManyToOne @JoinColumn(name = "organization_id") private Organization organization; public Partnership() { } public Partnership(Long id, String name, Integer partnerStartYear, String partner_type, String partner_status, Organization organization) { this.id = id; this.name = name; this.partnerStartYear = partnerStartYear; this.partner_type = partner_type; this.partner_status = partner_status; this.organization = organization; } public Partnership(String name, Integer partnerStartYear, String partner_type, String partner_status, Organization organization) { this.name = name; this.partnerStartYear = partnerStartYear; this.partner_type = partner_type; this.partner_status = partner_status; this.organization = organization; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPartnerStartYear() { return partnerStartYear; } public void setPartnerStartYear(Integer partnerStartYear) { this.partnerStartYear = partnerStartYear; } public String getPartner_type() { return partner_type; } public void setPartner_type(String partner_type) { this.partner_type = partner_type; } public String getPartner_status() { return partner_status; } public void setPartner_status(String partner_status) { this.partner_status = partner_status; } public Organization getOrganization() { return organization; } public void setOrganization(Organization organization) { this.organization = organization; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Partnership that = (Partnership) o; return Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(partnerStartYear, that.partnerStartYear) && Objects.equals(partner_type, that.partner_type) && Objects.equals(partner_status, that.partner_status) && Objects.equals(organization, that.organization); } @Override public int hashCode() { return Objects.hash(id, name, partnerStartYear, partner_type, partner_status, organization); } @Override public String toString() { return "Partnership{" + "id=" + id + ", name='" + name + '\'' + ", partnerStartYear=" + partnerStartYear + ", partner_type='" + partner_type + '\'' + ", partner_status='" + partner_status + '\'' + ", organization=" + organization + '}'; } }
#include "binary_trees.h" /** * binary_tree_leaves - a binary tree's leaves are counted. * @tree: a direction to the tree's root node that will allow you to count its. * * Return: how many leaves there are on the tree. */ size_t binary_tree_leaves(const binary_tree_t *tree) { size_t leaves = 0; if (tree) { leaves += (!tree->left && !tree->right) ? 1 : 0; leaves += binary_tree_leaves(tree->left); leaves += binary_tree_leaves(tree->right); } return (leaves); }
import React from 'react' import axios from 'axios' import '../styles/Carousel.css'; import Arrow from './Arrow'; import { useEffect,useState } from 'react'; import {Link as LinkRouter} from 'react-router-dom' import APIurl from '../APIBack' export default function Carousel() { const [cities, setCities] = useState([]) useEffect(() => { axios.get(`${APIurl}/cities/?city=all`) .then( res => setCities(res.data.response)) .catch( err => console.error(err)) }, []) const range = 4 const [getStart, setStart] = useState(0) const [getEnd, setEnd] = useState(getStart + range); const [intervalId, setIntervalId] = useState(); function previus(){ if(getStart >= range){ setStart( getStart - range ); setEnd( getEnd - range ); }else{ setEnd(12); setStart(12 - 4); } clearInterval(intervalId); } function next(){ if(getEnd < 12){ setStart( getStart + range ); setEnd( getEnd + range ); }else{ setStart(0); setEnd(range) } clearInterval(intervalId); } useEffect(() => { let id = setInterval( function(){ next(); }, 3000) setIntervalId(id) return () => clearInterval(intervalId); },[getStart]); const itemView = (item) => ( <div className="item"> <LinkRouter to={'/details?' + item._id}><img className="citiesImgs" src={item.photo} alt="" /></LinkRouter> <p className="citiesName">{item.city}</p> </div> ) return ( <> <div className="slide-title"> <h1>Popular MYtineraries</h1> </div> <div className="slide-container"> <div className="slide-arrow1"> <Arrow click={previus}> <input className="arrow-img" type="image" src="https://cdn-icons-png.flaticon.com/512/271/271220.png" alt="Left arrow"></input> </Arrow> </div> <div className="slide"> {cities.slice(getStart, getEnd).map(itemView)} </div> <div className="slide-arrow2"> <Arrow click={next}> <input className="arrow-img" type="image" src="https://cdn-icons-png.flaticon.com/512/271/271228.png" alt="Right arrow"></input> </Arrow> </div> </div> </> ) }
/** * Copyright (C) 2010-2023 The Catrobat Team * (http://developer.catrobat.org/credits) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * An additional term exception under section 7 of the GNU Affero * General Public License, version 3, is available at * (http://developer.catrobat.org/license_additional_term) * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see http://www.gnu.org/licenses/. */ import Foundation class FormulaCache { private var cachedResults = [FormulaElement: AnyObject]() private let cacheQueue = DispatchQueue(label: "cache") func insert(object: AnyObject, forKey key: FormulaElement) { cacheQueue.sync { cachedResults[key] = object } } func retrieve(forKey key: FormulaElement) -> AnyObject? { var result: AnyObject? cacheQueue.sync { result = cachedResults[key] } return result } func remove(forKey key: FormulaElement) { _ = cacheQueue.sync { cachedResults.removeValue(forKey: key) } } func clear() { cacheQueue.sync { cachedResults.removeAll() } } func count() -> Int { var result = Int() cacheQueue.sync { result = cachedResults.count } return result } }
import datetime from .commons.ErrorType import ErrorType from .commons.database import get_db_connection from .commons.type_response import response_200, response_400, response_500 from .commons.utils import validate_id, exists_by_id def datetime_handler(obj): if isinstance(obj, datetime.datetime): return obj.isoformat() raise TypeError("Type %s not serializable" % type(obj)) def lambda_handler(event, context): try: data = read_event(event['pathParameters']) return response_200(data) except ValueError as e: return response_400(ErrorType.english(str(e))) except RuntimeError as e: return response_500(ErrorType.english(str(e))) def read_event(parameters): connection = None try: _id = parameters.get('id') if not validate_id(_id): raise ValueError(ErrorType.INVALID_ID) if not exists_by_id(_id): raise ValueError(ErrorType.EVENT_NOT_FOUND) connection = get_db_connection() with connection.cursor() as cursor: query = """SELECT * FROM events WHERE id = %s""" cursor.execute(query, _id) row = cursor.fetchone() if row is not None: column_names = [desc[0] for desc in cursor.description] row_dict = dict(zip(column_names, row)) return row_dict else: return None finally: if connection is not None: connection.close()
const chatInput = document.querySelector(".chat-input textarea"); const sendChatBtn =document.querySelector(".chat-input span"); const chatbox =document.querySelector(".chatbox"); const chatbotToggler =document.querySelector(".chatbot-toggler"); const chatbotCloseBtn =document.querySelector(".close-btn"); let userMessage; const API_KEY="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"; const inputInitHeight=chatInput.scrollHeight; const createChatLi = (message,className)=> { const chatLi = document.createElement("li"); chatLi.classList.add("chat",className); let chatContent = className === "outgoing" ? `<p></p>` : ` <span class="material-symbols-outlined">smart_toy</span><p></p>` chatLi.innerHTML = chatContent; chatLi.querySelector("p").textContent=message; return chatLi; } const generateResponse = (incomingChatLi) => { const API_URL = "https://api.openai.com/v1/chat/completions"; const messageElement=incomingChatLi.querySelector("p"); const requestOptions = { method:"POST", headers:{ "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body:JSON.stringify({ model:"gpt-3.5-turbo", messages:[{role:"user",content: userMessage}] }) } fetch(API_URL, requestOptions).then(res=>res.json()).then(data=>{ messageElement.textContent = data.choices[0].message.content; }).catch((error) =>{ messageElement.classList.add("error"); messageElement.textContent = "Oops! Something went wrong.Please try again."; }).finally(()=>chatbox.scrollTo(0,chatbox.scrollHeight)); } const handleChat = () => { userMessage = chatInput.value.trim(); if(!userMessage) return; chatInput.value=""; chatInput.style.height=`${inputInitHeight}px`; chatbox.appendChild(createChatLi(userMessage,"outgoing")); chatbox.scrollTo(0,chatbox.scrollHeight); setTimeout(() => { const incomingChatLi= createChatLi("Thinking...","incoming"); chatbox.appendChild(incomingChatLi); chatbox.scrollTo(0,chatbox.scrollHeight); generateResponse(incomingChatLi); },600); } chatInput.addEventListener("input",()=>{ chatInput.style.height=`${inputInitHeight}px`; chatInput.style.height=`${chatInput.scrollHeight}px`; }); chatInput.addEventListener("keydown",(e)=>{ if(e.key==="Enter" && !e.shiftkey && window.innerWidth > 800){ e.preventDefault(); handleChat(); } }); chatbotToggler.addEventListener("click",()=>document.body.classList.toggle("show-chatbot")); chatbotCloseBtn.addEventListener("click",()=>document.body.classList.remove("show-chatbot")) sendChatBtn.addEventListener("click",handleChat);
var main = function (input) { // var myOutputValue = drawChar(input) // var myOutputValue = drawSq(input); // var myOutputValue = drawTri(input) var myOutputValue = borderSquare(input) return myOutputValue; }; // Number of characters let drawChar = function(numChar) { let myOutputValue = ''; var counter = 0 while (counter < numChar){ myOutputValue = myOutputValue + '🌼'; counter = counter + 1 } return myOutputValue; }; // Square var drawSq = function (input) { var myOutputValue = ''; // Initialise the outer counter, rowCounter var rowCounter = 0; while (rowCounter < input) { // Inside the outer loop, initialise the inner counter, columnCounter var columnCounter = 0; // Every time the outer loop runs, the inner loop runs repeatedly until // the inner loop condition is met. while (columnCounter < input) { // Each time the inner loop runs, it adds "x" to output myOutputValue = myOutputValue + '🌼'; columnCounter = columnCounter + 1; } // At the end of each outer loop, add a <br> tag to begin a new row myOutputValue = myOutputValue + '<br>'; rowCounter = rowCounter + 1; } // After the outer loop has run to completion, return the output compiled // by the above loops. return myOutputValue; }; // trianagle var drawTri = function(input) { var myOutputValue = ''; // initiate a column counter in the inner loop var columnCounter = input; // initiate the outer counter for depth var rowCounter = 0; while (rowCounter < columnCounter) { var spotCounter = 0; // loop to match row and column while (spotCounter <= rowCounter) { myOutputValue += '🍀' spotCounter = spotCounter + 1 ; } // at the end of each level ie outer loop, add a <br> tag to begin a new row myOutputValue += '<br>'; rowCounter +=1; } return myOutputValue; } // while loop // Initialise counter var counter = 0; // Declare loop condition while (counter < 10) { console.log('hello'); // Increment counter counter += 1; } // Initialise counter, declare loop condition, and increment counter in 1 line for (var counter = 0; counter < 10; counter += 1) { console.log('hello'); } // Outline Sq var borderSquare = function (input) { var myOutputValue = ''; // sideLength represents the length of each side of the square var height = input; var rowCounter = 0; while (rowCounter < height) { var innerCounter = 0; while (innerCounter < height) { // If current iteration represents a border element, draw 🌸 instead. if ( rowCounter == 0 || // top row innerCounter == 0 || // left most column rowCounter == height -1 || // last row innerCounter == height - 1 // last column ) { myOutputValue += '🌸'; } else { // Add a 🍀 to the current row myOutputValue += '🍀'; } innerCounter += 1; } // Insert a line break to start a new row myOutputValue += '<br>'; rowCounter += 1; } return myOutputValue; };
const todoFormEl = document.querySelector('#uid_todo_form'); const todoInputEl = todoFormEl?.querySelector('input'); const ulEl = document.querySelector('ul'); type Todo = { id: string; todo: string; }; let todos: Todo[] = []; const handleSaveTodo = (event: Event) => { event.preventDefault(); if (todoInputEl) { const uuid = crypto.randomUUID(); const newTodo = { id: uuid, todo: todoInputEl.value, }; todos.push(newTodo); drawTodo(newTodo); localStorage.setItem('todos', JSON.stringify(todos)); todoInputEl.value = ''; } }; const drawTodo = (newTodo: Todo) => { const liEl = document.createElement('li'); liEl.dataset.id = newTodo.id; liEl.innerHTML = `${newTodo.todo} <button>X</button>`; ulEl?.appendChild(liEl); }; const handleDelTodo = (event: MouseEvent) => { event.preventDefault(); const target = event.target; if (target instanceof HTMLButtonElement) { const parentElement = target.parentElement; if (parentElement) { const delID = parentElement.dataset.id; parentElement.remove(); const newTodos = todos.filter((todo) => todo.id !== delID); localStorage.setItem('todos', JSON.stringify(newTodos)); todos = newTodos; } } }; export const todoInit = () => { todoFormEl?.addEventListener('submit', handleSaveTodo); ulEl?.addEventListener('click', handleDelTodo); const localStorageTodos = localStorage.getItem('todos'); if (localStorageTodos) { todos = JSON.parse(localStorageTodos); todos.forEach((todo: Todo) => drawTodo(todo)); } };
import { useQuery } from '@tanstack/react-query'; import React from 'react'; import { toast } from 'react-hot-toast'; import Loading from '../Loading/Loading'; const Alluser = () => { const { data: users = [], refetch, isLoading } = useQuery({ queryKey: ['users'], queryFn: async () => { const res = await fetch("https://y-alpha-sage.vercel.app/users"); const data = await res.json(); return data; } }); const handleAdmin = (id) => { fetch(`https://y-alpha-sage.vercel.app/users/admin/${id}`, { method: "PUT", headers: { authorization: `bearer ${localStorage.getItem('accessToken')}` } }) .then(res => res.json()) .then(data => { if (data.modifiedCount > 0) { toast.success("Make Admin Successfully"); refetch(); } }) } if (isLoading) { return <Loading></Loading> } refetch(); return ( <div className="overflow-x-auto"> <h2 className='text-xl'>All Users:</h2> <table className="table w-full"> <thead> <tr> <th></th> <th>Name</th> <th>Email</th> <th>Admin</th> </tr> </thead> <tbody> { users.map((user, i) => <tr key={user._id}> <th>{i + 1}</th> <td>{user.name}</td> <td>{user.email}</td> <td>{user?.role !== 'admin' && <button onClick={() => handleAdmin(user._id)} className='btn btn-xs btn-primary'>Make Admin</button>}</td> </tr>) } </tbody> </table> </div> ); }; export default Alluser;
<div class="container"> <div class="row"> <div class="col-xs-12"> <button class="btn btn-primary" (click)="onlyOdd = !onlyOdd">Only show odd numbers</button> <br><br> <ul class="list-group"> <div *ngIf="onlyOdd"> <li class="list-group-item" [ngClass] = "{odd: odd % 2 !==0}" [ngStyle] = "{backgroundColor: odd % 2 !== 0 ? 'yellow' : 'transparent' }" *ngFor = "let odd of oddNumbers"> {{odd}} </li> </div> <!-- <div *ngIf="!onlyOdd"> <li class="list-group-item" [ngClass] = "{even: even % 2 === 0}" [ngStyle] = "{backgroundColor: even % 2 === 0 ? 'skyblue' : 'transparent' }" *ngFor = "let even of evenNumbers"> {{even}} </li> </div> --> <div *appUnless="onlyOdd"> <li class="list-group-item" [ngClass] = "{even: even % 2 === 0}" [ngStyle] = "{backgroundColor: even % 2 === 0 ? 'skyblue' : 'transparent' }" *ngFor = "let even of evenNumbers"> {{even}} </li> </div> </ul> <p appBasicHighlight >Style with Basic Directive!</p> <p appBetterHighlight [defaultColor] = "'grey'" [highlightColor] = "'cyan'">Style with Better Directive!</p> <div [ngSwitch]="value"> <p *ngSwitchCase = "5">Value is 5</p> <p *ngSwitchCase = "10">Value is 10</p> <p *ngSwitchCase = "100">Value is 100</p> <p *ngSwitchDefault >Value is Default</p> </div> </div> </div> </div>
<template> <form @submit.prevent="emitSubmit" class="flex flex-col items-center justify-center" > <div> <InputElement label="ID Dokumen" type="text" mode="small" id="id" :value="idState.input.value" @blur="idProps.onBlur" @input="idProps.onInput" :class="idInputClass" :placeholder="idProps.placeHolder.value" /> </div> <div> <InputElement label="Nilai Dokumen" type="text" mode="small" id="nilai" :value="nilaiState.input.value" @blur="nilaiProps.onBlur" @input="nilaiProps.onInput" :class="nilaiInputClass" :placeholder="nilaiProps.placeHolder.value" /> </div> <div> <InputElement label="Keterangan" type="text" mode="small" id="ket" :value="ketState.input.value" @blur="ketProps.onBlur" @input="ketProps.onInput" :class="ketInputClass" :placeholder="ketProps.placeHolder.value" /> </div> <Button :disabled="!isFormValid" type="submit">{{ btnLabel }}</Button> </form> </template> <script setup> import InputElement from "../forms/InputElement.vue"; import { useInput } from "../../composables/useInput"; import { validateNoEmpty } from "../../helpers/validateHelpers"; import { computed } from "vue"; const props = defineProps({ btnLabel: String, id: { type: String, default: "", }, nilai: { type: String, default: "", }, keterangan: { type: String, default: "", }, }); const emit = defineEmits(["submit"]); const [idState, idProps] = useInput(validateNoEmpty, props.id); const [nilaiState, nilaiProps] = useInput(validateNoEmpty, props.nilai); const [ketState, ketProps] = useInput(validateNoEmpty, props.keterangan); const isFormValid = computed( () => idState.isValid.value && nilaiState.isValid.value && ketState.isValid.value ); const idInputClass = computed(() => { return idState.isInputInvalid.value ? "bg-[#fddddd] border-solid border-[#b40e0e]" : ""; }); const nilaiInputClass = computed(() => { return nilaiState.isInputInvalid.value ? "bg-[#fddddd] border-solid border-[#b40e0e]" : ""; }); const ketInputClass = computed(() => { return ketState.isInputInvalid.value ? "bg-[#fddddd] border-solid border-[#b40e0e]" : ""; }); // due to tailwind constraint, can't pass arbitrary values from useInput composables since it won't be compiled function emitSubmit() { emit( "submit", props.id, idState.input.value, nilaiState.input.value, ketState.input.value ); idState.reset(); nilaiState.reset(); ketState.reset(); } </script>
#ifndef __VIDEO_GR_H #define __VIDEO_GR_H #include "bitmap.h" /** @defgroup video_gr video_gr * @{ * * Functions for outputing data to screen in graphics mode */ /** * @brief Initializes the video module in graphics mode * * Uses the VBE INT 0x10 interface to set the desired * graphics mode, maps VRAM to the process' address space and * initializes static global variables with the resolution of the screen, * and the number of colors * * @param mode 16-bit VBE mode to set * @return Virtual address VRAM was mapped to. NULL, upon failure. */ void *vg_init(unsigned short mode); /** * @brief Returns to default Minix 3 text mode (0x03: 25 x 80, 16 colors) * * @return 0 upon success, non-zero upon failure */ int vg_exit(void); /** * @brief copies the second buffer to the video memory. */ void drawMainBuffer(); /** * @brief draws the bitmap on the second buffer on the specified coordinates. * @param bmp bitmap pointer to the bitmap. * @param x x coordinate to the start of the bitmap. * @param y y coordinate to the start of the bitmap. */ void drawSecondBuffer(Bitmap* bmp, int x, int y); /** * @brief copies the second buffer to the third buffer. */ void drawThirdBuffer(); /** * @brief copies the third buffer to the second buffer. */ void copyThirdBuffer(); /** @} end of video_gr */ #endif /* __VIDEO_GR_H */
import fs from 'fs'; import handlebars from 'handlebars'; import { IUserData } from '@/data/protocols/emailService/ISendEmailDTO'; export interface IMailTemplateProvider { parse(file: string, variables: IUserData): Promise<string>; } export class HandlebarsMailTemplateProvider implements IMailTemplateProvider { public async parse(file: string, variables: IUserData) { const templateFileContent = await fs.promises.readFile(file, { encoding: 'utf-8', }); const parseTemplate = handlebars.compile(templateFileContent); return parseTemplate(variables); } }
/*Write a multithreaded program for generating prime numbers from a given starting number to the given ending number.*/ #include <stdio.h> #include <stdlib.h> #include <pthread.h> // Function to check if a number is prime int isPrime(int num) { if (num <= 1) { return 0; // 0 and 1 are not prime } for (int i = 2; i * i <= num; i++) { if (num % i == 0) { return 0; // It's divisible by a number other than 1 and itself } } return 1; // It's prime } // Function to find prime numbers in a range and store them in an array void* findPrimes(void* arg) { int* params = (int*)arg; int start = params[0]; int end = params[1]; // Find prime numbers in the given range for (int num = start; num <= end; num++) { if (isPrime(num)) { printf("%d is prime.\n", num); } } pthread_exit(NULL); } int main() { int start, end, numThreads; // Prompt the user for input printf("Enter the starting number: "); scanf("%d", &start); printf("Enter the ending number: "); scanf("%d", &end); printf("Enter the number of threads: "); scanf("%d", &numThreads); //if you dont want the user to specify the number of threads // numThreads = 4; // Use 4 threads if (start < 2 || end < 2 || start > end || numThreads <= 0) { printf("Invalid input.\n"); return 1; } // Calculate the range for each thread int range = (end - start + 1) / numThreads; pthread_t threads[numThreads]; int params[numThreads][2]; // Create and start the threads for (int i = 0; i < numThreads; i++) { params[i][0] = start + i * range; params[i][1] = i == numThreads - 1 ? end : start + (i + 1) * range - 1; if (pthread_create(&threads[i], 0, findPrimes, params[i]) != 0) { perror("pthread_create"); return 1; } } // Wait for the threads to finish for (int i = 0; i < numThreads; i++) { if (pthread_join(threads[i], 0) != 0) { perror("pthread_join"); return 1; } } return 0; }
import { SigningStargateClient } from "@cosmjs/stargate"; import { OfflineDirectSigner } from "@cosmjs/proto-signing"; import { AppCurrency, Bech32Config, BIP44, Currency, Key, } from "@keplr-wallet/types"; import { V1Beta1QueryParamsResponse } from "./cosmos.staking.v1beta1/rest"; import { V1Beta1QueryTotalSupplyResponse } from "./cosmos.bank.v1beta1/rest"; import axios from "axios"; import ReconnectingWebSocket from "reconnecting-websocket"; import EventEmitter from "eventemitter3"; declare global { interface Window { keplr: any; } } interface Env { chainID?: string; chainName?: string; apiURL: string; rpcURL: string; wsURL: string; prefix?: string; status?: { apiConnected?: boolean; rpcConnected?: boolean; wsConnected?: boolean; }; } function plugEnv(initial: Env): { env: Env; } { return { env: { ...initial, }, }; } function plugSigner(): { signer: { client?: SigningStargateClient; addr?: string; }; } { return { signer: { client: undefined, addr: undefined, }, }; } function plugKeplr(): { keplr: { connect: ( onSuccessCb: () => void, onErrorCb: () => void, params: { stakinParams: V1Beta1QueryParamsResponse; tokens: V1Beta1QueryTotalSupplyResponse; env: Env; } ) => void; isAvailable: () => boolean; getOfflineSigner: (chainId: string) => OfflineDirectSigner; getAccParams: (chainId: string) => Promise<Key>; listenToAccChange: (cb: EventListener) => void; }; } { return { keplr: { connect: async (onSuccessCb: () => void, onErrorCb: () => void, p) => { try { let staking = p.stakinParams; let tokens = p.tokens; let chainId: string = p.env.chainID || "ee"; let chainName: string = p.env.chainName || "Ee"; let rpc: string = p.env.rpcURL || ""; let rest: string = p.env.apiURL || ""; let addrPrefix: string = p.env.prefix || ""; let stakeCurrency: Currency = { coinDenom: staking.params?.bond_denom?.toUpperCase() || "", coinMinimalDenom: staking.params?.bond_denom || "", coinDecimals: 0, }; let bip44: BIP44 = { coinType: 118, }; let bech32Config: Bech32Config = { bech32PrefixAccAddr: addrPrefix, bech32PrefixAccPub: addrPrefix + "pub", bech32PrefixValAddr: addrPrefix + "valoper", bech32PrefixValPub: addrPrefix + "valoperpub", bech32PrefixConsAddr: addrPrefix + "valcons", bech32PrefixConsPub: addrPrefix + "valconspub", }; let currencies: AppCurrency[] = tokens.supply?.map((c) => { const y: any = { amount: "0", denom: "", coinDenom: "", coinMinimalDenom: "", coinDecimals: 0, }; y.coinDenom = c.denom?.toUpperCase() || ""; y.coinMinimalDenom = c.denom || ""; y.coinDecimals = 0; return y; }) as AppCurrency[]; let feeCurrencies: AppCurrency[] = tokens.supply?.map((c) => { const y: any = { amount: "0", denom: "", coinDenom: "", coinMinimalDenom: "", coinDecimals: 0, }; y.coinDenom = c.denom?.toUpperCase() || ""; y.coinMinimalDenom = c.denom || ""; y.coinDecimals = 0; return y; }) as AppCurrency[]; let coinType = 118; let gasPriceStep = { low: 0.01, average: 0.025, high: 0.04, }; if (chainId) { await window.keplr.experimentalSuggestChain({ chainId, chainName, rpc, rest, stakeCurrency, bip44, bech32Config, currencies, feeCurrencies, coinType, gasPriceStep, }); window.keplr.defaultOptions = { sign: { preferNoSetFee: true, preferNoSetMemo: true, }, }; await window.keplr.enable(chainId); onSuccessCb(); } else { console.error("Cannot access chain data"); onErrorCb(); } } catch (e) { console.error(e); onErrorCb(); } }, isAvailable: () => { // @ts-ignore return !!window.keplr; }, getOfflineSigner: (chainId: string) => // @ts-ignore window.keplr.getOfflineSigner(chainId), getAccParams: async (chainId: string) => // @ts-ignore await window.keplr.getKey(chainId), listenToAccChange: (cb: EventListener) => { window.addEventListener("keplr_keystorechange", cb); }, }, }; } function plugWebsocket(env: Env): { ws: { ee: () => EventEmitter; close: () => void; connect: () => void; }; } { let _refresh: number = 5000; let _socket: ReconnectingWebSocket; let _timer: any; let _ee = new EventEmitter(); let ping = async () => { if (env.apiURL) { try { const status: any = await axios.get(env.apiURL + "/node_info"); _ee.emit("ws-newblock", "ws-chain-id", status.data.node_info.network); status.data.application_version.name ? _ee.emit("ws-chain-name", status.data.application_version.name) : _ee.emit("ws-chain-name", status.data.node_info.network); _ee.emit("ws-api-status"); } catch (error: any) { if (!error.response) { _ee.emit("ws-api-status"); console.error(new Error("WebSocketClient: API Node unavailable")); } else { _ee.emit("ws-api-status"); } } } if (env.rpcURL) { try { await axios.get(env.rpcURL); _ee.emit("ws-rpc-status"); } catch (error: any) { if (!error.response) { console.error(new Error("WebSocketClient: RPC Node unavailable")); _ee.emit("ws-rpc-status"); } else { _ee.emit("ws-rpc-status"); } } } }; let onError = () => { console.error( new Error("WebSocketClient: Could not connect to websocket.") ); }; let onClose = () => { _ee.emit("ws-close"); }; let onOpen = () => { _ee.emit("ws-open"); _socket.send( JSON.stringify({ jsonrpc: "2.0", method: "subscribe", id: "1", params: ["tm.event = 'NewBlock'"], }) ); }; let onMessage = (msg: any) => { const result = JSON.parse(msg.data).result; if (result.data && result.data.type === "tendermint/event/NewBlock") { _ee.emit("ws-newblock", JSON.parse(msg.data).result); } }; return { ws: { ee: () => _ee, close: () => { clearInterval(_timer); _timer = undefined; _socket.close(); }, connect: () => { _socket = new ReconnectingWebSocket(env.wsURL); ping(); _timer = setInterval(() => ping(), _refresh); _socket.onopen = onOpen.bind(this); _socket.onmessage = onMessage.bind(this); _socket.onerror = onError.bind(this); _socket.onclose = onClose.bind(this); }, }, }; } export { plugEnv, plugWebsocket, plugSigner, plugKeplr, Env };
#!/usr/bin/perl -Tw use strict; $|++; use CGI qw(:all); ## set up the cache use File::Cache; my $cache = File::Cache->new({namespace => 'surveyonce', username => 'nobody', filemode => 0666, expires_in => 3600, # one hour }); unless ($cache->get(" _purge_ ")) { # cleanup? $cache->purge; $cache->set(" _purge_ ", 1); } my $SCRIPT_ID = join ".", (stat $0)[0,1,10]; print header, start_html("Survey"), h1("Survey"); if (param) { ## returning with form data ## verify first submit of this form data, ## and from the form generated by this particular script only my $session = param('session'); if (defined $session and do { my $id = $cache->get($session); $cache->remove($session); # let this be the only one $id and $id eq $SCRIPT_ID; }) { ## good session, process form data print h2("Thank you"); print "Your information has been processed."; my $name = param('name'); $name = "(Unspecified)" unless defined $name and length $name; my ($color) = grep $_ ne '-other-', param('color'); $color = "(Unspecified)" unless defined $color and length $color; print p, "Your name is ", b(escapeHTML($name)); print " and your favorite color is ", b(escapeHTML($color)), "."; } else { print h2("Error"), "Hmm, I can't process your input. Please "; print a({href => script_name()}, "start over"),"."; } } else { ## initial invocation -- print form ## get unique non-guessable stamp for this form require MD5; param('session', my $session = MD5->hexhash(MD5->hexhash(time.{}.rand().$$))); ## store session key in cache $cache->set($session, $SCRIPT_ID); ## print form print hr, start_form; print "What's your name? ",textfield('name'), br; print "What's your favorite color? "; print popup_menu(-name=>'color', -values=>[qw(-other- red orange yellow green blue purple)]); print " if -other-: ", textfield('color'), br; print hidden('session'); print submit, end_form, hr; } print end_html;
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { app } from '../firebaseConfig'; import { getFirestore, collection, addDoc, query, where, getDocs } from "firebase/firestore"; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { AlertController } from '@ionic/angular'; const db = getFirestore(app) interface NotaFiscal { numNota: number fornecedor: string medico: string paciente: string dataEmissao: any dataMovimento: any item: any movimentacao: string usuario: string } @Component({ selector: 'app-entrada', templateUrl: './entrada.page.html', styleUrls: ['./entrada.page.scss'], }) export class EntradaPage implements OnInit { public formNote: FormGroup public serie: number public volume: number public product: string public entryDate: any public notaFiscal: NotaFiscal public itens = {} public movement: string public confirm: boolean public doctorList = [] public providerList = [] public user: string constructor(public router: Router, private fb: FormBuilder, public alertController: AlertController) { } ngOnInit() { this.product = "PRÓTESE DE MAMA" localStorage.setItem('item', '1') this.user = localStorage.getItem('user') this.formNote = this.fb.group({ noteNumber: ['', Validators.required], provider: ['', Validators.required], issueDate: ['', Validators.required], patient: ['', Validators.required], doctor: ['', Validators.required], }) this.doctorList = [ 'Marcelo Alonso', 'Felipe Magno', 'Marcio Teixeira', 'Marcio Bistene', 'Marcio Wallace', 'Ramon Ramalho', 'Orido Pinheiro', 'Orido Felipe', 'Acrysio Peixoto', 'Eduardo Sucupira', 'Fernando Serra', 'Renata Wanick', 'Flavia Dantas', 'Sílvia Baima', 'Roberta Alvares', 'Guilherme Miranda', 'Ricardo Cunha', 'Adriano Medeiros', 'José Horácio', 'Horácio Gomes', 'Renato Monteiro', 'Gustavo Merheb', 'George Soares', 'George Mofoud', 'Bruno Herkenhoff', 'Ruben Bartz', 'Bruno Anastácio' ] this.doctorList.sort() this.providerList = ['SILIMED', 'POLYTECH', 'MOTIVA', 'MENTOR'] } async noteEntry() { let date = new Date() let day = ('0' + date.getDate()).slice(-2) let month = ('0' + (date.getMonth() + 1)).slice(-2) let year = date.getFullYear() let storage = parseInt(localStorage.getItem('item')) this.confirm = true for(let i=1; i<=storage; i++) { if((<HTMLSelectElement>document.getElementById('serie'+i.toString())).value == '') { this.confirm = false } } if(!this.formNote.valid) { this.confirm = false } if(this.confirm) { const q = query(collection(db, "NotaFiscal"), where("numNota", "==", this.formNote.value.noteNumber)) const querySnapshot = await getDocs(q) let serieExist = false for(let i=1; i<=storage; i++) { const q2 = query(collection(db, "Estoque"), where("serie", "==", (<HTMLSelectElement>document.getElementById('serie'+i.toString())).value)) const querySnapshot2 = await getDocs(q2) if(querySnapshot2.size != 0) { serieExist = true } } if(querySnapshot.size != 0) { this.presentAlert('Número de nota já cadastrada') } else if(serieExist) { this.presentAlert('Número de série de um ou mais produtos já exixtem no estoque') } else { for(let j=0, i=1; i<=storage; i++, j++) { let serie = (<HTMLSelectElement>document.getElementById('serie'+i.toString())).value let volume = (<HTMLSelectElement>document.getElementById('volume'+i.toString())).value this.itens[j] = { 'descricao': this.product, 'serie': serie, 'volume': volume, } } this.movement = "Entrada" this.entryDate = year + '-' + month + '-' + day this.notaFiscal = { numNota: this.formNote.value.noteNumber, fornecedor: this.formNote.value.provider, medico: this.formNote.value.doctor, paciente: this.formNote.value.patient, dataEmissao: this.formNote.value.issueDate, dataMovimento: this.entryDate, item: this.itens, movimentacao: this.movement, usuario: this.user } const docRef = await addDoc(collection(db, "NotaFiscal"), this.notaFiscal) let docRefId = docRef.id for(let i=0; i<storage; i++) { this.itens[i].idNota = docRefId let docRef2 = addDoc(collection(db, "Estoque"), this.itens[i]) } this.presentAlert('Entrada confirmada!') this.router.navigateByUrl('/home') } } else { this.presentAlert('Preencha todos os campos') } } addItem() { let id = parseInt(localStorage.getItem('item')) + 1 localStorage.setItem('item', id.toString()) let divMom = document.getElementById('itens') let div = document.createElement('div') div.id = id.toString() divMom.appendChild(div) let select = document.createElement('select') select.className = 'form-select' let option = document.createElement('option') option.innerHTML = this.product option.selected div.appendChild(select) select.appendChild(option) let divRow = document.createElement('div') divRow.className = "row my-3" div.appendChild(divRow) let divCol1 = document.createElement('div') divCol1.className = 'col-4' let ionItem1 = document.createElement('ion-item') let inputCol1 = document.createElement('ion-input') inputCol1.placeholder = 'Número de série' inputCol1.type = 'number' inputCol1.id = 'serie'+id.toString() divRow.appendChild(divCol1) divCol1.appendChild(ionItem1) ionItem1.appendChild(inputCol1) let divCol2 = document.createElement('div') divCol2.className = 'col-4' let ionItem2 = document.createElement('ion-item') let inputCol2 = document.createElement('ion-input') inputCol2.placeholder = 'Volume' inputCol2.type = 'number' inputCol2.id = 'volume'+id.toString() divRow.appendChild(divCol2) divCol2.appendChild(ionItem2) ionItem2.appendChild(inputCol2) let divCol3 = document.createElement('div') divCol3.className = 'col-4 text-end' divCol3.id = 'icon' + id.toString() let icon = document.createElement('ion-icon') icon.id = 'remove' + id.toString() icon.className = "text-danger" icon.name = "trash" icon.size = "large" icon.addEventListener("click", () => { document.getElementById(id.toString()).remove() let storage = parseInt(localStorage.getItem('item')) localStorage.setItem('item', (storage-1).toString()) }) divRow.appendChild(divCol3) divCol3.appendChild(icon) } cancel() { this.router.navigateByUrl('/home') } async presentAlert(message) { const alert = await this.alertController.create({ cssClass: 'custom-alert', message: message, buttons: ['OK'] }); await alert.present(); } }
import axios from "axios"; import { useRef } from "react"; import Product from "../models/Product.js"; const AddProduct = () => { const formRef = useRef(); const nameRef = useRef(); const imgRef = useRef(); const descriptionRef = useRef(); const priceRef = useRef(); const formHandler = (e) => { e.preventDefault(); axios .post( "http://localhost:5000/products", new Product( nameRef.current.value, imgRef.current.value, descriptionRef.current.value, +priceRef.current.value ) ) .then((response) => { console.log( `The product ${response.data.name} has been added to the store` ); formRef.current.reset(); }); }; return ( <> <h2>Add Product</h2> <form onSubmit={formHandler} ref={formRef}> <div> <label htmlFor="name">Name : </label> <input type="text" name="name" id="name" ref={nameRef} required /> </div> <div> <label htmlFor="img">Image URL : </label> <input type="text" name="img" id="img" ref={imgRef} required /> </div> <div> <label htmlFor="description">Description : </label> <textarea name="description" id="description" cols="30" rows="10" ref={descriptionRef} required ></textarea> </div> <div> <label htmlFor="price">Price : </label> <input type="number" name="price" id="price" ref={priceRef} required /> </div> <button type="submit">Add Product</button> </form> </> ); }; export default AddProduct;
#include <stdio.h> #include "util.h" #include "symbol.h" #include "absyn.h" #include "types.h" #include "temp.h" #include "translate.h" #include "env.h" E_enventry E_VarEntry(Tr_access access, Ty_ty ty) { E_enventry e = (E_enventry) checked_malloc(sizeof(*e)); e->kind = E_varEntry; e->u.var.ty = ty; e->u.var.access = access; return e; } E_enventry E_FunEntry(Tr_level level, Temp_label label, Ty_tyList formals, Ty_ty result) { E_enventry e = (E_enventry) checked_malloc(sizeof(*e)); e->kind = E_funEntry; e->u.fun.formals = formals; e->u.fun.result = result; e->u.fun.level = level; e->u.fun.label = label; return e; } S_table E_base_tenv() { // S_symbol -> Ty_ty S_table table = S_empty(); S_enter(table, S_Symbol("int"), Ty_Int()); S_enter(table, S_Symbol("string"), Ty_String()); return table; } S_table E_base_venv() { // S_symbol -> E_enventry S_table table; Ty_tyList formals; Ty_ty result; Tr_level level; Temp_label label; U_boolList boolList; table = S_empty(); // print(s : string) formals = Ty_TyList(Ty_String(), 0); boolList = U_BoolList(TRUE, 0); result = Ty_Void(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("print"), E_FunEntry(level, label, formals, result)); // Eventually I decided to use Ty_Void() to indicate the function // has no argument and to avoid the fact that the formals field of // E_funEntry may be null though that would means I must add some // condition judgement when resolving the call and declaration of // function. // However, the code is not elegant when using Ty_Void() as we // had to add some condition judgement. // Finally, I still decided to use null to indicate the function has // no argument // flush() formals = 0; // no argument boolList = 0; result = Ty_Void(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("flush"), E_FunEntry(level, label, formals, result)); // getchar() : string formals = 0; // no argument boolList = 0; result = Ty_String(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("getchar"), E_FunEntry(level, label, formals, result)); // ord(s : string) : int formals = Ty_TyList(Ty_String(), 0); boolList = U_BoolList(TRUE, 0); result = Ty_Int(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("ord"), E_FunEntry(level, label, formals, result)); // chr(i : int) : string formals = Ty_TyList(Ty_Int(), 0); boolList = U_BoolList(TRUE, 0); result = Ty_String(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("chr"), E_FunEntry(level, label, formals, result)); // size(s : string) : int formals = Ty_TyList(Ty_String(), 0); boolList = U_BoolList(TRUE, 0); result = Ty_Int(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("size"), E_FunEntry(level, label, formals, result)); // substring(s:string, first:int, n:int) : string formals = Ty_TyList(Ty_String(), Ty_TyList(Ty_Int(), Ty_TyList(Ty_Int(), 0))); boolList = U_BoolList(TRUE, U_BoolList(TRUE, U_BoolList(TRUE, 0))); result = Ty_String(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("substring"), E_FunEntry(level, label, formals, result)); // concat(s1: string, s2: string) : string formals = Ty_TyList(Ty_String(), Ty_TyList(Ty_String(), 0)); boolList = U_BoolList(TRUE, U_BoolList(TRUE, 0)); result = Ty_String(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("concat"), E_FunEntry(level, label, formals, result)); // not(i : integer) : integer (integer?) // Let's assume 'integer' is alias about 'int'. // However, according to the assumption above, we should add a new // binding into the type environment or else the function 'not' would // contain a undeclared type parameter, which is so monstrous. // So let's substitute 'integer' with 'int' temporarily to avoid above // confusion. formals = Ty_TyList(Ty_Int(), 0); boolList = U_BoolList(TRUE, 0); result = Ty_Int(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("not"), E_FunEntry(level, label, formals, result)); // exit(i : int) formals = Ty_TyList(Ty_Int(), 0); boolList = U_BoolList(TRUE, 0); result = Ty_Void(); label = Temp_newlabel(); level = Tr_newLevel(Tr_outermost(), label, boolList); S_enter(table, S_Symbol("exit"), E_FunEntry(level, label, formals, result)); return table; }
import { createContext, ParentComponent, useContext } from "solid-js"; import { createStore } from "solid-js/store"; import { defaultMargin, MarginIdType } from "../../_models/Margin"; import { defaultGridThumbnailSize, ThumbnailSizeIdType } from "../../_models/ThumbnailSize"; import { KEY_SETTINGS_SEARCH_VIEW_GRID, loadJson, saveJson } from "./_storage"; export type SearchGridViewSettingsState = { margin: MarginIdType; showTitles: boolean; showYears: boolean; thumbnailSize: ThumbnailSizeIdType; }; export const defaultSearchGridViewSettings: SearchGridViewSettingsState = { margin: defaultMargin, showTitles: true, showYears: true, thumbnailSize: defaultGridThumbnailSize, }; export type SearchGridViewSettingsContextValue = [ state: SearchGridViewSettingsState, actions: { setMargin: (margin: MarginIdType) => void; setShowTitles: (showTitles: boolean) => void; setShowYears: (showYears: boolean) => void; setThumbnailSize: (thumbnailSize: ThumbnailSizeIdType) => void; } ]; const SearchGridViewSettingsContext = createContext<SearchGridViewSettingsContextValue>(); export const SearchGridSettingsProvider: ParentComponent = (props) => { const [state, setState] = createStore(loadState()); const setMargin = (margin: MarginIdType) => updateState({margin}); const setShowTitles = (showTitles: boolean) => updateState({showTitles}); const setShowYears = (showYears: boolean) => updateState({showYears}); const setThumbnailSize = (thumbnailSize: ThumbnailSizeIdType) => updateState({thumbnailSize}); const updateState = (update: Partial<SearchGridViewSettingsState>) => { setState(update); saveState(state); }; return ( <SearchGridViewSettingsContext.Provider value={[state, { setMargin, setShowTitles, setShowYears, setThumbnailSize }]}> {props.children} </SearchGridViewSettingsContext.Provider> ); }; export const useSearchGridViewSettingsContext = () => useContext(SearchGridViewSettingsContext); function loadState() { return loadJson(KEY_SETTINGS_SEARCH_VIEW_GRID, defaultSearchGridViewSettings); } function saveState(state: SearchGridViewSettingsState) { saveJson(KEY_SETTINGS_SEARCH_VIEW_GRID, state); }
import React, {useState} from 'react'; import {Button} from "@chakra-ui/react"; import {Link as ReachLink} from "react-router-dom" function Link({children,to,shouldBeActive}) { const [isActive, setIsActive] = useState(false); return ( <> <Button as={ReachLink} to={to} size="md" fontSize="16px" fontWeight="600" borderRadius="md" borderWidth="2px" borderStyle="solid" border= "none" bg="transparent" _hover={!isActive ? { bg: "#e5e5e5", borderColor: "#dcdcdc", color: "#111" } : {bg:"none",borderBottom: "4px solid black"}} onClick={shouldBeActive ? ()=>setIsActive(true) : ""} _active={{ transform:"scale(0.95)"}} > {children} </Button> </> ); } export default Link;
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Chapter 3: Electroluminescent sources" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.15: Calculation_of_external_efficiency.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "// Example 3.15 \n", "// Calculation of external efficiency \n", "// Page no 484\n", "\n", "clc;\n", "clear;\n", "close;\n", "\n", "//Given data\n", "ne1=0.20; //Total efficiency \n", "V=3; // Voltage applied\n", "Eg=1.43; // Bandgap energy\n", "\n", "// External efficiency\n", "ne=(ne1*Eg/V)*100;\n", "\n", "//Display result on command window\n", "printf('\n External efficiency of the device (in percentage)= %0.1f ',ne);\n", "" ] } , { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.16: Calculation_of_ratio_of_threshold_current_densities.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "// Example 3.16\n", "// Calculation of ratio of threshold current densities\n", "// Page no 484\n", "\n", "clc;\n", "clear;\n", "close;\n", "\n", "// Given data\n", "To1=160; // Device temperature\n", "To2=55; // Device temperature\n", "T1=293;\n", "T2=353;\n", "J81=exp(T1/To1); // Threshold current density \n", "J21=exp(T2/To1);\n", "J82=exp(T1/To2);; \n", "J22=exp(T2/To2);; \n", "cd1=J21/J81; // Ratio of threshold current densities\n", "cd2=J22/J82;\n", "\n", "//Display result on command window\n", "printf('\n Ratio of threshold current densities= %0.2f ',cd1);\n", "printf('\n Ratio of threshold current densities= %0.2f ',cd2);" ] } , { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.17: Computation_of_conversion_efficiency.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "// Example 3.17 \n", "//Computation of conversion efficiency \n", "// Page no 484\n", "\n", "clc;\n", "clear;\n", "\n", "//Given data\n", "i=10*10^-6; // Device current\n", "p=5; // Electrical power\n", "op=50 *10^-6; // Optical power\n", "ip=5*10*10^-3; // Input power\n", "\n", "//Conversion efficiency\n", "c=op/ip*100; \n", "//Display result on command window\n", "printf('\n Conversion efficiency (in percentage)= %0.1f ',c);\n", "" ] } , { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.18: Calculation_of_total_power_emitted.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "// Example 3.18 \n", "// Calculation of total power emitted\n", "// Page no 485\n", "\n", "clc;\n", "clear;\n", "close;\n", "\n", "//Given data\n", "r=0.7; // Emissivity\n", "r0=5.67*10^-8; // Stephen's constant\n", "A=10^-4; // Surface area\n", "T=2000; // Temperature\n", "\n", "// Total power emitted\n", "P=r*r0*A*T^4; \n", "\n", "//Display result on command window\n", "printf('\n Total power emitted (Watts)= %0.1f ',P);\n", "" ] } , { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.19: Computation_of_total_energy.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "// Example 3.19 \n", "// Computation of total energy\n", "// Page no 485\n", "\n", "clc;\n", "clear;\n", "close;\n", "\n", "//Given data\n", "h=6.63*10^-34; // Planck constant\n", "v=5*10^14; // Bandgap frequency of laser\n", "N=10^24; // Population inversion density\n", "V=10^-5; // Volume of laser medium\n", "\n", "// Total energy\n", "E=(1/2)*h*v*(N)*V; \n", "\n", "//Display result on command window\n", "printf('\n Total energy (J)= %0.1f ',E);\n", "" ] } , { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.1: Calculation_of_barrier_potential.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "//Calculation of barrier potential\n", "// Example 3.1 \n", "// Page no 80\n", "clc;\n", "clear all;\n", "close;\n", "\n", "\n", "//Given data\n", "p=5; // Resistivity of p-region\n", "n=2; // Resistivity of n-region\n", "mu=3900;\n", "k=0.026; //Boltzmann constant\n", "ni=2.5*10^13; //Density of the electron hole pair\n", "e=1.6*10^-19; //charge of electron\n", " \n", "//Barrier potential calculation\n", "r0=(1/p); // Reflection at the fiber air interface \n", "r1=(1/n);\n", "m=r1/(mu*e);\n", "p=6.5*10^14; //Density of hole in p -region\n", "Vb=k*log(p*m/ni^2);\n", "\n", "//Displaying the result in command window\n", "printf('\n Barrier potential(in V) = %0.3f',Vb);\n", "\n", "// The answers vary due to round off error" ] } , { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3.20: Computation_of_pulse_power.sce" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "// Example 3.20 \n", "// Computation of pulse power\n", "// Page no 485\n", "\n", "clc;\n", "clear;\n", "close;\n", "\n", "// Given data\n", "L=0.1; // Length of laser\n", "R=0.8; // Mirror reflectance of end mirror\n", "E=1.7; // Laser pulse energy\n", "c=3*10^8; // Velocity of light\n", "t=L/((1-R)*c); // Cavity life time\n", "\n", "// Pulse power\n", "p=E/t; \n", "\n", "//Display result on command window\n", "printf('\n Pulse power (W)= %0.0f ',p);\n", "" ] } ], "metadata": { "kernelspec": { "display_name": "Scilab", "language": "scilab", "name": "scilab" }, "language_info": { "file_extension": ".sce", "help_links": [ { "text": "MetaKernel Magics", "url": "https://github.com/calysto/metakernel/blob/master/metakernel/magics/README.md" } ], "mimetype": "text/x-octave", "name": "scilab", "version": "0.7.1" } }, "nbformat": 4, "nbformat_minor": 0 }
public protocol Symbol { var id: Int { get set } var belongsToTable: Int { get set } var name: String { get } } internal protocol FunctionLikeSymbol: Symbol { var returnType: QsType { get set } var paramRange: ClosedRange<Int> { get } var functionParams: [FunctionParam] { get set } } public enum VariableStatus { case uninit, initing, globalIniting, fieldIniting, finishedInit } public enum VariableType { case global, local, instance, staticVar } public class VariableSymbol: Symbol { init(type: QsType? = nil, name: String, variableStatus: VariableStatus, variableType: VariableType) { self.id = -1 self.belongsToTable = -1 self.type = type self.name = name self.variableStatus = variableStatus self.variableType = variableType } public var id: Int public var belongsToTable: Int public let name: String public var type: QsType? public var variableStatus: VariableStatus public var variableType: VariableType } public class GlobalVariableSymbol: VariableSymbol { init(type: QsType? = nil, name: String, globalDefiningSetExpr: SetStmt, variableStatus: VariableStatus) { self.globalDefiningSetExpr = globalDefiningSetExpr super.init(type: type, name: name, variableStatus: variableStatus, variableType: .global) } var globalDefiningSetExpr: SetStmt } public class FunctionNameSymbol: Symbol { // Represents a collection of functions underneath the same name, in the same scope init(isForMethods: Bool, name: String, belongingFunctions: [Int]) { self.id = -1 self.belongsToTable = -1 self.isForMethods = isForMethods self.name = name self.belongingFunctions = belongingFunctions } // multiple overloaded functions are under the same signature public var id: Int public var belongsToTable: Int public let name: String public var isForMethods: Bool public var belongingFunctions: [Int] } internal func getParamRangeForFunction(functionStmt: FunctionStmt) -> ClosedRange<Int> { var lowerBound = functionStmt.params.count for i in 0..<functionStmt.params.count { let index = functionStmt.params.count - i - 1 if functionStmt.params[index].initializer != nil { lowerBound = index } } return lowerBound...functionStmt.params.count } public struct FunctionParam { var name: String var type: QsType } public class FunctionSymbol: FunctionLikeSymbol { init(name: String, functionStmt: FunctionStmt, returnType: QsType) { self.id = -1 self.belongsToTable = -1 self.name = name self.functionStmt = functionStmt self.returnType = returnType self.paramRange = getParamRangeForFunction(functionStmt: functionStmt) self.functionParams = [] } init(name: String, functionParams: [FunctionParam], paramRange: ClosedRange<Int>, returnType: QsType) { self.id = -1 self.belongsToTable = -1 self.name = name self.functionParams = functionParams self.paramRange = paramRange self.returnType = returnType self.functionStmt = nil } public var id: Int public var belongsToTable: Int public let name: String public var returnType: QsType public let functionStmt: FunctionStmt? public var functionParams: [FunctionParam] public let paramRange: ClosedRange<Int> } public class MethodSymbol: FunctionLikeSymbol { init(name: String, withinClass: Int, overridedBy: [Int], methodStmt: MethodStmt, returnType: QsType, finishedInit: Bool, isConstructor: Bool) { self.id = -1 self.belongsToTable = -1 self.name = name self.withinClass = withinClass self.overridedBy = overridedBy self.methodStmt = methodStmt self.paramRange = getParamRangeForFunction(functionStmt: methodStmt.function) self.returnType = returnType self.finishedInit = finishedInit self.isConstructor = isConstructor self.isStatic = methodStmt.isStatic self.visibility = methodStmt.visibilityModifier self.functionParams = [] } init( name: String, withinClass: Int, overridedBy: [Int], isStatic: Bool, visibility: VisibilityModifier, functionParams: [FunctionParam], paramRange: ClosedRange<Int>, returnType: QsType, isConstructor: Bool ) { self.id = -1 self.belongsToTable = -1 self.name = name self.withinClass = withinClass self.overridedBy = overridedBy self.methodStmt = nil self.isStatic = isStatic self.visibility = visibility self.functionParams = functionParams self.paramRange = paramRange self.returnType = returnType self.finishedInit = true self.isConstructor = isConstructor } public var id: Int public var belongsToTable: Int public let name: String public var returnType: QsType public let withinClass: Int public var overridedBy: [Int] public let methodStmt: MethodStmt? public let isStatic: Bool public let visibility: VisibilityModifier public var functionParams: [FunctionParam] public let paramRange: ClosedRange<Int> public var finishedInit: Bool public let isConstructor: Bool } internal class ClassChain { init(upperClass: Int?, depth: Int, classStmt: ClassStmt, parentOf: [Int]) { self.upperClass = upperClass self.parentOf = parentOf self.depth = depth } var upperClass: Int? var depth: Int var parentOf: [Int] } public class ClassSymbol: Symbol { init( name: String, displayName: String, nonSignatureName: String, builtin: Bool, classScopeSymbolTableIndex: Int? = nil, upperClass: Int? = nil, depth: Int? = nil, parentOf: [Int] ) { self.id = -1 self.belongsToTable = -1 self.runtimeId = -1 self.name = name self.displayName = displayName self.nonSignatureName = nonSignatureName self.builtin = builtin self.classScopeSymbolTableIndex = classScopeSymbolTableIndex self.upperClass = upperClass self.depth = depth self.parentOf = parentOf } init(name: String, classStmt: ClassStmt, upperClass: Int?, depth: Int?, parentOf: [Int]) { self.id = -1 self.belongsToTable = -1 self.runtimeId = -1 self.name = name self.nonSignatureName = classStmt.name.lexeme if classStmt.expandedTemplateParameters == nil || classStmt.expandedTemplateParameters!.isEmpty { displayName = classStmt.name.lexeme } else { displayName = name } self.builtin = classStmt.builtin self.classScopeSymbolTableIndex = classStmt.symbolTableIndex self.depth = depth self.parentOf = parentOf self.upperClass = upperClass } public var id: Int public var belongsToTable: Int public let name: String // is actually its signature public var runtimeId: Int public let displayName: String public let nonSignatureName: String public let builtin: Bool public var classScopeSymbolTableIndex: Int? public var upperClass: Int? public var depth: Int? public var parentOf: [Int] public func getMethodSymbols(symbolTable: SymbolTable) -> [MethodSymbol] { if classScopeSymbolTableIndex == nil { return [] } let currentSymbolTablePosition = symbolTable.getCurrentTableId() defer { symbolTable.gotoTable(currentSymbolTablePosition) } symbolTable.gotoTable(classScopeSymbolTableIndex!) let allSymbols = symbolTable.getAllSymbols() var result: [MethodSymbol] = [] for symbol in allSymbols where symbol is MethodSymbol { result.append(symbol as! MethodSymbol) } return result } } public class ClassNameSymbol: Symbol { init(name: String, builtin: Bool) { self.id = -1 self.belongsToTable = -1 self.name = name self.builtin = builtin } public var id: Int public var belongsToTable: Int public let name: String public let builtin: Bool }
import { useState } from 'react' import './Pratos.css' import ModalAddPrato from '../ModalAddPrato/Addprato' import { useAuth } from '../../contexts/AuthContexts' import { useEdicaoMode } from '../../contexts/EdicaoContexts' type PratosProps = { id: number foto: string nome: String descricao: string valor: number } type Props = { showFunctionButtons?: () => void } export default function Pratos({ id, foto, nome, descricao, valor }: PratosProps) { const { token } = useAuth() const { emEdicao } = useEdicaoMode() const [visibleModalAddprato, setVisibleModalAddPrato] = useState(false) async function deletarPrato(id: number) { try { const response = await fetch(`https://restaurante-poo-api.up.railway.app/restaurante/${id}`, { method: 'DELETE', headers: { authorization: `Bearer ${token}` } }); if (!response.ok) { throw new Error('Erro ao excluir o prato: ' + response.status); } console.log('Prato excluído com sucesso.'); } catch (error) { console.error('Erro ao excluir o prato:', error); } } return ( <> {visibleModalAddprato && ( <ModalAddPrato id={id} closeFunction={() => setVisibleModalAddPrato(!visibleModalAddprato)} /> )} <div className='pratos-father'> <div className='prato-photo-father'> <div className='prato-photo'> <img className='prato-photo-img' src={foto}></img></div> </div> <div className='description-info'> <div className='informations'> <div className='prato-name'> {nome}</div> <div className='prato-description'>{descricao}</div> <div className='prato-value'>R${valor}</div> </div> {emEdicao && ( <div className='function-buttons'> <> <div onClick={() => setVisibleModalAddPrato(!visibleModalAddprato)} className='prato-edit'> Editar </div> <div onClick={() => { deletarPrato(id).finally(() => setTimeout(() => window.location.reload(), 500)) }} className='prato-delete'> Excluir </div> </> </div> )} </div> </div> </> ) }
import { createFeatureSelector, createSelector } from '@ngrx/store'; import { Customer } from '../../model/customer'; import * as fromCustomers from '../reducers/customer.reducer'; export const selectCustomersState = createFeatureSelector<fromCustomers.State>( fromCustomers.customerFeatureKey ); export const selectCustomers = createSelector( selectCustomersState, (customersState) => { return customersState.customerRecords; } ); export const selectCustomersCount = createSelector( selectCustomersState, (customersState) => { return customersState.customerRecords.length; } ); export const selectCustomer = (id: number) => { console.log(id); return createSelector( selectCustomers, (customers) => { const match = customers.find((c) => { return c.id === id; }); console.log(match); return match as Customer; } ); };
import { motion } from "framer-motion"; import { useEffect } from "react"; import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'; const SpeakBar = (props: { phrases: string[], setPhrase: React.Dispatch<React.SetStateAction<string[]>> }) => { const { transcript, listening, resetTranscript, browserSupportsSpeechRecognition } = useSpeechRecognition(); useEffect(() => { if (listening) { resetTranscript() return; } if (transcript.length > 0) { props.setPhrase(p => [...p, transcript]) } }, [listening]); if (!browserSupportsSpeechRecognition) return <p>Este navegador no es compatible con la funcionalidad de Speech-to-Text 🤷‍</p>; return ( <div className='border rounded-lg w-1/3 cursor-default shadow-lg'> <div className="flex items-center w-full h-12 rounded-xl focus-within:shadow-lg bg-white overflow-hidden px-2"> <span className="w-full list-none font-semibold"> <span> {listening ? transcript : props.phrases[props.phrases.length - 1]} </span> </span> { listening ? <motion.div whileHover={{ scale: 1.1 }} className={`hover:cursor-pointer animate-bounce text-red-500`} onClick={SpeechRecognition.stopListening}> <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" /> </svg> </motion.div> : <motion.div whileHover={{ scale: 1.1 }} className={`text-gray-400 hover:cursor-pointer hover:text-blue-500`} onClick={() => SpeechRecognition.startListening({ continuous: true, language: 'es-ES' })}> <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}> <path strokeLinecap="round" strokeLinejoin="round" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" /> </svg> </motion.div> } </div> </div > ) } export default SpeakBar;
import React from "react"; const Notes = ({ overlocks, setOverlocks, reverseOverlocks, setReverseOverlocks, cleans, setCleans, toDoList, setToDoList, otherNotes, setOtherNotes, readOnly, }) => { const handleInputChange = (index, setter) => (event) => { setter((prev) => { const copy = [...prev]; copy[index] = event.target.value; return copy; }); }; return ( <div className="notesTab"> <div className="notes"> <div className="storageUnits"> <div className="overlocks"> <label>Overlocks:</label> {overlocks.map((value, index) => ( <input readOnly={readOnly} key={index} name={`overlock${index}`} value={value} onChange={handleInputChange(index, setOverlocks)} /> ))} </div> <div className="reverseOverlocks"> <label>Reverse Overlocks:</label> {reverseOverlocks.map((value, index) => ( <input readOnly={readOnly} key={index} name={`reverseOverlock${index}`} value={value} onChange={handleInputChange(index, setReverseOverlocks)} /> ))} </div> <div className="cleaned"> <label>Cleaned:</label> {cleans.map((value, index) => ( <input readOnly={readOnly} key={index} name={`clean${index}`} value={value} onChange={handleInputChange(index, setCleans)} /> ))} </div> </div> <div className="todoList"> <label>Todo List:</label> {toDoList.map((value, index) => ( <input readOnly={readOnly} key={index} name={`toDoList${index}`} value={value} onChange={handleInputChange(index, setToDoList)} /> ))} </div> <div className="otherNotes"> <label>Other Notes:</label> {otherNotes.map((value, index) => ( <input readOnly={readOnly} key={index} name={`otherNotes${index}`} value={value} onChange={handleInputChange(index, setOtherNotes)} /> ))} </div> </div> </div> ); }; export default Notes;
<?php use App\Models\Siswa; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('dokumen_siswas', function (Blueprint $table) { $table->id(); $table->foreignIdFor(Siswa::class)->constrained()->cascadeOnDelete(); $table->string('file_pendukung'); $table->string('file_kk'); $table->string('file_akta'); $table->string('file_foto'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('dokumen_siswas'); } };
//Minimum Number of Arrows to Burst Balloons //Example 1: // //Input: points = [[10,16],[2,8],[1,6],[7,12]] //Output: 2 //Explanation: The balloons can be burst by 2 arrows: //- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. //- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. class Balloons { public int findMinArrowShots(int[][] points) { if (points.length == 0) return 0; Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1])); int count = 1; int preEnd = points[0][1]; for (int i = 1; i < points.length; i++) { if (points[i][0] > preEnd) { count++; preEnd = points[i][1]; } } return count; } }
import * as model from './model.js'; import recipeView from './views/recipeview.js'; import searchView from './views/searchView.js'; import resultsView from './views/resultView.js'; import paginationView from './views/paginationView.js'; import bookmarksView from './views/bookmarkview.js'; // import 'core-js'; import 'regenerator-runtime/runtime'; // https://forkify-api.herokuapp.com/v2 // only parcel can understand // if (module.hot) { // module.hot.accept(); // } const controlRecipes = async function () { try { const id = window.location.hash.slice(1); // console.log(id); if (!id) return; // spinner recipeView.renderSpinner(); // 0)Updating results view to mark selected search result resultsView.update(model.getSearchresultPage()); // Update bookmark view bookmarksView.update(model.state.bookmarks); // 1) loading data await model.loadRecipe(id); //because it return promise // 2)rendering data recipeView.render(model.state.recipe); } catch (err) { recipeView.renderError(); console.log(err); } }; const controlSearchResults = async function () { try { // 1) Get search query const query = searchView.getQuery(); // console.log(query); if (!query) return; resultsView.renderSpinner(); // 2)Load search results await model.loadSearchResults(query); // 3)Render search results // resultsView.render(model.state.search.results); resultsView.render(model.getSearchresultPage()); // 4)render the initial pagination buttons paginationView.render(model.state.search); } catch (error) { console.log(error); } }; const controlPagination = function (goToPage) { // 1)Render new results resultsView.render(model.getSearchresultPage(goToPage)); // 2)render new pagination buttons paginationView.render(model.state.search); }; const controlServings = function (newServings) { // Update the recipe serving (in state) model.updateServings(newServings); // Update the recipe view // recipeView.render(model.state.recipe); recipeView.update(model.state.recipe); }; const controlAddBookmark = function () { // Add or remove bookmarks if (!model.state.recipe.bookmarked) { model.addBookmark(model.state.recipe); } else { model.deleteBookmark(model.state.recipe.id); } // Update recipe view recipeView.update(model.state.recipe); // Render bookmarks bookmarksView.render(model.state.bookmarks); }; const controlBookmarks = function () { bookmarksView.render(model.state.bookmarks); }; const init = function () { bookmarksView.addHandler(controlBookmarks); recipeView.addHandlerRender(controlRecipes); recipeView.addHandlerUpdateServings(controlServings); recipeView.addHandlerAddBookmark(controlAddBookmark); searchView.addHandlerSearch(controlSearchResults); paginationView.addHandlerclick(controlPagination); }; init();
package com.enerzai.optimium.example.android import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeContent import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.Card import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.SnackbarHost import androidx.compose.material.SnackbarHostState import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.core.content.ContextCompat import androidx.lifecycle.viewmodel.compose.viewModel import kotlinx.coroutines.launch import org.opencv.android.OpenCVLoader const val TAG = "optimium-android" val DEFAULT_PADDING = 16.dp val ITEMS = arrayOf("Preprocess", "Input", "Infer", "Output", "PostProcess") class MainActivity : ComponentActivity() { companion object { val REQUIRED_PERMISSIONS = mutableListOf( Manifest.permission.CAMERA ).apply { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) add(Manifest.permission.WRITE_EXTERNAL_STORAGE) }.toTypedArray() } init { if (!OpenCVLoader.initLocal()) Log.d(TAG, "failed to load opencv") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { val data: InferenceViewModel = viewModel(initializer = { InferenceViewModel(applicationContext) }) Content(data) } } } } fun checkPermissions(context: Context) = MainActivity.REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED } @Composable fun Content(data: InferenceViewModel) { val scaffoldState = rememberScaffoldState() val snackbarHostState = remember { SnackbarHostState() } Scaffold( scaffoldState = scaffoldState, snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, modifier = Modifier.windowInsetsPadding(WindowInsets.safeContent), topBar = { TopAppBar(title = { Text("Optimium Example App") }) } ) { innerPadding -> Box( modifier = Modifier .padding(innerPadding) .fillMaxSize() ) { when (data.uiState) { UiState.INIT -> { Column(modifier = Modifier.align(Alignment.Center)) { CircularProgressIndicator( modifier = Modifier.width(64.dp) ) Text("loading...") } } UiState.ERROR -> { Text("Error: ${data.cause ?: "unknown error"}") } else -> { MainView( snackbar = snackbarHostState, data = data ) } } } } } fun getPhotoReq() = PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) fun Map<String, Boolean>.accepted(): Boolean = all { it.value } @Composable fun MainView(snackbar: SnackbarHostState, data: InferenceViewModel) { val context = LocalContext.current val scope = rememberCoroutineScope() val cameraLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.TakePicture()) { if (!it) { Log.d(TAG, "cannot get image") data.cancel() } else { Log.d(TAG, "image found. start inference.") data.infer(data.imagePath) } } val photoLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.PickVisualMedia()) { if (it == null) { data.cancel() } else { data.infer(it) } } val cameraPermissionLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestMultiplePermissions()) { if (it.accepted()) { data.createTempImage() cameraLauncher.launch(data.imagePath) } else { scope.launch { snackbar.showSnackbar("Please grant permissions for camera.") } } } val photoPermissionLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestMultiplePermissions()) { if (it.accepted()) { photoLauncher.launch(getPhotoReq()) } else { scope.launch { snackbar.showSnackbar("Please grant permissions for photo.") } } } val scrollState = rememberScrollState() Column(Modifier.padding(DEFAULT_PADDING)) { Image(data.outputImage.asImageBitmap(), null, modifier = Modifier .fillMaxWidth() .clip(shape = RoundedCornerShape(15.dp)) .background(Color.LightGray) .clickable { data.selectData() } ) Spacer(modifier = Modifier.padding(vertical = 10.dp)) Column(modifier = Modifier.verticalScroll(scrollState)) { if (data.results.isEmpty()) { Text("Not executed or not detected.") } else { data.results.forEach { Text("${it.box} / ${it.score}") } } ITEMS.forEach { val time = data.stats.get(it) if (time == null) Text("$it: -") else Text(String.format("%s: %.03fus", it, time)) } } } when (data.uiState) { UiState.DATA_SELECTION -> { PhotoSelectionDialog( onDismiss = { data.cancel() }, fromCamera = { if (checkPermissions(context)) { data.createTempImage() cameraLauncher.launch(data.imagePath) } else cameraPermissionLauncher.launch(MainActivity.REQUIRED_PERMISSIONS) }, fromPhoto = { if (checkPermissions(context)) { photoLauncher.launch(getPhotoReq()) } else { photoPermissionLauncher.launch(MainActivity.REQUIRED_PERMISSIONS) } } ) } UiState.INFER -> { InferWaitDialog() } else -> {} } } @Composable fun InferWaitDialog() { Dialog(onDismissRequest = {}) { Card( modifier = Modifier .fillMaxWidth() .height(200.dp) .padding(DEFAULT_PADDING), shape = RoundedCornerShape(16.dp) ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { CircularProgressIndicator() Text("Running...") } } } } @Composable fun PhotoSelectionDialog(onDismiss: () -> Unit, fromCamera: () -> Unit, fromPhoto: () -> Unit) { Dialog(onDismissRequest = { onDismiss() }) { Card( modifier = Modifier .fillMaxWidth() .height(200.dp) .padding(DEFAULT_PADDING), shape = RoundedCornerShape(16.dp) ) { Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text("Where to get a photo?", Modifier.padding(DEFAULT_PADDING)) Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = DEFAULT_PADDING), horizontalArrangement = Arrangement.Center ) { Button(onClick = fromCamera) { Text("From Camera") } Button(onClick = fromPhoto) { Text("From Photo") } } } } } } @Preview @Composable fun PreviewContent() { // Content(InferenceViewModel(android.test)) }
import { useClientSize } from '@anton.bobrov/react-hooks'; import { RefObject, useEffect, useMemo, useRef } from 'react'; interface IProps { containerRef: RefObject<HTMLElement>; sourceWidth: number; sourceHeight: number; } interface IReturns { x: number; y: number; xLine: number; yLine: number; width: number; height: number; } export function useMapDimensions({ containerRef, sourceWidth, sourceHeight, }: IProps) { const { clientWidth, clientHeight } = useClientSize(containerRef); const dimensions = useMemo(() => { let width = clientWidth; let height = (sourceHeight * width) / sourceWidth; if (height < clientHeight) { height = clientHeight; width = (sourceWidth * height) / sourceHeight; } const xLine = Math.abs(clientWidth - width); const yLine = Math.abs(clientHeight - height); const x = (clientWidth - width) / 2; const y = (clientHeight - height) / 2; return { x, y, xLine, yLine, width, height }; }, [clientHeight, clientWidth, sourceHeight, sourceWidth]); const dimensionsRef = useRef<IReturns>(dimensions); useEffect(() => { dimensionsRef.current = dimensions; }, [dimensions]); return { dimensions, dimensionsRef }; }
# -*- coding: utf-8 -*- # Copyright 2022 Shang Xie. # All rights reserved. # # This file is part of the CatMOD distribution and # governed by your choice of the "CatMOD License Agreement" # or the "GNU General Public License v3.0". # Please see the LICENSE file that should # have been included as part of this package. """Represent a full help argument parser and execute. What's here: Loads the relevant script modules and executes the script. ---------------------------------------------------------- Classes: - ScriptExecutor Identical to the built-in argument parser. ------------------------------------------ Classes: - FullHelpArgumentParser Smart formatter for allowing raw formatting in help text and lists in the helptext. --------------------------------------------------- Classes: - SmartFormatter CatMOD argument parser functions. ---------------------------------- Classes: - CatMODArgs Parse the sub-command line arguments. ------------------------------------- Classes: - DPArgs - EFArgs - TrainArgs - PredictArgs """ from argparse import ArgumentParser, HelpFormatter from importlib import import_module from logging import getLogger from os import getpid from re import ASCII, compile from sys import exit, stderr from textwrap import wrap from CatMOD.sys_output import Output logger = getLogger(__name__) # pylint: disable=invalid-name class ScriptExecutor(object): """Loads the relevant script modules and executes the script. This class is initialised in each of the argparsers for the relevant command, then execute script is called within their set_default function. Attributes: - command (str): Full commands. - subparsers: Subparsers for each subcommand. - output: Output info, warning and error. """ def __init__(self, command: str, subparsers=None): """Initialize ScriptExecutor. Args: - command (str): Full commands. - subparsers: Subparsers for each subcommand. """ self.command = command.lower() self.subparsers = subparsers self.output = Output() def import_script(self): """Only import a script's modules when running that script.""" # cmd = os.path.basename(sys.argv[0]) src = 'CatMOD' mod = '.'.join((src, self.command.lower())) module = import_module(mod) script = getattr(module, self.command.title().replace('_', '')) return script def execute_script(self, arguments): """Run the script for called command.""" self.output.info(f'Executing: {self.command}. PID: {getpid()}') logger.debug(f'Executing: {self.command}. PID: {getpid()}') try: script = self.import_script() process = script(arguments) process.process() except KeyboardInterrupt: # pylint: disable=try-except-raise raise except SystemExit: pass except Exception: # pylint: disable=broad-except logger.exception('Got Exception on main handler:') logger.critical( 'An unexpected crash has occurred. ' 'Crash report written to logfile. ' 'Please verify you are running the latest version of CatMOD ' 'before reporting.') finally: exit() class FullHelpArgumentParser(ArgumentParser): """Identical to the built-in argument parser. On error it prints full help message instead of just usage information. """ def error(self, message: str): """Print full help messages.""" self.print_help(stderr) args = {'prog': self.prog, 'message': message} self.exit(2, f'{self.prog}: error: {message}\n') class SmartFormatter(HelpFormatter): """Smart formatter for allowing raw formatting. Mainly acting in help text and lists in the helptext. To use: prefix the help item with 'R|' to overide default formatting. List items can be marked with 'L|' at the start of a newline. Adapted from: https://stackoverflow.com/questions/3853722 """ def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width=None): """Initialize SmartFormatter. Args: - prog (str): Program name. - indent_increment (int): Indent increment. default 2. - max_help_position (int): Max help position. default 24. - width: Width. """ super().__init__(prog, indent_increment, max_help_position, width) self._whitespace_matcher_limited = compile(r'[ \r\f\v]+', ASCII) def _split_lines(self, text: str, width): if text.startswith('R|'): text = self._whitespace_matcher_limited.sub(' ', text).strip()[2:] output = [] for txt in text.splitlines(): indent = '' if txt.startswith('L|'): indent = ' ' txt = ' - {}'.format(txt[2:]) output.extend(wrap( txt, width, subsequent_indent=indent)) return output return HelpFormatter._split_lines(self, text, width) class CatmodArgs(object): """CatMOD argument parser functions. It is universal to all commands. Should be the parent function of all subsequent argparsers. Attributes: - global_arguments: Global arguments. - argument_list: Argument list. - optional_arguments: Optional arguments. - parser: Parser. """ def __init__(self, subparser, command: str, description: str = 'default', subparsers=None): """Initialize CatmodArgs. Args: - subparser: Subparser. - command (str): Command. - description (str): Description. default 'default'. - subparsers: Subparsers. """ self.global_arguments = self.get_global_arguments() self.argument_list = self.get_argument_list() self.optional_arguments = self.get_optional_arguments() if not subparser: return self.parser = self.create_parser(subparser, command, description) self.add_arguments() script = ScriptExecutor(command, subparsers) self.parser.set_defaults(func=script.execute_script) @staticmethod def get_argument_list(): """Put the arguments in a list so that they are accessible.""" argument_list = [] return argument_list @staticmethod def get_optional_arguments(): """Put the arguments in a list so that they are accessible. This is used for when there are sub-children. (e.g. convert and extract) Override this for custom arguments. """ argument_list = [] return argument_list @staticmethod def get_global_arguments(): """Arguments that are used in ALL parts of CatMOD. DO NOT override this! """ global_args = [] global_args.append({'opts': ('-v', '--version'), 'action': 'version', 'version': 'CatMOD v0.0.1a'}) return global_args @staticmethod def create_parser(subparser, command: str, description: str): """Create the parser for the selected command.""" parser = subparser.add_parser( command, help=description, description=description, epilog='Questions and feedback: ' 'https://github.com/CatMOD/CatMOD', formatter_class=SmartFormatter) return parser def add_arguments(self): """Parse the arguments passed in from argparse.""" options = (self.global_arguments + self.argument_list + self.optional_arguments) for option in options: args = option['opts'] kwargs = {key: option[key] for key in option.keys() if key != 'opts'} self.parser.add_argument(*args, **kwargs) class DPArgs(CatmodArgs): """.""" @staticmethod def get_argument_list(): """Put the arguments in a list so that they are accessible.""" argument_list = [] argument_list.append({ 'opts': ('-r', '--ref'), 'dest': 'reference', 'required': True, 'type': str, 'help': 'input reference fasta file.'}) argument_list.append({ 'opts': ('-c', '--current'), 'dest': 'current', 'required': True, 'type': str, 'help': 'input ONT fast5 dictionary.'}) # argument_list.append({ # 'opts': ('-n', '--neg'), # 'dest': 'negative', # 'required': True, # 'type': str, # 'nargs': '+', # 'help': 'input negative bed files.'}) argument_list.append({ 'opts': ('-o', '--output'), 'dest': 'output', 'required': True, 'type': str, 'help': 'output folder path.'}) return argument_list class EFArgs(CatmodArgs): """.""" @staticmethod def get_argument_list(): """Put the arguments in a list so that they are accessible.""" argument_list = [] argument_list.append({ 'opts': ('-b', '--bed'), 'dest': 'bed', 'required': True, 'type': str, 'help': 'input all samples bed file.'}) argument_list.append({ 'opts': ('-r', '--ref'), 'dest': 'reference', 'required': True, 'type': str, 'help': 'input reference fasta file.'}) argument_list.append({ 'opts': ('-a', '--align'), 'dest': 'align', 'required': True, 'type': str, 'help': 'input ONT alignment bam file.'}) argument_list.append({ 'opts': ('-c', '--current'), 'dest': 'current', 'required': True, 'type': str, 'help': 'input ONT current folder or index file.'}) argument_list.append({ 'opts': ('-sw', '--seq_window'), 'dest': 'seq_window', 'required': False, 'type': int, 'default': 101, 'help': 'length of sequence window to use [default=101].'}) argument_list.append({ 'opts': ('-aw', '--ali_window'), 'dest': 'ali_window', 'required': False, 'type': int, 'default': 41, 'help': 'length of alignment window to use [default=41].'}) argument_list.append({ 'opts': ('-cw', '--cur_window'), 'dest': 'cur_window', 'required': False, 'type': int, 'default': 256, 'help': 'length of current window window to use [default=256].'}) argument_list.append({ 'opts': ('-ck', '--current_kind'), 'dest': 'current_kind', 'required': False, 'type': str, 'default': 'linear', 'help': 'Specifies the kind of interpolation as a string or as an ' 'integer specifying the order of the spline interpolator ' 'to use. The string has to be one of `linear`, `nearest`, ' '`nearest-up`, `zero`, `slinear`, `quadratic`, `cubic`, ' '`previous`, or `next`. `zero`, `slinear`, `quadratic` ' 'and `cubic` refer to a spline interpolation of zeroth, ' 'first, second or third order; `previous` and `next` ' 'simply return the previous or next value of the point; ' '`nearest-up` and `nearest` differ when interpolating ' 'half-integers (e.g. 0.5, 1.5) in that `nearest-up` ' 'rounds up and `nearest` rounds down. Default is `linear`.' }) argument_list.append({ 'opts': ('-t', '--threads'), 'dest': 'threads', 'required': False, 'type': int, 'default': 0, 'help': 'number of threads to use [default=all].'}) argument_list.append({ 'opts': ('-s', '--seed'), 'dest': 'seed', 'required': False, 'type': int, 'default': 0, 'help': 'random seed for sampling to use [default=0].'}) argument_list.append({ 'opts': ('--use_memory',), 'dest': 'use_memory', 'required': False, 'type': bool, 'default': False, 'help': 'use memory to speed up [default=False].'}) argument_list.append({ 'opts': ('--overwrite',), 'dest': 'overwrite', 'required': False, 'type': bool, 'default': False, 'help': 'overwrite [default=False].'}) argument_list.append({ 'opts': ('-o', '--output'), 'dest': 'output', 'required': True, 'type': str, 'help': 'output folder path.'}) return argument_list class TrainArgs(CatmodArgs): """.""" @staticmethod def get_argument_list(): """Put the arguments in a list so that they are accessible.""" argument_list = [] return argument_list class PredictArgs(CatmodArgs): """.""" @staticmethod def get_argument_list(): """Put the arguments in a list so that they are accessible.""" argument_list = [] argument_list.append({ 'opts': ('-b', '--bed'), 'dest': 'bed', 'required': True, 'type': str, 'help': 'input all samples bed file.'}) argument_list.append({ 'opts': ('-d', '--datasets'), 'dest': 'datasets', 'required': True, 'type': str, 'help': 'input datasets folder path.'}) argument_list.append({ 'opts': ('-m', '--model'), 'dest': 'model', 'required': True, 'type': str, 'help': 'input saved model file path.'}) argument_list.append({ 'opts': ('-t', '--threads'), 'dest': 'threads', 'required': False, 'type': int, 'default': 0, 'help': 'number of threads to use [default=all].'}) argument_list.append({ 'opts': ('-o', '--output'), 'dest': 'output', 'required': True, 'type': str, 'help': 'output file path.'}) return argument_list
import { render, screen} from "@testing-library/react" import { MemoryRouter, Route } from "react-router-dom" import { OrderDetailsProvider } from "../../context/OrderDetails" import userEvent from "@testing-library/user-event" import ProductCard from "../ProductCard" const WrapperWithRoute = ({children}) => { return ( <MemoryRouter initialEntries={["/products/bikesPreview/3"]}> <OrderDetailsProvider> <Route path="/products/:typeId/:id"> {children} </Route> </OrderDetailsProvider> </MemoryRouter> ) } const renderWithRoute = (ui, options) => render(ui, {wrapper: WrapperWithRoute, ...options }); test("Toggling active classes in ImgSlider component", async () => { window.scrollTo = jest.fn() renderWithRoute(<ProductCard/>) const slideOne = await screen.findByAltText("Griffon one") const slideTwo = await screen.findByAltText("Griffon two") expect(slideOne).toHaveClass("card__images--active") expect(slideTwo).toHaveClass("card__images--inActive") const optionTwo = await screen.findByAltText("Griffon min two") userEvent.click(optionTwo) expect(slideOne).toHaveClass("card__images--inActive") expect(slideTwo).toHaveClass("card__images--active") })
// // File.swift // // // Created by Tibor Bodecs on 2021. 12. 14.. // @_exported import FeatherCore @_exported import BlogApi public extension HookName { // static let permission: HookName = "permission" } struct BlogModule: FeatherModule { let router = BlogRouter() var bundleUrl: URL? { Bundle.module.resourceURL?.appendingPathComponent("Bundle") } func boot(_ app: Application) throws { app.migrations.add(BlogMigrations.v1()) app.databases.middleware.use(MetadataModelMiddleware<BlogPostModel>()) app.databases.middleware.use(MetadataModelMiddleware<BlogCategoryModel>()) app.databases.middleware.use(MetadataModelMiddleware<BlogAuthorModel>()) app.hooks.register(.installStep, use: installStepHook) app.hooks.register(.installUserPermissions, use: installUserPermissionsHook) app.hooks.register(.installCommonVariables, use: installCommonVariablesHook) app.hooks.register(.installWebMenuItems, use: installWebMenuItemsHook) app.hooks.register(.installWebPages, use: installWebPagesHook) app.hooks.register(.adminRoutes, use: router.adminRoutesHook) app.hooks.register(.apiRoutes, use: router.apiRoutesHook) app.hooks.register(.adminWidgets, use: adminWidgetsHook) app.hooks.registerAsync(.installResponse, use: installResponseHook) app.hooks.registerAsync(.response, use: categoryResponseHook) app.hooks.registerAsync(.response, use: authorResponseHook) app.hooks.registerAsync(.response, use: postResponseHook) app.hooks.registerAsync("blog-home-page", use: homePageHook) app.hooks.registerAsync("blog-posts-page", use: postsPageHook) app.hooks.registerAsync("blog-categories-page", use: categoriesPageHook) app.hooks.registerAsync("blog-authors-page", use: authorsPageHook) } func adminWidgetsHook(args: HookArguments) -> [TemplateRepresentable] { if args.req.checkPermission(Blog.permission(for: .detail)) { return [ BlogAdminWidgetTemplate(), ] } return [] } // MARK: - pages func homePageHook(args: HookArguments) async throws -> Response? { let items = try await BlogPostApiController.list(args.req) let template = BlogHomePageTemplate(.init(posts: items)) return args.req.templates.renderHtml(template) } func postsPageHook(args: HookArguments) async throws -> Response? { let items = try await BlogPostApiController.list(args.req) let template = BlogPostsPageTemplate(.init(posts: items)) return args.req.templates.renderHtml(template) } func categoriesPageHook(args: HookArguments) async throws -> Response? { let items = try await BlogCategoryApiController.list(args.req) let template = BlogCategoriesPageTemplate(.init(categories: items)) return args.req.templates.renderHtml(template) } func authorsPageHook(args: HookArguments) async throws -> Response? { let items = try await BlogAuthorApiController.list(args.req) let template = BlogAuthorsPageTemplate(.init(authors: items)) return args.req.templates.renderHtml(template) } // MARK: - responses func categoryResponseHook(args: HookArguments) async throws -> Response? { guard let category = try await BlogCategoryApiController.detailBy(path: args.req.url.path, args.req) else { return nil } let template = BlogCategoryPageTemplate(.init(category: category)) return args.req.templates.renderHtml(template) } func authorResponseHook(args: HookArguments) async throws -> Response? { guard let author = try await BlogAuthorApiController.detailBy(path: args.req.url.path, args.req) else { return nil } let template = BlogAuthorPageTemplate(.init(author: author)) return args.req.templates.renderHtml(template) } func postResponseHook(args: HookArguments) async throws -> Response? { guard let post = try await BlogPostApiController.detailBy(path: args.req.url.path, args.req) else { return nil } let template = BlogPostPageTemplate(.init(post: post)) return args.req.templates.renderHtml(template) } // MARK: - install func installStepHook(args: HookArguments) -> [SystemInstallStep] { [ .init(key: Self.featherIdentifier, priority: 100), ] } func installResponseHook(args: HookArguments) async throws -> Response? { guard args.installInfo.currentStep == Self.featherIdentifier else { return nil } return try await BlogInstallStepController().handleInstallStep(args.req, info: args.installInfo) } func installUserPermissionsHook(args: HookArguments) -> [User.Permission.Create] { var permissions = Blog.availablePermissions() permissions += Blog.Post.availablePermissions() permissions += Blog.Category.availablePermissions() permissions += Blog.Author.availablePermissions() permissions += Blog.AuthorLink.availablePermissions() return permissions.map { .init($0) } } func installCommonVariablesHook(args: HookArguments) -> [Common.Variable.Create] { [ .init(key: "blogHomePageTitle", name: "Blog home page title", value: "Blog", notes: "Title of the blog home page"), .init(key: "blogHomePageExcerpt", name: "Blog home page excerpt", value: "Latest posts", notes: "Short description of the blog home page"), .init(key: "blogPostsPageTitle", name: "Blog posts page title", value: "Posts", notes: "Title for the blog posts page"), .init(key: "blogPostsPageExcerpt", name: "Blog posts page excerpt", value: "Every single post", notes: "Excerpt for the blog posts page"), .init(key: "blogCategoriesPageTitle", name: "Blog categories page title", value: "Categories", notes: "Title for the blog categories page"), .init(key: "blogCategoriesPageExcerpt", name: "Blog categories page excerpt", value: "Blog posts by categories", notes: "Excerpt for the blog categories page"), .init(key: "blogAuthorsPageTitle", name: "Blog authors page title", value: "Authors", notes: "Title for the blog authors page"), .init(key: "blogAuthorsPageExcerpt", name: "Blog authors page excerpt", value: "Blog posts by authors", notes: "Excerpt for the blog authors page"), .init(key: "blogPostShareIsEnabled", name: "Is post sharing enabled?", value: "true", notes: "The share box is only displayed if this variable is true"), .init(key: "blogPostShareLinkPrefix", name: "Share box link prefix", value: "Thanks for reading, if you liked this article please ", notes: "Appears before the share link (prefix[link]suffix)"), .init(key: "blogPostShareLink", name: "Share box link label", value: "share it on Twitter", notes: "Share link will be placed between the prefix & suffix (prefix[link]suffix)"), .init(key: "blogPostShareLinkSuffix", name: "Share box link suffix", value: ".", notes: "Appears after the share link (prefix[link]suffix)"), .init(key: "blogPostShareAuthor", name: "Share box author Twitter profile", value: "tiborbodecs", notes: "Share author"), .init(key: "blogPostShareHashtags", name: "Share box hashtags (coma separated)", value: "SwiftLang", notes: "Share hashtasgs"), .init(key: "blogPostAuthorBoxIsEnabled", name: "Post author is enabled", value: "true", notes: "Display post author box if this variable is true"), .init(key: "blogPostFooter", name: "Post footer text", notes: "Display the contents of this value under every post entry"), ] } func installWebMenuItemsHook(args: HookArguments) -> [Web.MenuItem.Create] { let menuId = args["menuId"] as! UUID return [ .init(label: "Blog", url: "/blog/", priority: 900, menuId: menuId), .init(label: "Posts", url: "/posts/", priority: 800, menuId: menuId), .init(label: "Categories", url: "/categories/", priority: 700, menuId: menuId), .init(label: "Authors", url: "/authors/", priority: 600, menuId: menuId), ] } func installWebPagesHook(args: HookArguments) -> [Web.Page.Create] { [ .init(title: "Blog", content: "[blog-home-page]"), .init(title: "Posts", content: "[blog-posts-page]"), .init(title: "Categories", content: "[blog-categories-page]"), .init(title: "Authors", content: "[blog-authors-page]"), ] } }
mod bucket; use std::fmt::Debug; use std::hash::Hasher; use std::ptr; use std::sync::atomic::AtomicPtr; use std::sync::atomic::Ordering; use std::sync::Arc; use std::sync::RwLock; use bucket::*; /** * Things we need to support: * * Resizing (to deal with bucket lengths getting too long and which will cause hash collisions) * * Garbage collection ( This and the above will require keeping track of writers and readers) * * Unique enforcement - Done * * Iterable support - Done * * Internal mutability support - Done * * Support remove operation - Done * */ const INITIAL_CAPACITY: usize = 64; pub struct ConcurrentHashMap<K, V> where K: Eq + std::hash::Hash + Clone + Debug, { buckets: Vec<AtomicBucketItem<K, V>>, capacity: usize, } impl<K, V> Default for ConcurrentHashMap<K, V> where K: Eq + std::hash::Hash + Clone + Debug, { fn default() -> Self { Self::new(INITIAL_CAPACITY) } } impl<'a, K, V> ConcurrentHashMap<K, V> where K: Eq + std::hash::Hash + Clone + Debug, { pub fn iter(&'a self) -> impl Iterator<Item = ExternalBucketItem<K, V>> + 'a { self.buckets.iter().flat_map(|bucket| { bucket.iter().map(|item| ExternalBucketItem { key: item.key.clone(), value: Arc::clone(&item.value), }) }) } } impl<K, V> ConcurrentHashMap<K, V> where K: Eq + std::hash::Hash + Clone + Debug, { pub fn new(capacity: usize) -> Self { let mut buckets = Vec::with_capacity(capacity); for _ in 0..capacity { buckets.push(AtomicBucketItem(AtomicPtr::new(ptr::null_mut()))); } ConcurrentHashMap { buckets, capacity: capacity, } } /** Inserts an element associated with the given key with the provided value into the concurrent hash map. It uses atomic `compare_exchange` operations to allow thread safe concurrent usage. If the key already exists it will replace the existing value with the value provided */ pub fn insert(&self, key: K, value: V) { let index = self.get_bucket_slot(&key); let new_bucket_item = Box::into_raw(Box::new(BucketItem { key: key, value: Arc::new(RwLock::new(value)), next: AtomicPtr::new(ptr::null_mut()), })); if self.update_existing_key(new_bucket_item, index).is_err() { // no current bucket item has the new_bucket_item key, so add new key via new_bucket_item self.insert_new_key(new_bucket_item, index); } } /** Removes the element associated with the given key from the concurrent hash map. It uses atomic `compare_exchange` operations to allow thread safe concurrent usage. */ pub fn remove(&self, key: K) { let index = self.get_bucket_slot(&key); let head = self.buckets[index].0.load(Ordering::SeqCst); let mut prev = ptr::null_mut::<BucketItem<K, V>>(); let mut current = head; while !current.is_null() { let node = unsafe { &*current }; let next_node = node.next.load(Ordering::SeqCst); if node.key.eq(&key) { // If prev is equal to null it means that the key of `head` is the same as the key of new_bucket_item if prev.is_null() { // Set buckets[index] equal to next_node match self.buckets[index].0.compare_exchange( current, next_node, Ordering::SeqCst, Ordering::SeqCst, ) { Ok(_) => return, // Successfully inserted Err(new_head) => { // The value in buckets[index] was updated in between the load and compare_exchange and you must restart current = new_head; continue; } } } else { //set prev.next equal to next_node // deletion in place // Set prev.next to new_bucket_item if prev is not null. let raw_prev = unsafe { &*prev }; match raw_prev.next.compare_exchange( current, next_node, Ordering::SeqCst, Ordering::SeqCst, ) { Ok(_) => return, // Successfully inserted Err(actual_next) => { // actual_next is what the pointer for the element after the previous bucket item is in reality (`current` was incorrect) // The value in buckets[index] was updated in between the load and compare_exchange and you must restart current = actual_next; continue; } } } } prev = current; current = node.next.load(Ordering::SeqCst); } } /** * `insert_new_key` assumes that there are no bucket items in the bucket at `index` with the same key as `new_bucket_item`. * It will attempt to append to the front of the LinkedList at bucket `index` the bucket item `new_bucket_item` until it succeeds. * Utilizes the atomic operation `compare_exchange` to handle the list mutations. If the `compare_exchange` operation fails it will continue to retry until it succeeds */ fn insert_new_key(&self, new_bucket_item: *mut BucketItem<K, V>, index: usize) { let mut head = self.buckets[index].0.load(Ordering::SeqCst); loop { unsafe { (*new_bucket_item).next.store(head, Ordering::SeqCst) }; match self.buckets[index].0.compare_exchange( head, new_bucket_item, Ordering::SeqCst, Ordering::SeqCst, ) { Ok(_) => break, // Successfully inserted Err(new_head) => { // The value in buckets[index] was updated in between the load and compare_exchange and you must restart head = new_head; // Collision, retry // Optimization // Only check the distance between the new head and the old head since you've already checked everything after the old head // Only do this if you know there aren't any duplicates in the old head list // Consider simply rejecting duplicate wries (two conflicting writes on the same key) // You'll know cause you've iterated the whole list finding no duplicates and then the new head will be of the same key } } } } /** * Returns Ok if a bucket item with the same key as new_bucket_item is found, otherwise returns an error if no bucket item with the same key is found. * * Gets the bucket at `index`, then iterates through the LinkedIn starting at the head of the bucket. * Starts by setting a current node to `head` and then iterating to the list, trying to find any bucket item that has the same key as `new_bucket_item` * If it finds a bucket item with the same key, it will use `prev` and `current` as needed to replace that bucket item with the `new_bucket_item` pointer. * Utilize the atomic operation `compare_exchange` to handle the list mutations. If the `compare_exchange` operation fails it will continue to retry until it succeeds */ fn update_existing_key( &self, new_bucket_item: *mut BucketItem<K, V>, index: usize, ) -> Result<(), ()> { let key = unsafe { &(*new_bucket_item).key }; let head = self.buckets[index].0.load(Ordering::SeqCst); let mut prev = ptr::null_mut::<BucketItem<K, V>>(); let mut current = head; while !current.is_null() { let node = unsafe { &*current }; let next_node = node.next.load(Ordering::SeqCst); if node.key.eq(&key) { // Change the next value of new node unsafe { (*new_bucket_item).next.store(next_node, Ordering::SeqCst) }; // If prev is equal to null it means that the key of `head` is the same as the key of new_bucket_item if prev.is_null() { match self.buckets[index].0.compare_exchange( head, new_bucket_item, Ordering::SeqCst, Ordering::SeqCst, ) { Ok(_) => return Ok(()), // Successfully inserted Err(new_head) => { // The value in buckets[index] was updated in between the load and compare_exchange and you must restart current = new_head; continue; } } } else { // There was an existing BucketItem with a matching key but it was not the first item in the bucket. So it's somewhere within the list. // Set prev.next to new_bucket_item if prev is not null. let raw_prev = unsafe { &*prev }; match raw_prev.next.compare_exchange( current, new_bucket_item, Ordering::SeqCst, Ordering::SeqCst, ) { Ok(_) => return Ok(()), // Successfully inserted Err(actual_next) => { // actual_next is what the pointer for the element after the previous bucket item is in reality (`current` was incorrect) // The value in buckets[index] was updated in between the load and compare_exchange and you must restart current = actual_next; continue; } } } } prev = current; current = node.next.load(Ordering::SeqCst); } Err(()) } /** * We really don't want to return a reference as that's error prone and will make garbage collection much harder in the future * This is intentional append-only but we may need to add garbage collection in the future */ pub fn get(&self, key: &K) -> Option<BucketValue<V>> { let index = self.get_bucket_slot(key); let mut current = self.buckets[index].0.load(Ordering::SeqCst); while !current.is_null() { let node = unsafe { &*current }; if node.key.eq(key) { return Some(node.value.clone()); } current = node.next.load(Ordering::SeqCst); } None } fn hash(&self, key: &K) -> usize { let mut hasher = std::collections::hash_map::DefaultHasher::new(); key.hash(&mut hasher); hasher.finish() as usize } fn get_bucket_slot(&self, key: &K) -> usize { let hash = self.hash(&key); return hash % self.capacity; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_insert_new_key() { let map = ConcurrentHashMap::default(); let key = "test2".to_string(); let value = "hello".to_string(); map.insert(key.clone(), value.clone()); if let Some(retrieved_value) = map.get(&key) { let retrieved_value = retrieved_value.read().unwrap(); let retrieved_value = retrieved_value.clone(); assert_eq!(value, retrieved_value); } else { assert!( false, "Test failed. Could not find any value associated with the key that was utilized" ) } } #[test] fn test_insert_existing_key() { // let map = ConcurrentHashMap::default(); let key = "test2".to_string(); let value = "hello".to_string(); let value_two = "world".to_string(); map.insert(key.clone(), value.clone()); if let Some(retrieved_value) = map.get(&key) { let retrieved_value = retrieved_value.read().unwrap(); let retrieved_value = retrieved_value.clone(); assert_eq!(value, retrieved_value); } else { assert!( false, "Test failed. Could not find any value associated with the key that was utilized" ) } map.insert(key.clone(), value_two.clone()); if let Some(retrieved_value) = map.get(&key) { let retrieved_value = retrieved_value.read().unwrap(); let retrieved_value = retrieved_value.clone(); assert_eq!(value_two, retrieved_value); } else { assert!( false, "Test failed. Could not find any value associated with the key that was utilized" ) } } #[test] fn test_iteration() { // panic!("Lockfree HashMap Insert Test Not Implemented") } #[test] fn test_remove() { // panic!("Lockfree HashMap Insert Test Not Implemented") } #[test] fn test_remove_fails_due_to_non_existance() { // panic!("Lockfree HashMap Insert Test Not Implemented") } }