text
stringlengths
184
4.48M
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* nickCommand.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: alaaouam <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/08/23 01:45:31 by alaaouam #+# #+# */ /* Updated: 2023/09/17 00:41:53 by alaaouam ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../inc/Server.hpp" static bool invalidNickname(std::string& nickname) { if (!nickname.empty() && !isalpha(nickname[0]) && nickname[0] != '_' && nickname[0] != '[' && nickname[0] != ']' && nickname[0] != '{' && nickname[0] != '}') return true; return false; } static bool nicknameInUse(std::map<int, Client> clients, std::string& nickname) { std::map<int, Client>::const_iterator it = clients.begin(); while (it != clients.end()) { if (toUpperCase(it->second.getNickname()) == toUpperCase(nickname)) return true; it++; } return false; } static bool handleErrors(Server& server, Client& client, std::string& buffer, std::vector<std::string>& message) { if (message.size() < 2 || message[1].empty() || message[1] == ":") { buffer = ERR_NONICKNAMEGIVEN(client.getNickname()); return true; } else if (nicknameInUse(server.getClients(), message[1]) && toUpperCase(message[1]) != toUpperCase(client.getNickname())) { buffer = ERR_NICKNAMEINUSE(client.getNickname(), message[1]); return true; } else if (invalidNickname(message[1])) { buffer = ERR_ERRONEUSNICKNAME(client.getNickname(), message[1]); if (client.getAuth() == false) client.setWrongNickname(message[1]); return true; } return false; } static std::string getNewNickname(std::string nickname) { std::string newNickname; size_t pos = 0; while (pos < nickname.size() && (isalnum(nickname[pos]) || nickname[pos] == '_' || nickname[pos] == '[' || nickname[pos] == ']' || nickname[pos] == '{' || nickname[pos] == '}' || nickname[pos] == '-')) pos++; return newNickname = nickname.substr(0, pos); } void nickCommand(Command& command) { bool firstConnection = false; Server& server = *command.server; Client& client = *command.client; std::string& buffer = *command.buffer; std::string newNickname; if (handleErrors(server, client, buffer, command.message)) return ; newNickname = getNewNickname(command.message[1].substr(0, 12)); if (toUpperCase(newNickname) == toUpperCase(client.getNickname())) return ; if (client.getNickAuth() == true) buffer = RPL_NICKNAMECHANGED(client.getNickname(), client.getUsername(), newNickname); else firstConnection = true; client.setNickname(newNickname); client.setNickAuth(true); if (firstConnection && client.getAuth() == true) buffer = RPL_WELCOME(client.getNickname()); }
import Form from "react-bootstrap/Form"; type InputLabeled = { containerStyle?: string; inputType: string; inputWrapperStyle?: string; inputStyle: string; inputValue: string | number; inputPlaceholder?: string; onChange: (e?: any) => void; labelValue?: string; labelStyle?: string; animationData?: string; inputKey?: string; pattern?: string; }; export default function InputLabeled(props: InputLabeled) { return ( <Form.Group className={props.containerStyle}> {props.labelValue ? ( <Form.Label className={props.labelStyle}>{props.labelValue}</Form.Label> ) : null} <div data-animation={props.animationData} className={props.inputWrapperStyle} > <input pattern={props.pattern} key={props.inputKey} className={props.inputStyle} type={props.inputType} placeholder={props.inputPlaceholder} value={props.inputValue} onChange={props.onChange} style={{ outline: "none" }} /> </div> </Form.Group> ); }
import { useEffect, useState } from "react"; import Team from "./components/Team"; import Whyus from "./components/Whyus"; import bg from "/images/hero-image.png"; import Loader from "./components/Loader"; import axios from "axios"; import { useSelector, useDispatch } from "react-redux"; import { dataFetchFailure, dataFetchStart, dataFetchSuccess, } from "./userSlice/dataFetchSlice"; const Artists = () => { const { loading } = useSelector((state) => state.dataFetch); const dispatch = useDispatch(); useEffect(() => { const getData = async () => { dispatch(dataFetchStart()); console.log('team fetch start') try { const res = await axios.get( "https://render-2pmo.onrender.com/api/artist" ); dispatch(dataFetchSuccess()); console.log('team fetch success') } catch (error) { dispatch(dataFetchFailure("Cannot get data")); console.log('team fetch fail') } }; getData(); }, []); return ( <> {loading ? <Loader />:( <main className=""> <section style={{ backgroundImage: `url(${bg})`, }} className={`relative h-[40vh] object-cover bg-center bg-cover z-20 `} > <div className="overlay absolute top-0 right-0 z-30 bg-black opacity-40 w-full h-full"></div> <div className="relative z-40 grid place-items-center h-full"> <div className=""> <h1>Contact Us</h1> <p className="text-center">Home/ Team</p> </div> </div> </section> <Team /> <Whyus /> </main> )} </> ); }; export default Artists;
<div class="outer-div"> <div class="inner-div"> <h4>User Registration Form</h4> </div> <form id="user-form" [formGroup]="userForm" (ngSubmit)="onSubmit()" novalidate> <table> <tbody> <tr> <td class="expand-col"> First Name </td> <td> <input formControlName="firstName" placeholder="First Name" class="form-control" /> </td> </tr> <tr> <td> Last Name </td> <td> <input formControlName="lastName" placeholder="Last Name" class="form-control" /> </td> </tr> <tr> <td> SSO ID </td> <td> <input formControlName="ssoId" placeholder="SSO ID" class="form-control" /> </td> </tr> <tr> <td> Email </td> <td> <input formControlName="email" placeholder="Email" class="form-control" /> </td> </tr> <tr> <td></td> <td> <button type="button" class="cancel" (click)="onCancel()">CANCEL</button><button type=submit class="add" [disabled]="!userForm.valid">REGISTER</button> </td> </tr> </tbody> </table> </form> <div *ngIf="msg"> <div class="alert alert-success" role="alert"> {{msg}} </div> <span> <a routerLink="/add-doc" [queryParams]="{id: id}">Click here to manage/upload your documents</a> <span style="float:right"> Go To &nbsp;<a routerLink="/list-users">Users List</a></span> </span> </div> <div class="alert alert-danger" role="alert" *ngIf="error"> {{error}} </div> </div>
import { ElementRef, Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { distinctUntilChanged, map, mergeMap } from 'rxjs/operators'; /** * Wrapper for intersection observer. * Minor adaptions made to Piotr Sobuś @ https://stackoverflow.com/a/67273415/7396007 */ @Injectable({ providedIn: 'root', }) export class IntersectionObserverService { /** * Create interception observer and observe it. * @param { ElementRef } element - element to observe * @returns { Observable<boolean> } true when element is visible, else false. */ public createAndObserve(element: ElementRef): Observable<boolean> { return new Observable(observer => { const intersectionObserver = new IntersectionObserver(entries => { observer.next(entries); }); intersectionObserver.observe(element.nativeElement); return () => { intersectionObserver.disconnect(); }; }).pipe( mergeMap((entries: IntersectionObserverEntry[]) => entries), map((entry: IntersectionObserverEntry) => entry.isIntersecting), distinctUntilChanged() ); } }
![title_image.png](https://upload-images.jianshu.io/upload_images/9487547-307a9d5bbbb2e523.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) 开发过程中总是会遇到一些繁琐且枯燥的机械式代码(俗称:拧螺丝)。比如在布局时声明完控件属性,需要一个个属性的去生成懒加载方法,并在懒加载中设置控件的属性;比如接口返回JSON数据,需要先将JSON转成Model对象,就需要根据JSON中的字段,一个个声明成对应的属性。那有什么办法可以更加快捷完成这些拧螺丝的部分吗?答案是肯定的,用电动螺丝刀就好了。本文将提供"电动螺丝刀"插件,高效完成懒加载生成与JSON转Model。 ## 一、快速声明属性 属性结构如下,每次声明一个属性,每次都需要重复输入声明、修饰符、类型和变量名。其实除了类型和变量名,其他结构基本一致,这种情况其实完全可以将重复的部分生成代码块,这样就可以通过极短的输入提示出完整的属性声明。 ![1.gif](https://upload-images.jianshu.io/upload_images/9487547-5f2b52708187cea6.gif?imageMogr2/auto-orient/strip) 常规输入,虽然IDE也会有自动提示,不过还是不够快。 ![2.gif](https://upload-images.jianshu.io/upload_images/9487547-b6c5bcaaa179ab82.gif?imageMogr2/auto-orient/strip) 代码块输入,只需要输入代码块对应的关键字,就会直接提示整个代码块。直接tab选中占位符即可直接输入类型和变量名。 ## 二、代码块创建 1. 选中代码块,右键,再选择项中点击Create Code Snippet。 ![image.png](https://upload-images.jianshu.io/upload_images/9487547-66397f1e489ca18e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) 2. 输入代码块名称和关键字(根据个人喜好编辑即可)。编辑代码块,将类型和变量名修改为占位形式,这样可以直接tab选中占位并直接输入。 ![image.png](https://upload-images.jianshu.io/upload_images/9487547-993493947e535f89.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) 3. 测试。输入pstrong,即可提示出刚刚创建的代码块了。 ![image.png](https://upload-images.jianshu.io/upload_images/9487547-88278e67208a7627.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) ## 三、批量生成懒加载 点击工具栏 Editor -> ESExtension -> Generator Property Getter 或快捷键 ^ + G 生成属性懒加载。 效果: ![3.gif](https://upload-images.jianshu.io/upload_images/9487547-7fc90a6abba4959b.gif?imageMogr2/auto-orient/strip) ## 四、JSON转OC Model 效果: ![4.gif](https://upload-images.jianshu.io/upload_images/9487547-48a935b4d6410863.gif?imageMogr2/auto-orient/strip) 示例 1. 将如下JSON复制到Xcode中,点击工具栏 Editor -> ESExtension -> JSON To OC Model ```json { "name":"Xiao Wang", "email":"xiaowang@example.com", "father":{ "name":"Lao Wang", "email":"laowang@example.com" }, "friends":[ { "name":"Zhang San", "email":"zhangsan@example.com" }, { "name":"Li Si", "email":"lisi@example.com" } ] } ``` 2. 此时会在直接将以上JSON转成如下Model。 ```objectivec @class HMFriendsModel; @class HMFatherModel; @interface XiaoWang : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, strong) NSArray<HMFriendsModel > friends; @property (nonatomic, strong) HMFatherModel *father; @property (nonatomic, copy) NSString *email; @end @interface HMFriendsModel : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *email; @end @interface HMFatherModel : NSObject @property (nonatomic, copy) NSString *email; @property (nonatomic, copy) NSString *name; @end @implementation XiaoWang - (NSDictionary *)modelContainerPropertyGenericClass { return @{ @"friends" : [HMFriendsModel class] }; } @end @implementation HMFriendsModel @end @implementation HMFatherModel @end ``` 3. 以上JSON转Model乍一看貌似感觉挺好。直接就全部生成了,并且引用关系也建立了,但是仔细一想,这貌似不是想要的效果。这里边的Model,不管是xiaowang还是laowang都应该是同一个Person对象才是。所以我们期望生成的Model应该是下面这样的: ```objectivec @interface HMPersonModel : NSObject @property (nonatomic, strong) NSArray<HMPersonModel > friends; @property (nonatomic, strong) HMPersonModel *father; @property (nonatomic, copy) NSString *email; @property (nonatomic, copy) NSString *name; @end @implementation HMPersonModel - (NSDictionary *)modelContainerPropertyGenericClass { return @{ @"friends" : [HMPersonModel class] }; } @end ``` 这时,我们只需要在转成Model之前简单修改一下JSON,添加一些特殊标志。 ```json { "$class":"HMPersonModel", "name":"Xiao Wang", "email":"xiaowang@example.com", "father":"$HMPersonModel", "friends":"$[]HMPersonModel" } ``` > 说明:"$prefix"自定义前缀,默认前缀"HM";"$class"用来自定义当前类名;可以通过"$<自定义类名>"来自定义属性对象类名,或通过"$[]<自定义类名>"自定义数组对象类名。如以上示例的"$HMPersonModel"和"$[]HMPersonModel"。 > 由于Xcode Extension只能获取和编辑当前文件的内容,所以如果是在.h文件中JSON转Model,需要将生成的@implementation部分手动拷贝到.m文件中。 ## 五、插件 插件下载: https://github.com/devhusky/ElectricScrewdriver 插件设置,授权扩展权限 ![扩展设置_1.png](https://upload-images.jianshu.io/upload_images/9487547-ae5f9166faadb5ab.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) ![扩展开启_2.png](https://upload-images.jianshu.io/upload_images/9487547-b9cfce641e78fdc7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) ![扩展开启_3.png](https://upload-images.jianshu.io/upload_images/9487547-9e97025d54ce4c13.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) 设置快捷键 点击工具栏 Xcode -> Perferences -> Key Bindings -> 搜索 ESExtension -> 点击key输入框编辑快捷键 ![image.png](https://upload-images.jianshu.io/upload_images/9487547-2bc350030ca72e8b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/800) Tips: 如果Key Bindings 无法编辑,切换到系统英文输入法,再进行编辑。
<template> <div class="content"> <div class="row"> <div class="col-sm-12"> <h4 class="page-title">Order</h4> </div> </div> <div class="row"> <div class="col-sm-12"> <div class="card-box"> <div class="card-block"> <h6 class="card-title text-bold">All Order</h6> <div style="margin-bottom: 10px"> <input type="text" v-model="searchTerm" class="form-control" style="width: 300px" placeholder="Search Name Here" /> </div> <div class="table-responsive"> <table class="table table-bordered table-striped table-hover table-sm" > <thead> <tr> <th>Name</th> <th>Total Amount</th> <th>Pay</th> <th>Due</th> <th>Payment Method</th> <th>Action</th> </tr> </thead> <tbody> <tr v-for="order in filterSearch" :key="order.id" > <td>{{ order.name }}</td> <td>{{ order.total }} $</td> <td>{{ order.pay }} $</td> <td>{{ order.due }} $</td> <td>{{ order.payment_method }}</td> <td> <router-link :to="{ name: 'view-order', params: { id: order.id }, }" class="btn btn-sm btn-primary" > View </router-link> </td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> </template> <script> export default { data() { return { orders: [], searchTerm: "", }; }, mounted() { if (!User.isLoggedIn()) { this.$router.push("/"); } this.allOrder(); }, computed: { filterSearch() { return this.orders.filter((order) => { return order.name.match(this.searchTerm); }); }, }, methods: { allOrder() { axios .get("/api/auth/orders") .then(({ data }) => (this.orders = data)) .catch(); }, }, }; </script>
const Video = require('../model/Video'); const mongoose = require('mongoose'); const asyncHandler = require('express-async-handler'); const { constants } = require('../constants'); const fs = require('fs'); const getAllVideos = asyncHandler(async (req, res) => { try { const videos = await Video.find(); console.log(videos) const videosWithLinks = videos.map((video) => { return { ...video.toObject(), thumbnailFilename: video.thumbnail ? `/uploads/${video.thumbnail}` : null, }; }); console.log(videosWithLinks) res.json(videosWithLinks); console.log("all video fetched"); } catch (error) { res.status(500).json({ message: error.message }); } }); const addVideo = asyncHandler(async (req, res) => { const { title, description, link } = req.body; // Validate required fields if (!title || !description || !link) { return res.status(400).json({ message: 'Title, description, and link are required fields.' }); } let thumbnail = null; // Handle file upload if a file is provided in the request if (req.file) { const imagePath = `uploads/${Date.now()}_${req.file.originalname}`; await fs.promises.writeFile(imagePath, req.file.buffer); thumbnail = imagePath; } console.log(thumbnail) const video = new Video({ title, description, thumbnail, link, }); try { const newVideo = await video.save(); res.status(201).json(newVideo); } catch (error) { res.status(400).json({ message: error.message }); } }); module.exports = { getAllVideos, addVideo };
// ==UserScript== // @name 2022 11 | Huckberry / CDP+P // @namespace SitecoreCDP_DemoScript_Huckberry // @version 1.0 // @description https://sitecore.lightning.force.com/lightning/r/Opportunity/0063m00000qRnFQAA0/view // @author Marcus Conway // @match https://*.huckberry.com/* // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== // ==/UserScript== (function() { 'use strict'; /* Notes: This script is meant to work with Chris Castle's slide out menus. These menus should be loaded into the tenant as Web Experiences. The github repo for the menus is at: https://github.com/Chris-Castle/Sitecore-CDP-Scripts/tree/master/Experiences/Web To customize this script for each unique demo's needs: 1. Set the ==UserScript== settings for TamperMonkey in the header block above 2. Complete the SETTINGS block immediately below this notes block - Set which of the tenant object blocks to map into the Boxever settings. - Set the appropriate cookie domain, POS, currency, and language for your demo. 3. Configure which Events you want enabled by setting each to true/false in the ENABLE EVENTS block below This script came from a github repo at: https://github.com/linoscore/standardTamperMonkey/blob/main/tampermonkey.js */ /** **************** SETTINGS ************** ***/ const tenant = "SC_SalesEngr1USA"; // pick a tenant from the list in (tenant) below const cookie_domain = "*.huckberry.com"; // your demo website TLD const pos = "StandardDemo"; // set to your POS, usually 'StandardDemo' const currency = "USD"; // set to USD or EUR const language = "EN"; // leave as EN unless you have a specific use case const vendor = "Sitecore"; // set to Sitecore or Acxiom /***********************************************/ //Sitecore CDP Settings const SITECORECDP_POINT_OF_SALE = pos; const SITECORECDP_CURRENCY = currency; const SITECORECDP_COOKIEDOMAIN = cookie_domain; const SITECORECDP_LANGUAGE = language; //const SITECORECDP_API_TARGET_APAC = "https://api-ap-southeast-2-production.boxever.com/v1.2"; const SITECORECDP_API_TARGET_EMEA = "https://api.boxever.com/v1.2"; const SITECORECDP_API_TARGET_US = "https://api-us.boxever.com/v1.2"; const SITECORECDP_WEB_FLOW_TARGET = "https://d35vb5cccm4xzp.cloudfront.net"; const SITECORECDP_JS_LIB_SRC = "https://d1mj578wat5n4o.cloudfront.net/boxever-1.4.8.min.js"; const SITECORECDP_REST_BASIC_AUTH = "Basic ..."; // Set only if needed for Interactive API functions const SITECORECDP_PAGE = unsafeWindow.location.pathname + unsafeWindow.location.search; let SC_CDP_Settings = { point_of_sale: SITECORECDP_POINT_OF_SALE, currency: SITECORECDP_CURRENCY, cookie_domain: SITECORECDP_COOKIEDOMAIN, language: SITECORECDP_LANGUAGE, rest_api_basic_auth: SITECORECDP_REST_BASIC_AUTH, api_target: SITECORECDP_API_TARGET_EMEA, web_flow_target: SITECORECDP_WEB_FLOW_TARGET, js_lib_src: SITECORECDP_JS_LIB_SRC, page: SITECORECDP_PAGE, idProvider: "SITECORE_ID" } //Acxiom CDP Settings const ACXIOMCDP_POINT_OF_SALE = pos; const ACXIOMCDP_CURRENCY = currency; const ACXIOMCDP_COOKIEDOMAIN = cookie_domain; const ACXIOMCDP_LANGUAGE = language; const ACXIOMCDP_API_TARGET = "https://us-east-1a-api-decisioning.myacxiom.com/v1.2"; const ACXIOMCDP_WEB_FLOW_TARGET = "https://dtt5ihfhc3f13.cloudfront.net"; const ACXIOMCDP_JS_LIB_SRC = "https://d1mj578wat5n4o.cloudfront.net/boxever-1.4.8.min.js"; const ACXIOMCDP_REST_API_BASIC_AUTH = "Basic..." // Set only if needed for Interactive API functions let Ax_CDP_Settings = { point_of_sale: ACXIOMCDP_POINT_OF_SALE, currency: ACXIOMCDP_CURRENCY, cookie_domain: ACXIOMCDP_COOKIEDOMAIN, language: ACXIOMCDP_LANGUAGE, rest_api_basic_auth: ACXIOMCDP_REST_API_BASIC_AUTH, api_target: ACXIOMCDP_API_TARGET, web_flow_target: ACXIOMCDP_WEB_FLOW_TARGET, js_lib_src: ACXIOMCDP_JS_LIB_SRC } /***** Map Tenant Settings to CDP Settings *****/ let CDPSettings = {}; switch (vendor) { case "Sitecore": CDPSettings = Object.assign({}, SC_CDP_Settings); break; case "Acxiom": CDPSettings = Object.assign({}, Ax_CDP_Settings); break; default: break; } switch (tenant) { /* Sitecore SpinFinance - EU */ case "SC_SpinFinance": CDPSettings.client_key = "pqsFinGP4nW3iqC4JzgRMGZMgODLuDVM"; break; /* Sitecore Boxever Labs (Spinair) - EU */ case "SC_SpinAir": CDPSettings.client_key = "wjtc2eog1lvueo72kts3mn1ean0nentz"; break; /* Sitecore Partner Sandbox - EU */ case "SC_PartnerSandbox": CDPSettings.client_key = "psfu6uh05hsr9c34rptlr06dn864cqrx"; break; /* Sitecore Spin Gaming - EU */ case "SC_SpinGaming": CDPSettings.client_key = "pqsGAMEJ9jsRlJMQPTrnpk0cGxD4ab70"; break; /* Sitecore Spinach Air - EU */ case "SC_SpinachAir": CDPSettings.client_key = "pqsPERS3lw12v5a9rrHPW1c4hET73GxQ"; break; /* Sitecore SpinHome - EU */ case "SC_SpinHome": CDPSettings.client_key = "pqsHoMeZqwc3fXgLCQs1p21ImhAr6tPL"; break; /* Sitecore SpinMedia - EU */ case "SC_SpinMedia": CDPSettings.client_key = "pqsMedIa6PvIs50quSIOAPHcL0TJTQpk"; break; /* Sitecore SpinShop - EU */ case "SC_SpinShop": CDPSettings.client_key = "pqsSIOPAxhMC9zJLJSZNFURPNqALIFwd"; break; /* Sitecore Sales Engineering 2 - EU */ case "SC_SalesEngr2EU": CDPSettings.client_key = "sise2euno5hfjrh1xmt2pgt6utd2oafs"; break; /* Sitecore EMEA-Personalize - EU */ case "EMEA-Personalize": CDPSettings.client_key = ""; break; /* Sitecore Sales Engineering 1 - USA */ case "SC_SalesEngr1USA": CDPSettings.client_key = "sise1uscpabezjawzpn5z2djcai3v07u"; CDPSettings.api_target = SITECORECDP_API_TARGET_US; break; /* Sitecore Sales Engineering 2 - USA */ case "SC_SalesEngr2USA": CDPSettings.client_key = "sise2usl84d0ouwq5w7zd4wvq1wn5xkd"; CDPSettings.api_target = SITECORECDP_API_TARGET_US; break; /* Sitecore Sales Engineering 3 - USA */ case "SC_SalesEngr3USA": CDPSettings.client_key = "sise3uskv36mas604747apa9g4f4so0v"; CDPSettings.api_target = SITECORECDP_API_TARGET_US; break; /* Sitecore Sales Engineering 4 - USA */ case "SC_SalesEngr4USA": CDPSettings.client_key = "sise4uss4r4bct75biztbzjtssc2xvaf"; CDPSettings.api_target = SITECORECDP_API_TARGET_US; break; /* Sitecore Sales Engineering 5 - USA */ case "SC_SalesEngr5USA": CDPSettings.client_key = "sise5uscggg2lw1qfcrq1j2wg6pmg3wx"; CDPSettings.api_target = SITECORECDP_API_TARGET_US; break; /* Sitecore AMS-Personalize - USA */ case "AMS-Personalize": CDPSettings.client_key = "psluszgchlfrucgpq87c48sipf10n4gv"; CDPSettings.api_target = SITECORECDP_API_TARGET_US; break; /* Acxiom Demo_Prod (SpinShop) */ case "Ax_DemoProd": CDPSettings.client_key = "pqsSIOPAxhMC9zJLJSZNFURPNqALIFwd"; break; /* Acxiom SpinBank */ case "Ax_SpinBank": CDPSettings.client_key = "pqsFinGP4nW3iqC4JzgRMGZMgODLuDVM"; break; default: break; } // Don't Touch: this maps all the specific tenant settings into the object needed for // the _boxever_settings object unsafeWindow._boxever_settings = { client_key: CDPSettings.client_key, target: CDPSettings.api_target, pointOfSale: CDPSettings.point_of_sale, cookie_domain: CDPSettings.cookie_domain, web_flow_target: CDPSettings.web_flow_target, browser_id: '' }; /***** ********************** ********************** *****/ // Timestamp creator function getDate(){ // Create a date object from a date string var date = new Date().toISOString; // Return the formatted date return date; } // 3. ENABLE EVENTS // Set each of these to true/false depending on need for Events var SEND_VIEW_EVENT = true; var SEND_URLPARAMS_EVENT = false; var SEND_INTERACTIVE_TRIGGER1 = false; // Set up and Send Events loadScCdpLib(); if (SEND_VIEW_EVENT) { delayUntilBrowserIdIsAvailable(sendViewEvent); } if (SEND_URLPARAMS_EVENT){ delayUntilBrowserIdIsAvailable(sendCmpIDEvent); } if (SEND_INTERACTIVE_TRIGGER1){ delayUntilBrowserIdIsAvailable(interactiveExperienceTrigger1); } // Capture and Store URL Query Parameters var urlSearchParams = new URLSearchParams(window.location.search); CDPSettings.params = Object.fromEntries(urlSearchParams.entries()); SEND_URLPARAMS_EVENT = Object.keys(CDPSettings.params).length === 0 ? false : true; // Set up URL variables for parsing out page taxonomy terms var siteHost = unsafeWindow.location.host; var subDomain = siteHost.split('.')[0]; var pageURL = unsafeWindow.location.pathname; var pageTaxonomy = {}; var pageTopic = ''; var siteSection = ''; var prodCat = ''; // Set Site Section for View Event if (pageURL.length > 1){ siteSection = pageURL.split('/')[3]; } else { siteSection = 'default'; } //console.log('Sitecore CDP Tampermonkey script - siteSection: ' + siteSection); // Set Page Topic for View Event if (subDomain === 'www'){ pageTopic = pageURL.split('/')[4]; } // Set Product Category for View Event if (subDomain === 'www'){ prodCat = pageURL.split('/')[5]; } // Set Page Taxonomy for the View Event pageTaxonomy = { subDomain: subDomain, //www siteSection: siteSection, //clothing pageTopic: pageTopic, //women prodCat: prodCat, //shorts arbitraryFlag: '' }; console.log('Sitecore CDP Tampermonkey script - Page Taxonomy: ' + pageTaxonomy.subDomain + ' | ' + pageTaxonomy.siteSection + ' | ' + pageTaxonomy.pageTopic + ' | ' + pageTaxonomy.prodCat); CDPSettings.pageTaxonomy = pageTaxonomy; function loadScCdpLib(callback) { console.log('Sitecore CDP Tampermonkey script - loadScCdpLib'); var scriptElement = document.createElement('script'); scriptElement.type = 'text/javascript'; scriptElement.src = CDPSettings.js_lib_src; scriptElement.async = false; document.head.appendChild(scriptElement); } // Standard View Event function sendViewEvent() { CDPSettings.browser_id = Boxever.getID(); var pageTaxonomy = CDPSettings.pageTaxonomy; console.log('Sitecore CDP Tampermonkey script - Browser ID: ' + CDPSettings.browser_id); console.log('Sitecore CDP Tampermonkey script - sendViewEvent BEFORE'); var viewEvent = { "browser_id": CDPSettings.browser_id, "channel": "WEB", "type": "VIEW", "language": CDPSettings.language, "currency": CDPSettings.currency, "page": unsafeWindow.location.pathname + unsafeWindow.location.search, "pos": CDPSettings.point_of_sale, "session_data": { pageTaxonomy, "uri": unsafeWindow.location.pathname //"LO_Key1": "first value", //"LO_Key2": "second value" } /*"arbitrary_data": { "A LO_Key1": "A first value", "A LO_Key2": "A second value" }*/ }; //viewEvent = Boxever.addUTMParams(viewEvent); Boxever.eventCreate(viewEvent, function(data) {}, 'json'); console.log('Sitecore CDP Tampermonkey script - sendViewEvent SENT'); } // Custom Event to Send URL Query Params function sendCmpIDEvent(){ var params = CDPSettings.params; var cmpIDEvent = { "browser_id": CDPSettings.browser_id, "channel": "WEB", "type": "CMPID", "language": CDPSettings.language, "currency": CDPSettings.currency, "page": unsafeWindow.location.pathname + unsafeWindow.location.search, "pos": CDPSettings.point_of_sale, "session_data": { "uri": unsafeWindow.location.pathname //"LO_Key1": "first value", //"LO_Key2": "second value" }, params }; Boxever.eventCreate(cmpIDEvent, function(data) {}, 'json'); } // Standard Identity Events function sendIdentityEvent(email, username){ var identifyEvent = { "browser_id": CDPSettings.browser_id, "channel": "WEB", "type": "IDENTITY", "language": CDPSettings.language, "currency": CDPSettings.currency, "page": unsafeWindow.location.pathname + unsafeWindow.location.search, "pos": CDPSettings.point_of_sale, "email": email, "identifiers": [{ "provider": CDPSettings.idProvider, "id": username }] }; Boxever.eventCreate(identifyEvent, function(data) {}, 'json'); alert("Identification Returned: " + email); } // Delay Sending any Events until Browser ID is Available function delayUntilBrowserIdIsAvailable(functionToDelay) { if (unsafeWindow.Boxever == null || unsafeWindow.Boxever == undefined || unsafeWindow.Boxever === "undefined" || unsafeWindow.Boxever.getID() === "anonymous") { const timeToWaitInMilliseconds = 300; console.log(`Sitecore CDP Tampermonkey script - browserId is not yet available. Waiting ${timeToWaitInMilliseconds}ms before retrying.`); unsafeWindow.setTimeout(delayUntilBrowserIdIsAvailable, timeToWaitInMilliseconds, functionToDelay); } else { functionToDelay(); } } /***** ***** ***** ***** ***** *****/ /***** Demo Customizations *****/ /***** ***** ***** ***** ***** *****/ // Set up the DOM with custom HTML Attributes // // We'll use these later to help us attach our data to DOM elements // //$('#main-featured-trending > div > div.table-frame-col-30.trending').attr('sc_htmlcomponent','articleList'); // Fetch the a Custom Full Stack Experience API Response // // Must set the Full Stack Experience ID or this won't call in the data // function interactiveExperienceTrigger1(){ CDPSettings.fullStackExp1 = "feature_trending_articles"; // set the Full Stack Experience ID var callFlowsContext = { context: { "channel": "WEB", // update before using. e.g. “WEB” "language": CDPSettings.language, // update before using. e.g. “en” "currencyCode": CDPSettings.currency, // update before using. e.g. “EUR” "pointOfSale": CDPSettings.point_of_sale, // or value from your data layer "browserId": CDPSettings.browser_id, "clientKey": CDPSettings.client_key, "friendlyId": CDPSettings.fullStackExp1 } }; function sendMyCustomEvent(email){ var customEvent = { "browser_id": CDPSettings.browser_id, "channel": "WEB", "type": "LOGIN", "language": CDPSettings.language, "currency": CDPSettings.currency, "page": unsafeWindow.location.pathname + unsafeWindow.location.search, "pos": CDPSettings.point_of_sale, "email": email }; Boxever.eventCreate(customEvent, function(data) {}, 'json'); alert("Identification Returned: " + email); } Boxever.callFlows(callFlowsContext, function(response) { // use the response object CDPSettings.interactiveExpData1 = { 'feature_trending_articles': response }; }, 'json'); // Inject API Response to Trending Articles Component // function buildInjectedArticleList(){ var list = CDPSettings.interactiveExpData1.feature_trending_articles.articles; var injectedList = ''; for (let i = 0; i < list.length; i++) { list[i].articleType = 'article'; list[i].articleLink = '/global/en/pages/about-deloitte/press-releases/deloitte-ranked-consulting-service-provider-worldwide-by-revenue-according-to-gartner.html'; injectedList += '<li class="trending-item" data-promoname="' + list[i].articleTitle + '" data-promocategory="dynamic" data-promotype="standard" data-promocontenttype="' + list[i].articleType + '" id="trending-promo1" data-cq-id="ebf2c9ea">' + '<a href="' + list[i].articleLink + '" id="trending' + i + '" style="height:143.36px"' + '<h4>' + list[i].articleTitle + '</h4><h4>' + list[i].articleBlurb + '</h4><h5>' + list[i].articleType + '</h5></a></li>'; } $('div[sc_htmlcomponent="articleList"] ol.trending-list').empty().append(injectedList); } setTimeout(buildInjectedArticleList,1500); // Create a timeout to account for the race conditions of loading DOM, calling CDP, adjusting DOM } // Keystroke Triggers var evtListener = document.querySelector('body'); evtListener.addEventListener("keydown", (event) => { switch (event.which){ // Anonymous Session case 65: console.log('Keydown a'); Boxever.reset(); alert("Session Reset: Refresh the Page"); break; // Identity Events case 49: console.log('Keydown 1'); var email1 = 'travis.doe+1@gmail.com'; var username1 = 'travis doe' sendIdentityEvent(email1, username1); break; case 50: console.log('Keydown 2'); var email2 = 'lindsay.ogden+kd2@gmail.com'; sendMyCustomEvent(email2); break; default: console.log('some other key was pressed'); } }); })();
/********************************************************************* * Description : Handler class for ContentDocument Trigger to update Number_Of_Attached_Files on Education_Record__c based on deletion of its attached files * Test Class : ContentDocumentLinkTriggerHandlerTest.apxc * Author(s) : Saya Zhangabatyr - saya.zhangabatyr@teleflex.com * Date : 12/14/2023 * Work Item : W- **********************************************************************/ public class ContentDocumentTrigHandler { public static void beforeDeleteHandler(List<ContentDocument> contentDocList){ deleteFiles(contentDocList); } //deleteFiles method takes List of ContentDocuments as a param //below method grabs a Set of ContentDocument IDs in trigger.old, // then queries ContentDocumentLinks with ContentDocumentIDs matching with those in list public static void deleteFiles(List<ContentDocument> contentDocList){ Set<Id> contentDocumentIds=new Set<Id>(); for(ContentDocument contentDocument:contentDocList){ contentDocumentIds.add(contentDocument.Id); } List<ContentDocumentLink> contentDocLinks = [SELECT Id,LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIds]; Set<Id> educationRecordIds=new Set<Id>(); for(ContentDocumentLink contentDocLink:contentDocLinks){ educationRecordIds.add(contentDocLink.LinkedEntityId); } //a method is being called to update Education Records after deleting linked files to it educationRecordAttachmentDeleteUpdate(educationRecordIds); } @future public static void educationRecordAttachmentDeleteUpdate(Set<Id>educationRecordIds){ // quering for Education Records with IDs that match the LinkedEntityId from the ContentDocumentLink records in the query List<Education_Record__c> educationRecordList=[SELECT Id, (SELECT Id FROM ContentDocumentLinks) FROM Education_Record__c WHERE Id IN:educationRecordIds]; System.debug('Education Records List=> '+educationRecordList); System.debug('Education Records List Size=> '+educationRecordList.size()); for(Education_Record__c educationRecord : educationRecordList){ educationRecord.Number_Of_Attached_Files__c = educationRecord.ContentDocumentLinks.size(); } update educationRecordList; } }
import React, { useRef, useEffect } from 'react' import { MenuOutlined, ReconciliationOutlined, SearchOutlined, ShoppingCartOutlined, UserOutlined } from '@ant-design/icons' import { AutoComplete, Badge, Button, Drawer, Dropdown, Input, Menu, message } from 'antd' import Avatar from 'antd/lib/avatar/avatar' import defaultAvt from '../../assets/images/default-avt.png' import { Container } from 'reactstrap' import logo from '../../assets/images/logo.png' import { NavLink, Link } from 'react-router-dom' import { useSelector, useDispatch } from 'react-redux' import { toggleCartUi } from '../../store/cart_ui/cart_ui.action.jsx' import './header.css' const nav__links = [ { display: 'Trang chủ', path: '/home', }, { display: 'Sản phẩm', path: '/products', }, { display: 'Giỏ hàng', path: '/cart', }, { display: 'Liên hệ', path: '/contact', }, ] const Header = () => { const menuRef = useRef(null) const isAuth = useSelector((state) => state.AuthReducer.currentUser) const username = useSelector((state) => state.AuthReducer.infoUser) const img = useSelector((state) => state.AuthReducer.infoUser) const totalQuantity = useSelector((state) => state.CartReducer.totalQuantity) const dispatch = useDispatch() const toggleMenu = () => menuRef.current.classList.toggle('show__menu') const toggleCart = () => { dispatch(toggleCartUi(true)) } return ( <header className="header header__shrink"> <Container> <div className="nav__wrapper d-flex align-items-center justify-content-between"> <Link to={'/'} className="logo"> <img src={logo} alt="logo" /> {/* <h5>Tasty Treat</h5> */} </Link> {/* ======= menu ======= */} <div className="navigation" ref={menuRef} onClick={toggleMenu}> <div className="menu d-flex align-items-center gap-5"> {nav__links.map((item, index) => ( <NavLink to={item.path} key={index} className={(navClass) => (navClass.isActive ? 'active__menu' : '')}> {item.display} </NavLink> ))} </div> </div> {/* ======== nav right icons ========= */} <div className="nav__right text d-flex align-items-center gap-4"> <span className="cart__icon" onClick={toggleCart}> {/* <i class="ri-shopping-basket-line"></i> */} <i class="ri-shopping-cart-2-line"></i> <span className="cart__badge">{totalQuantity}</span> <span className="title">Giỏ hàng</span> </span> <Link to={isAuth ? '/account' : '/login'}> {!isAuth ? ( <div className="d-flex flex-column navbar-tool-item p-l-0"> {/* <UserOutlined className="icon m-r-12" /> */} <Avatar src={defaultAvt} className="" /> <span className="title">Đăng nhập</span> </div> ) : ( <div className="d-flex flex-column navbar-tool-item p-l-0"> <Avatar src={img} size={20} className="" /> <span className="title">{username}</span> </div> )} </Link> {/* mobile menu */} <span className="mobile__menu" onClick={toggleMenu}> <i class="ri-menu-line"></i> </span> </div> </div> </Container> </header> ) } export default Header
#!/usr/bin/env bash sic_store=${SIC_FILE:=~/.sic} gpg_recipient="${SIC_KEYID:=}" gpg_command=${SIC_GPG:="$(command -v gpg2 || command -v gpg)"} copy_command=${SIC_COPY:=xclip -sel clip} _list () { read_password_entries printf "%-50s\t%-50s\n" 'KEY' 'VALUE' while read -r line; do [ -z "$line" ] && continue local key_val=(${line//:[[:space:]]/ }) printf "%-50s\t%-50s\n" "${key_val[0]}" "${key_val[*]:1}" done <<< "$password_entries" } _get () { read_password_entries local key="${1}" if ! sic_key_exists; then fail "Key does not exist" fi local entry=$(grep "^$key:[[:space:]]" <(echo "$password_entries")) local key_val=(${entry//:[[:space:]]/ }) if [ -z "$2" ]; then echo ${key_val[*]:1} else echo ${key_val[*]:1} | $copy_command fi } _add () { read_password_entries local key="${1}" local value="${2}" if sic_key_exists; then fail "Key already exists" fi local NEWLINE=$'\n' local password_entries="${password_entries}${NEWLINE}${key}: ${value}" write_password_entries "$password_entries" } _edit () { read_password_entries local key="${1}" local value="${2}" local key_val="$key: $value" if ! sic_key_exists; then fail "Key does not exist" fi local password_entries=$(echo "$password_entries" | sed -e "s/^$key: \S*/$key_val/") write_password_entries "$password_entries" } _remove () { read_password_entries local key="${1}" if ! sic_key_exists; then fail "Key does not exist" fi local password_entries=$(echo "$password_entries" | grep -v "^$key:[[:space:]]") write_password_entries "$password_entries" } _help () { cat << EOF NAME: sic - A Command Line Password Manager Backed By GPG's Asymmetric Encryption USAGE: $(basename "$0") [options...] command [arguments...] [command options] COMMANDS list, ls List all entries in the password store get, g <key> Get the value of a password entry. Pass the optional "-c" argument to copy the password to the clipboard add, a <key> <value> Add a password entry to the password store. To prevent shell expansion, wrap the argument in single quotes edit, e <key> <value> Edit an existing entry remove, rm <key> Remove an existing entry help, h Show this message OPTIONS -f File to store passwords or set \$SIC_FILE. Defaults to "~/.sic" -k GPG keyid used for encryption & decryption or set \$SIC_KEYID. Defaults to GPG's option "--default-key" -g GPG used command or set \$SIC_GPG. Defaults to "gpg2" then "gpg" if it was not found -y Copying/yanking command or set \$SIC_COPY. Defaults to "xclip -sel clip" EOF exit 1 } read_password_entries () { [[ $(gpg --list-keys) ]] || fail "No GPG keys found" prompt_for_passphrase [[ -s $sic_store ]] && check_passphrase password_entries=$(decrypt "${passphrase}" | sort) } write_password_entries () { echo "$password_entries" | encrypt $passphrase - } prompt_for_passphrase () { local passphrase_for=${gpg_recipient:-"default key"} read -p "Enter GPG Passphrase for ($passphrase_for): " -s passphrase; echo -e '\n' } check_passphrase () { decrypt "${passphrase}" >/dev/null || fail "Incorrect Passphrase" } sic_key_exists () { grep -q "^$key:[[:space:]]" <(echo "$password_entries") } decrypt () { echo "${1}" | ${gpg_command} \ --decrypt \ --armor --batch --no-tty --quiet \ --passphrase-fd 0 \ "${sic_store}" 2>/dev/null } encrypt () { recipient_option="--recipient=$gpg_recipient" local_user_option="--local-user=$gpg_recipient" if [[ "$gpg_recipient" == "" ]]; then recipient_option="--default-recipient-self" local_user_option="" fi ${gpg_command} \ --encrypt \ $recipient_option \ $local_user_option \ --sign \ --armor --batch --no-tty --yes \ --passphrase-fd 3 \ --output "$sic_store" "${2}" 3< <(echo "${1}") 2>/dev/null } fail () { echo "Error: ${1}"; exit 1 } while getopts ':f:k:g:y:' opt; do case $opt in f) sic_store="$OPTARG" ;; k) gpg_recipient="$OPTARG" ;; g) gpg_command="$OPTARG" ;; y) copy_command="$OPTARG" ;; esac done shift "$((OPTIND-1))" if [[ $# == 0 ]]; then _help else case "$1" in list|ls) if [[ "$#" -ne 1 ]]; then _help fi _list ;; get|g) if [ \( "$#" -eq 3 -a "$3" == '-c' \) -o "$#" -eq 2 ]; then _get "$2" "$3" else _help fi ;; add|a) if [[ "$#" -ne 3 ]]; then _help fi _add "$2" "$3" ;; edit|e) if [[ "$#" -ne 3 ]]; then _help fi _edit "$2" "$3" ;; remove|rm) if [[ "$#" -ne 2 ]]; then _help fi _remove "$2" ;; help|h) _help ;; *) _help esac fi
SELECT * FROM actor SELECT * FROM address SELECT * FROM category SELECT * FROM city SELECT * FROM country SELECT * FROM customer SELECT * FROM film SELECT * FROM film_actor SELECT * FROM film_category SELECT * FROM inventory SELECT * FROM language SELECT * FROM payment SELECT * FROM rental SELECT * FROM staff SELECT * FROM store -- 1. List all customers who live in Texas (use JOINs) SELECT customer.first_name, customer.last_name, address.district FROM customer JOIN address ON customer.address_id = address.address_id WHERE address.district = 'Texas'; -- 2. Get all payments above $6.99 with the Customer's Full Name SELECT customer.first_name, customer.last_name, payment.amount FROM customer JOIN payment ON customer.customer_id = payment.customer_id WHERE payment.amount > 6.99; -- 3. Show all customers names who have made payments over $175(use subqueries) SELECT customer.first_name, customer.last_name FROM customer WHERE customer.customer_id IN( SELECT payment.customer_id FROM payment WHERE payment.amount > 175 ); -- 4. List all customers that live in Nepal (use the city table) SELECT customer.first_name, customer.last_name FROM customer JOIN address ON customer.address_id = address.address_id JOIN city ON address.city_id = city.city_id WHERE city.city = 'Nepal'; -- 5. Which staff member had the most transactions? SELECT staff.first_name, staff.last_name FROM staff JOIN payment ON staff.staff_id = payment.staff_id GROUP BY staff.first_name, staff.last_name ORDER BY COUNT(payment.payment_id) DESC LIMIT 1; -- 6. What film had the most actors in it? SELECT film.title, COUNT(film_actor.actor_id) AS most_actors_count FROM film JOIN film_actor ON film.film_id = film_actor.film_id GROUP BY film.title ORDER BY Most_actors_count DESC LIMIT 1; -- 7. Show all customers who have made a single payment above $6.99 (Use Subqueries) SELECT customer.first_name, customer.last_name FROM customer WHERE customer.customer_id IN( SELECT payment.customer_id FROM payment WHERE payment.amount > 6.99 GROUP BY payment.customer_id HAVING COUNT(*) = 1 ); -- 8. Which category is most prevalent in the films? SELECT category.name, COUNT(*) FROM Film_category JOIN category ON film_category.category_id = category.category_id GROUP BY category.name ORDER BY COUNT(*) DESC LIMIT 1;
@extends('admin.layouts.master') @section('title','Events') @section('content') <div class="content-i"> <div class="content-box"> <div class="element-wrapper"> <h6 class="element-header"> Events <a class="btn btn-success btn-sm float-right mr-2" href="{{route('events.create')}}">Add New</a> </h6> <div class="element-box"> <div class="table-responsive"> <table width="100%" class="table table-bordered table-striped table-lightfont"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Sub Title</th> <th>Location</th> <th>Image</th> <th class="text-center">Action</th> </tr> </thead> <tbody> @foreach($events as $key=>$item) <tr> <td>{{$key + 1}}</td> <td>{{$item->title}}</td> <td>{{$item->sub_title}}</td> <td>{{$item->location}}</td> <td style="width:100px;"><img class="img-thumbnail" src="{{ asset('uploads/events/'.$item->image) }}" alt=""></td> <td class="text-center"> <a class="btn btn-success btn-sm" href="{{route('events.edit',$item->id)}}" title="edit"><i class="fa fa-edit"></i></a> <form id="delete-form-{{ $item->id }}" action="{{ route('events.destroy',$item->id) }}" style="display: none;" method="POST"> @csrf @method('DELETE') </form> <button type="button" title="Delete" class="btn btn-danger btn-sm mt-2" onclick="if(confirm('Are you sure? You want to delete this?')){ event.preventDefault(); document.getElementById('delete-form-{{ $item->id }}').submit(); }else { event.preventDefault(); }"><i class="fa fa-trash"></i> </button> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> @endsection
"use client"; import { useEffect, useState } from "react"; import { HomeSection } from "./components"; import Cookies from 'js-cookie' import Axios from './Helpers/Axios' import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton, useDisclosure, useToast, FormControl, FormLabel, Input, Button, Box, Flex, Avatar, Text, } from '@chakra-ui/react' export default function HomePage() { const sponsorModal = useDisclosure() const [sponsor, setSponsor] = useState(null) const [username, setUsername] = useState(null) const toast = useToast() useEffect(() => { const sponsorUsername = Cookies.get('sponsor') console.log('sponsorUsername', sponsorUsername) if (!sponsorUsername) { sponsorModal.onOpen() } else { console.log('sponsor', sponsor) if (!sponsor) { verifySponsor(sponsorUsername) } } }, []) const handleVerify = async () => { if (!username) { return alert('Please enter a username') } await verifySponsor(username) } const verifySponsor = async (sponsorUsername) => { const res = await Axios.get(`/sponsor/validate/${sponsorUsername}`) if (!res?.data?.ok) { return toast({ title: 'Sponsor verification failed', description: "", status: 'error', duration: 9000, isClosable: true, }) } else { Cookies.set('sponsor', res?.data?.user?.username) setSponsor(res?.data?.user) toast({ title: 'Sponsor verified', description: "", status: 'success', duration: 9000, isClosable: true, }) sponsorModal.onClose() // setTimeout(() => { // window.location.href = `/` // }, 500) } } return ( <> <HomeSection.Navbar /> <HomeSection.Hero /> <HomeSection.QuoteSection /> <HomeSection.ButtonImgSection onOpen={sponsorModal.onOpen} /> <HomeSection.HandSection /> <HomeSection.Challange /> <HomeSection.AgingSection /> <HomeSection.Information /> <HomeSection.Benefits /> {/* <HomeSection.Suger /> */} <Box mt={16} bgImage={`url(/assets/bottom_image.png)`} w="full" h={{ base: "240px", md: "220px", }} mb="20" bgPos={{ base: "-280px", md: "center", }} mx="auto" maxW={{ base: "full", md: "1135px", }} bgSize={{ base: "cover", md: "contain", }} ></Box> <HomeSection.Footer /> <Modal isOpen={sponsorModal.isOpen} onClose={sponsorModal.onClose}> <ModalOverlay /> <ModalContent> <ModalHeader borderBottom={'1px'} borderColor='gray.300'> Who referred you? </ModalHeader> {/* <ModalCloseButton /> */} <ModalBody> <FormControl isRequired> <FormLabel>Sponsor username</FormLabel> <Input value={username} onChange={e => setUsername(e.target.value)} placeholder='Enter sponsor id' /> </FormControl> </ModalBody> <ModalFooter borderTop={'1px'} borderColor='gray.300' as={'sponsor'}> <Button onClick={handleVerify} colorScheme='blue'>Submit</Button> </ModalFooter> </ModalContent> </Modal> {sponsor && <Box as='section' position={'fixed'} zIndex='9999' bottom='12px' left='12px' bg='white' shadow={'md'} px='3' py={1} rounded='full'> <Flex gap={2} alignItems='center'> <Avatar size='sm' src={sponsor?.avatar} /> <Box lineHeight={1}> <Text mb={0} lineHeight={1} fontSize={'9px'} color='gray.500'>Referred by</Text> <Text as={'span'} fontSize={'14px'}>{sponsor.full_name}</Text> </Box> </Flex> </Box>} </> ); }
import React, { DOMAttributes, EventHandler, SyntheticEvent } from "react"; type StopPropagation_Props_t = { readonly events?: ReadonlyArray<EventNames> | EventNames, readonly children: React.ReactElement<EventDOMAttributes>, }; type EventHandlerPropertyNames<T> = { [K in keyof T]: T[K] extends EventHandler<any> ? K : never }[keyof T]; type AllDOMAttributes = Required<DOMAttributes<HTMLElement>>; type EventDOMAttributes = { [k in EventHandlerPropertyNames<AllDOMAttributes>]: AllDOMAttributes[k] }; type EventNames = keyof EventDOMAttributes; const eventNames: ReadonlyArray<EventNames> = [ // Mouse events "onClick", "onContextMenu", "onDoubleClick", "onDrag", "onDragEnd", "onDragEnter", "onDragExit", "onDragLeave", "onDragOver", "onDragStart", "onDrop", "onMouseDown", "onMouseEnter", "onMouseLeave", "onMouseMove", "onMouseOut", "onMouseOver", "onMouseUp", // Keyboard events "onKeyDown", "onKeyPress", "onKeyUp", ]; const defaultHandler: EventHandler<SyntheticEvent> = (ev) => ev.stopPropagation(); function createDefaultHandlers(events: ReadonlyArray<EventNames>) { const handlers: Partial<EventDOMAttributes> = {}; for (const eventName of events) { handlers[eventName] = defaultHandler; } return handlers; } function containsCustomHandler(obj: object, events: ReadonlyArray<EventNames>) { for (const objKey of Object.keys(obj)) { if (events.indexOf(objKey as any) !== -1) { return true; } } return false; } function createCustomHandlers(obj: object, events: ReadonlyArray<EventNames>) { const customHandlers: Partial<EventDOMAttributes> = {}; for (const objKey of Object.keys(obj)) { if (obj[objKey] instanceof Function && events.indexOf(objKey as any) !== -1) { customHandlers[objKey as any] = (ev: SyntheticEvent) => { obj[objKey](ev); defaultHandler(ev); }; } } return customHandlers; } /** * Stops event propagation to the parents. * * This is useful when, for example, embedding clickable elements inside other clickable elements, * without having to call stopPropagation() on every click event you can imagine. * * This component only accepts one child element, and requires it to have *ALL* HTML event handlers, * so you will have to use either a HTML element as a child, or a component that passes all other props to the HTML element. */ export default function StopPropagation({ children, events = eventNames}: StopPropagation_Props_t) { const child = React.Children.only(children); const finishedEvents = Array.isArray(events) ? events : [events]; const defaultHandlers = createDefaultHandlers(finishedEvents); if (!containsCustomHandler(child.props, finishedEvents)) { return React.cloneElement(child, defaultHandlers); } else { const handlers = { ...defaultHandlers, ...createCustomHandlers(child.props, finishedEvents), }; return React.cloneElement(child, handlers); } }
/* eslint-disable @typescript-eslint/space-before-function-paren */ import '../../../../dist/output.css' import AddIconSvg from '../../../Common/Icons/AddIconSvg' import ArchiveIconSvg from '../../../Common/Icons/ArchiveIconSvg' import EditIconSvg from '../../../Common/Icons/EditIconSvg' import RemoveIconSvg from '../../../Common/Icons/RemoveIconSvg' interface BordMoreOptionProps { color: string text: string type: string onClickFunc?: () => void } function BordMoreOption({ color, text, type, onClickFunc }: BordMoreOptionProps): JSX.Element { function iconChoose(): JSX.Element | undefined { switch (type) { case 'edit': return <EditIconSvg /> case 'add': return <AddIconSvg /> case 'archive': return <ArchiveIconSvg /> case 'remove': return <RemoveIconSvg /> } } return ( <button className="flex w-[142px] items-center gap-2"> {iconChoose()} <span className={` text-[14px] font-normal ${color} leading-[19.73px]`}> <div onClick={onClickFunc}> {text}</div> </span> </button> ) } export default BordMoreOption
export const calculateHandTotal = hand => { let ace let value = hand.reduce((sum, current) => { ace |= current.value === 1 sum += current.value return sum }, 0) if (ace && value + 10 <= 21) { value += 10 } return value } export const shuffleAndDeal = (deck) => { let uGameDeck = [...deck] let uPlayerHand = [] let uDealerHand = [] // Shuffle the deck for (let i = 0; i < uGameDeck.length - 1; i++) { let j = i + Math.floor(Math.random() * (uGameDeck.length - i)) let temp = uGameDeck[j] uGameDeck[j] = uGameDeck[i] uGameDeck[i] = temp } // Add the first card to player's hand and then remove it from the deck uPlayerHand.push(uGameDeck[0]) uGameDeck = [...uGameDeck.filter((card, index) => index !== 0)] // Add the second card to the dealer's hand and then remove it from the deck uDealerHand.push(uGameDeck[0]) uGameDeck = [...uGameDeck.filter((card, index) => index !== 0)] // Add the third card to player's hand and then remove it from the deck uPlayerHand.push(uGameDeck[0]) uGameDeck = [...uGameDeck.filter((card, index) => index !== 0)] // Add the fourth card to the dealer's hand and then remove it from the deck uDealerHand.push(uGameDeck[0]) uGameDeck = [...uGameDeck.filter((card, index) => index !== 0)] // Calculate the player's hand total let uPlayerHandTotal = calculateHandTotal(uPlayerHand) // Calculate the dealer's hand total let uDealerHandTotal = calculateHandTotal(uDealerHand) return { uGameDeck, uPlayerHand, uDealerHand, uPlayerHandTotal, uDealerHandTotal } } export const dealCardToPlayer = (deck, playerHand) => { let uGameDeck = [...deck] let uPlayerHand = [...playerHand] // Add the first card to player's hand uPlayerHand.push(uGameDeck[0]) // Remove the first card from the deck uGameDeck = [...uGameDeck.filter((card, index) => index !== 0)] // Calculate the player's hand total let uHandTotal = calculateHandTotal(uPlayerHand) return { uGameDeck, uPlayerHand, uHandTotal } } export const dealCardsToDealer = (deck, dealerHand) => { let uGameDeck = [...deck] let uDealerHand = [...dealerHand] let uHandTotal = calculateHandTotal(uDealerHand) let dealerHitCount = 0 // Dealer must hit until they reach 17, so keep dealing the first card // and removing it from the deck until the dealer's hand total is 17 or greater while (uHandTotal < 17) { // NOTE: This should never happen, but in order to prevent an infinite loop break out if // the dealer hits more than 10 times since this shouldn't be possible without busting if (dealerHitCount > 10) break uDealerHand.push(uGameDeck[0]) uGameDeck = [...uGameDeck.filter((card, index) => index !== 0)] uHandTotal = calculateHandTotal(uDealerHand) // Counts the number of times the dealer hits dealerHitCount++ } return { uGameDeck, uDealerHand, uHandTotal } }
FOR THE CLIENT SIDE npm i --save socket.io-client Note: • socket.on will receive the notifications data • socket.emit will trigger the notifications and pass data at the same time • socket.on is idealy put inside the "created" hook. This will initialize the use of socket.io like a setInterval import io from "socket.io-client"; data() { return { sample_data_object_her: [] } } created() { this.socket = io.connect(http://webhost:port, { secure: true}); // to connect to server this.socket.on("sample_string_matcher", sample_object_data => { // this will receive the notifs alert(sample_object_data); }); }, methods: { sample_method() { this.sample_data_object_her.push( { date: "when the was the action, done", action: "what was the action", user: "who did the action", entity: "to whom the action was made" } ); this.socket = io.connect(http://webhost:port, { secure: true}); // to connect to server this.socket.emit("sample_string_matcher", this.sample_data_object_here ); // this will trigger to send notifs // You can also add API route here to record the notification using axios } } FOR THE SERVER SIDE npm i --save socket.io Note: • This js file must be placed along with the APIs (inside the usecase folder) • ledsDb is the database name • sample_string_matcher should be used to match the sockets • you can either store the notification data in the db through here or in the client side (would need API route) const webSocket = ({ ledsDb, io }) => { return function socket(info) { io.on("connection", (socket) => { console.log("Someone has connected."); socket.on("sample_string_matcher", async (data) => { // insert to db const toInsert = { triggeredThru: `Turn on using app.`, }; await ledsDb.insertLedLogs({ toInsert }); // emit to all client that led is on; const toEmit = { value: 1, }; io.emit("sample_string_matcher", toEmit); }); }); }; }; module.exports = webSocket;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> <!-- Font Google --> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Ubuntu+Condensed&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@100&display=swap" rel="stylesheet"> <!-- Font Awesome --> <script src="https://kit.fontawesome.com/97faadae9c.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="./styles/common.css"> <link rel="stylesheet" href="./styles/nav.css"> <link rel="stylesheet" href="./styles/homepage.css"> <link rel="stylesheet" href="./styles/footer.css"> <link rel="stylesheet" href="./styles/media-queries.css"> </head> <body> <!-- Navigation wrapper --> <div class="navigation-wrapper"> <div class="left-column"> <!-- icon phone --> <div class="icon"> <i class="fa-solid fa-phone-volume"></i> </div> <!-- Hours + phone --> <div class="contact-hours-wrapper"> <!-- Hours --> <div class="phone"> 555 555 5555 </div> <!-- Phone --> <div class="hours"> 10 AM - MIDNIGHT </div> </div> </div> <div class="center-column"> <!-- image --> <div class="banner-image"> <img src="./image/logo/decamp-fantastic-fries-logo-white.png" alt="logo"> </div> <!-- Link wrapper --> <div class="links-wrapper"> <!-- nav Link --> <div class="nav-link"> <a href="index.html">Home</a> </div> <!-- nav Link --> <div class="nav-link"> <a href="about.html">About</a> </div> <!-- nav Link --> <div class="nav-link"> <a href="menu.html">Menu</a> </div> <!-- nav Link --> <div class="nav-link"> <a href="contact.html">Contact</a> </div> </div> </div> <div class="right-column"> <!-- Adress --> <div class="address-wrapper"> <a href="contact.html"> 123 Any Street<br> Scottsdale, AZ, 85251 </a> </div> <div class="contact-icon"> <a href="contact.html"> <i class="fas fa-map-marker-alt"></i> </a> </div> </div> </div> <div class="hero-section"> <div class="top-heading"> <h3>HTML Styled Fries</h3> </div> <div class="bottom-heading"> <h3>Coding fuel.</h3> </div> </div> <div class="features-section"> <div class="columns-wrapper"> <div class="column"> <!-- Icons goes here --> <i class="fas fa-truck-monster"></i> <p>We Deliver!</p> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. </p> </div> <div class="column"> <!-- Icons goes here --> <i class="fas fa-wifi"></i> <p>You can code from here!</p> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. </p> </div> <div class="column"> <!-- Icons goes here --> <i class="fas fa-chart-line"></i> <p>100+ types of friends!</p> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. </p> </div> </div> </div> <div> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3327.0765176913264!2d-111.92875828479936!3d33.49938628076005!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x872b0bbdbed13a73%3A0xfab78c0f014377d8!2sDiego+Pops!5e0!3m2!1sen!2sus!4v1534788183429" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe> </div> <div class="footer"> <div class="logo-footer"> <img src="image/logo/decamp-fantastic-fries-logo-white.png" alt="Logo"> </div> <div class="footer-phone-hours"> <span class="phone"> 555 555 5555 </span> <span class="hours"> 10 am - midnight </span> </div> <!-- Link wrapper --> <div class="links-wrapper"> <!-- nav Link --> <div class="nav-link"> <a href="index.html">Home</a> </div> <!-- nav Link --> <div class="nav-link"> <a href="about.html">About</a> </div> <!-- nav Link --> <div class="nav-link"> <a href="menu.html">Menu</a> </div> <!-- nav Link --> <div class="nav-link"> <a href="contact.html">Contact</a> </div> </div> <div class="social-media-icons-wrapper"> <a href="#"> <i class="fab fa-instagram"></i> </a> <a href="#"> <i class="fab fa-twitter"></i> </a> <a href="#"> <i class="fab fa-facebook-f"></i> </a> </div> <div class="copyright-wrapper"> &copy; 2022 María Diez &#124; All rights reserved </div> </div> </body> </html> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>건의사항 게시판</title> </head> <header> <!-- 메뉴 바 --> <jsp:include page="../menubar.jsp" flush="false" /> </header> <body style="overflow: scroll;"> <br> <p style="text-align: center"> <font size="6" color="#5bc0de">공지사항 게시판</font> <br> <div class="container"> <div class="row justify-content-center"> <table class="table table-bordered table-hover" width="500" cellpadding="0" cellspacing="0" border="1"> <tr> <td>글번호</td> <td>아이디</td> <td>제 목</td> <td>작성일</td> <td>조회수</td> </tr> <c:forEach items="${notice}" var="dto"> <tr> <td>${dto.notice_num}</td> <td>${dto.notice_id}</td> <td><a href="noticeview?num=${dto.notice_num}"> <!-- 현재 날짜 받아오기 --> <jsp:useBean id="now" class="java.util.Date" /> <!-- 날짜 형식 맞추기 --> <fmt:formatDate value="${now}" pattern="MMdd" var="todayDate" /> <fmt:formatDate value="${dto.notice_date}" pattern="MMdd" var="dtoDate" /> <!-- 날짜 형식 맞춘거 숫자형으로 변환 --> <fmt:parseNumber value="${todayDate}" type="number" var="today" /> <fmt:parseNumber value="${dtoDate}" type="number" var="uploadDate" /> <!-- 업로드 된 날짜 형식 바꿔서 테이블에 적용해주기 --> <fmt:formatDate value="${dto.notice_date}" pattern="yyyy-MM-dd" var="uploadDate2" /> <c:if test="${ 1 > today-uploadDate }"> <span id="date" class="badge badge-secondary">New</span> </c:if> ${dto.notice_title} </a></td> <td>${dto.notice_date}</td> <td>${dto.notice_hit}</td> </tr> </c:forEach> </table> </div> </div> <sec:authorize access="hasRole('ADMIN')"> <div class="container"> <div class="row justify-content-end"> <a class="btn btn-info" href="admin/writeForm">글작성</a> </div> </div> </sec:authorize> <div class="container"> <div class="row justify-content-center"> <form class="form-inline my-2 my-md-0" action="noticesearch" method="get"> <input class="form-control mr-sm-2" name="title" type="text" placeholder="제목으로 검색"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">검색</button> </form> </div> </div> <nav aria-label="..." class="row justify-content-md-center"> <ul class="pagination"> <c:choose> <c:when test="${(page.curPage -1) <1}"> <li class="page-item disabled"><span class="page-link">&lt;&lt;</span></li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="noticesearch?page=1&title=${title}">&lt;&lt;</a></li> </c:otherwise> </c:choose> <c:choose> <c:when test="${(page.curPage -1) <1}"> <li class="page-item disabled"><span class="page-link">&lt;</span></li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="noticesearch?page=${page.curPage - 1}&title=${title}">&lt;</a></li> </c:otherwise> </c:choose> <c:forEach var="fEach" begin="${page.startPage}" end="${page.endPage}" step="1"> <c:choose> <c:when test="${page.curPage == fEach}"> <li class="page-item"><a class="page-link" href="#">${fEach}</a></li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="noticesearch?page=${fEach}&title=${title}">${fEach}</a></li> </c:otherwise> </c:choose> </c:forEach> <c:choose> <c:when test="${page.curPage >= page.totalPage}"> <li class="page-item disabled"><span class="page-link">&gt;</span></li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="noticesearch?page=${page.curPage + 1}&title=${title}">&gt;</a></li> </c:otherwise> </c:choose> <c:choose> <c:when test="${page.curPage == page.totalPage}"> <li class="page-item"><a class="page-link">&gt;&gt;</a></li> </c:when> <c:otherwise> <li class="page-item"><a class="page-link" href="noticesearch?page=${page.totalPage}&title=${title}">&gt;&gt;</a></li> </c:otherwise> </c:choose> </ul> </nav> </body> <jsp:include page="../footer.jsp" flush="false" /> </html>
;******* Pep/8 Jeu de roche-papier-ciseaux, 2021/02/25 ; ; Cette classe represente un programme avec lequel deux joueurs humains ; peuvent jouer au jeu de roche-papier-ciseaux entre eux. ; Regle du jeu: Chaque joueur choisit l'un des trois objets et on determine ; qui gagne la manche en comparant leur choix. ; Roche (r) gagne contre ciseaux (c), ciseaux (c) gagne contre papier (p) et ; papier (p) gagne contre roche (r). ; ; Author: Fang, Xin Ran ; Ah-Lan, Steven Chia ; ;******* Debut du programme main: LDA 0,i STRO msgTiret,d ; Afficher message de bienvenue STRO msgWelc,d STRO msgTiret,d STRO msgLine,d STRO msgTour,d ; Demander le nombre de manches a jouer DECI nbrTour,d ; Stocker le nombre saisi par l'utilisateur dans nbrTour STRO msgLines,d LDA nbrTour,d CPA 0,i ; Comparer nbrTour avec 0, fin du programme s'il s'agit d'un nombre negatif BRLT endError ; Si nbrTour >= 0 LDA 0,i ; Reinitialiser A a 0 avant de brancher parite BR parite ; ;******* Verifier si le nombre de manches saisi par l'utilisateur est pair ou impair parite: CPA nbrTour,d BREQ pair ; Si A != nbrTour ADDA 1,i ; A = A + 1 CPA nbrTour,d BREQ impair ; Si A != nbrTour ADDA 1,i ; A = A + 1 BR parite pair: LDA nbrTour,d ADDA 1,i ; A = nbrTour + 1 STA nbrTour,d ; Stocker A dans nbrTour STA nbrLeft,d ; Stocker A dans nbrLeft BR findMin impair: STA nbrLeft,d ; Stocker A dans nbrLeft BR findMin ; ;******* Determiner le score minimal necessaire pour atteindre la victoire findMin: LDA scoreWin,d ; scoreWin est initialise a 1 ADDA scoreWin,d ; A = scoreWin + scoreWin CPA nbrTour,d BRGE tourJ1 ; Si A <= nbrTour LDA scoreWin,d ADDA 1,i ; A = scoreWin + 1 STA scoreWin,d ; Stocker A dans scoreWin BR findMin ; ;******* Jouer le jeu tourJ1: LDA 0,i LDA scoreWin,d CPA scoreJ1,d BRLE winnerJ1 ; Si scoreWin > scoreJ1, joueur 1 n'a pas encore gagne, on continue le jeu CPA scoreJ2,d BRLE winnerJ2 ; Si scoreWin > scoreJ2, joueur 2 n'a pas encore gagne, on continue le jeu STRO msgReste,d ; Afficher le nombre de manches restant DECO nbrLeft,d STRO msgTours,d STRO msgJ1,d ; Demander au joueur 1 d'entrer son choix (r, p ou c) STRO msgChoix,d CHARI choixJ1,d ; Stocker le 1er char saisi par joueur 1 dans choixJ1 CHARI charIn,d ; Stocker le 2e char saisi par joueur 1 dans charIn LDA 0,i LDBYTEA choixJ1,d ; Load choixJ1 dans A avant de brancher checkRPC BR checkRPC tourJ2: LDA 0,i STRO msgJ2,d ; Demander au joueur 2 d'entrer son choix (r, p ou c) STRO msgChoix,d CHARI choixJ2,d ; Stocker le 1er char saisi par joueur 2 dans choixJ2 CHARI charIn,d ; Stocker le 2e char saisi par joueur 2 dans charIn LDA 0,i LDBYTEA choixJ2,d ; Load choixJ2 dans A avant de brancher checkRPC BR checkRPC ; ;******* Verifier si l'entree du joueur est valide checkRPC: CPA 'r',i BREQ enterKey ; Si choixJ1 != 'r' CPA 'p',i BREQ enterKey ; Si choixJ1 != 'p' CPA 'c',i BREQ enterKey ; Si choixJ1 != 'c' BR endError ; ;******* Verifier si le 2e caractere saisi par les joueurs est bien un retour de chariot enterKey: LDA 0,i LDBYTEA charIn,d CPA '\n',i BRNE endError ; Si charIn == '\n' LDA 0,i LDA nbrPlyed,d ADDA 1,i ; A = nbrPlyed + 1 (tout est verifie pour ce joueur, on incremente nbrPlyed de 1) STA nbrPlyed,d ; Stocker A dans nbrPlyed BR count ; ;******* Verifier qui a joue count: LDA 0,i LDA nbrPlyed,d CPA 1,i ; Si nbrPlyed == 1, c'est a joueur 2 de jouer BREQ tourJ2 ; Si nbrPlyed != 1 CPA 2,i ; Si nbrPlyed == 2, toutes les entrees des deux joueurs sont validees, brancher rpcJ1 BREQ rpcJ1 ; Si nbrPlyed != 2 ; ;******* Comparer le choix des deux joueurs rpcJ1: LDA 0,i LDBYTEA choixJ1,d CPA 'r',i BREQ rocheJ1 ; Si choixJ1 != 'r' CPA 'p',i BREQ papierJ1 ; Si choixJ1 != 'p' CPA 'c',i BREQ ciseauJ1 ; Si (choixJ1 != 'r') && (choixJ1 != 'p'), il est certain que choixJ1 == 'c' rocheJ1: LDA 0,i LDBYTEA choixJ2,d CPA 'r',i BREQ nulle ; Si choixJ2 != 'r' CPA 'p',i BREQ calculJ2 ; Si choixJ2 != 'p' CPA 'c',i BREQ calculJ1 ; Si (choixJ2 != 'r') && (choixJ2 != 'p'), il est certain que choixJ2 == 'c' papierJ1: LDA 0,i LDBYTEA choixJ2,d CPA 'r',i BREQ calculJ1 CPA 'p',i BREQ nulle CPA 'c',i BREQ calculJ2 ciseauJ1: LDA 0,i LDBYTEA choixJ2,d CPA 'r',i BREQ calculJ2 CPA 'p',i BREQ calculJ1 CPA 'c',i BREQ nulle nulle: STRO msgNulle,d ; Afficher le message de manche nulle STRO msgLine,d LDA 0,i LDA nbrPlyed,d SUBA 2,i ; A = nbrPlyed - 2 (pour recommencer a compter le tour de chacun a partir de 0) STA nbrPlyed,d ; Stocker A dans nbrPlyed BR tourJ1 ; ;******* Le joueur 1 a gagne la manche calculJ1: LDA 0,i LDA scoreJ1,d ADDA 1,i ; A = ScoreJ1 + 1 STA scoreJ1,d ; Stocker A dans scoreJ1 STRO msgJ1,d ; Afficher le message pour annoncer le gagnant de la manche STRO msgWin,d DECO scoreJ1,d ; Afficher le score des deux joueurs STRO msgWin2,d LDA 0,i DECO scoreJ2,d STRO msgLines,d LDA nbrLeft,d SUBA 1,i ; A = nbrLeft - 1 (une manche completee, le nombre de manches restant diminue de 1) STA nbrLeft,d ; Stocker A dans nbrLeft LDA 0,i LDA nbrPlyed,d SUBA 2,i ; A = nbrPlyed - 2 (pour recommencer a compter le tour de chacun a partir de 0) STA nbrPlyed,d ; Stocker A dans nbrPlyed BR tourJ1 ; ;******* Le joueur 2 a gagne la manche calculJ2: LDA 0,i LDA scoreJ2,d ADDA 1,i STA scoreJ2,d STRO msgJ2,d STRO msgWin,d DECO scoreJ1,d STRO msgWin2,d LDA 0,i DECO scoreJ2,d STRO msgLines,d LDA nbrLeft,d SUBA 1,i STA nbrLeft,d LDA 0,i LDA nbrPlyed,d SUBA 2,i STA nbrPlyed,d BR tourJ1 ; ;******* Annoncer le gagnant du jeu winnerJ1: STRO msgJ1,d STRO msgCongr,d BR endWin winnerJ2: STRO msgJ2,d STRO msgCongr,d BR endWin ; ; Afficher le message d'erreur si l'entree est invalide endError: STRO msgError,d STOP ; ;******* Afficher le score final endWin: STRO msgScore,d DECO scoreJ1,d STRO msgWin2,d DECO scoreJ2,d STOP ; ;******* Variables numeriques nbrTour: .WORD 0 ; Nombre de manches entre par l'utilisateur (manches à jouer) nbrLeft: .WORD 0 ; Nombre de manches restant nbrPlyed: .WORD 0 ; Si nbrPlyed == 0, c'est a joueur 1 de jouer; Si nbrPlyed == 1, c'est a joueur 2 de jouer; Si nbrPlyed == 2, tous les deux ont joue, on peut commencer a comparer leur choix scoreWin: .WORD 1 ; Score minimal pour atteindre la victoire scoreJ1: .WORD 0 ; Score du joueur 1 scoreJ2: .WORD 0 ; Score du joueur 2 ; ;******* Variables char choixJ1: .BYTE ' ' ; Choix du joueur 1 choixJ2: .BYTE ' ' ; Choix du joueur 2 charIn: .BYTE ' ' ; Le 2e caratere saisi par les joueurs ; ;******* Constantes (chaines de caracteres) msgTiret: .ASCII "-----------------------------------------------\n\x00" msgWelc: .ASCII "--- Bienvenue au jeu de roche-papier-ciseau ---\n\x00" msgTour: .ASCII "Combien de manches voulez-vous jouer?\n\x00" msgReste: .ASCII "Il reste \x00" msgTours: .ASCII " manche(s) a jouer.\n\x00" msgJ1: .ASCII "JOUEUR 1\x00" msgJ2: .ASCII "JOUEUR 2\x00" msgChoix: .ASCII ", quel est votre choix? [r/p/c]\n\x00" msgWin: .ASCII " a gagne cette manche! Score: \x00" msgWin2: .ASCII "-\x00" msgNulle: .ASCII "Manche nulle...\n\x00" msgCongr: .ASCII " A GAGNE LE MATCH! FELICITATIONS!\n\x00" msgScore: .ASCII "SCORE FINAL: \x00" msgError: .ASCII "Erreur d'entree! Programme termine.\n\x00" msgLine: .ASCII "\n\x00" msgLines: .ASCII "\n\n\x00" ; .END
import { Fab, Icon, SpeedDialIcon, useMediaQuery, useTheme } from '@mui/material'; import { useT } from '../../locales/hooks/useT'; export const HilariouslyBigAddRoundModalTrigger = ({ onOpenModal, ...attrs }: { onOpenModal?: () => void; }) => { const theme = useTheme(); const t = useT(); const scale = useMediaQuery(theme.breakpoints.down('md')).valueOf() ? 1.8 : 3; return ( <Fab color="primary" variant="extended" sx={{ gap: 1, transform: `scale(${scale})`, boxShadow: `0px 0px 50px 10px ${theme.palette.grey[600]}`, '&::after': { content: `"${t.addRound}"` }, }} onClick={onOpenModal} size="large" {...attrs} > <SpeedDialIcon icon={<Icon>ramen_dining</Icon>} /> </Fab> ); };
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue3事件处理</title> <script src="vue.global.js"></script> <link rel="stylesheet" href="Vue8.css"> </head> <body> <p> 我们可以使用v-on指令来监听DOM事件,从而执行Javascript代码。 <br> v-on指令可以缩写为@符号。 </p> <div id="app1"> <button @click="counter += 1" class="btn">点击可以增加1</button> <p>这个按钮被点击了{{counter}}次</p> </div> <script> const app1 = { data () { return { counter: 0 } } } Vue.createApp(app1).mount('#app1') </script> <div> <p>通常情况下,我们需要使用一个方法来调用JS方法</p> <p>v-on可以接受一个定义的方法来调用</p> </div> <h5>实例</h5> <div id="app2"> <button @click="greet">点击</button> </div> <script> const app2 = { data (){ return { name: 'Google' } }, methods: { greet(event){ alert('Hello ' + this.name + '!') if (event) { alert(event.target.tagName) } } } } Vue.createApp(app2).mount('#app2') </script> <p> 除了直接绑定到一个方法,也可以用内联JS语句 </p> </body> </html>
import { PutObjectCommand } from "@aws-sdk/client-s3"; import { v4 as uuid } from "uuid"; import prisma from "~/lib/prisma"; import redisClient from "~/lib/redis.server"; import { s3Client } from "~/lib/s3.server"; export async function createTrackerAttachmentTypeLink({ displayName, trackerItemId, url, ownerId, type = "LINK", }: { trackerItemId: string; url: string; displayName: string; ownerId: string; type?: "DOCUMENT" | "LINK"; }) { const cacheKey = `task-tracker:${ownerId}`; await redisClient.del(cacheKey); const trackerItem = await prisma.taskTrackerItem.findUnique({ where: { id: trackerItemId }, include: { task: true }, }); if (!trackerItem) { throw new Error("Not found"); } const attachment = await prisma.attachment.create({ data: { type, taskId: trackerItem.taskId, trackerItemId: trackerItemId, url, displayName, ownerId, }, }); return attachment; } export async function createTrackerAttachmentTypeFile({ displayName, trackerItemId, file, ownerId, }: { trackerItemId: string; file: File; displayName?: string; ownerId: string; }) { const cacheKey = `task-tracker:${ownerId}`; await redisClient.del(cacheKey); const trackerItem = await prisma.taskTrackerItem.findUnique({ where: { id: trackerItemId }, include: { task: true }, }); if (!trackerItem) { throw new Error("Not found"); } const fileId = uuid(); const fileName = `task/${ trackerItem.taskId }/tracker/${trackerItemId}/${fileId}.${file.name.split(".").slice(-1)}`; const command = new PutObjectCommand({ Bucket: process.env.S3_BUCKET_NAME, Key: fileName, Body: Buffer.from(await file.arrayBuffer()), ContentType: file.type, ACL: "public-read", }); await s3Client.send(command); const url = `${process.env.S3_END_POINT}/${process.env.S3_BUCKET_NAME}/${fileName}`; const attachment = await prisma.attachment.create({ data: { type: "FILE", taskId: trackerItem.taskId, trackerItemId: trackerItemId, url, displayName: displayName || fileId, ownerId, }, }); return attachment; } export async function deleteAttachmentById({ attachmentId, ownerId, }: { attachmentId: string; ownerId: string; }) { const cacheKey = `task-tracker:${ownerId}`; await redisClient.del(cacheKey); const attachment = await prisma.attachment.delete({ where: { id: attachmentId }, }); return attachment; }
import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; const Registration = () => { const [username, setUsername] = useState(''); const [message, setMessage] = useState(''); const handleSubmit = (event) => { event.preventDefault(); axios.post('http://localhost:3001/register', { username }) .then(res => { setMessage(res.data); }) .catch(err => { if (err.response) { setMessage(err.response.data); } else { setMessage('An error occurred. Please try again.'); } }); }; return ( <div className='body light-background'> <section className="container"> <h1>Registration</h1> <form onSubmit={handleSubmit}> <article className='form-group'> <label htmlFor="username">Username:</label> <input id='username' type='text' value={username} onChange={(e) => setUsername(e.target.value)} required /> </article> <button type='submit'>Create an Account</button> </form> {message && <p className='message'>{message}</p>} <section className='link'> <Link to="/login">Login</Link> </section> </section> </div> ); }; export default Registration;
import { Component, OnInit } from '@angular/core'; // grc import { Routes, RouterModule } from '@angular/router'; import { FoodItemService } from 'app/food-item.service'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'], // Providers allow us to inject an object instance through the constructor. // In this case we enable injection of FoodItemService into AppComponent. providers: [FoodItemService] }) export class HomeComponent implements OnInit { myFoodItems: Array<any>; myDataService: FoodItemService; // Since we are using a provider above we can receive // an instance through an instructor. constructor(myDataService: FoodItemService) { // Store local reference to MyDataService. this.myDataService = myDataService; this.myDataService.getFoodItems() // Subscribe to changes in the observable object // that is returned by getRemoteData. .subscribe( // You basically get three handlers. // 1. Handle successful data. data => { this.myFoodItems = data console.log("home page data: " + JSON.stringify(data)) // list of the json objects }, // 2. Handle error. error => { alert(error) }, // 3. Execute final instructions when successful. () => { console.log("Finished home data") }); } ngOnInit() { } }
package MnogoPotochnost.Synchonyzed; public class WaitNotifyExm { public static void main(String[] args) { Market market = new Market(); Producer producer = new Producer(market); Consumer consumer = new Consumer(market); Thread thread1 = new Thread(producer); Thread thread2 = new Thread(consumer); thread1.start(); thread2.start(); } } class Market { private int breadCount = 0; private final Object lock = new Object(); public void getBread() { synchronized (lock) { while (breadCount < 1) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // System.out.println(this); breadCount--; System.out.println("Продана одна буханка хлеба"); System.out.println("В магазине осталось " + breadCount + " хлеба"); lock.notify(); } } public void putBread() { synchronized (lock) { while (breadCount >= 5) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // System.out.println(this.toString()); breadCount++; System.out.println("Производитель добавил на витрину 1 буханку хлеба"); System.out.println("Количество буханок хлеба на витрине " + breadCount); lock.notify(); } } } class Producer implements Runnable { Market market; public Producer(Market market) { this.market = market; } @Override public void run() { for (int i = 0; i < 10; i++) { market.putBread(); } } } class Consumer implements Runnable { Market market; public Consumer(Market market) { this.market = market; } @Override public void run() { for (int i = 0; i < 10; i++) { market.getBread(); } } }
import mongoose from 'mongoose'; import User from './User'; import { ApiError, HttpStatus } from '@/utils'; import { QueryResult, IOptions } from '@/components'; import { NewCreatedUser, UpdateUserBody, IUserDoc, NewRegisteredUser } from "./UserInterface" class UserService { /** * Create a user * @param {NewCreatedUser} userBody * @returns {Promise<IUserDoc>} */ static async createUser(userBody: NewCreatedUser): Promise<IUserDoc> { if (await User.isEmailTaken(userBody.email)) { throw new ApiError(HttpStatus.BAD_REQUEST, 'Email already taken'); } return User.create(userBody); }; /** * Register a user * @param {NewRegisteredUser} userBody * @returns {Promise<IUserDoc>} */ static async registerUser(userBody: NewRegisteredUser): Promise<IUserDoc> { if (await User.isEmailTaken(userBody.email)) { throw new ApiError(HttpStatus.BAD_REQUEST, 'Email already taken'); } return User.create(userBody); }; /** * Query for users * @param {Object} filter - Mongo filter * @param {Object} options - Query options * @returns {Promise<QueryResult>} */ static async queryUsers(filter: Record<string, any>, options: IOptions): Promise<QueryResult> { const users = await User.paginate(filter, options); return users; }; /** * Get user by id * @param {mongoose.Types.ObjectId} id * @returns {Promise<IUserDoc | null>} */ static async getUserById(id: mongoose.Types.ObjectId): Promise<IUserDoc | null> { return User.findById(id) }; /** * Get user by email * @param {string} email * @returns {Promise<IUserDoc | null>} */ static async getUserByEmail(email: string): Promise<IUserDoc | null> { return User.findOne({ email }) }; /** * Update user by id * @param {mongoose.Types.ObjectId} userId * @param {UpdateUserBody} updateBody * @returns {Promise<IUserDoc | null>} */ static async updateUserById( userId: mongoose.Types.ObjectId, updateBody: UpdateUserBody ): Promise<IUserDoc | null> { const user = await this.getUserById(userId); if (!user) { throw new ApiError(HttpStatus.NOT_FOUND, 'User not found'); } if (updateBody.email && (await User.isEmailTaken(updateBody.email, userId))) { throw new ApiError(HttpStatus.BAD_REQUEST, 'Email already taken'); } Object.assign(user, updateBody); await user.save(); return user; }; /** * Delete user by id * @param {mongoose.Types.ObjectId} userId * @returns {Promise<IUserDoc | null>} */ static async deleteUserById(userId: mongoose.Types.ObjectId): Promise<IUserDoc | null> { const user = await this.getUserById(userId); if (!user) { throw new ApiError(HttpStatus.NOT_FOUND, 'User not found'); } await user.deleteOne(); return user; }; } export default UserService;
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>노드 다루기 - 모든 자식 노드 찾기(children(), contents())</title> <style> body{ font-size: 15px; font-family: "굴림"; } div, p, ul, li { border: 1px solid gray; margin: 10px; } ul { padding: 10px; } li.select { background-color: #ccc; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(document).ready(function(){ //특정 노드의 모든 자식 노드를 찾고 싶을 때 children(),contents()를 이용한다. //children() : 자식 노드 중 태그 노드만 찾음 //contents() : 태그 노드 뿐 아니라 텍스트 노드 까지 찾음 $("#samplePage").children().css("border", "2px solid blue"); $("#samplePage").contents().css("border", "2px solid blue"); //특정 노드의 자식 노드의 길이를 구하고있다. console.log($("#samplePage").children().length); //특정 노드의 자식 노드의 길이 + 텍스트 노드의 개수를 구하고있다. console.log($("#samplePage").contents().length); }); </script> </head> <body> <div id="samplePage" class="page"> 샘플페이지(div, id=samplePage, class=page) <div id="header"> 헤더 영역(div, id=header) </div> <div id="content" class="sample-content"> 노드 찾기(div, id=content class=sample-content) <ul class="menu"> 일반 노드 찾기(ul, class=menu) <li data-value="1">id로 찾기(li, data-value=1)</li> <li class="select">tag로 찾기(li, class=select)</li> <li data-value="2">class로 찾기(li, data-value=2)</li> <li class="test1">속성으로 찾기(li, class=test1)</li> </ul> <div class="content-data"> 자식 노드 찾기(div, class=content-data) <p class="test1">1. 모든 자식 노드 찾기(p, class=test1)</p> <p>2. 특정 자식 노드만 찾기(p)</p> <p class="test2">2. 마지막 자식 노드 찾기(p, class=test2)</p> </div> </div> <div id="footer"> 푸터 영역(div, id=footer) </div> </div> </body> </html>
// Internal Modules \\ const fs = require("fs"); const http = require("http"); const https = require("https"); const path = require("path"); const url = require("url"); // NPM Modules \\ const express = require("express"); const mysql = require("mysql"); const session = require("express-session"); // Local Assets \\ const config = require("./config.json"); // Database Object \\ const database = mysql.createConnection({ host: config.server.ip, port: config.server.port, user: config.auth.username, password: config.auth.password, }); // Connect to the Database \\ database.connect((err) => { if (err) throw err; console.log( `Connected to MySQL Server at ${config.server.ip}:${config.server.port} as ${config.auth.username}` ); }); // Initialize Website \\ const website = express(); website .use(session({ secret: "secret", resave: true, saveUninitialized: true })) .use(express.json()) .use(express.urlencoded({ extended: true })) .use(express.static(path.join(__dirname, "static"))); // Send Error To Client \\ function sendPopup(message, response) { response.send(`<script>alert("${message}"); history.back();</script>`); response.end(); return; } // Home Page \\ // example.com \\ website.get("/", (request, response) => { if (request.session.loggedin) response.sendFile(path.join(__dirname + "/home.html")); else response.sendFile(path.join(__dirname + "/login.html")); }); // The Chat History Window on the homepage \\ // example.com/chathistory \\ website.get("/chathistory", (request, response) => { database.query("SELECT * FROM chat_rooms.messages", (err, messages, x) => { if (err) sendPopup(err, response); database.query("SELECT * FROM auth.accounts", (err, accounts, x) => { if (err) sendPopup(err, response); let payload = "<style>body {font-family: Arial, sans-serif;background-color: white;} html, body {max-width: 100%;overflow-x: hidden;}</style><div style=\"overflow: auto; display: flex; flex-direction: column-reverse;\">"; for (message in messages) { let author = "debug"; for (account in accounts) { if (accounts[account].ID == messages[message].userID) { author = accounts[account].username; break; } else continue; } payload += `<div style="width: 100%;"><h2>${author}</h2><h3>${messages[message].dateCreated}</h3><h1>${messages[message].content}</h1><hr></div>`; } response.write(payload); setInterval(() => { database.query( "SELECT * FROM chat_rooms.messages", (err, messages2, x) => { if (err) sendPopup(err, response); database.query( "SELECT * FROM auth.accounts", (err, accounts, x) => { if (err) sendPopup(err, response); let payload = ""; for (message in messages2) { if (!message) continue; if (messages.includes(messages[message])) continue; let author = "debug"; for (account in accounts) { if (accounts[account].ID == messages2[message].userID) { author = accounts[account].username; break; } else continue; } payload += `<div style="width: 100%;"><h2>${author}</h2><h3>${messages2[message].dateCreated}</h3><h1>${messages2[message].content}</h1><hr></div>`; messages.push(messages2[message]) } response.write(payload); } ); } ); }, 1000); }); }); }); // Called When a Message is Sent \\ // example.com/sendmessage \\ website.post("/sendmessage", (request, response) => { const message = request.body.message; database.query( `INSERT INTO chat_rooms.messages (\`userID\`, \`room\`, \`content\`) VALUES ('${request.session.userid}', '0', '${message}');`, (err, results) => { if (err) sendPopup(err, response); response.redirect("/"); response.end(); } ); }); // Called During a Login Attempt \\ // example.com/login \\ website.post("/login", (request, response) => { const username = request.body.username; const password = request.body.password; let previous_query = url.parse(request.rawHeaders[33], true).search; if (previous_query == null) { previous_query = ""; } if (username && password) { database.query( "SELECT * FROM auth.accounts WHERE username = ? AND password = ?", [username, password], function (err, results, fields) { if (err) sendPopup(err, response); if (results.length > 0) { request.session.loggedin = true; request.session.username = username; request.session.userid = results[0].ID; } response.redirect(`/${previous_query}`); response.end(); } ); } }); // Open Up Website Ports 8080 and 443 (if secured) \\ try { https .createServer( { key: fs.readFileSync(`${config.ssl}/privkey.pem`, "utf8"), cert: fs.readFileSync(`${config.ssl}/cert.pem`, "utf8"), ca: fs.readFileSync(`${config.ssl}/chain.pem`, "utf8"), }, website ) .listen(443, () => { console.log("HTTPS Server running on port 443"); }); } catch { console.log("Caution: Connections will not be secured"); } http.createServer(website).listen(8080, () => { console.log("HTTP Server running on port 8080"); });
#!/usr/bin/env guile -e !# ;; -*- mode: snippet -*- ;; name: fn.scm ;; key: ;; binding: ;; expand-env: ((some-var some-value)) ;; -- ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;; This program implements iterative Factorial version. Copied from SICP ;; book. (define (fact-iter product counter max-count) (if (> counter max-count) product (fact-iter (* counter product) (+ counter 1) max-count))) (define (fact n) (fact-iter 1 1 n)) (display (fact 1)) (newline) (display (fact 2)) (newline) (display (fact 3)) (newline) (display (fact 4)) (newline) (display (fact 5)) (newline) (display (fact 6)) (newline) (display (fact 7)) (newline) (display (fact 8)) (newline) (display (fact 9)) (newline) (display (fact 10)) (newline) (display (fact 100)) (newline) (display (fact 5000)) (newline) (display (fact 200000)) (newline) (display (fact 0)) (newline) (display (fact -2)) (newline)
A transaction is a set of one or more statements that is executed as a unit, so either all of the statements are executed, or none of the statements is executed. 1. Disabling Auto-Commit Mode When a connection is created, it is in auto-commit mode. Default is for a SQL statement to be committed when it is completed, not when it is executed. 2. Committing Transactions After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. 3. Using Transactions to Preserve Data Integrity For protection against conflicts that arise when two users access data at the same time. A DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. In auto-commit mode, where each statement is a transaction, locks are held for only one statement. After a lock is set, it remains in force until the transaction is committed or rolled back. How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules. Isolation Level Transactions Dirty Reads Non-Repeatable Reads Phantom Reads TRANSACTION_NONE Not supported Not applicable Not applicable Not applicable TRANSACTION_READ_COMMITTED Supported Prevented Allowed Allowed TRANSACTION_READ_UNCOMMITTED Supported Allowed Allowed Allowed TRANSACTION_REPEATABLE_READ Supported Prevented Prevented Allowed TRANSACTION_SERIALIZABLE Supported Prevented Prevented Prevented A non-repeatable read occurs when transaction A retrieves a row, transaction B subsequently updates the row, and transaction A later retrieves the same row again. Transaction A retrieves the same row twice but sees different data. A phantom read occurs when transaction A retrieves a set of rows satisfying a given condition, transaction B subsequently inserts or updates a row such that the row now meets the condition in transaction A, and transaction A later repeats the conditional retrieval. Transaction A now sees an additional row. This row is referred to as a phantom. Connection.getTransactionIsolation to find isolation level. 4. Setting and Rolling Back to Savepoints creating a Savepoint with the following statement: Savepoint save1 = con.setSavepoint(); the method rolls back the transaction with the following statement: con.rollback(save1); 5. Releasing Savepoints The method Connection.releaseSavepoint takes a Savepoint object as a parameter and removes it from the current transaction. 6. When to Call Method rollback Calling the method rollback terminates a transaction and returns any values that were modified to their previous values. If you are trying to execute one or more statements in a transaction and get a SQLException, call the method rollback to end the transaction and start the transaction all over again.
<?php declare(strict_types=1); namespace loophp\iterators; use Generator; use IteratorAggregate; /** * @template TKey * @template T * * @implements IteratorAggregate<int, array{0: TKey, 1: T}> */ final class PackIterableAggregate implements IteratorAggregate { /** * @param iterable<TKey, T> $iterable */ public function __construct(private iterable $iterable) {} /** * @return Generator<int, array{0: TKey, 1: T}> */ public function getIterator(): Generator { foreach ($this->iterable as $key => $value) { yield [$key, $value]; } } }
import React, { useState, useEffect } from "react"; const GoToTop = () => { const [visible, setVisible] = useState(false); const listenToScroll = () => { let heightToHidden = 20; const winScroll = document.body.scrollTop || document.documentElement.scrollTop; winScroll > heightToHidden ? setVisible(true) : setVisible(false); }; useEffect(() => { window.addEventListener("scroll", listenToScroll); return () => window.removeEventListener("scroll", listenToScroll); }, []); const MoveToTop = () => { window.scrollTo({ top: 0, left: 0, behavior: "smooth" }); }; return ( <div className="relative"> {visible && ( <button className="fixed bottom-10 right-5 md:right-10 shadow-xl bg-light text-main font-bold rounded-full w-10 h-10 z-999 animate-bounce" onClick={MoveToTop} > &uarr; </button> )} </div> ); }; export default GoToTop;
import React from "react"; import { CalendarIcon, AtSymbolIcon, UsersIcon } from "@heroicons/react/solid"; import { Link } from "react-router-dom"; const RequestDeposit = () => { const positions = [ { id: 1, title: "Jamie Oliver", type: "Paid", location: "jamieoliver@gmail.com", department: "Engineering", closeDate: "2020-01-07", closeDateFull: "January 7, 2020", }, { id: 2, title: "Alex Delson", type: "Not Paid", location: "alexdelson@gmail.com", department: "Engineering", closeDate: "2020-01-07", closeDateFull: "January 7, 2020", }, { id: 3, title: "Ben Afflick", type: "Not Paid", location: "benafflick@gmail.com", department: "Design", closeDate: "2020-01-14", closeDateFull: "January 14, 2020", }, { id: 4, title: "Alex Joe", type: "Not Paid", location: "benafflick@gmail.com", department: "Design", closeDate: "2020-01-14", closeDateFull: "January 14, 2020", }, { id: 5, title: "Sylvia Synthia", type: "Not Paid", location: "benafflick@gmail.com", department: "Design", closeDate: "2020-01-14", closeDateFull: "January 14, 2020", }, ]; return ( <> <div className="bg-white shadow overflow-hidden sm:rounded-md w-5/6 mx-auto my-10"> <ul className="divide-y divide-gray-200"> {positions.map((position) => ( <li key={position.id}> <Link to="#" className="block hover:bg-gray-50"> <div className="px-4 py-4 sm:px-6"> <div className="flex items-center justify-between"> <p className="text-sm font-medium text-cyan-600 truncate"> {position.title} </p> <div className="ml-2 flex-shrink-0 flex"> <p className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800"> {position.type} </p> </div> </div> <div className="mt-2 sm:flex sm:justify-between"> <div className="sm:flex"> <p className="flex items-center text-sm text-gray-500"> <UsersIcon className="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" aria-hidden="true" /> {position.department} </p> <p className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0 sm:ml-6"> <AtSymbolIcon className="flex-shrink-0 h-5 w-5 text-gray-400" aria-hidden="true" /> {position.location} </p> </div> <div className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0"> <CalendarIcon className="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" aria-hidden="true" /> <p> Closing on{" "} <time dateTime={position.closeDate}> {position.closeDateFull} </time> </p> </div> </div> </div> </Link> </li> ))} </ul> </div> </> ); }; export default RequestDeposit;
import { Dispatch, MouseEvent, SetStateAction, useEffect, useState } from "react"; import type { NextComponent } from "../../lib/types"; import { scrollToElement } from "scroll-util"; import { handleClick } from "../../helpers/handleClick"; import { sectionInView } from "../../helpers/sectionInView"; export const Nav: NextComponent = (): JSX.Element => { const [sectionVisible, setSection]: [ string, Dispatch<SetStateAction<string>> ] = useState<string>("header"); useEffect((): void => { const sections: string[] = ["header", "about", "skills"]; document.addEventListener("scroll", (): void => { const e: string | undefined = sections.find( (section: string): boolean => sectionInView( document.getElementById(section) as HTMLElement ) ); if (e) setSection(e); }); }); return ( <div className="w-full flex flex-row justify-between items-center fixed top-0 left-0 pt-7 pl-7 pr-7 pb-12 text-g2 dark:text-white font-made transition duration-700 ease-in-out z-[9999] nav"> <div className="flex flex-row items-center"> <span className="font-bold text-xl hover:brightness-75" onClick={(): void => scrollToElement("header", "smooth")}> tncz<span className="text-p1">.dev()</span> </span> </div> <ul className="hidden lg:flex flex-row items-center list-none gap-x-10"> <li className={`${ sectionVisible === "header" && "text-p1" } cursor-pointer hover:text-p1 transition-all duration-200 ease-in-out`} onClick={(e: MouseEvent): void => handleClick(e, "header")}> home() </li> <li className={`${ sectionVisible === "about" && "text-p1" } cursor-pointer hover:text-p1 transition-all duration-200 ease-in-out`} onClick={(e: MouseEvent): void => handleClick(e, "about")}> about() </li> <li className={`${ sectionVisible === "skills" && "text-p1" } cursor-pointer hover:text-p1 transition-all duration-200 ease-in-out`} onClick={(e: MouseEvent): void => handleClick(e, "skills")}> skills() </li> </ul> </div> ); };
import { LightningElement } from 'lwc'; export default class LifeCycleParent extends LightningElement { constructor(){ super() //this.template.addEventListener('mouseover', fun) // this we rarely use console.log('Parent constructer called') } connectedCallback(){ console.log('Parent connectedCallback called') } renderedCallback(){ console.log('Parent renderedCallback called') } //Performance impact of renderedCallback() : this method called everytime you change anything in the component //hence we should not use renderedCallback() method to change state or update property //below code is ex. name changeHandler(event){ this.name = event.target.value } isChildVisible=false handleClick(){ //this.isChildVisible = true this.isChildVisible = !this.isChildVisible //to toggle the button } //errorCallback(error, stack) takes 2 argument errorCallback(error, stack){ console.log(error.message) console.log(stack) //it will show the stack(component) from where error is occuring } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> // 访问属性:obj.foo // const obj = {foo:1 } // const p = new Proxy(obj, { // get(target, key,receiver) { // //建立联系 // track(target,key) // //返回属性值 // return Reflect.get(target,key,receiver) // } // }) // key in obj // const obj = {foo:1 } // const p = new Proxy(obj, { // has(target, key) { // //建立联系 // track(target,key) // //返回属性值 // return Reflect.get(target,key) // } // }) // effect(() => { // 'foo' in p // }) // for in // const obj = { foo: 1 } // const ITERATE_KEY = Symbol() // const p = new Proxy(obj, { // ownKeys(target) { // // 将副作用函数与 ITERATE_KEY 关联 // track(target, ITERATE_KEY) // return Reflect.ownKeys(target) // } // }) // 触发响应时: // trigger(target, ITERATE_KEY) const p = new Proxy(obj, { deleteProperty(target, key) { // 检查被操作的属性是否是对象自己的属性 const hadKey = Object.prototype.hasOwnProperty.call(target,key) // 使用 Reflect.deleteProperty 完成属性的删除 const res = Reflect.deleteProperty(target, key) if (res && hadKey) { // 只有当被删除的属性是对象自己的属性并且成功删除时,才触发更新 trigger(target, key, 'DELETE') } return res } }) function trigger(target, key, type) { const depsMap = bucket.get(target) if (!depsMap) return const effects = depsMap.get(key) const effectsToRun = new Set() effects && effects.forEach(effectFn => { if (effectFn !== activeEffect) { effectsToRun.add(effectFn) } }) // 当操作类型为 ADD 或 DELETE 时,需要触发与 ITERATE_KEY 相关联的副作用函数重新执行 if (type === 'ADD' || type === 'DELETE') { const iterateEffects = depsMap.get(ITERATE_KEY) iterateEffects && iterateEffects.forEach(effectFn => { if (effectFn !== activeEffect) { effectsToRun.add(effectFn) } }) } effectsToRun.forEach(effectFn => { if (effectFn.options.scheduler) { effectFn.options.scheduler(effectFn) } else { effectFn() } }) } </script> </body> </html>
package com.codeup.springblog.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; @Controller class HelloController { @GetMapping("/hello") public String hello(Model model) {return "hello";} @RequestMapping(path = "/hello/{name}", method = RequestMethod.GET) public String helloToYou(@PathVariable String name, Model model) { model.addAttribute("name", name); return String.format("Nice to meet you, %s!", name); } String fizzBuzzEvaluation (int num){ if(num % 3 == 0 && num % 5 == 0) { return "FizzBuzz"; }else if(num % 3 == 0){ return "Fizz"; }else if(num % 5 == 0) { return "Buzz"; }else { return String.format("%d", num); } } @GetMapping("/number/{num}") @ResponseBody public String reportNumber(@PathVariable int num) { String intro = String.format("Here are some truths of the number %d.", num); String isEven = String.format("The number %d is even: %b.", num, num % 2 == 0., num); String numSquared = String.format("The number %d is squared: %d.", num, (int) (Math.pow(num, 2))); String fizzBuzzEval = String.format("The number %d when run through FizzBuzz would print %s", num, fizzBuzzEvaluation(num)); return String.format("<h3>%s</h3>" + "<ul><li>%n</li>" + "<li>%s</li>" + "<li>%n</li>" + "<li>%s</li>" + "<li>%n</li>" + "<li>%s</li>" + "</ul>", intro, isEven, numSquared, fizzBuzzEval); } }
import React from 'react'; import {NavLink} from "react-router-dom"; import styled from 'styled-components'; import styles from './main.module.css'; import DrawMov from '../../media/video/Drawings.webm'; import DrawMov2 from '../../media/video/Drawings.mp4'; import DrawingsPoster from '../../media/video/DrawingsPoster.jpg'; export default function Main({data}) { const MainView = () => { const Background = styled.div` width: 100%; height: 100%; background-color: #000; opacity: 0.5; `; const EggVideoBackground = styled.div` background-color: #000; animation-duration: .5s; animation-name: showPic; `; return ( <main className={styles.app__main__mainView}> <Background> <EggVideoBackground> <video className={styles.app__main__mainViewVideoDrawings} muted autoPlay playsInline loop poster={DrawingsPoster} > <source src={DrawMov} type="video/webm"/> <source src={DrawMov2} type="video/mp4"/> </video> </EggVideoBackground> </Background> <div className={styles.app__main__mainTitle}> {data.title.map(title => <p key={title.id}>{title.word}</p>)} <NavLink to={data.linkToEng}> <button className={styles.app__main__languageToggle}> <h4>{data.switchTo}</h4> </button> </NavLink> </div> <NavLink to={data.linkToSlider}> <button className={styles.app__main__nextSlidePage}> <div className={styles.app__main__nextSlidePage_nextSlidePageArrow}/> </button> </NavLink> { data.linkToEggPage ? <NavLink to={data.linkToEggPage}> <button className={styles.app__main__EggsPage}> <div className={styles.app__main__EggsPage_nextPageArrow}/> </button> </NavLink> : null } </main> ); }; return ( <MainView/> ) }
import React, { useEffect, useState } from "react" import { useDispatch, useSelector } from "react-redux" import { useHistory } from "react-router" import { logout } from "../../redux/actions" import { setUserToLocalStorage } from "../../utils/localStorage" import API from "../../env/api" import { checkoutCart, counterOrderByStatus, formatMoney, priceByDiscount, priceByQuantity, } from "../../containers/functions" import { Col, Row } from "antd" import { LogoutOutlined } from "@ant-design/icons" import api from "../../env/api" const Shipper = () => { const dispatch = useDispatch() const history = useHistory() const { currentUser } = useSelector((store) => store) const [orders, setOrders] = useState([]) const [ordersDetail, setOrdersDetail] = useState([]) const fetchOrders = () => { API.get(`get_all_order.php`).then((response) => setOrders(response.data)) API.get(`get_all_order_detail.php`).then((response) => setOrdersDetail(response.data) ) } useEffect(() => { fetchOrders() }, []) if (currentUser) { if (currentUser.role !== 3) { if (currentUser.role === 2) { history.push("/salesman") } else if (currentUser.role === 1) { history.push("/admin") } else { history.push("/") } } } else { history.push("/") } const handleLogout = () => { dispatch(logout()) setUserToLocalStorage(null) history.push("/") } const handlePickUp = (id, status) => { const formData = new FormData() formData.append("id", id) formData.append("updateStatus", status) api.post(`update_status_order.php`, formData) fetchOrders() } return ( <> <div className="salesman"> <div className="salesman__header"> <span>Nông sản sạch</span> <span>Trang của shipper</span> <span> {currentUser && currentUser.name}{" "} <LogoutOutlined style={{ marginLeft: "15px", color: "white" }} onClick={handleLogout} /> </span> </div> <Row className="salesman__title"> <Col span={8}> <h2> Đang chờ giao hàng{" "} <span style={{ color: "red" }}> {counterOrderByStatus(orders, 2)} đơn </span> </h2> </Col> <Col span={8}> <h2> Đang vận chuyển{" "} <span style={{ color: "red" }}> {counterOrderByStatus(orders, 3)} đơn </span> </h2> </Col> <Col span={8}> <h2>Đã thanh toán</h2> </Col> </Row> <div className="salesman__wrapper"> <Col className="salesman__wrapper__list" span={8}> {orders .filter((orderFilter) => orderFilter.id_order_status === 2) .map((order) => ( <div key={order.id_order} className="order__item"> <p> <b>id đơn hàng:</b> {order.id_order} </p> <p> <b>Tên khách:</b> {order.name} </p> <p> <b>Số điện thoại:</b> {order.phone} </p> <p> <b>Địa chỉ:</b> {order.address} </p> <p> <b>Ngày tạo đơn hàng:</b> {order.create_date} </p> <div> <b>Danh sách sản phẩm</b> {ordersDetail .filter((item) => item.id_order === order.id_order) .map((item) => ( <p> {item.id_product} - {item.name}{" "} {formatMoney( priceByDiscount(item.price, item.discount) )}{" "} x {item.quantity} ={" "} {formatMoney( priceByQuantity( priceByDiscount(item.price, item.discount), item.quantity ) )} </p> ))} </div> <p> <b>Tổng tiền:</b>{" "} {formatMoney( checkoutCart( ordersDetail.filter( (item) => item.id_order === order.id_order ) ) )} </p> <button onClick={() => handlePickUp(order.id_order, 3)}> Bắt đầu giao hàng </button> </div> ))} </Col> <Col className="salesman__wrapper__list" span={8}> {orders .filter((orderFilter) => orderFilter.id_order_status === 3) .map((order) => ( <div key={order.id_order} className="order__item"> <p> <b>id đơn hàng:</b> {order.id_order} </p> <p> <b>Tên khách:</b> {order.name} </p> <p> <b>Số điện thoại:</b> {order.phone} </p> <p> <b>Địa chỉ:</b> {order.address} </p> <p> <b>Ngày tạo đơn hàng:</b> {order.create_date} </p> <div> <b>Danh sách sản phẩm</b> {ordersDetail .filter((item) => item.id_order === order.id_order) .map((item) => ( <p> {item.id_product} - {item.name}{" "} {formatMoney( priceByDiscount(item.price, item.discount) )}{" "} x {item.quantity} ={" "} {formatMoney( priceByQuantity( priceByDiscount(item.price, item.discount), item.quantity ) )} </p> ))} </div> <p> <b>Tổng tiền:</b>{" "} {formatMoney( checkoutCart( ordersDetail.filter( (item) => item.id_order === order.id_order ) ) )} </p> <button onClick={() => handlePickUp(order.id_order, 4)}> Xác nhận thanh toán </button> </div> ))} </Col> <Col className="salesman__wrapper__list" span={8}> {orders .filter((orderFilter) => orderFilter.id_order_status === 4) .map((order) => ( <div key={order.id_order} className="order__item"> <p> <b>id đơn hàng:</b> {order.id_order} </p> <p> <b>Tên khách:</b> {order.name} </p> <p> <b>Số điện thoại:</b> {order.phone} </p> <p> <b>Địa chỉ:</b> {order.address} </p> <p> <b>Ngày tạo đơn hàng:</b> {order.create_date} </p> <div> <b>Danh sách sản phẩm</b> {ordersDetail .filter((item) => item.id_order === order.id_order) .map((item) => ( <p> {item.id_product} - {item.name}{" "} {formatMoney( priceByDiscount(item.price, item.discount) )}{" "} x {item.quantity} ={" "} {formatMoney( priceByQuantity( priceByDiscount(item.price, item.discount), item.quantity ) )} </p> ))} </div> <p> <b>Tổng tiền:</b>{" "} {formatMoney( checkoutCart( ordersDetail.filter( (item) => item.id_order === order.id_order ) ) )} </p> </div> ))} </Col> </div> </div> </> ) } export default Shipper
import 'package:chat2p/shared/widgets/profile_list_wedget.dart'; import 'package:flutter/material.dart'; import 'package:matrix/matrix.dart'; import 'package:provider/provider.dart'; class SearchPage extends StatefulWidget { @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { final TextEditingController _searchController = TextEditingController(); Client? client; List<dynamic> _searchResults = []; @override void initState() { super.initState(); _initializeMatrixClient(); _searchController.addListener(_onSearchChanged); } void _initializeMatrixClient() async { client = Provider.of<Client>(context, listen: false); setState(() {}); } void _onSearchChanged() { if (_searchController.text.isNotEmpty) { _search(_searchController.text); } else { setState(() { _searchResults.clear(); }); } } void _search(String searchTerm) async { try { var response = await client!.searchUserDirectory(searchTerm, ); setState(() { _searchResults = response.results; });} catch (e) { _searchResults.clear(); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Pesquisa Matrix'), backgroundColor:Theme.of(context).primaryColor, ), body: Column( children: <Widget>[ Divider(height: 1,color: Theme.of(context).indicatorColor,), Padding( padding: const EdgeInsets.all(8.0), child: TextField( controller: _searchController, decoration: InputDecoration( labelText: 'Pesquisar usuário', suffixIcon: Icon(Icons.search), ), ), ), Expanded( child: ListView.builder( itemCount: _searchResults.length, itemBuilder: (context, index) { var result = _searchResults[index]; return ProfileListWedget(profile: result,); // ListTile( // title: Text(result.displayName), // subtitle: Text(result.userId), // ); }, ), ), ], ), ); } @override void dispose() { _searchController.dispose(); super.dispose(); } }
import { Injectable } from '@nestjs/common'; import { DataReplicationRepository } from 'src/infrastructure/repositories/data-replication.service'; type PrimaryKeys = string[]; type TableInfo = { primaryKeys: PrimaryKeys }; type ReplicationTableInfo = { [key: string]: TableInfo; }; @Injectable() export class DataReplicationUseCase { constructor( private readonly dataReplicationRepository: DataReplicationRepository, ) {} async execute(data: any): Promise<void> { const tableInfo = await this.getTableInfo(); const { clinicId, rows } = data; for (const tableName of Object.keys(rows)) { if (tableInfo[tableName]) { const primaryKeys = tableInfo[tableName].primaryKeys; const records = rows[tableName]; await this.dataReplicationRepository.upsertData( clinicId, tableName, records, primaryKeys, ); } else { console.log(`Table ${tableName} not found`); } } } private async getTableInfo(): Promise<ReplicationTableInfo> { return { patient: { primaryKeys: ['PatNum', 'ClinicSyncId'] }, appointment: { primaryKeys: ['AptNum', 'ClinicSyncId'] }, referral: { primaryKeys: ['ReferralNum', 'ClinicSyncId'] }, insplan: { primaryKeys: ['PlanNum', 'ClinicSyncId'] }, inssub: { primaryKeys: ['InsSubNum', 'ClinicSyncId'] }, patplan: { primaryKeys: ['PatPlanNum', 'ClinicSyncId'] }, commlog: { primaryKeys: ['CommlogNum', 'ClinicSyncId'] }, definition: { primaryKeys: ['DefNum', 'ClinicSyncId'] }, refattach: { primaryKeys: ['RefAttachNum', 'ClinicSyncId'] }, }; } }
# Working import streamlit as st import pandas as pd import numpy as np import altair as alt import time import zipfile import pdfplumber from openai import OpenAI from pathlib import Path import os from dotenv import load_dotenv # Set your OpenAI API key load_dotenv() client = OpenAI(api_key=os.environ['OPENAI_API_KEY']) # Page title st.set_page_config(page_title='pdfPod', page_icon='🤖') st.title('🤖 pdfPod') with st.expander('About this app'): # Your app description here "Use me to synthesize your research paper pdfs into podcasts." # Load data st.header('1.1. Input data') st.markdown('**1. Upload PDF file**') uploaded_file = st.file_uploader("Upload a PDF file", type=["pdf"]) # Initiate the model building process if uploaded_file: with st.status("Running ...", expanded=True) as status: # Read PDF contents with pdfplumber.open(uploaded_file) as pdf: pdf_text = "" for page in pdf.pages: pdf_text += page.extract_text() # Send contents to OpenAI API for text generation completion = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "Hello ChatGPT, I have a PDF of a research paper. I would like you to generate a concise summary of this paper for a podcast episode of the podcast TechTide. The target audience of the podcast is well-versed in technology and computer science, but not necessarily in the specific area covered by the paper. Please focus on the following in your summary: Key concepts and technologies introduced in the paper. Any innovative methods or findings. Implications of the research and its practical applications. Future directions mentioned in the research or potential impact on the field. Aim for the summary to be engaging and accessible, providing explanations of technical terms and concepts to ensure clarity. The duration of the podcast segment should be around ten minutes, so please keep your summary concise but informative. The total number of characters must be less than 2000."}, {"role": "user", "content": pdf_text} ] ) speech_file_path = Path(__file__).parent / "speech.mp3" response = client.audio.speech.create( model="tts-1", voice="alloy", input=completion.choices[0].message.content ) response.stream_to_file(speech_file_path) st.audio("speech.mp3") # Display the generated podcast script st.subheader("Generated Podcast Script") st.write(completion.choices[0].message.content) else: st.warning('👈 Upload a PDF file to get started!')
from typing import Optional CRLF = "\r\n" class ResponseHandler: """ Given the headers, body, version, code and text generates the response string. Stateless. """ http_ver = "HTTP/1.1" success_code = "200" success_text = "OK" created_code = "201" created_text = "Created" failure_code = "404" failure_text = "Not Found" def _create_status_line(self, http_ver: str, code: str, text: str) -> str: return f"{http_ver} {code} {text}" def _end_status_line(self, status_line: str) -> str: return status_line + CRLF def _create_response_headers(self, headers: dict[str, str]) -> str: if not headers: return "" headers_str: list[str] = [] for key in headers: val = headers[key] str_repr = f"{key}: {val}" headers_str.append(str_repr) return f"{CRLF}".join(headers_str) + CRLF def _end_response_headers(self, response_headers: str) -> str: return response_headers + CRLF def create_response( self, http_ver: str, code: str, text: str, headers: dict[str, str], body: Optional[str] ) -> str: # Creates generic response. status_line = self._create_status_line(http_ver, code, text) status_line = self._end_status_line(status_line) response_headers = self._create_response_headers(headers) response_headers = self._end_response_headers(response_headers) resp = status_line + response_headers if body: resp += body resp = self._end_response(resp) return resp def create_success_response( self, headers: dict[str, str] = {}, body: Optional[str] = None ) -> str: # Creates response for a successful operation (200). return self.create_response( self.http_ver, self.success_code, self.success_text, headers, body ) def create_created_response( self, headers: dict[str, str] = {}, body: Optional[str] = None ) -> str: # Creates response for a successfully created operation (201). return self.create_response( self.http_ver, self.created_code, self.created_text, headers, body ) def create_failure_response( self, headers: dict[str, str] = {}, body: Optional[str] = None ) -> str: # Creates response for a failed operation (404). return self.create_response( self.http_ver, self.failure_code, self.failure_text, headers, body ) def _end_response(self, response: str) -> str: return response + CRLF
// // VULUpdateTool.m // VideoULimit // // Created by svnlan on 2018/10/12. // Copyright © 2018年 svnlan. All rights reserved. // #import "VULUpdateTool.h" #import "VULUpdatePopupView.h" //#import "BGFMDB.h" @implementation VULAppstoreInfo - (instancetype)initWithDictionary:(NSDictionary *)dictionary { if (self = [super init]) { if (!dictionary || dictionary.count <= 0) { return nil; } _version = dictionary[@"version"]; _releaseNotes = dictionary[@"releaseNotes"]; } return self; } @end @interface VULUpdateTool ()<SKStoreProductViewControllerDelegate> typedef void (^CacheBlockData)(NSError *error, VULAppstoreInfo *info); @end @implementation VULUpdateTool + (VULUpdateTool *)shareInstance { static dispatch_once_t once; static id __singleton__; dispatch_once(&once, ^{ __singleton__ = [[self alloc] init]; }); return __singleton__; } - (instancetype)init { if (self = [super init]) { _remindDay = 1; } return self; } - (void)begin { __weak __typeof(self) weakSelf = self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSAssert(weakSelf.appleID.length > 0, @"you must give \'appleID\' a value"); NSAssert(weakSelf.curAppVersion.length > 0, @"you must give \'curAppVersion\' a value"); [weakSelf updateInfo:^(NSError *error, VULAppstoreInfo *info) { [weakSelf updateAppWithInfo:info]; }]; }); } /** * 从appstore获取app的信息 */ - (void)updateInfo:(CacheBlockData)block { NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/lookup?id=%@", self.appleID]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; request.HTTPBody = [[NSString stringWithFormat:@"id=%@", self.appleID] dataUsingEncoding:NSUTF8StringEncoding]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { dispatch_async(dispatch_get_main_queue(), ^{ if (!error) { NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSArray *appInfos = responseObject[@"results"]; if (!appInfos || appInfos.count <= 0) { block(nil, nil); } NSDictionary *appInfo = appInfos[0]; VULAppstoreInfo *appstoreInfo = [[VULAppstoreInfo alloc] initWithDictionary:appInfo]; block(nil, appstoreInfo); } else { block(error, nil); } }); }]; [task resume]; } /** * 根据app信息判断当前版本是否需要更新,以及更新逻辑。 用户点击忽略版本号时未记录版本号 会忽略所有的版本号 */ - (void)updateAppWithInfo:(VULAppstoreInfo *)updateInfo { if (!updateInfo) { return; } self.isUpdate = NO; if ([self.curAppVersion compare:updateInfo.version options:NSNumericSearch] == NSOrderedAscending) { self.isUpdate = YES; } if (self.isUpdate) { //需要升级 if ([VULUserDefaults boolForKey:@"ignoreVersion"]) { //忽略此版本,不需要更新 NSLog(@"用户忽略此版本更新"); return; } NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970]; NSTimeInterval savedInterval = [VULUserDefaults doubleForKey:@"newVersionTime"]; // NSString *title = [NSString stringWithFormat:@"有新版本%@更新", updateInfo.version]; //选择稍后更新,默认为3天后提示 if (timeInterval - savedInterval > self.remindDay * 24 * 60 * 60) { dispatch_async(dispatch_get_main_queue(), ^{ VULUpdatePopupView *updateview = [[VULUpdatePopupView alloc] initWithFrame:CGRectMake(0, 0, VULSCREEN_WIDTH, VULSCREEN_HEIGHT) withUpdateInfo:updateInfo]; [kWindow addSubview:updateview]; [updateview showUpdatePopupView]; updateview.GoToUpgradeBlock = ^{ SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init]; [storeViewController loadProductWithParameters:@{ SKStoreProductParameterITunesItemIdentifier: self.appleID } completionBlock:nil]; storeViewController.delegate = self; [self.controller presentViewController:storeViewController animated:YES completion:nil]; }; /* UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:updateInfo.releaseNotes preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"稍后提醒我" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { //稍后提醒 记录下当前时间 NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970]; [VULUserDefaults setDouble:timeInterval forKey:@"newVersionTime"]; }]; [alertController addAction:cancelAction]; UIAlertAction *updateAction = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //去更新 SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init]; [storeViewController loadProductWithParameters:@{SKStoreProductParameterITunesItemIdentifier:self.appleID} completionBlock:nil]; storeViewController.delegate = self; [self.controller presentViewController:storeViewController animated:YES completion:nil]; }]; [alertController addAction:updateAction]; UIAlertAction *laterAction = [UIAlertAction actionWithTitle:@"忽略此版本" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [VULUserDefaults setBool:YES forKey:@"ignoreVersion"]; }]; [alertController addAction:laterAction]; if (self.controller) { [self.controller presentViewController:alertController animated:YES completion:nil]; } else { NSLog(@"Error:controller is nil, and the update alertController can not be shown!"); } */ }); } else { NSLog(@"稍后提醒,未到更新时间"); } } else { NSLog(@"当前版本已是最新,不需要更新"); //重置升级标识 [VULUserDefaults removeObjectForKey:@"ignoreVersion"]; [VULUserDefaults removeObjectForKey:@"newVersionTime"]; } } - (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController { [viewController dismissViewControllerAnimated:YES completion:nil]; } - (BOOL)isUpdateBool { return self.isUpdate; } @end
//general--- const timestamp = new Date().getTime(); const root = document.documentElement; // css + font awesome document.head.insertAdjacentHTML('beforeend', ` <link rel="stylesheet" href="/static/main-CSS_JS/style-01.css?dev=${timestamp}"> <link rel="stylesheet" href="/static/vendor/fontawesome-06/css/all.css?dev=${timestamp}"> <style>:root {display:none;}</style> `); // to prevent unstyled HTML flashing window.addEventListener('load', () => { setTimeout(function() { // :root {display:none;} in the page. root.style.display = 'block'; }, 250);//ms }); // ------------------------------------------------------------------------------------------------------------------------------------- // theme control--- window.addEventListener('load', () => { const colorThemes = document.querySelectorAll('[name="theme"]'); // set theme when visitor returns const setTheme = function () { const activeTheme = localStorage.getItem("theme"); colorThemes.forEach((themeOption) => { if (themeOption.id === activeTheme) { themeOption.checked = true; } }); root.setAttribute('data-theme', activeTheme); }; // store theme const storeTheme = function (theme) { localStorage.setItem("theme", theme); }; // Initializing the theme function isThemeInLocalStorage() { return localStorage.getItem('theme') !== null; } if (isThemeInLocalStorage()) { // 'theme' exists in local storage console.log('Theme exists:', localStorage.getItem('theme')); } else { // 'theme' does not exist in local storage console.log('Theme does not exist in local storage'); root.setAttribute('data-theme', 'darkness'); localStorage.setItem("theme", 'darkness'); const activeTheme = localStorage.getItem("theme"); colorThemes.forEach((themeOption) => { if (themeOption.id === activeTheme) { themeOption.checked = true; } }); root.setAttribute('data-theme', activeTheme); } colorThemes.forEach((themeOption) => { themeOption.addEventListener("click", () => { storeTheme(themeOption.id); root.setAttribute('data-theme', themeOption.id); }); }); document.onload = setTheme(); }); // ------------------------------------------------------------------------------------------------------------------------------------- // header code--- class MyHeader extends HTMLElement { connectedCallback() { this.innerHTML = ` <!-- header / nav --> <style> my-header { position: relative; top: 0; left: 0; right: 0; z-index: 9999999; min-width: 100vw; margin-bottom: auto; backdrop-filter: blur(15px); box-shadow: 0px 1px 31px 1px var(--shadow-color); } header { display: flex; flex-direction: column; min-width: 100%; } header * { margin: 0; padding: 0; box-sizing: border-box; color: var(--primary-color); } nav { box-sizing: border-box; border-bottom: solid 1px var(--primary-color); min-width: 100%; display: flex; justify-content: space-between; margin: 0; padding: 9px 15px; } nav .logo { order: 1; font-weight: 900; } nav .logo a { text-decoration: none; } nav .icons { order: 3; display: flex; justify-content: center; align-items: center; gap: 15px; } nav #menu_toggle { cursor: pointer; display: none; } nav #theme_toggle { cursor: pointer; } .menu { order: 2; } .menu *{ text-decoration: none; list-style: none; font-weight: 500; } .menu ul { display: flex; gap: 15px; } #menu-1 { transform: translate(-3rem); } #menu-2 { display: none; justify-content: center; padding: 15px 5px; border-bottom: solid 1px var(--primary-color); animation: fade_in 250ms ease-in-out; } #menu-2 ul { flex-direction: column; } .themes { order: 5; padding: 10px 0; border-bottom: solid 1px var(--primary-color); display: none; justify-content: center; animation: fade_in 250ms ease-in-out; } /* style for different screens */ /* [laptop] */ @media screen and (min-width: 1025px){ } /* [ipad] */ @media screen and (min-width: 768px) and (max-width: 1024px) { nav #menu_toggle { display: block; } #menu-1 { display: none; } } /* [phone] */ @media screen and (max-width: 767px){ nav #menu_toggle { display: block; } #menu-1 { display: none; } } </style> <!-- themes options --> <style> .visually-hidden { clip: rect(0 0 0 0); clip-path: inset(50%); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } .color-picker > fieldset { border: 0; display: flex; gap: 1rem; width: fit-content; padding: 0; margin: 0; border-radius: 0 0 1rem 1rem; } .color-picker input[type="radio"] { appearance: none; width: .5rem; height: .5rem; aspect-ratio: 1/1; outline: 2px solid var(--radio-color, currentColor); outline-offset: 1.5px; border-radius: 50%; cursor: pointer; } .color-picker input[type="radio"]:checked { background-color: var(--radio-color); } .color-picker input[type="radio"]#light { --radio-color: rgb(188, 188, 255); } .color-picker input[type="radio"]#dark { --radio-color: rgb(81, 81, 172); } .color-picker input[type="radio"]#darkness { --radio-color: rgb(0, 0, 0); } </style> <!-- menu toggle icon --> <style> .menu_icon_animation svg { /* The size of the SVG defines the overall size */ height: 1.5rem; /* Define the transition for transforming the SVG */ transition: transform 750ms cubic-bezier(0.4, 0, 0.2, 1); cursor: pointer; } .line { fill: none; stroke: var(--primary-color); stroke-linecap: round; stroke-linejoin: round; stroke-width: 3; /* Define the transition for transforming the Stroke */ transition: stroke-dasharray 750ms cubic-bezier(0.4, 0, 0.2, 1), stroke-dashoffset 750ms cubic-bezier(0.4, 0, 0.2, 1); } .line-top-bottom { stroke-dasharray: 12 63; } .line-top-bottom { stroke-dasharray: 12 63; } .menu_icon_animation input:checked + svg { transform: rotate(-45deg); } .menu_icon_animation input:checked + svg .line-top-bottom { stroke-dasharray: 20 300; stroke-dashoffset: -32.42; } </style> <header> <nav> <div class="logo"><a href="/">Blockchain Demo - Miner</a></div> <div class="icons"> <label class="menu_icon_animation" for="toggle"> <input type="checkbox" id="toggle" style="display: none;"> <svg id="menu_toggle" viewBox="0 0 32 32"> <path class="line line-top-bottom" d="M27 10 13 10C10.8 10 9 8.2 9 6 9 3.5 10.8 2 13 2 15.2 2 17 3.8 17 6L17 26C17 28.2 18.8 30 21 30 23.2 30 25 28.2 25 26 25 23.8 23.2 22 21 22L7 22"></path> <path class="line" d="M7 16 27 16"></path> </svg> </label> <i id="theme_toggle" class="fa-solid fa-circle-half-stroke"></i> </div> <div id="menu-1" class="menu"> <ul> <li><a href="/mine_page">MINE</a></li> <li><a href="/configure">CONFIGURE</a></li> </ul> </div> </nav> <div id="menu-2" class="menu"> <ul> <li><a href="/mine_page">MINE</a></li> <li><a href="/configure">CONFIGURE</a></li> </ul> </div> <div id="themes" class="themes"> <form class="color-picker" action=""> <fieldset> <legend class="visually-hidden">Pick a color scheme</legend> <label for="light" class="visually-hidden">light theme</label> <input type="radio" id="light" name="theme"> <label for="dark" class="visually-hidden">dark theme</label> <input type="radio" id="dark" name="theme"> <label for="darkness" class="visually-hidden">darkness theme</label> <input type="radio" id="darkness" name="theme"> </fieldset> </form> </div> </header> ` } } customElements.define('my-header', MyHeader) // themes & nav menu toggles window.addEventListener('load', () => { document.getElementById('theme_toggle').addEventListener('click', function () { if (document.getElementById('themes').style.display == 'flex'){ document.getElementById('themes').style.display = 'none'; } else { document.getElementById('themes').style.display = 'flex'; } }); document.getElementById('menu_toggle').addEventListener('click', function () { if (document.getElementById('menu-2').style.display == 'flex'){ document.getElementById('menu-2').style.display = 'none'; } else { document.getElementById('menu-2').style.display = 'flex'; } }); }); // ------------------------------------------------------------------------------------------------------------------------------------- // footer code--- class MyFooter extends HTMLElement { connectedCallback() { this.innerHTML = ` <style> my-footer{ position: relative; bottom: 0; left: 0; right: 0; z-index: 9999999; min-width: 100vw; margin-top: auto; background: transparent; backdrop-filter: blur(15px); box-shadow: 0px 1px 31px 1px var(--shadow-color); } footer { min-width: 100%; box-sizing: border-box; border-top: solid 1px var(--primary-color); backdrop-filter: blur(15px); display: flex; flex-direction: column; justify-content: space-between; text-align: center; align-items: center; gap: 1rem; padding: 9px 15px; } footer a { color: var(--accent-color); text-decoration: none; } footer p { color: var(--accent-color); font-size: 0.75rem; } footer .social_media_container { width: 100%; display: flex; flex-wrap: wrap; justify-content: center; gap: 7px; } footer .social_media_container a i { font-size: 1.75rem; color: var(--text-color); } footer .social_media_container a i:hover { transform: scale(1.15); transition: transform 0.25s ease-out; color: var(--accent-color); } footer .social_media_container a i:not(hover) { transform: scale(1); transition: transform 0.25s ease-out; } footer .copyright p a { color: var(--text-color); } </style> <footer> <div class="social_media_container"> <a href="https://facebook.com/" target="_blank" aria-placeholder="hello"><i class="fa-brands fa-square-facebook"></i></a> <a href="https://instagram.com/FaisalBj1" target="_blank"><i class="fa-brands fa-square-instagram"></i></a> <a href="https://t.snapchat.com/Eo0muP3W" target="_blank"><i class="fa-brands fa-square-snapchat"></i></a> <a href="https://x.com/FaisalBj1" target="_blank"><i class="fa-brands fa-square-x-twitter"></i></a> <a href="https://wa.me/+966562629866" target="_blank"><i class="fa-brands fa-square-whatsapp"></i></a> <a href="https://www.linkedin.com/in/faisal-banjar-943b791ba/" target="_blank"><i class="fa-brands fa-linkedin"></i></a> <a href="https://github.com/FaisalBj1" target="_blank"><i class="fa-brands fa-square-github"></i></a> </div> <div class='copyright'> <p>Copyright ©${new Date().getFullYear()} All rights reserved | Desined & Developed by <a href="http://FaisalBj1.com" target="_blank">FaisalBj1</a></p> </div> </footer> ` } } customElements.define('my-footer', MyFooter) // ------------------------------------------------------------------------------------------------------------------------------------- // TEST---
# Copyright Materialize, Inc. and contributors. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software will be governed # by the Apache License, Version 2.0. # # Test the BOOLEAN data type # # Insert data pre-snapshot $ postgres-execute connection=postgres://postgres:postgres@postgres ALTER USER postgres WITH replication; DROP SCHEMA IF EXISTS public CASCADE; DROP PUBLICATION IF EXISTS mz_source; CREATE SCHEMA public; # set up boolean CREATE TABLE t_boolean_array (c boolean[]); ALTER TABLE t_boolean_array REPLICA IDENTITY FULL; INSERT INTO t_boolean_array VALUES ('{true,false}'); # set up smallint CREATE TABLE t_smallint_array (c smallint[]); ALTER TABLE t_smallint_array REPLICA IDENTITY FULL; INSERT INTO t_smallint_array VALUES ('{1,2}'); # set up integer CREATE TABLE t_integer_array (c integer[]); ALTER TABLE t_integer_array REPLICA IDENTITY FULL; INSERT INTO t_integer_array VALUES ('{1,2}'); # set up bigint CREATE TABLE t_bigint_array (c bigint[]); ALTER TABLE t_bigint_array REPLICA IDENTITY FULL; INSERT INTO t_bigint_array VALUES ('{1,2}'); # set up date CREATE TABLE t_date_array (c date[]); ALTER TABLE t_date_array REPLICA IDENTITY FULL; INSERT INTO t_date_array VALUES ('{''2007-02-01'',''2007-02-02''}'); # set up double_precision CREATE TABLE t_double_precision_array (c double precision[]); ALTER TABLE t_double_precision_array REPLICA IDENTITY FULL; INSERT INTO t_double_precision_array VALUES ('{1.1,2.1}'); # set up interval CREATE TABLE t_interval_array (c interval[]); ALTER TABLE t_interval_array REPLICA IDENTITY FULL; INSERT INTO t_interval_array VALUES ('{''1y'',''2d''}'); # set up numeric CREATE TABLE t_numeric_array (c numeric[]); ALTER TABLE t_numeric_array REPLICA IDENTITY FULL; INSERT INTO t_numeric_array VALUES ('{1.1,2E2}'); # set up oid CREATE TABLE t_oid_array (c oid[]); ALTER TABLE t_oid_array REPLICA IDENTITY FULL; INSERT INTO t_oid_array VALUES ('{123,234}'); # set up real CREATE TABLE t_real_array (c real[]); ALTER TABLE t_real_array REPLICA IDENTITY FULL; INSERT INTO t_real_array VALUES ('{1.1,2.1}'); # set up text CREATE TABLE t_text_array (c text[]); ALTER TABLE t_text_array REPLICA IDENTITY FULL; INSERT INTO t_text_array VALUES ('{a,b}'); # set up time CREATE TABLE t_time_array (c time[]); ALTER TABLE t_time_array REPLICA IDENTITY FULL; INSERT INTO t_time_array VALUES ('{''01:23:45'',''01:23:46''}'); # set up timestamp CREATE TABLE t_timestamp_array (c timestamp[]); ALTER TABLE t_timestamp_array REPLICA IDENTITY FULL; INSERT INTO t_timestamp_array VALUES ('{''2007-02-01 15:04:05'',''2007-02-01 15:04:06''}'); # set up timestamptz CREATE TABLE t_timestamptz_array (c timestamp with time zone[]); ALTER TABLE t_timestamptz_array REPLICA IDENTITY FULL; INSERT INTO t_timestamptz_array VALUES ('{''2007-02-01 15:04:05+06'',''2007-02-01 15:04:06+06''}'); CREATE PUBLICATION mz_source FOR ALL TABLES; > CREATE SECRET pgpass AS 'postgres' > CREATE CONNECTION pg TO POSTGRES ( HOST postgres, DATABASE postgres, USER postgres, PASSWORD SECRET pgpass ) > CREATE SOURCE mz_source FROM POSTGRES CONNECTION pg (PUBLICATION 'mz_source') FOR ALL TABLES; # Insert the same data post-snapshot $ postgres-execute connection=postgres://postgres:postgres@postgres # rewrite boolean INSERT INTO t_boolean_array SELECT * FROM t_boolean_array; # rewrite smallint INSERT INTO t_smallint_array SELECT * FROM t_smallint_array; # rewrite integer INSERT INTO t_integer_array SELECT * FROM t_integer_array; # rewrite bigint INSERT INTO t_bigint_array SELECT * FROM t_bigint_array; # rewrite date INSERT INTO t_date_array SELECT * FROM t_date_array; # rewrite double_precision INSERT INTO t_double_precision_array SELECT * FROM t_double_precision_array; # rewrite interval INSERT INTO t_interval_array SELECT * FROM t_interval_array; # rewrite numeric INSERT INTO t_numeric_array SELECT * FROM t_numeric_array; # rewrite oid INSERT INTO t_oid_array SELECT * FROM t_oid_array; # rewrite real INSERT INTO t_real_array SELECT * FROM t_real_array; # rewrite text INSERT INTO t_text_array SELECT * FROM t_text_array; # rewrite time INSERT INTO t_time_array SELECT * FROM t_time_array; # rewrite timestamp INSERT INTO t_timestamp_array SELECT * FROM t_timestamp_array; # rewrite timestamptz INSERT INTO t_timestamptz_array SELECT * FROM t_timestamptz_array; # read boolean > SELECT pg_typeof(c) FROM t_boolean_array LIMIT 1; boolean[] > SELECT * FROM t_boolean_array; {true,false} {true,false} # read smallint > SELECT pg_typeof(c) FROM t_smallint_array LIMIT 1; smallint[] > SELECT * FROM t_smallint_array; {1,2} {1,2} # read integer > SELECT pg_typeof(c) FROM t_integer_array LIMIT 1; integer[] > SELECT * FROM t_integer_array; {1,2} {1,2} # read bigint > SELECT pg_typeof(c) FROM t_bigint_array LIMIT 1; bigint[] > SELECT * FROM t_bigint_array; {1,2} {1,2} # read date > SELECT pg_typeof(c) FROM t_date_array LIMIT 1; date[] > SELECT * FROM t_date_array; {2007-02-01,2007-02-02} {2007-02-01,2007-02-02} # read double_precision > SELECT pg_typeof(c) FROM t_double_precision_array LIMIT 1; "double precision[]" > SELECT * FROM t_double_precision_array; {1.1,2.1} {1.1,2.1} # read interval > SELECT pg_typeof(c) FROM t_interval_array LIMIT 1; interval[] > SELECT * FROM t_interval_array; "{1 year,2 days}" "{1 year,2 days}" # read numeric > SELECT pg_typeof(c) FROM t_numeric_array LIMIT 1; numeric[] > SELECT * FROM t_numeric_array; {1.1,200} {1.1,200} # read oid > SELECT pg_typeof(c) FROM t_oid_array LIMIT 1; oid[] > SELECT * FROM t_oid_array; {123,234} {123,234} # read real > SELECT pg_typeof(c) FROM t_real_array LIMIT 1; real[] > SELECT * FROM t_real_array; {1.1,2.1} {1.1,2.1} # read text > SELECT pg_typeof(c) FROM t_text_array LIMIT 1; text[] > SELECT * FROM t_text_array; {a,b} {a,b} # read time > SELECT pg_typeof(c) FROM t_time_array LIMIT 1; time[] > SELECT * FROM t_time_array; {01:23:45,01:23:46} {01:23:45,01:23:46} # read timestamp > SELECT pg_typeof(c) FROM t_timestamp_array LIMIT 1; "timestamp without time zone[]" > SELECT * FROM t_timestamp_array; "{2007-02-01 15:04:05,2007-02-01 15:04:06}" "{2007-02-01 15:04:05,2007-02-01 15:04:06}" # read timestamptz > SELECT pg_typeof(c) FROM t_timestamptz_array LIMIT 1; "timestamp with time zone[]" > SELECT * FROM t_timestamptz_array; "{2007-02-01 09:04:05 UTC,2007-02-01 09:04:06 UTC}" "{2007-02-01 09:04:05 UTC,2007-02-01 09:04:06 UTC}" # cannot handle multi-dimensional arrays $ postgres-execute connection=postgres://postgres:postgres@postgres INSERT INTO t_integer_array VALUES ('{{1},{2}}'); INSERT INTO t_integer_array SELECT * FROM t_integer_array; > SELECT * FROM t_integer_array; {1,2} {1,2} {1,2} {1,2} {{1},{2}} {{1},{2}}
package tn.mbhc.tudev.spring.rest.app; import java.text.MessageFormat; import java.util.List; import java.util.Optional; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Profile; import org.springframework.web.client.RestTemplate; import tn.mbhc.tudev.spring.rest.core.parser.ProductsParser; import tn.mbhc.tudev.spring.rest.core.provider.DataProvider; import tn.mbhc.tudev.spring.rest.core.provider.RestDataProviderImpl; import tn.mbhc.tudev.spring.rest.data.Product; import tn.mbhc.tudev.spring.rest.utils.LocalStringUtils; //The app class is not in the base backage @ComponentScan(basePackages = "tn.mbhc.tudev") @SpringBootApplication public class ConsumingRestServiceApplication { private static final Logger LOGGER = Logger.getLogger(ConsumingRestServiceApplication.class.getSimpleName()); private static final String SEPARATOR_REPEAT = LocalStringUtils.repeat("-", 80); /** * Launcher function * @param args */ public static void main(String[] args) { SpringApplication.run(ConsumingRestServiceApplication.class, args); } /* * Properties */ @Value("${spring.application.data.provider.one_product_rest_url}") private String oneProductRestUrl; @Value("${spring.application.data.provider.list_of_product_rest_url}") private String listOfProductsRestUrl; /* * Beans */ @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } @Bean public DataProvider dataProvider(RestTemplate restTemplate) { return new RestDataProviderImpl(restTemplate, productsParser()); } @Bean public ProductsParser productsParser() { return new ProductsParser(); } @Bean @Profile("!test") public CommandLineRunner run(RestTemplate restTemplate) throws Exception { return args -> { DataProvider dataProvider = dataProvider(restTemplate); LOGGER.info(MessageFormat.format("Fetching products from REST Api : {0}", oneProductRestUrl)); LOGGER.info(SEPARATOR_REPEAT); Optional<Product> optionalProduct = dataProvider.getOne(); optionalProduct.ifPresent(value -> LOGGER.info(MessageFormat.format("One product (ignoring null fields) : {0} ", optionalProduct.get()))); LOGGER.info(SEPARATOR_REPEAT); LOGGER.info(MessageFormat.format("Fetching a list of products (ignoring null fields) : {0}", listOfProductsRestUrl)); LOGGER.info(SEPARATOR_REPEAT); List<Product> products = dataProvider.getList(); LOGGER.info("List of Products : "); products.forEach(product -> LOGGER.info(MessageFormat.format("{0}", product))); }; } }
import { Alert, Platform } from 'react-native' import { check, PERMISSIONS, RESULTS, request, openSettings, Permission, } from 'react-native-permissions' export enum PermissionStatus { granted, denied, unavailable, } const CAMERA_PERMISSIONS = { ios: PERMISSIONS.IOS.CAMERA, android: PERMISSIONS.ANDROID.CAMERA, } const BIOMETRY_PERMISSIONS = { ios: PERMISSIONS.IOS.FACE_ID, } const APP_TRACKING_TRANSPARENCY = { ios: PERMISSIONS.IOS.APP_TRACKING_TRANSPARENCY, } const REQUEST_PERMISSION_TYPE = { camera: CAMERA_PERMISSIONS, biometry: BIOMETRY_PERMISSIONS, appTrackingTransparency: APP_TRACKING_TRANSPARENCY, } export const PERMISSION_TYPE = { camera: 'camera', biometry: 'biometry', appTrackingTransparency: 'appTrackingTransparency', } export const usePermission = () => { const requestPermission = async (permissions: Permission) => { try { const granted = await request(permissions) if (granted === RESULTS.GRANTED) { return true } return false } catch (err) { return false } } const checkPermission = async (type: String) => { const permissions = REQUEST_PERMISSION_TYPE[type][Platform.OS] const result = await check(permissions) switch (result) { case RESULTS.UNAVAILABLE: return PermissionStatus.unavailable case RESULTS.DENIED: return PermissionStatus.denied case RESULTS.GRANTED: return PermissionStatus.granted } } const showPermissionDialog = async (type: String) => { const permissions = REQUEST_PERMISSION_TYPE[type][Platform.OS] try { const result = await check(permissions) switch (result) { case RESULTS.UNAVAILABLE: return false case RESULTS.BLOCKED: if (type === 'camera') { Alert.alert( 'Camera permission', 'OBL Wallet need camera permission to read barcode', [ { text: 'Go to Settings', onPress: () => openSettings(), style: 'cancel', }, { text: 'Cancel', style: 'default', onPress: () => { return false }, }, ], ) } else if (type === 'biometry') { Alert.alert( 'Face ID permission', 'We need your FaceID permission for authenticate faster', [ { text: 'Go to Settings', onPress: () => openSettings(), style: 'cancel', }, { text: 'Cancel', style: 'default', onPress: () => { return false }, }, ], ) } break case RESULTS.DENIED: break case RESULTS.GRANTED: return true } return requestPermission(permissions) } catch (err) { return false } } return { checkPermission, showPermissionDialog, } }
/* Copyright 2013-2021 Paul Colby This file is part of QtAws. QtAws is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. QtAws is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the QtAws. If not, see <http://www.gnu.org/licenses/>. */ #ifndef QTAWS_SIMPLEDBCLIENT_H #define QTAWS_SIMPLEDBCLIENT_H #include "core/awsabstractclient.h" #include "qtawssimpledbglobal.h" class QNetworkReply; namespace QtAws { namespace SimpleDB { class SimpleDBClientPrivate; class BatchDeleteAttributesRequest; class BatchDeleteAttributesResponse; class BatchPutAttributesRequest; class BatchPutAttributesResponse; class CreateDomainRequest; class CreateDomainResponse; class DeleteAttributesRequest; class DeleteAttributesResponse; class DeleteDomainRequest; class DeleteDomainResponse; class DomainMetadataRequest; class DomainMetadataResponse; class GetAttributesRequest; class GetAttributesResponse; class ListDomainsRequest; class ListDomainsResponse; class PutAttributesRequest; class PutAttributesResponse; class SelectRequest; class SelectResponse; class QTAWSSIMPLEDB_EXPORT SimpleDBClient : public QtAws::Core::AwsAbstractClient { Q_OBJECT public: SimpleDBClient( const QtAws::Core::AwsRegion::Region region = QtAws::Core::AwsRegion::InvalidRegion, QtAws::Core::AwsAbstractCredentials * credentials = NULL, QNetworkAccessManager * const manager = NULL, QObject * const parent = 0); explicit SimpleDBClient( const QUrl &endpoint, QtAws::Core::AwsAbstractCredentials * credentials = NULL, QNetworkAccessManager * const manager = NULL, QObject * const parent = 0); public slots: BatchDeleteAttributesResponse * batchDeleteAttributes(const BatchDeleteAttributesRequest &request); BatchPutAttributesResponse * batchPutAttributes(const BatchPutAttributesRequest &request); CreateDomainResponse * createDomain(const CreateDomainRequest &request); DeleteAttributesResponse * deleteAttributes(const DeleteAttributesRequest &request); DeleteDomainResponse * deleteDomain(const DeleteDomainRequest &request); DomainMetadataResponse * domainMetadata(const DomainMetadataRequest &request); GetAttributesResponse * getAttributes(const GetAttributesRequest &request); ListDomainsResponse * listDomains(const ListDomainsRequest &request); PutAttributesResponse * putAttributes(const PutAttributesRequest &request); SelectResponse * select(const SelectRequest &request); private: Q_DECLARE_PRIVATE(SimpleDBClient) Q_DISABLE_COPY(SimpleDBClient) }; } // namespace SimpleDB } // namespace QtAws #endif
import React from "react"; import { Box, Sprite, InfoTable } from "@/components"; import { Skill } from "@/models"; import { getHighlightedElements } from "@/utils/getHighlightedElements"; import { styled } from "@/styles"; export interface IdolSkillBoxProps { title: string; skills?: Skill[]; } const IdolSkillBoxStyled = styled(Box, { width: "500px", "& > main": { padding: 0, }, }); const SkillName = styled("div", { padding: "$2", fontSize: "20px", display: "flex", alignItems: "center", }); const DescOnly = styled("div", { padding: "0 $2 $2 $2", }); export const IdolSkillBox = ({ title, skills }: IdolSkillBoxProps) => { return ( <IdolSkillBoxStyled label={title}> {skills?.map((skill) => ( <React.Fragment key={skill?.name}> <SkillName> <Sprite type="skills" name={skill?.name} showBackground={false} /> {skill?.name} </SkillName> {skill?.levels?.length === 1 ? ( <DescOnly>{skill?.levels[0].desc}</DescOnly> ) : ( <InfoTable> <tbody> {skill?.levels.map((level) => ( <tr key={level.level}> <td className="name">Level {level.level}</td> <td>{getHighlightedElements(level.desc)}</td> </tr> ))} </tbody> </InfoTable> )} </React.Fragment> ))} </IdolSkillBoxStyled> ); };
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <table id="calendar"> </table> </body> <script> const weekDays = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'] function createElement(tag, innerText) { const result = document.createElement(tag) result.innerText = innerText return result } function getWeekHeader() { const tr = document.createElement('tr') tr.append(...weekDays.map(w => createElement('th', w))) return tr } function createTable(elem, year, month) { elem.append(getWeekHeader()) const date = new Date(year, month) console.log(date) const offset = date.getDay(); const totalDays = new Date(year, month + 1, 0).getDate() let day = 1; for (let y = 0; y < 5; ++y) { let tr = document.createElement('tr') for (let x = 0; x < 7; ++x) { const td = document.createElement('td') if (++day > offset && (day - offset) <= totalDays) td.innerText = (day - offset) + '' tr.append(td) } elem.append(tr) } } const calendar = document.getElementById('calendar') createTable(calendar, 2023, 2) </script> </html>
import React, {useState} from "react"; import styles from './Paginator.module.css'; let Paginator = ({totalItemsCount, pageSize, currentPage, onPageChanged, portionSize = 10 }) => { let pagesCount = Math.ceil(totalItemsCount / pageSize); let pages = []; for (let i = 1; i <= pagesCount; i++) { pages.push(i); } const portionCount = Math.ceil( pagesCount/portionSize); const [portionNumber, setPortionNumber] = useState(1); const leftPortionPageNumber = (portionNumber-1) * portionSize+ 1; const rightPortionPageNumber = portionNumber * portionSize; return <div className={styles.paginator}> {portionNumber>1 && <button onClick={()=>{ setPortionNumber(portionNumber-1)}}> &#60; </button>} {pages .filter(p=> p>=leftPortionPageNumber && p<=rightPortionPageNumber) .map(p => { return <span className={currentPage === p && styles.selectedPage} onClick={() => { onPageChanged(p) }}>{p} </span> })} { portionCount > portionNumber && <button onClick={()=>{ setPortionNumber(portionNumber+1)}}> &#62; </button>} </div> }; export default Paginator;
/* * Copyright 2009-2012 by KNURT Systeme (http://www.knurt.de) * * Licensed under the Creative Commons License Attribution-NonCommercial-ShareAlike 3.0 Unported; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://creativecommons.org/licenses/by-nc-sa/3.0/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.knurt.fam.news; import java.util.Date; /** * The default news item - a simple bean of the attributes. * * @author Daniel Oltmanns <info@knurt.de> * @since 1.5.0 (07/29/2011) * */ public class NewsItemDefault implements NewsItem { private Date eventStarts, eventEnds; private String linkToFurtherInformation, description; /** {@inheritDoc} */ @Override public Date getEventStarts() { return eventStarts; } /** {@inheritDoc} */ @Override public void setEventStarts(Date eventStarts) { this.eventStarts = eventStarts; } /** {@inheritDoc} */ @Override public Date getEventEnds() { return eventEnds; } /** {@inheritDoc} */ @Override public void setEventEnds(Date eventEnds) { this.eventEnds = eventEnds; } /** {@inheritDoc} */ @Override public String getLinkToFurtherInformation() { return linkToFurtherInformation; } /** {@inheritDoc} */ @Override public void setLinkToFurtherInformation(String linkToFurtherInformation) { this.linkToFurtherInformation = linkToFurtherInformation; } /** {@inheritDoc} */ @Override public String getDescription() { return description; } /** {@inheritDoc} */ @Override public void setDescription(String description) { this.description = description; } /** {@inheritDoc} */ @Override public int compareTo(NewsItem o) { if (this.getEventStarts() == null) return 1; else return this.getEventStarts().before(o.getEventStarts()) ? -1 : 1; } }
import { MainContent } from "@liexp/ui/lib/components/MainContent"; import EventSliderModal, { type EventSliderModalProps, } from "@liexp/ui/lib/components/Modal/EventSliderModal"; import { type Meta, type StoryFn } from "@storybook/react"; import * as React from "react"; const meta: Meta<EventSliderModalProps> = { title: "Components/Modal/EventSliderModal", component: EventSliderModal, argTypes: { query: {}, }, }; export default meta; const Template: StoryFn<EventSliderModalProps> = ({ query: _query, ...props }) => { const [query, setQuery] = React.useState({ eventType: undefined, title: undefined, actors: [], groups: [], groupsMembers: [], keywords: [], media: [], links: [], locations: undefined, startDate: undefined, endDate: undefined, exclude: undefined, withDeleted: undefined, withDrafts: undefined, draft: undefined, _sort: null, _order: null, ..._query, }); const onQueryChange = (q: any): void => { setQuery({ ...query, ...q }); }; return ( <MainContent> <EventSliderModal open={true} {...props} query={query} onQueryChange={onQueryChange} onActorClick={(a) => { onQueryChange({ actors: [a.id], }); }} onKeywordClick={(k) => { onQueryChange({ keywords: [k.id], }); }} /> </MainContent> ); }; const ExampleSliderModal = Template.bind({}); ExampleSliderModal.args = { query: { hash: "event-slider-modal-story", }, onClick: () => {}, }; export { ExampleSliderModal };
package chap01; import java.util.ArrayList; import java.util.Collections; public class ArrayListEx1 { public static void main(String[] args) { ArrayList list1 = new ArrayList(10); // ArrayList는 용량이 부족하면 자동으로 추가한다 list1.add(new Integer(5)); list1.add(4); list1.add(2); list1.add(0); list1.add(1); list1.add(3); ArrayList list2 = new ArrayList(list1.subList(1, 4)); // list1의 1~3번 인덱스에 해당하는 값을 가진 list2를 만든다 print(list1, list2); Collections.sort(list1); // list1을 정렬 Collections.sort(list2); // list2를 정렬 print(list1, list2); // list1에 지정된 list2의 모든 요소가 포함되어 있으면 true반환 System.out.println("list1.containsAll(list2): " + list1.containsAll(list2)); System.out.println(); list2.add("B"); // list2에 문자열 B를 추가 list2.add("C"); // list2에 문자열 C를 추가 list2.add(3, "A"); // list2의 3번 인덱스 위치에 문자열 A을 추가 print(list1, list2); list2.set(3, "AA"); // set 메서드는 지정한 인덱스위치의 값을 덮어쓰기 함 print(list1, list2); // list1에서 list2와 겹치는 부분만 남기고 나머지는 삭제한다. System.out.println("list1.retainAll(list2): " + list1.retainAll(list2)); print(list1, list2); // list2에서 list1에 포함된 객체들을 삭제한다. // ArrayList의 앞에서 부터 삭제하면 앞 인덱스가 삭제된 후 재정렬 하기 때문에 의도대로 삭제되지 않는다. for (int i = list2.size() - 1; i >= 0; i--) { if (list1.contains(list2.get(i))) { list2.remove(i); } // end if } // end for print(list1, list2); }// end main static void print(ArrayList list1, ArrayList list2) { System.out.println("list1: " + list1); System.out.println("list2: " + list2); System.out.println(); }// end print }// end ArrayListEx1
// // GameScene.swift // Failing Boxes // // Created by Aasem Hany on 07/12/2022. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var balls = ["ballRed","ballBlue","ballGreen","ballCyan","ballGrey","ballYellow","ballPurple"] var ballLimit = 5 { didSet { ballsLimitLabel.text = "Balls Limit: \(ballLimit)" } } var scoreLabel: SKLabelNode! var editLabel: SKLabelNode! var ballsLimitLabel: SKLabelNode! var isEditing = false { didSet { editLabel.text = isEditing ? "Done" : "Edit" } } var score = 0 { didSet { scoreLabel.text = "Score: \(score)" } } override func didMove(to view: SKView) { /// Create SpriteNode let background = SKSpriteNode(imageNamed: "background") /// Position it to the middle of the screen background.position = CGPoint(x: 512 , y: 384) background.blendMode = .replace background.zPosition = -1 configureScoreLabel() configureEditingLabel() configureBallLimitLabel() /// Add it to the game scene addChild(background) physicsBody = SKPhysicsBody(edgeLoopFrom: frame) physicsWorld.contactDelegate = self makeGoodSlot(at: CGPoint(x: 128, y: 50)) makeBadSlot(at: CGPoint(x: 384, y: 50)) makeGoodSlot(at: CGPoint(x: 640, y: 50)) makeBadSlot(at: CGPoint(x: 896, y: 50)) makeBouncer(at: CGPoint(x: 0, y: 50)) makeBouncer(at: CGPoint(x: 256, y: 50)) makeBouncer(at: CGPoint(x: 512, y: 50)) makeBouncer(at: CGPoint(x: 768, y: 50)) makeBouncer(at: CGPoint(x: 1024, y: 50)) } func configureBallLimitLabel() { ballsLimitLabel = SKLabelNode(text: "Balls Limit: 5") ballsLimitLabel.fontName = "Chalkduster" ballsLimitLabel.position = CGPoint(x: 470, y: 670) addChild(ballsLimitLabel) } func configureEditingLabel() { editLabel = SKLabelNode(text: "Edit") editLabel.fontName = "Chalkduster" editLabel.position = CGPoint(x: 50, y: 670) addChild(editLabel) } func configureScoreLabel() { scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.text = "Score: 0" scoreLabel.horizontalAlignmentMode = .right scoreLabel.position = CGPoint(x: 990, y: 670) addChild(scoreLabel) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { /// Get the first touch guard let touch = touches.first else {return} /// Get the location of that first touch in the GameScene let locationOfTouch = touch.location(in: self) let objects = nodes(at: locationOfTouch) if objects.contains(editLabel) { isEditing.toggle() }else{ if isEditing { let obstacle = SKSpriteNode(color: UIColor(red: CGFloat.random(in: 0...1), green: CGFloat.random(in: 0...1), blue: CGFloat.random(in: 0...1), alpha: 1), size: CGSize(width: CGFloat.random(in: 16...128), height: 16)) obstacle.name = "obstacle" obstacle.position = locationOfTouch obstacle.physicsBody = SKPhysicsBody(rectangleOf: obstacle.size) obstacle.physicsBody?.isDynamic = false obstacle.zRotation = CGFloat.random(in: 0...3) addChild(obstacle) }else{ if locationOfTouch.y<500 || ballLimit <= 0 {return} /// Create a ball ballLimit -= 1 let ball = SKSpriteNode(imageNamed: balls.randomElement() ?? "ballRed") ball.name = "ball" ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2) ball.physicsBody!.restitution = 0.4 ball.physicsBody!.contactTestBitMask = ball.physicsBody!.categoryBitMask ball.position = locationOfTouch /// Add that ball to the GameScene addChild(ball) } } } func makeBouncer(at position:CGPoint) { let bouncer = SKSpriteNode(imageNamed: "bouncer") bouncer.position = position bouncer.physicsBody = SKPhysicsBody(circleOfRadius: bouncer.size.width/2) bouncer.physicsBody!.isDynamic = false addChild(bouncer) } func makeBadSlot(at position:CGPoint) { let badSlot = SKSpriteNode(imageNamed: "slotBaseBad") badSlot.name = "bad" badSlot.physicsBody = SKPhysicsBody(rectangleOf: badSlot.size) badSlot.physicsBody!.isDynamic = false badSlot.position = position let slotBadGlow = SKSpriteNode(imageNamed: "slotGlowBad") slotBadGlow.position = position let spin = SKAction.rotate(byAngle: .pi, duration: 10) let spinForever = SKAction.repeatForever(spin) slotBadGlow.run(spinForever) addChild(badSlot) addChild(slotBadGlow) } func makeGoodSlot(at position:CGPoint) { let goodSlot = SKSpriteNode(imageNamed: "slotBaseGood") goodSlot.name = "good" goodSlot.physicsBody = SKPhysicsBody(rectangleOf: goodSlot.size) goodSlot.physicsBody!.isDynamic = false goodSlot.position = position let slotGoodGlow = SKSpriteNode(imageNamed: "slotGlowGood") slotGoodGlow.position = position let spin = SKAction.rotate(byAngle: .pi, duration: 10) let spinForever = SKAction.repeatForever(spin) slotGoodGlow.run(spinForever) addChild(goodSlot) addChild(slotGoodGlow) } func didBegin(_ contact: SKPhysicsContact) { guard let nodeA = contact.bodyA.node else {return} guard let nodeB = contact.bodyB.node else {return} if nodeA.name == "ball" { collision(between: nodeA, object: nodeB) }else if nodeB.name == "ball" { collision(between: nodeB, object: nodeA) } } func collision(between ball:SKNode,object:SKNode) { if object.name == "good" { destroy(ball) score += 1 ballLimit += 1 } if object.name == "bad" { destroy(ball) score -= 1 } if object.name == "obstacle" { object.removeFromParent() } } func destroy(_ ball: SKNode){ if let particles = SKEmitterNode(fileNamed: "FireParticles"){ particles.position = ball.position addChild(particles) } ball.removeFromParent() } }
<template> <div class="tab-bar-item" @click="itemClick"> <div v-if="!isActive"> <slot name="item-icon"></slot> </div> <div v-else> <slot name="item-icon-active"></slot> </div> <div :style="activeStyle"> <slot name="item-text"></slot> </div> </div> </template> <script> export default { name: 'TabBarItem', props: { path: String, activeColor: { type: String, default: "red" } }, data(){ return { } }, computed: { isActive (){ return this.$route.path.includes(this.path) }, activeStyle (){ return this.isActive ? {color: this.activeColor}: {} } }, methods: { itemClick(){ this.$router.replace(this.path) } } } </script> <style> .tab-bar-item { flex: 1; height: 49px; text-align: center; font-size: 14px; } .tab-bar-item img { width: 24px; height: 24px; bottom: 20px; margin-top: 3px; vertical-align: middle; margin-bottom: 2px; } </style>
import { v4 as uuidv4 } from 'uuid'; export interface ITranslation { _id: string; language: 'en' | 'ua'; text: string; } export interface IAboutHeaderData { _id: string; imgPhath: string; translations: ITranslation[]; } const aboutHeaderData: IAboutHeaderData[] = [ { translations: [ { language: 'en', text: 'We bring together donors, volunteers, and beneficiaries.', _id: uuidv4(), }, { language: 'ua', text: 'Ми об’єднуємо донорів, волонтерів та бенефіціарів.', _id: uuidv4(), }, ], _id: uuidv4(), imgPhath: 'image-1.jpg', }, { translations: [ { language: 'en', text: 'Provide guiding light for the millions of Ukrainians', _id: uuidv4(), }, { language: 'ua', text: 'Дати дороговказ для мільйонів українців', _id: uuidv4(), }, ], _id: uuidv4(), imgPhath: 'image-2.jpg', }, { translations: [ { language: 'en', text: 'Cultivate a compassionate community that unites displaced Ukrainians', _id: uuidv4(), }, { language: 'ua', text: 'Розвивайте співчутливу спільноту, яка об’єднує переміщених українців', _id: uuidv4(), }, ], _id: uuidv4(), imgPhath: 'image-3.jpg', }, { translations: [ { language: 'en', text: 'Illuminate the path toward stability, justice, and the promise of a new start', _id: uuidv4(), }, { language: 'ua', text: 'Освітлюйте шлях до стабільності, справедливості та обіцянки нового початку', _id: uuidv4(), }, ], _id: uuidv4(), imgPhath: 'image-4.jpg', }, ]; export default aboutHeaderData;
<div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h3 class="text-theme-primary">{{ formStatus }} Post</h3> <p class="mb-5">Lorem ipsum dolor sit amet.</p> </div> </div> <form [formGroup]="postForm" (ngSubmit)="onSubmit()"> <div class="row"> <div class="col-md-7"> <div class="card shadow-effect"> <div class="card-body"> <div class="form-group"> <label for="Title">Title</label> <input type="text" class="form-control" formControlName="title" [ngClass]="{ 'is-invalid': fc['title'].touched && fc['title'].invalid }" (keyup)="onTitleChanged($event)" /> <!-- Structure pour verifie que le champ et valid et non pas vide --> <div *ngIf="fc['title'].errors?.['required']"> <div class="alert alert-danger" *ngIf="fc['title'].touched && fc['title'].invalid" > Title is required . </div> </div> <div *ngIf="fc['title'].errors?.['minLength']"> <div class="alert alert-danger" *ngIf="fc['title'].touched && fc['title'].invalid" > Title is required . </div> </div> </div> <div class="form-group"> <label for="Title">PermeLink</label> <input type="text" class="form-control" [(ngModel)]="permaLink" name="permaLink" formControlName="permaLink" [ngClass]="{ 'is-invalid': fc['permaLink'].touched && fc['permaLink'].invalid }" /> <div *ngIf="fc['permaLink'].errors?.['required']"> <div class="alert alert-danger" *ngIf="fc['permaLink'].touched && fc['permaLink'].invalid" > permaLink is required . </div> </div> </div> <div class="form-group"> <label for="Title">Excerpt</label> <textarea name="" class="form-control" id="" cols="30" rows="10" formControlName="excerpt" [ngClass]="{ 'is-invalid': fc['excerpt'].touched && fc['excerpt'].invalid }" ></textarea> <div *ngIf="fc['excerpt'].errors?.['required']"> <div class="alert alert-danger" *ngIf="fc['excerpt'].touched && fc['excerpt'].invalid" > excerpt is required . </div> </div> </div> </div> </div> </div> <div class="col-md-5"> <div class="card shadow-effect"> <div class="card-body"> <div class="form-group"> <label for="">Please select a post categorie</label> <select name="" id="" class="form-control" formControlName="categorie" [ngClass]="{ 'is-invalid': fc['categorie'].touched && fc['categorie'].invalid }" > <option>Please select Categorie</option> <option *ngFor="let categorie of categories" value=" {{ categorie.id }}-{{ categorie.data.categorie }}" > {{ categorie.data.categorie }} </option> </select> <div *ngIf="fc['categorie'].errors?.['required']"> <div class="alert alert-danger" *ngIf="fc['categorie'].touched && fc['categorie'].invalid" > categorie is required . </div> </div> </div> <div class="form-group"> <label for="">Post Image</label> <img [src]="imgSrc" class="form-control img-fluid img-preview" alt="" /> <input type="file" class="form-control" accept="image/*" (change)="showPreview($event)" formControlName="postImg" [ngClass]="{ 'is-invalid': fc['postImg'].touched && fc['postImg'].invalid }" /> <div *ngIf="fc['postImg'].errors?.['required']"> <div class="alert alert-danger" *ngIf="fc['postImg'].touched && fc['postImg'].invalid" > postImg is required . </div> </div> </div> </div> </div> </div> </div> <div class="row mt-3 mb-5"> <div class="col-md-12"> <div class="card shadow-effect"> <div class="card-body"> <div class="form-group"> <label for="">Content</label> <!-- Pour un editor de text instaler kolkov/angular-editor --> <angular-editor placeholder="Add Yout content Hee" formControlName="content" > </angular-editor> <div *ngIf="fc['content'].errors?.['required']"> <div class="alert alert-danger" *ngIf="fc['content'].touched && fc['content'].invalid" > content is required . </div> </div> </div> </div> </div> </div> <div class="col-md-12 text-center mb-5 mt-5"> <button class="btn btn-info bg-theme" [disabled]="postForm.invalid"> {{ formStatus }} </button> <button class="btn btn-warning ml-3" routerLink="/"> Back to Post </button> </div> </div> </form> </div>
type Callback = () => void; export class Eventing { events: { [key: string]: Callback[] } = {}; // registers an event handler with this object so other parts of the app // know when something changes on = (eventName: string, callback: Callback): void => { const handlers = this.events[eventName] || []; handlers.push(callback); this.events[eventName] = handlers; }; // triggers an event to tell other parts of the app that something has changed trigger = (eventName: string): void => { const handlers = this.events[eventName]; if (!handlers || handlers.length === 0) return; handlers.forEach((cb) => { cb(); }); }; }
/* * Listener.h * * Created on: 2014-03-03 * Author: Kenan Kigunda */ #ifndef LISTENER_H_ #define LISTENER_H_ #include "includes.h" #include "Status.h" #define LISTENER_RECEIVE_QUEUE_SIZE 4 /** * The bridge abstract class provides a common structure for classes * that listen to data sources and forward relevant events to recipients. */ class Listener { public: /** * Creates a new listener. */ Listener(); virtual ~Listener() {} /** * Gets the queue used to accept events. * @return the receive queue */ OS_EVENT *listener(); /** * Waits on the receive queue for event. * When events are received, they are forwarded to parse(). * @throw QueuePendException if this listener cannot read the receive queue */ void update(); protected: /* The buffer and queue used to receive events. */ int receiveBuffer[LISTENER_RECEIVE_QUEUE_SIZE]; OS_EVENT *receiveQueue; /** * Parses the given event. * The listener will carry out the action associated with the event. * @param event specifies the type of event, and its parameters */ virtual void parse(char *event) = 0; }; class QueueCreateException : ARCapException { public: virtual const char *what() const throw() { return "Failed to create listener queue."; } }; class QueuePendException : ARCapException { public: virtual const char *what() const throw() { return "Failed to pend on listener queue."; } }; #endif /* LISTENER_H_ */
package dataStructure; public class Queue { private Node first; private Node last; private int lenght; public class Node { int value; Node next; // Construtores Node(int value) { this.value = value; } public int getValue(){ return this.value; } } public Queue(int value) { Node newNode = new Node(value); first = newNode; last = newNode; lenght++; } // Métodos public void getFirst() { if (first != null) { System.out.println(" First: " + first.value); } else { System.out.println("A fila está vazia"); } } // Método GetLast public void getLast() { if (last != null) { System.out.println(" Last: " + last.value); } else { System.out.println("A fila está vazia"); } } // Método GetLenght private void getLength() { System.out.println("Length: " + lenght); } // Método Print public void print() { System.out.println("----------------------------------"); Node temp = first; while (temp != null) { System.out.println(temp.value); temp = temp.next; } System.out.println("----------------------------------"); } // Método Enfileirar public void enqueue(int value) { Node newNode = new Node(value); if (lenght == 0) { first = newNode; last = newNode; } else { last.next = newNode; last = newNode; } lenght++; } // Método Desenfileirar public Node dequeue() { if (lenght == 0) return null; Node temp = first; if (lenght == 1) { first = null; last = null; } else { first = first.next; temp.next = null; } lenght++; return temp; } public static void main(String[] args) { Queue myQueue = new Queue(1); myQueue.enqueue(2); myQueue.enqueue(3); System.out.println(myQueue.dequeue().value); System.out.println(myQueue.dequeue().value); System.out.println(myQueue.dequeue().value); // myQueue.getFirst(); // myQueue.getLast(); // myQueue.getLength(); // // myQueue.print(); // myQueue.getFirst(); // myQueue.getLast(); // myQueue.getLength(); // // // myQueue.print(); } }
package com.madou.gebase.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.madou.gebase.common.ErrorCode; import com.madou.gebase.contant.RedisConstant; import com.madou.gebase.exception.BusinessException; import com.madou.gebase.mapper.TeamMapper; import com.madou.gebase.model.Team; import com.madou.gebase.model.User; import com.madou.gebase.model.UserTeam; import com.madou.gebase.model.dto.TeamQuery; import com.madou.gebase.model.enums.TeamStatusEnums; import com.madou.gebase.model.request.TeamJoinRequest; import com.madou.gebase.model.request.TeamQuitRequest; import com.madou.gebase.model.request.TeamUpdateRequest; import com.madou.gebase.model.vo.TeamVO; import com.madou.gebase.model.vo.UserTeamVO; import com.madou.gebase.model.vo.UserVO; import com.madou.gebase.service.TeamService; import com.madou.gebase.service.UserService; import com.madou.gebase.service.UserTeamService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** * @author MA_dou * @description 针对表【team(队伍)】的数据库操作Service实现 * @createDate 2023-01-31 14:09:19 */ @Service @Slf4j public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team> implements TeamService { @Resource private UserService userService; @Resource private UserTeamService userTeamService; @Resource private RedissonClient redissonClient; @Override @Transactional(rollbackFor = Exception.class) public long addTeam(Team team, User loginUser) { //请求参数是否为空 if (team == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } //用户是否登录 if (loginUser == null) { throw new BusinessException(ErrorCode.LOGIN_ERROR); } final long userId = loginUser.getId(); //队伍最大人数不大于20不小于1 int maxNum = Optional.ofNullable(team.getMaxNum()).orElse(0); if (maxNum < 1 || maxNum > 20) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍人数不满足要求"); } //队伍名称 <=20 String teamName = team.getTeamName(); if (StringUtils.isNotBlank(teamName) && teamName.length() > 20) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍名不满足要求"); } //描述小于512 String description = team.getDescription(); if (StringUtils.isNotBlank(description) && description.length() > 512) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍描述不满足要求"); } // teamStatue 0为公开 默认为0 int statue = Optional.ofNullable(team.getTeamState()).orElse(0); TeamStatusEnums teamStatusEnums = TeamStatusEnums.getEnumByValues(statue); if (teamStatusEnums == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态不满足要求"); } // teamStatue 为加密状态 需要密码,密码<=32 String teamPassword = team.getTeamPassword(); if (TeamStatusEnums.SECRET.equals(teamStatusEnums) && (StringUtils.isBlank(teamPassword) || teamPassword.length() > 32)) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍加密不满足要求"); } //超时时间大于当前时间 Date expireTime = team.getExpireTime(); if (new Date().after(expireTime)) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "超时时间小于当前时间"); } //校验用户最多创建5个队伍 QueryWrapper<Team> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("userId", userId); long teamCount = this.count(queryWrapper); if (teamCount >= 5) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍数量不能大于5"); } //信息插入队伍表 team.setId(null); team.setUserId(userId); boolean result = this.save(team); Long teamId = team.getId(); if (!result || teamId == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建队伍失败"); } //信息插入队伍关系表 UserTeam userTeam = new UserTeam(); userTeam.setTeamId(teamId); userTeam.setUserId(userId); userTeam.setJoinTime(new Date()); result = userTeamService.save(userTeam); if (!result) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建队伍失败"); } return teamId; } @Override public List<UserTeamVO> listTeams(TeamQuery teamQuery, boolean isAdmin) { QueryWrapper<Team> queryWrapper = new QueryWrapper<>(); if (teamQuery != null) { Long id = teamQuery.getId(); if (id != null && id > 0) { queryWrapper.eq("id", id); } List<Long> listUserId = teamQuery.getListUserId(); if (!CollectionUtils.isEmpty(listUserId)) { queryWrapper.in("id", listUserId); } String searchText = teamQuery.getSearchText(); if (StringUtils.isNotBlank(searchText)) { queryWrapper.and(qw -> qw.like("teamName", searchText).or().like("description", searchText)); } String teamName = teamQuery.getTeamName(); if (StringUtils.isNotBlank(teamName)) { queryWrapper.like("teamName", teamName); } String description = teamQuery.getDescription(); if (StringUtils.isNotBlank(description)) { queryWrapper.like("description", description); } Integer maxNum = teamQuery.getMaxNum(); if (maxNum != null && maxNum <= 5) { queryWrapper.like("maxNum", maxNum); } Long userId = teamQuery.getUserId(); if (userId != null && userId > 0) { queryWrapper.eq("userId", userId); } Integer teamState = teamQuery.getTeamState(); TeamStatusEnums enumByValues = TeamStatusEnums.getEnumByValues(teamState); if (enumByValues == null) { //为空 默认公开 enumByValues = TeamStatusEnums.PUBLIC; } if (!isAdmin && userId == null && enumByValues.equals(TeamStatusEnums.PRIVATE)) { throw new BusinessException(ErrorCode.NO_ADMIN); } queryWrapper.eq("teamState", enumByValues.getValue()); } //不展示过期队伍 queryWrapper.and(qw -> qw.gt("expireTime", new Date()).or().isNull("expireTime")); List<Team> teamList = this.list(queryWrapper); if (CollectionUtils.isEmpty(teamList)) { return new ArrayList<>(); } List<UserTeamVO> userTeamVOList = new ArrayList<>(); for (Team team : teamList) { Long userId = team.getUserId(); if (userId == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } User user = userService.getById(userId); UserTeamVO userTeamVO = new UserTeamVO(); //脱敏信息 if (user != null) { UserVO userVO = new UserVO(); BeanUtils.copyProperties(user, userVO); userTeamVO.setCreateUser(userVO); } BeanUtils.copyProperties(team, userTeamVO); userTeamVOList.add(userTeamVO); } //队伍id List<Long> teamIdList = userTeamVOList.stream().map(UserTeamVO::getId).collect(Collectors.toList()); //加入队伍人数 QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>(); userTeamJoinQueryWrapper.in("teamId", teamIdList); List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper); //队伍Id => 加入这个队伍的用户 Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId)); userTeamVOList.forEach(team -> { team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()); }); return userTeamVOList; } @Override public boolean updateTeam(TeamUpdateRequest teamUpdateRequest, User loginUser) { if (teamUpdateRequest == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新数据不能为空"); } Long id = teamUpdateRequest.getId(); if (id == null || id <= 0) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } Team oldTeam = this.getById(id); if (oldTeam == null) { throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在"); } //只要管理员和队长才能修改 if (oldTeam.getUserId() != loginUser.getId() && !userService.isAdmin(loginUser)) { throw new BusinessException(ErrorCode.NO_ADMIN); } TeamStatusEnums teamStatusEnums = TeamStatusEnums.getEnumByValues(teamUpdateRequest.getTeamState()); if (teamStatusEnums.equals(TeamStatusEnums.SECRET)) { if (StringUtils.isBlank(teamUpdateRequest.getTeamPassword())) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "加密房间需要设置密码"); } } Team updateTeam = new Team(); BeanUtils.copyProperties(teamUpdateRequest, updateTeam); return this.updateById(updateTeam); } @Override public boolean joinTeam(TeamJoinRequest teamJoinRequest, User loginUser) { if (teamJoinRequest == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } Long teamId = teamJoinRequest.getTeamId(); if (teamId == null || teamId <= 0) { throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在"); } Team team = this.getById(teamId); if (team == null) { throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在"); } Date expireTime = team.getExpireTime(); if (expireTime != null && expireTime.before(new Date())) { throw new BusinessException(ErrorCode.NULL_ERROR, "队伍已过期"); } TeamStatusEnums teamStatusEnums = TeamStatusEnums.getEnumByValues(team.getTeamState()); if (teamStatusEnums.equals(TeamStatusEnums.PRIVATE)) { throw new BusinessException(ErrorCode.NULL_ERROR, "不能加入私有队伍"); } String teamPassword = teamJoinRequest.getTeamPassword(); if (TeamStatusEnums.SECRET.equals(teamStatusEnums)) { if (StringUtils.isBlank(teamPassword) || !team.getTeamPassword().equals(teamPassword)) { throw new BusinessException(ErrorCode.NULL_ERROR, "密码错误"); } } //该用户加入队伍数量 long userId = loginUser.getId(); //只有一个线程抢到加入该队伍的锁 RLock lock = redissonClient.getLock(RedisConstant.REDIS_JOIN_TEAM_KEY + teamId); try { //重复抢锁 while (true) { if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)){ QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>(); userTeamQueryWrapper.eq("userId", userId); long hasJoinNum = userTeamService.count(userTeamQueryWrapper); if (hasJoinNum > 5) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多加入或者创建5个队伍"); } //不能重复加入队伍 userTeamQueryWrapper.eq("teamId", teamId); long hasUserJoinTeam = userTeamService.count(userTeamQueryWrapper); if (hasUserJoinTeam > 0) { throw new BusinessException(ErrorCode.NULL_ERROR, "用户已加入该队伍"); } //已经加入队伍数量 long hasTeamJoinNum = getHasTeamJoinTeam(teamId); if (hasTeamJoinNum >= team.getMaxNum()) { throw new BusinessException(ErrorCode.NULL_ERROR, "队伍已满"); } //修改队伍信息 UserTeam userTeam = new UserTeam(); userTeam.setUserId(userId); userTeam.setTeamId(teamId); userTeam.setJoinTime(new Date()); return userTeamService.save(userTeam); } } } catch (InterruptedException e) { log.error("doCache joinTeam error", e); return false; }finally { //释放自己的锁 if (lock.isHeldByCurrentThread()){ lock.unlock(); } } } @Override @Transactional(rollbackFor = Exception.class) public boolean quitTeam(TeamQuitRequest teamQuitRequest, User loginUser) { if (teamQuitRequest == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } Long teamId = teamQuitRequest.getTeamId(); Team team = getTeamById(teamId); long userId = loginUser.getId(); QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("userId", userId); queryWrapper.eq("teamId", teamId); long hasJoinNum = userTeamService.count(queryWrapper); if (hasJoinNum == 0) { throw new BusinessException(ErrorCode.PARAMS_ERROR, "未加入该队伍"); } long hasUserJoinTeam = getHasTeamJoinTeam(teamId); //只剩一人删除队伍 队长退出,队长顺位 if (hasUserJoinTeam == 1) { //删除队伍和队伍关系 this.removeById(teamId); } else { //队长退出 if (team.getUserId() == userId) { queryWrapper = new QueryWrapper<>(); queryWrapper.eq("teamId", teamId); queryWrapper.last("order by id asc limit 2"); List<UserTeam> userTeamList = userTeamService.list(queryWrapper); if (CollectionUtils.isEmpty(userTeamList) && userTeamList.size() <= 1) { throw new BusinessException(ErrorCode.SYSTEM_ERROR); } //删除队长关系 UserTeam nextTeam = userTeamList.get(1); Long nextUserId = nextTeam.getUserId(); Team updateTeam = new Team(); updateTeam.setUserId(nextUserId); updateTeam.setId(teamId); boolean result = this.updateById(updateTeam); if (!result) { throw new BusinessException(ErrorCode.SYSTEM_ERROR, "队伍队长更新失败"); } queryWrapper = new QueryWrapper<>(); queryWrapper.eq("teamId", teamId); queryWrapper.eq("userId", userId); } } //移除关系 return userTeamService.remove(queryWrapper); } @Override public boolean deleteTeam(long teamId, User loginUser) { Team team = getTeamById(teamId); //是否为队长 long userId = loginUser.getId(); if (team.getUserId() != userId) { throw new BusinessException(ErrorCode.NO_ADMIN); } //移除队伍 return removeByTeamId(teamId); } @Override public TeamVO getTeamInfoById(long id) { Team team = this.getById(id); Long userId = team.getUserId(); if (userId == null) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } User createUser = userService.getById(userId); TeamVO teamVO = new TeamVO(); //脱敏信息 if (createUser != null) { UserVO userVO = new UserVO(); BeanUtils.copyProperties(createUser, userVO); teamVO.setCreateUser(userVO); } BeanUtils.copyProperties(team, teamVO); QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("teamId", id); List<UserTeam> userTeamList = userTeamService.list(queryWrapper); //获取加入队伍的用户id List<Long> userIdList = userTeamList.stream().map(UserTeam::getUserId).collect(Collectors.toList()); //根据用户id查出详细的信息 QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(); userQueryWrapper.in("id", userIdList); List<User> userList = userService.list(userQueryWrapper); //用户脱敏 List<UserVO> userVOList = new ArrayList<>(); for (User user : userList) { UserVO userVO = new UserVO(); BeanUtils.copyProperties(user, userVO); userVOList.add(userVO); } teamVO.setUserJoinList(userVOList); teamVO.setHasJoinNum(userVOList.size()); return teamVO; } /** * 获取队伍中的人数 * * @param teamId * @return */ private long getHasTeamJoinTeam(long teamId) { QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>(); userTeamQueryWrapper.eq("teamId", teamId); return userTeamService.count(userTeamQueryWrapper); } /** * 根据队伍teamId获取队伍信息 * * @param teamId * @return */ private Team getTeamById(long teamId) { if (teamId <= 0) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } Team team = this.getById(teamId); if (team == null) { throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在"); } return team; } /** * 根据队伍id解散队伍 * * @param teamId * @return */ @Override @Transactional(rollbackFor = Exception.class) public boolean removeByTeamId(long teamId) { QueryWrapper<UserTeam> teamIdQueryWrapper = new QueryWrapper<>(); teamIdQueryWrapper.eq("teamId", teamId); boolean result = userTeamService.remove(teamIdQueryWrapper); if (!result) { throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除队伍中用户失败"); } return this.removeById(teamId); } }
import React, { useContext } from 'react'; import { Field, ErrorMessage } from 'formik'; import TextError from './TextError'; import styled from 'styled-components'; import { AppContext } from '../../context/AppContext'; interface InputProps { label: string; name: string; [x: string]: any; } interface MyInputProps { field: any; form: any; } const MyInput = ({ field, form }: MyInputProps) => { const { darkMode } = useContext(AppContext); return <InputStyled {...field} {...form} type='text' darkMode={darkMode} />; }; const Input = ({ label, name, ...rest }: InputProps) => { const { darkMode } = useContext(AppContext); return ( <InputDiv> <StyledLabel htmlFor={name}>{label}</StyledLabel> <Field id={name} name={name} darkMode={darkMode} component={MyInput} {...rest} ></Field> <ErrorMessage name={name}> {(error) => <TextError>{error}</TextError>} </ErrorMessage> </InputDiv> ); }; export default Input; const InputDiv = styled.div` display: flex; flex-direction: column; margin-bottom: 10px; margin-bottom: 1em; min-height: 75px; `; const StyledLabel = styled.label` margin-bottom: 2px; font-size: 12px; `; const InputStyled = styled.input<InputProps>` transition: 0.4s; font-size: 14px; width: 95%; background-color: ${(p) => (p.darkMode ? '#ffffff22' : '#006bae32')}; font-size: 16px; padding: 0.5em 1em; border-radius: 3px; border: 0px; color: ${(p) => (p.darkMode ? 'white' : 'rgb(4, 34, 78)')}; &:focus-visible { border: transparent; outline: none; } `;
import { TrendingList } from 'components/TrendingList/TrendingList'; import { fetchSearchMovies } from 'helppers/fetch'; import React, { useEffect, useState } from 'react'; import { SearchDiv, Form, StyledSearchIcon } from './Movies.styled'; import { useSearchParams } from 'react-router-dom'; import { HomeDiv, TextInfo } from '../Home/Home.styled'; import { Loader } from 'components/Loader/Loader'; function Movies() { const [movies, setMovies] = useState([]); const [loading, setLoading] = useState(false); // const [noName, setNoName] = useState(false); const [searchParams, setSearchParams] = useSearchParams(); const searchQuery = searchParams.get('searchQuery'); useEffect(() => { const fetchMoviesSearch = () => { setLoading(true); fetchSearchMovies(searchQuery) .then(movies => { setMovies(movies); // setNoName(queryMovieName.length === 0); }) .catch(error => { console.log(error); }) .finally(() => { setLoading(false); }); }; if (searchQuery) { fetchMoviesSearch(); } else { setMovies([]); // setNoName(false); setLoading(false); } }, [searchQuery]); const handleSubmit = e => { e.preventDefault(); const form = e.currentTarget; setSearchParams({ searchQuery: form.elements.searchQuery.value }); form.reset(); }; return ( <HomeDiv> <SearchDiv> <Form autoComplete="off" onSubmit={handleSubmit}> <input type="text" placeholder="Enter movie name..." name="searchQuery" autoFocus // value={query} /> <button type="submit"> <StyledSearchIcon /> </button> </Form> </SearchDiv> {loading && <Loader />} {movies.length > 0 && <TrendingList movies={movies} />} {movies.length === 0 && searchQuery && ( <TextInfo> There is no movies with this request. Please, try again </TextInfo> )} </HomeDiv> ); } export default Movies;
package tz.or.mkapafoundation.hrmis.web.rest; import tz.or.mkapafoundation.hrmis.HrmisApp; import tz.or.mkapafoundation.hrmis.config.TestSecurityConfiguration; import tz.or.mkapafoundation.hrmis.domain.EmployeeRecord; import tz.or.mkapafoundation.hrmis.domain.Attachment; import tz.or.mkapafoundation.hrmis.domain.Department; import tz.or.mkapafoundation.hrmis.domain.EmploymentCategory; import tz.or.mkapafoundation.hrmis.domain.Carder; import tz.or.mkapafoundation.hrmis.domain.Facility; import tz.or.mkapafoundation.hrmis.domain.Project; import tz.or.mkapafoundation.hrmis.repository.EmployeeRecordRepository; import tz.or.mkapafoundation.hrmis.service.EmployeeRecordService; import tz.or.mkapafoundation.hrmis.service.dto.EmployeeRecordDTO; import tz.or.mkapafoundation.hrmis.service.mapper.EmployeeRecordMapper; import tz.or.mkapafoundation.hrmis.service.dto.EmployeeRecordCriteria; import tz.or.mkapafoundation.hrmis.service.EmployeeRecordQueryService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Base64Utils; import javax.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link EmployeeRecordResource} REST controller. */ @SpringBootTest(classes = { HrmisApp.class, TestSecurityConfiguration.class }) @AutoConfigureMockMvc @WithMockUser public class EmployeeRecordResourceIT { private static final String DEFAULT_FIRST_NAME = "AAAAAAAAAA"; private static final String UPDATED_FIRST_NAME = "BBBBBBBBBB"; private static final String DEFAULT_MIDDLE_NAME = "AAAAAAAAAA"; private static final String UPDATED_MIDDLE_NAME = "BBBBBBBBBB"; private static final String DEFAULT_LAST_NAME = "AAAAAAAAAA"; private static final String UPDATED_LAST_NAME = "BBBBBBBBBB"; private static final String DEFAULT_ADDRESS = "AAAAAAAAAA"; private static final String UPDATED_ADDRESS = "BBBBBBBBBB"; private static final String DEFAULT_GENDER = "AAAAAAAAAA"; private static final String UPDATED_GENDER = "BBBBBBBBBB"; private static final LocalDate DEFAULT_BIRTH_DATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_BIRTH_DATE = LocalDate.now(ZoneId.systemDefault()); private static final LocalDate SMALLER_BIRTH_DATE = LocalDate.ofEpochDay(-1L); private static final String DEFAULT_EMAIL = "AAAAAAAAAA"; private static final String UPDATED_EMAIL = "BBBBBBBBBB"; private static final String DEFAULT_CELL_PHONE = "AAAAAAAAAA"; private static final String UPDATED_CELL_PHONE = "BBBBBBBBBB"; private static final String DEFAULT_TELEPHONE = "AAAAAAAAAA"; private static final String UPDATED_TELEPHONE = "BBBBBBBBBB"; private static final String DEFAULT_MARITAL_STATUS = "AAAAAAAAAA"; private static final String UPDATED_MARITAL_STATUS = "BBBBBBBBBB"; private static final byte[] DEFAULT_PICTURE = TestUtil.createByteArray(1, "0"); private static final byte[] UPDATED_PICTURE = TestUtil.createByteArray(1, "1"); private static final String DEFAULT_PICTURE_CONTENT_TYPE = "image/jpg"; private static final String UPDATED_PICTURE_CONTENT_TYPE = "image/png"; private static final String DEFAULT_EMPLOYEE_NUMBER = "AAAAAAAAAA"; private static final String UPDATED_EMPLOYEE_NUMBER = "BBBBBBBBBB"; private static final Boolean DEFAULT_ACTIVE = false; private static final Boolean UPDATED_ACTIVE = true; private static final LocalDate DEFAULT_DATE_JOINING = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_DATE_JOINING = LocalDate.now(ZoneId.systemDefault()); private static final LocalDate SMALLER_DATE_JOINING = LocalDate.ofEpochDay(-1L); private static final Double DEFAULT_SALARY = 1D; private static final Double UPDATED_SALARY = 2D; private static final Double SMALLER_SALARY = 1D - 1D; private static final LocalDate DEFAULT_CONTRACT_START_DATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_CONTRACT_START_DATE = LocalDate.now(ZoneId.systemDefault()); private static final LocalDate SMALLER_CONTRACT_START_DATE = LocalDate.ofEpochDay(-1L); private static final LocalDate DEFAULT_CONTRACT_END_DATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_CONTRACT_END_DATE = LocalDate.now(ZoneId.systemDefault()); private static final LocalDate SMALLER_CONTRACT_END_DATE = LocalDate.ofEpochDay(-1L); private static final String DEFAULT_BANK_NAME = "AAAAAAAAAA"; private static final String UPDATED_BANK_NAME = "BBBBBBBBBB"; private static final String DEFAULT_BRANCH_NAME = "AAAAAAAAAA"; private static final String UPDATED_BRANCH_NAME = "BBBBBBBBBB"; private static final String DEFAULT_BANK_ACCOUNT = "AAAAAAAAAA"; private static final String UPDATED_BANK_ACCOUNT = "BBBBBBBBBB"; private static final String DEFAULT_INSURANCE_REGISTRATION_NUMBER = "AAAAAAAAAA"; private static final String UPDATED_INSURANCE_REGISTRATION_NUMBER = "BBBBBBBBBB"; @Autowired private EmployeeRecordRepository employeeRecordRepository; @Autowired private EmployeeRecordMapper employeeRecordMapper; @Autowired private EmployeeRecordService employeeRecordService; @Autowired private EmployeeRecordQueryService employeeRecordQueryService; @Autowired private EntityManager em; @Autowired private MockMvc restEmployeeRecordMockMvc; private EmployeeRecord employeeRecord; /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EmployeeRecord createEntity(EntityManager em) { EmployeeRecord employeeRecord = new EmployeeRecord() .firstName(DEFAULT_FIRST_NAME) .middleName(DEFAULT_MIDDLE_NAME) .lastName(DEFAULT_LAST_NAME) .address(DEFAULT_ADDRESS) .gender(DEFAULT_GENDER) .birthDate(DEFAULT_BIRTH_DATE) .email(DEFAULT_EMAIL) .cellPhone(DEFAULT_CELL_PHONE) .telephone(DEFAULT_TELEPHONE) .maritalStatus(DEFAULT_MARITAL_STATUS) .picture(DEFAULT_PICTURE) .pictureContentType(DEFAULT_PICTURE_CONTENT_TYPE) .employeeNumber(DEFAULT_EMPLOYEE_NUMBER) .active(DEFAULT_ACTIVE) .dateJoining(DEFAULT_DATE_JOINING) .salary(DEFAULT_SALARY) .contractStartDate(DEFAULT_CONTRACT_START_DATE) .contractEndDate(DEFAULT_CONTRACT_END_DATE) .bankName(DEFAULT_BANK_NAME) .branchName(DEFAULT_BRANCH_NAME) .bankAccount(DEFAULT_BANK_ACCOUNT) .insuranceRegistrationNumber(DEFAULT_INSURANCE_REGISTRATION_NUMBER); // Add required entity Department department; if (TestUtil.findAll(em, Department.class).isEmpty()) { department = DepartmentResourceIT.createEntity(em); em.persist(department); em.flush(); } else { department = TestUtil.findAll(em, Department.class).get(0); } employeeRecord.setDepartment(department); // Add required entity EmploymentCategory employmentCategory; if (TestUtil.findAll(em, EmploymentCategory.class).isEmpty()) { employmentCategory = EmploymentCategoryResourceIT.createEntity(em); em.persist(employmentCategory); em.flush(); } else { employmentCategory = TestUtil.findAll(em, EmploymentCategory.class).get(0); } employeeRecord.setEmployeeType(employmentCategory); // Add required entity Carder carder; if (TestUtil.findAll(em, Carder.class).isEmpty()) { carder = CarderResourceIT.createEntity(em); em.persist(carder); em.flush(); } else { carder = TestUtil.findAll(em, Carder.class).get(0); } employeeRecord.setDesignation(carder); // Add required entity Facility facility; if (TestUtil.findAll(em, Facility.class).isEmpty()) { facility = FacilityResourceIT.createEntity(em); em.persist(facility); em.flush(); } else { facility = TestUtil.findAll(em, Facility.class).get(0); } employeeRecord.setFacility(facility); // Add required entity Project project; if (TestUtil.findAll(em, Project.class).isEmpty()) { project = ProjectResourceIT.createEntity(em); em.persist(project); em.flush(); } else { project = TestUtil.findAll(em, Project.class).get(0); } employeeRecord.setProject(project); return employeeRecord; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static EmployeeRecord createUpdatedEntity(EntityManager em) { EmployeeRecord employeeRecord = new EmployeeRecord() .firstName(UPDATED_FIRST_NAME) .middleName(UPDATED_MIDDLE_NAME) .lastName(UPDATED_LAST_NAME) .address(UPDATED_ADDRESS) .gender(UPDATED_GENDER) .birthDate(UPDATED_BIRTH_DATE) .email(UPDATED_EMAIL) .cellPhone(UPDATED_CELL_PHONE) .telephone(UPDATED_TELEPHONE) .maritalStatus(UPDATED_MARITAL_STATUS) .picture(UPDATED_PICTURE) .pictureContentType(UPDATED_PICTURE_CONTENT_TYPE) .employeeNumber(UPDATED_EMPLOYEE_NUMBER) .active(UPDATED_ACTIVE) .dateJoining(UPDATED_DATE_JOINING) .salary(UPDATED_SALARY) .contractStartDate(UPDATED_CONTRACT_START_DATE) .contractEndDate(UPDATED_CONTRACT_END_DATE) .bankName(UPDATED_BANK_NAME) .branchName(UPDATED_BRANCH_NAME) .bankAccount(UPDATED_BANK_ACCOUNT) .insuranceRegistrationNumber(UPDATED_INSURANCE_REGISTRATION_NUMBER); // Add required entity Department department; if (TestUtil.findAll(em, Department.class).isEmpty()) { department = DepartmentResourceIT.createUpdatedEntity(em); em.persist(department); em.flush(); } else { department = TestUtil.findAll(em, Department.class).get(0); } employeeRecord.setDepartment(department); // Add required entity EmploymentCategory employmentCategory; if (TestUtil.findAll(em, EmploymentCategory.class).isEmpty()) { employmentCategory = EmploymentCategoryResourceIT.createUpdatedEntity(em); em.persist(employmentCategory); em.flush(); } else { employmentCategory = TestUtil.findAll(em, EmploymentCategory.class).get(0); } employeeRecord.setEmployeeType(employmentCategory); // Add required entity Carder carder; if (TestUtil.findAll(em, Carder.class).isEmpty()) { carder = CarderResourceIT.createUpdatedEntity(em); em.persist(carder); em.flush(); } else { carder = TestUtil.findAll(em, Carder.class).get(0); } employeeRecord.setDesignation(carder); // Add required entity Facility facility; if (TestUtil.findAll(em, Facility.class).isEmpty()) { facility = FacilityResourceIT.createUpdatedEntity(em); em.persist(facility); em.flush(); } else { facility = TestUtil.findAll(em, Facility.class).get(0); } employeeRecord.setFacility(facility); // Add required entity Project project; if (TestUtil.findAll(em, Project.class).isEmpty()) { project = ProjectResourceIT.createUpdatedEntity(em); em.persist(project); em.flush(); } else { project = TestUtil.findAll(em, Project.class).get(0); } employeeRecord.setProject(project); return employeeRecord; } @BeforeEach public void initTest() { employeeRecord = createEntity(em); } @Test @Transactional public void createEmployeeRecord() throws Exception { int databaseSizeBeforeCreate = employeeRecordRepository.findAll().size(); // Create the EmployeeRecord EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); restEmployeeRecordMockMvc.perform(post("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isCreated()); // Validate the EmployeeRecord in the database List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeCreate + 1); EmployeeRecord testEmployeeRecord = employeeRecordList.get(employeeRecordList.size() - 1); assertThat(testEmployeeRecord.getFirstName()).isEqualTo(DEFAULT_FIRST_NAME); assertThat(testEmployeeRecord.getMiddleName()).isEqualTo(DEFAULT_MIDDLE_NAME); assertThat(testEmployeeRecord.getLastName()).isEqualTo(DEFAULT_LAST_NAME); assertThat(testEmployeeRecord.getAddress()).isEqualTo(DEFAULT_ADDRESS); assertThat(testEmployeeRecord.getGender()).isEqualTo(DEFAULT_GENDER); assertThat(testEmployeeRecord.getBirthDate()).isEqualTo(DEFAULT_BIRTH_DATE); assertThat(testEmployeeRecord.getEmail()).isEqualTo(DEFAULT_EMAIL); assertThat(testEmployeeRecord.getCellPhone()).isEqualTo(DEFAULT_CELL_PHONE); assertThat(testEmployeeRecord.getTelephone()).isEqualTo(DEFAULT_TELEPHONE); assertThat(testEmployeeRecord.getMaritalStatus()).isEqualTo(DEFAULT_MARITAL_STATUS); assertThat(testEmployeeRecord.getPicture()).isEqualTo(DEFAULT_PICTURE); assertThat(testEmployeeRecord.getPictureContentType()).isEqualTo(DEFAULT_PICTURE_CONTENT_TYPE); assertThat(testEmployeeRecord.getEmployeeNumber()).isEqualTo(DEFAULT_EMPLOYEE_NUMBER); assertThat(testEmployeeRecord.isActive()).isEqualTo(DEFAULT_ACTIVE); assertThat(testEmployeeRecord.getDateJoining()).isEqualTo(DEFAULT_DATE_JOINING); assertThat(testEmployeeRecord.getSalary()).isEqualTo(DEFAULT_SALARY); assertThat(testEmployeeRecord.getContractStartDate()).isEqualTo(DEFAULT_CONTRACT_START_DATE); assertThat(testEmployeeRecord.getContractEndDate()).isEqualTo(DEFAULT_CONTRACT_END_DATE); assertThat(testEmployeeRecord.getBankName()).isEqualTo(DEFAULT_BANK_NAME); assertThat(testEmployeeRecord.getBranchName()).isEqualTo(DEFAULT_BRANCH_NAME); assertThat(testEmployeeRecord.getBankAccount()).isEqualTo(DEFAULT_BANK_ACCOUNT); assertThat(testEmployeeRecord.getInsuranceRegistrationNumber()).isEqualTo(DEFAULT_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void createEmployeeRecordWithExistingId() throws Exception { int databaseSizeBeforeCreate = employeeRecordRepository.findAll().size(); // Create the EmployeeRecord with an existing ID employeeRecord.setId(1L); EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); // An entity with an existing ID cannot be created, so this API call must fail restEmployeeRecordMockMvc.perform(post("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isBadRequest()); // Validate the EmployeeRecord in the database List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checkFirstNameIsRequired() throws Exception { int databaseSizeBeforeTest = employeeRecordRepository.findAll().size(); // set the field null employeeRecord.setFirstName(null); // Create the EmployeeRecord, which fails. EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); restEmployeeRecordMockMvc.perform(post("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isBadRequest()); List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checkLastNameIsRequired() throws Exception { int databaseSizeBeforeTest = employeeRecordRepository.findAll().size(); // set the field null employeeRecord.setLastName(null); // Create the EmployeeRecord, which fails. EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); restEmployeeRecordMockMvc.perform(post("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isBadRequest()); List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checkBirthDateIsRequired() throws Exception { int databaseSizeBeforeTest = employeeRecordRepository.findAll().size(); // set the field null employeeRecord.setBirthDate(null); // Create the EmployeeRecord, which fails. EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); restEmployeeRecordMockMvc.perform(post("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isBadRequest()); List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void checkEmployeeNumberIsRequired() throws Exception { int databaseSizeBeforeTest = employeeRecordRepository.findAll().size(); // set the field null employeeRecord.setEmployeeNumber(null); // Create the EmployeeRecord, which fails. EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); restEmployeeRecordMockMvc.perform(post("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isBadRequest()); List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllEmployeeRecords() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList restEmployeeRecordMockMvc.perform(get("/api/employee-records?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(employeeRecord.getId().intValue()))) .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME))) .andExpect(jsonPath("$.[*].middleName").value(hasItem(DEFAULT_MIDDLE_NAME))) .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME))) .andExpect(jsonPath("$.[*].address").value(hasItem(DEFAULT_ADDRESS))) .andExpect(jsonPath("$.[*].gender").value(hasItem(DEFAULT_GENDER))) .andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString()))) .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) .andExpect(jsonPath("$.[*].cellPhone").value(hasItem(DEFAULT_CELL_PHONE))) .andExpect(jsonPath("$.[*].telephone").value(hasItem(DEFAULT_TELEPHONE))) .andExpect(jsonPath("$.[*].maritalStatus").value(hasItem(DEFAULT_MARITAL_STATUS))) .andExpect(jsonPath("$.[*].pictureContentType").value(hasItem(DEFAULT_PICTURE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].picture").value(hasItem(Base64Utils.encodeToString(DEFAULT_PICTURE)))) .andExpect(jsonPath("$.[*].employeeNumber").value(hasItem(DEFAULT_EMPLOYEE_NUMBER))) .andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue()))) .andExpect(jsonPath("$.[*].dateJoining").value(hasItem(DEFAULT_DATE_JOINING.toString()))) .andExpect(jsonPath("$.[*].salary").value(hasItem(DEFAULT_SALARY.doubleValue()))) .andExpect(jsonPath("$.[*].contractStartDate").value(hasItem(DEFAULT_CONTRACT_START_DATE.toString()))) .andExpect(jsonPath("$.[*].contractEndDate").value(hasItem(DEFAULT_CONTRACT_END_DATE.toString()))) .andExpect(jsonPath("$.[*].bankName").value(hasItem(DEFAULT_BANK_NAME))) .andExpect(jsonPath("$.[*].branchName").value(hasItem(DEFAULT_BRANCH_NAME))) .andExpect(jsonPath("$.[*].bankAccount").value(hasItem(DEFAULT_BANK_ACCOUNT))) .andExpect(jsonPath("$.[*].insuranceRegistrationNumber").value(hasItem(DEFAULT_INSURANCE_REGISTRATION_NUMBER))); } @Test @Transactional public void getEmployeeRecord() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get the employeeRecord restEmployeeRecordMockMvc.perform(get("/api/employee-records/{id}", employeeRecord.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(employeeRecord.getId().intValue())) .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRST_NAME)) .andExpect(jsonPath("$.middleName").value(DEFAULT_MIDDLE_NAME)) .andExpect(jsonPath("$.lastName").value(DEFAULT_LAST_NAME)) .andExpect(jsonPath("$.address").value(DEFAULT_ADDRESS)) .andExpect(jsonPath("$.gender").value(DEFAULT_GENDER)) .andExpect(jsonPath("$.birthDate").value(DEFAULT_BIRTH_DATE.toString())) .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL)) .andExpect(jsonPath("$.cellPhone").value(DEFAULT_CELL_PHONE)) .andExpect(jsonPath("$.telephone").value(DEFAULT_TELEPHONE)) .andExpect(jsonPath("$.maritalStatus").value(DEFAULT_MARITAL_STATUS)) .andExpect(jsonPath("$.pictureContentType").value(DEFAULT_PICTURE_CONTENT_TYPE)) .andExpect(jsonPath("$.picture").value(Base64Utils.encodeToString(DEFAULT_PICTURE))) .andExpect(jsonPath("$.employeeNumber").value(DEFAULT_EMPLOYEE_NUMBER)) .andExpect(jsonPath("$.active").value(DEFAULT_ACTIVE.booleanValue())) .andExpect(jsonPath("$.dateJoining").value(DEFAULT_DATE_JOINING.toString())) .andExpect(jsonPath("$.salary").value(DEFAULT_SALARY.doubleValue())) .andExpect(jsonPath("$.contractStartDate").value(DEFAULT_CONTRACT_START_DATE.toString())) .andExpect(jsonPath("$.contractEndDate").value(DEFAULT_CONTRACT_END_DATE.toString())) .andExpect(jsonPath("$.bankName").value(DEFAULT_BANK_NAME)) .andExpect(jsonPath("$.branchName").value(DEFAULT_BRANCH_NAME)) .andExpect(jsonPath("$.bankAccount").value(DEFAULT_BANK_ACCOUNT)) .andExpect(jsonPath("$.insuranceRegistrationNumber").value(DEFAULT_INSURANCE_REGISTRATION_NUMBER)); } @Test @Transactional public void getEmployeeRecordsByIdFiltering() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); Long id = employeeRecord.getId(); defaultEmployeeRecordShouldBeFound("id.equals=" + id); defaultEmployeeRecordShouldNotBeFound("id.notEquals=" + id); defaultEmployeeRecordShouldBeFound("id.greaterThanOrEqual=" + id); defaultEmployeeRecordShouldNotBeFound("id.greaterThan=" + id); defaultEmployeeRecordShouldBeFound("id.lessThanOrEqual=" + id); defaultEmployeeRecordShouldNotBeFound("id.lessThan=" + id); } @Test @Transactional public void getAllEmployeeRecordsByFirstNameIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where firstName equals to DEFAULT_FIRST_NAME defaultEmployeeRecordShouldBeFound("firstName.equals=" + DEFAULT_FIRST_NAME); // Get all the employeeRecordList where firstName equals to UPDATED_FIRST_NAME defaultEmployeeRecordShouldNotBeFound("firstName.equals=" + UPDATED_FIRST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByFirstNameIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where firstName not equals to DEFAULT_FIRST_NAME defaultEmployeeRecordShouldNotBeFound("firstName.notEquals=" + DEFAULT_FIRST_NAME); // Get all the employeeRecordList where firstName not equals to UPDATED_FIRST_NAME defaultEmployeeRecordShouldBeFound("firstName.notEquals=" + UPDATED_FIRST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByFirstNameIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where firstName in DEFAULT_FIRST_NAME or UPDATED_FIRST_NAME defaultEmployeeRecordShouldBeFound("firstName.in=" + DEFAULT_FIRST_NAME + "," + UPDATED_FIRST_NAME); // Get all the employeeRecordList where firstName equals to UPDATED_FIRST_NAME defaultEmployeeRecordShouldNotBeFound("firstName.in=" + UPDATED_FIRST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByFirstNameIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where firstName is not null defaultEmployeeRecordShouldBeFound("firstName.specified=true"); // Get all the employeeRecordList where firstName is null defaultEmployeeRecordShouldNotBeFound("firstName.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByFirstNameContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where firstName contains DEFAULT_FIRST_NAME defaultEmployeeRecordShouldBeFound("firstName.contains=" + DEFAULT_FIRST_NAME); // Get all the employeeRecordList where firstName contains UPDATED_FIRST_NAME defaultEmployeeRecordShouldNotBeFound("firstName.contains=" + UPDATED_FIRST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByFirstNameNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where firstName does not contain DEFAULT_FIRST_NAME defaultEmployeeRecordShouldNotBeFound("firstName.doesNotContain=" + DEFAULT_FIRST_NAME); // Get all the employeeRecordList where firstName does not contain UPDATED_FIRST_NAME defaultEmployeeRecordShouldBeFound("firstName.doesNotContain=" + UPDATED_FIRST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByMiddleNameIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where middleName equals to DEFAULT_MIDDLE_NAME defaultEmployeeRecordShouldBeFound("middleName.equals=" + DEFAULT_MIDDLE_NAME); // Get all the employeeRecordList where middleName equals to UPDATED_MIDDLE_NAME defaultEmployeeRecordShouldNotBeFound("middleName.equals=" + UPDATED_MIDDLE_NAME); } @Test @Transactional public void getAllEmployeeRecordsByMiddleNameIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where middleName not equals to DEFAULT_MIDDLE_NAME defaultEmployeeRecordShouldNotBeFound("middleName.notEquals=" + DEFAULT_MIDDLE_NAME); // Get all the employeeRecordList where middleName not equals to UPDATED_MIDDLE_NAME defaultEmployeeRecordShouldBeFound("middleName.notEquals=" + UPDATED_MIDDLE_NAME); } @Test @Transactional public void getAllEmployeeRecordsByMiddleNameIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where middleName in DEFAULT_MIDDLE_NAME or UPDATED_MIDDLE_NAME defaultEmployeeRecordShouldBeFound("middleName.in=" + DEFAULT_MIDDLE_NAME + "," + UPDATED_MIDDLE_NAME); // Get all the employeeRecordList where middleName equals to UPDATED_MIDDLE_NAME defaultEmployeeRecordShouldNotBeFound("middleName.in=" + UPDATED_MIDDLE_NAME); } @Test @Transactional public void getAllEmployeeRecordsByMiddleNameIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where middleName is not null defaultEmployeeRecordShouldBeFound("middleName.specified=true"); // Get all the employeeRecordList where middleName is null defaultEmployeeRecordShouldNotBeFound("middleName.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByMiddleNameContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where middleName contains DEFAULT_MIDDLE_NAME defaultEmployeeRecordShouldBeFound("middleName.contains=" + DEFAULT_MIDDLE_NAME); // Get all the employeeRecordList where middleName contains UPDATED_MIDDLE_NAME defaultEmployeeRecordShouldNotBeFound("middleName.contains=" + UPDATED_MIDDLE_NAME); } @Test @Transactional public void getAllEmployeeRecordsByMiddleNameNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where middleName does not contain DEFAULT_MIDDLE_NAME defaultEmployeeRecordShouldNotBeFound("middleName.doesNotContain=" + DEFAULT_MIDDLE_NAME); // Get all the employeeRecordList where middleName does not contain UPDATED_MIDDLE_NAME defaultEmployeeRecordShouldBeFound("middleName.doesNotContain=" + UPDATED_MIDDLE_NAME); } @Test @Transactional public void getAllEmployeeRecordsByLastNameIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where lastName equals to DEFAULT_LAST_NAME defaultEmployeeRecordShouldBeFound("lastName.equals=" + DEFAULT_LAST_NAME); // Get all the employeeRecordList where lastName equals to UPDATED_LAST_NAME defaultEmployeeRecordShouldNotBeFound("lastName.equals=" + UPDATED_LAST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByLastNameIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where lastName not equals to DEFAULT_LAST_NAME defaultEmployeeRecordShouldNotBeFound("lastName.notEquals=" + DEFAULT_LAST_NAME); // Get all the employeeRecordList where lastName not equals to UPDATED_LAST_NAME defaultEmployeeRecordShouldBeFound("lastName.notEquals=" + UPDATED_LAST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByLastNameIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where lastName in DEFAULT_LAST_NAME or UPDATED_LAST_NAME defaultEmployeeRecordShouldBeFound("lastName.in=" + DEFAULT_LAST_NAME + "," + UPDATED_LAST_NAME); // Get all the employeeRecordList where lastName equals to UPDATED_LAST_NAME defaultEmployeeRecordShouldNotBeFound("lastName.in=" + UPDATED_LAST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByLastNameIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where lastName is not null defaultEmployeeRecordShouldBeFound("lastName.specified=true"); // Get all the employeeRecordList where lastName is null defaultEmployeeRecordShouldNotBeFound("lastName.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByLastNameContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where lastName contains DEFAULT_LAST_NAME defaultEmployeeRecordShouldBeFound("lastName.contains=" + DEFAULT_LAST_NAME); // Get all the employeeRecordList where lastName contains UPDATED_LAST_NAME defaultEmployeeRecordShouldNotBeFound("lastName.contains=" + UPDATED_LAST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByLastNameNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where lastName does not contain DEFAULT_LAST_NAME defaultEmployeeRecordShouldNotBeFound("lastName.doesNotContain=" + DEFAULT_LAST_NAME); // Get all the employeeRecordList where lastName does not contain UPDATED_LAST_NAME defaultEmployeeRecordShouldBeFound("lastName.doesNotContain=" + UPDATED_LAST_NAME); } @Test @Transactional public void getAllEmployeeRecordsByAddressIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where address equals to DEFAULT_ADDRESS defaultEmployeeRecordShouldBeFound("address.equals=" + DEFAULT_ADDRESS); // Get all the employeeRecordList where address equals to UPDATED_ADDRESS defaultEmployeeRecordShouldNotBeFound("address.equals=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllEmployeeRecordsByAddressIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where address not equals to DEFAULT_ADDRESS defaultEmployeeRecordShouldNotBeFound("address.notEquals=" + DEFAULT_ADDRESS); // Get all the employeeRecordList where address not equals to UPDATED_ADDRESS defaultEmployeeRecordShouldBeFound("address.notEquals=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllEmployeeRecordsByAddressIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where address in DEFAULT_ADDRESS or UPDATED_ADDRESS defaultEmployeeRecordShouldBeFound("address.in=" + DEFAULT_ADDRESS + "," + UPDATED_ADDRESS); // Get all the employeeRecordList where address equals to UPDATED_ADDRESS defaultEmployeeRecordShouldNotBeFound("address.in=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllEmployeeRecordsByAddressIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where address is not null defaultEmployeeRecordShouldBeFound("address.specified=true"); // Get all the employeeRecordList where address is null defaultEmployeeRecordShouldNotBeFound("address.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByAddressContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where address contains DEFAULT_ADDRESS defaultEmployeeRecordShouldBeFound("address.contains=" + DEFAULT_ADDRESS); // Get all the employeeRecordList where address contains UPDATED_ADDRESS defaultEmployeeRecordShouldNotBeFound("address.contains=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllEmployeeRecordsByAddressNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where address does not contain DEFAULT_ADDRESS defaultEmployeeRecordShouldNotBeFound("address.doesNotContain=" + DEFAULT_ADDRESS); // Get all the employeeRecordList where address does not contain UPDATED_ADDRESS defaultEmployeeRecordShouldBeFound("address.doesNotContain=" + UPDATED_ADDRESS); } @Test @Transactional public void getAllEmployeeRecordsByGenderIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where gender equals to DEFAULT_GENDER defaultEmployeeRecordShouldBeFound("gender.equals=" + DEFAULT_GENDER); // Get all the employeeRecordList where gender equals to UPDATED_GENDER defaultEmployeeRecordShouldNotBeFound("gender.equals=" + UPDATED_GENDER); } @Test @Transactional public void getAllEmployeeRecordsByGenderIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where gender not equals to DEFAULT_GENDER defaultEmployeeRecordShouldNotBeFound("gender.notEquals=" + DEFAULT_GENDER); // Get all the employeeRecordList where gender not equals to UPDATED_GENDER defaultEmployeeRecordShouldBeFound("gender.notEquals=" + UPDATED_GENDER); } @Test @Transactional public void getAllEmployeeRecordsByGenderIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where gender in DEFAULT_GENDER or UPDATED_GENDER defaultEmployeeRecordShouldBeFound("gender.in=" + DEFAULT_GENDER + "," + UPDATED_GENDER); // Get all the employeeRecordList where gender equals to UPDATED_GENDER defaultEmployeeRecordShouldNotBeFound("gender.in=" + UPDATED_GENDER); } @Test @Transactional public void getAllEmployeeRecordsByGenderIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where gender is not null defaultEmployeeRecordShouldBeFound("gender.specified=true"); // Get all the employeeRecordList where gender is null defaultEmployeeRecordShouldNotBeFound("gender.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByGenderContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where gender contains DEFAULT_GENDER defaultEmployeeRecordShouldBeFound("gender.contains=" + DEFAULT_GENDER); // Get all the employeeRecordList where gender contains UPDATED_GENDER defaultEmployeeRecordShouldNotBeFound("gender.contains=" + UPDATED_GENDER); } @Test @Transactional public void getAllEmployeeRecordsByGenderNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where gender does not contain DEFAULT_GENDER defaultEmployeeRecordShouldNotBeFound("gender.doesNotContain=" + DEFAULT_GENDER); // Get all the employeeRecordList where gender does not contain UPDATED_GENDER defaultEmployeeRecordShouldBeFound("gender.doesNotContain=" + UPDATED_GENDER); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate equals to DEFAULT_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.equals=" + DEFAULT_BIRTH_DATE); // Get all the employeeRecordList where birthDate equals to UPDATED_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.equals=" + UPDATED_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate not equals to DEFAULT_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.notEquals=" + DEFAULT_BIRTH_DATE); // Get all the employeeRecordList where birthDate not equals to UPDATED_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.notEquals=" + UPDATED_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate in DEFAULT_BIRTH_DATE or UPDATED_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.in=" + DEFAULT_BIRTH_DATE + "," + UPDATED_BIRTH_DATE); // Get all the employeeRecordList where birthDate equals to UPDATED_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.in=" + UPDATED_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate is not null defaultEmployeeRecordShouldBeFound("birthDate.specified=true"); // Get all the employeeRecordList where birthDate is null defaultEmployeeRecordShouldNotBeFound("birthDate.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate is greater than or equal to DEFAULT_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.greaterThanOrEqual=" + DEFAULT_BIRTH_DATE); // Get all the employeeRecordList where birthDate is greater than or equal to UPDATED_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.greaterThanOrEqual=" + UPDATED_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsLessThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate is less than or equal to DEFAULT_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.lessThanOrEqual=" + DEFAULT_BIRTH_DATE); // Get all the employeeRecordList where birthDate is less than or equal to SMALLER_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.lessThanOrEqual=" + SMALLER_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsLessThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate is less than DEFAULT_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.lessThan=" + DEFAULT_BIRTH_DATE); // Get all the employeeRecordList where birthDate is less than UPDATED_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.lessThan=" + UPDATED_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBirthDateIsGreaterThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where birthDate is greater than DEFAULT_BIRTH_DATE defaultEmployeeRecordShouldNotBeFound("birthDate.greaterThan=" + DEFAULT_BIRTH_DATE); // Get all the employeeRecordList where birthDate is greater than SMALLER_BIRTH_DATE defaultEmployeeRecordShouldBeFound("birthDate.greaterThan=" + SMALLER_BIRTH_DATE); } @Test @Transactional public void getAllEmployeeRecordsByEmailIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where email equals to DEFAULT_EMAIL defaultEmployeeRecordShouldBeFound("email.equals=" + DEFAULT_EMAIL); // Get all the employeeRecordList where email equals to UPDATED_EMAIL defaultEmployeeRecordShouldNotBeFound("email.equals=" + UPDATED_EMAIL); } @Test @Transactional public void getAllEmployeeRecordsByEmailIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where email not equals to DEFAULT_EMAIL defaultEmployeeRecordShouldNotBeFound("email.notEquals=" + DEFAULT_EMAIL); // Get all the employeeRecordList where email not equals to UPDATED_EMAIL defaultEmployeeRecordShouldBeFound("email.notEquals=" + UPDATED_EMAIL); } @Test @Transactional public void getAllEmployeeRecordsByEmailIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where email in DEFAULT_EMAIL or UPDATED_EMAIL defaultEmployeeRecordShouldBeFound("email.in=" + DEFAULT_EMAIL + "," + UPDATED_EMAIL); // Get all the employeeRecordList where email equals to UPDATED_EMAIL defaultEmployeeRecordShouldNotBeFound("email.in=" + UPDATED_EMAIL); } @Test @Transactional public void getAllEmployeeRecordsByEmailIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where email is not null defaultEmployeeRecordShouldBeFound("email.specified=true"); // Get all the employeeRecordList where email is null defaultEmployeeRecordShouldNotBeFound("email.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByEmailContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where email contains DEFAULT_EMAIL defaultEmployeeRecordShouldBeFound("email.contains=" + DEFAULT_EMAIL); // Get all the employeeRecordList where email contains UPDATED_EMAIL defaultEmployeeRecordShouldNotBeFound("email.contains=" + UPDATED_EMAIL); } @Test @Transactional public void getAllEmployeeRecordsByEmailNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where email does not contain DEFAULT_EMAIL defaultEmployeeRecordShouldNotBeFound("email.doesNotContain=" + DEFAULT_EMAIL); // Get all the employeeRecordList where email does not contain UPDATED_EMAIL defaultEmployeeRecordShouldBeFound("email.doesNotContain=" + UPDATED_EMAIL); } @Test @Transactional public void getAllEmployeeRecordsByCellPhoneIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where cellPhone equals to DEFAULT_CELL_PHONE defaultEmployeeRecordShouldBeFound("cellPhone.equals=" + DEFAULT_CELL_PHONE); // Get all the employeeRecordList where cellPhone equals to UPDATED_CELL_PHONE defaultEmployeeRecordShouldNotBeFound("cellPhone.equals=" + UPDATED_CELL_PHONE); } @Test @Transactional public void getAllEmployeeRecordsByCellPhoneIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where cellPhone not equals to DEFAULT_CELL_PHONE defaultEmployeeRecordShouldNotBeFound("cellPhone.notEquals=" + DEFAULT_CELL_PHONE); // Get all the employeeRecordList where cellPhone not equals to UPDATED_CELL_PHONE defaultEmployeeRecordShouldBeFound("cellPhone.notEquals=" + UPDATED_CELL_PHONE); } @Test @Transactional public void getAllEmployeeRecordsByCellPhoneIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where cellPhone in DEFAULT_CELL_PHONE or UPDATED_CELL_PHONE defaultEmployeeRecordShouldBeFound("cellPhone.in=" + DEFAULT_CELL_PHONE + "," + UPDATED_CELL_PHONE); // Get all the employeeRecordList where cellPhone equals to UPDATED_CELL_PHONE defaultEmployeeRecordShouldNotBeFound("cellPhone.in=" + UPDATED_CELL_PHONE); } @Test @Transactional public void getAllEmployeeRecordsByCellPhoneIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where cellPhone is not null defaultEmployeeRecordShouldBeFound("cellPhone.specified=true"); // Get all the employeeRecordList where cellPhone is null defaultEmployeeRecordShouldNotBeFound("cellPhone.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByCellPhoneContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where cellPhone contains DEFAULT_CELL_PHONE defaultEmployeeRecordShouldBeFound("cellPhone.contains=" + DEFAULT_CELL_PHONE); // Get all the employeeRecordList where cellPhone contains UPDATED_CELL_PHONE defaultEmployeeRecordShouldNotBeFound("cellPhone.contains=" + UPDATED_CELL_PHONE); } @Test @Transactional public void getAllEmployeeRecordsByCellPhoneNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where cellPhone does not contain DEFAULT_CELL_PHONE defaultEmployeeRecordShouldNotBeFound("cellPhone.doesNotContain=" + DEFAULT_CELL_PHONE); // Get all the employeeRecordList where cellPhone does not contain UPDATED_CELL_PHONE defaultEmployeeRecordShouldBeFound("cellPhone.doesNotContain=" + UPDATED_CELL_PHONE); } @Test @Transactional public void getAllEmployeeRecordsByTelephoneIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where telephone equals to DEFAULT_TELEPHONE defaultEmployeeRecordShouldBeFound("telephone.equals=" + DEFAULT_TELEPHONE); // Get all the employeeRecordList where telephone equals to UPDATED_TELEPHONE defaultEmployeeRecordShouldNotBeFound("telephone.equals=" + UPDATED_TELEPHONE); } @Test @Transactional public void getAllEmployeeRecordsByTelephoneIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where telephone not equals to DEFAULT_TELEPHONE defaultEmployeeRecordShouldNotBeFound("telephone.notEquals=" + DEFAULT_TELEPHONE); // Get all the employeeRecordList where telephone not equals to UPDATED_TELEPHONE defaultEmployeeRecordShouldBeFound("telephone.notEquals=" + UPDATED_TELEPHONE); } @Test @Transactional public void getAllEmployeeRecordsByTelephoneIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where telephone in DEFAULT_TELEPHONE or UPDATED_TELEPHONE defaultEmployeeRecordShouldBeFound("telephone.in=" + DEFAULT_TELEPHONE + "," + UPDATED_TELEPHONE); // Get all the employeeRecordList where telephone equals to UPDATED_TELEPHONE defaultEmployeeRecordShouldNotBeFound("telephone.in=" + UPDATED_TELEPHONE); } @Test @Transactional public void getAllEmployeeRecordsByTelephoneIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where telephone is not null defaultEmployeeRecordShouldBeFound("telephone.specified=true"); // Get all the employeeRecordList where telephone is null defaultEmployeeRecordShouldNotBeFound("telephone.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByTelephoneContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where telephone contains DEFAULT_TELEPHONE defaultEmployeeRecordShouldBeFound("telephone.contains=" + DEFAULT_TELEPHONE); // Get all the employeeRecordList where telephone contains UPDATED_TELEPHONE defaultEmployeeRecordShouldNotBeFound("telephone.contains=" + UPDATED_TELEPHONE); } @Test @Transactional public void getAllEmployeeRecordsByTelephoneNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where telephone does not contain DEFAULT_TELEPHONE defaultEmployeeRecordShouldNotBeFound("telephone.doesNotContain=" + DEFAULT_TELEPHONE); // Get all the employeeRecordList where telephone does not contain UPDATED_TELEPHONE defaultEmployeeRecordShouldBeFound("telephone.doesNotContain=" + UPDATED_TELEPHONE); } @Test @Transactional public void getAllEmployeeRecordsByMaritalStatusIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where maritalStatus equals to DEFAULT_MARITAL_STATUS defaultEmployeeRecordShouldBeFound("maritalStatus.equals=" + DEFAULT_MARITAL_STATUS); // Get all the employeeRecordList where maritalStatus equals to UPDATED_MARITAL_STATUS defaultEmployeeRecordShouldNotBeFound("maritalStatus.equals=" + UPDATED_MARITAL_STATUS); } @Test @Transactional public void getAllEmployeeRecordsByMaritalStatusIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where maritalStatus not equals to DEFAULT_MARITAL_STATUS defaultEmployeeRecordShouldNotBeFound("maritalStatus.notEquals=" + DEFAULT_MARITAL_STATUS); // Get all the employeeRecordList where maritalStatus not equals to UPDATED_MARITAL_STATUS defaultEmployeeRecordShouldBeFound("maritalStatus.notEquals=" + UPDATED_MARITAL_STATUS); } @Test @Transactional public void getAllEmployeeRecordsByMaritalStatusIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where maritalStatus in DEFAULT_MARITAL_STATUS or UPDATED_MARITAL_STATUS defaultEmployeeRecordShouldBeFound("maritalStatus.in=" + DEFAULT_MARITAL_STATUS + "," + UPDATED_MARITAL_STATUS); // Get all the employeeRecordList where maritalStatus equals to UPDATED_MARITAL_STATUS defaultEmployeeRecordShouldNotBeFound("maritalStatus.in=" + UPDATED_MARITAL_STATUS); } @Test @Transactional public void getAllEmployeeRecordsByMaritalStatusIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where maritalStatus is not null defaultEmployeeRecordShouldBeFound("maritalStatus.specified=true"); // Get all the employeeRecordList where maritalStatus is null defaultEmployeeRecordShouldNotBeFound("maritalStatus.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByMaritalStatusContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where maritalStatus contains DEFAULT_MARITAL_STATUS defaultEmployeeRecordShouldBeFound("maritalStatus.contains=" + DEFAULT_MARITAL_STATUS); // Get all the employeeRecordList where maritalStatus contains UPDATED_MARITAL_STATUS defaultEmployeeRecordShouldNotBeFound("maritalStatus.contains=" + UPDATED_MARITAL_STATUS); } @Test @Transactional public void getAllEmployeeRecordsByMaritalStatusNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where maritalStatus does not contain DEFAULT_MARITAL_STATUS defaultEmployeeRecordShouldNotBeFound("maritalStatus.doesNotContain=" + DEFAULT_MARITAL_STATUS); // Get all the employeeRecordList where maritalStatus does not contain UPDATED_MARITAL_STATUS defaultEmployeeRecordShouldBeFound("maritalStatus.doesNotContain=" + UPDATED_MARITAL_STATUS); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeNumberIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where employeeNumber equals to DEFAULT_EMPLOYEE_NUMBER defaultEmployeeRecordShouldBeFound("employeeNumber.equals=" + DEFAULT_EMPLOYEE_NUMBER); // Get all the employeeRecordList where employeeNumber equals to UPDATED_EMPLOYEE_NUMBER defaultEmployeeRecordShouldNotBeFound("employeeNumber.equals=" + UPDATED_EMPLOYEE_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeNumberIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where employeeNumber not equals to DEFAULT_EMPLOYEE_NUMBER defaultEmployeeRecordShouldNotBeFound("employeeNumber.notEquals=" + DEFAULT_EMPLOYEE_NUMBER); // Get all the employeeRecordList where employeeNumber not equals to UPDATED_EMPLOYEE_NUMBER defaultEmployeeRecordShouldBeFound("employeeNumber.notEquals=" + UPDATED_EMPLOYEE_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeNumberIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where employeeNumber in DEFAULT_EMPLOYEE_NUMBER or UPDATED_EMPLOYEE_NUMBER defaultEmployeeRecordShouldBeFound("employeeNumber.in=" + DEFAULT_EMPLOYEE_NUMBER + "," + UPDATED_EMPLOYEE_NUMBER); // Get all the employeeRecordList where employeeNumber equals to UPDATED_EMPLOYEE_NUMBER defaultEmployeeRecordShouldNotBeFound("employeeNumber.in=" + UPDATED_EMPLOYEE_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeNumberIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where employeeNumber is not null defaultEmployeeRecordShouldBeFound("employeeNumber.specified=true"); // Get all the employeeRecordList where employeeNumber is null defaultEmployeeRecordShouldNotBeFound("employeeNumber.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeNumberContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where employeeNumber contains DEFAULT_EMPLOYEE_NUMBER defaultEmployeeRecordShouldBeFound("employeeNumber.contains=" + DEFAULT_EMPLOYEE_NUMBER); // Get all the employeeRecordList where employeeNumber contains UPDATED_EMPLOYEE_NUMBER defaultEmployeeRecordShouldNotBeFound("employeeNumber.contains=" + UPDATED_EMPLOYEE_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeNumberNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where employeeNumber does not contain DEFAULT_EMPLOYEE_NUMBER defaultEmployeeRecordShouldNotBeFound("employeeNumber.doesNotContain=" + DEFAULT_EMPLOYEE_NUMBER); // Get all the employeeRecordList where employeeNumber does not contain UPDATED_EMPLOYEE_NUMBER defaultEmployeeRecordShouldBeFound("employeeNumber.doesNotContain=" + UPDATED_EMPLOYEE_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByActiveIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where active equals to DEFAULT_ACTIVE defaultEmployeeRecordShouldBeFound("active.equals=" + DEFAULT_ACTIVE); // Get all the employeeRecordList where active equals to UPDATED_ACTIVE defaultEmployeeRecordShouldNotBeFound("active.equals=" + UPDATED_ACTIVE); } @Test @Transactional public void getAllEmployeeRecordsByActiveIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where active not equals to DEFAULT_ACTIVE defaultEmployeeRecordShouldNotBeFound("active.notEquals=" + DEFAULT_ACTIVE); // Get all the employeeRecordList where active not equals to UPDATED_ACTIVE defaultEmployeeRecordShouldBeFound("active.notEquals=" + UPDATED_ACTIVE); } @Test @Transactional public void getAllEmployeeRecordsByActiveIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where active in DEFAULT_ACTIVE or UPDATED_ACTIVE defaultEmployeeRecordShouldBeFound("active.in=" + DEFAULT_ACTIVE + "," + UPDATED_ACTIVE); // Get all the employeeRecordList where active equals to UPDATED_ACTIVE defaultEmployeeRecordShouldNotBeFound("active.in=" + UPDATED_ACTIVE); } @Test @Transactional public void getAllEmployeeRecordsByActiveIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where active is not null defaultEmployeeRecordShouldBeFound("active.specified=true"); // Get all the employeeRecordList where active is null defaultEmployeeRecordShouldNotBeFound("active.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining equals to DEFAULT_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.equals=" + DEFAULT_DATE_JOINING); // Get all the employeeRecordList where dateJoining equals to UPDATED_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.equals=" + UPDATED_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining not equals to DEFAULT_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.notEquals=" + DEFAULT_DATE_JOINING); // Get all the employeeRecordList where dateJoining not equals to UPDATED_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.notEquals=" + UPDATED_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining in DEFAULT_DATE_JOINING or UPDATED_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.in=" + DEFAULT_DATE_JOINING + "," + UPDATED_DATE_JOINING); // Get all the employeeRecordList where dateJoining equals to UPDATED_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.in=" + UPDATED_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining is not null defaultEmployeeRecordShouldBeFound("dateJoining.specified=true"); // Get all the employeeRecordList where dateJoining is null defaultEmployeeRecordShouldNotBeFound("dateJoining.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining is greater than or equal to DEFAULT_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.greaterThanOrEqual=" + DEFAULT_DATE_JOINING); // Get all the employeeRecordList where dateJoining is greater than or equal to UPDATED_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.greaterThanOrEqual=" + UPDATED_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsLessThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining is less than or equal to DEFAULT_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.lessThanOrEqual=" + DEFAULT_DATE_JOINING); // Get all the employeeRecordList where dateJoining is less than or equal to SMALLER_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.lessThanOrEqual=" + SMALLER_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsLessThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining is less than DEFAULT_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.lessThan=" + DEFAULT_DATE_JOINING); // Get all the employeeRecordList where dateJoining is less than UPDATED_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.lessThan=" + UPDATED_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsByDateJoiningIsGreaterThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where dateJoining is greater than DEFAULT_DATE_JOINING defaultEmployeeRecordShouldNotBeFound("dateJoining.greaterThan=" + DEFAULT_DATE_JOINING); // Get all the employeeRecordList where dateJoining is greater than SMALLER_DATE_JOINING defaultEmployeeRecordShouldBeFound("dateJoining.greaterThan=" + SMALLER_DATE_JOINING); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary equals to DEFAULT_SALARY defaultEmployeeRecordShouldBeFound("salary.equals=" + DEFAULT_SALARY); // Get all the employeeRecordList where salary equals to UPDATED_SALARY defaultEmployeeRecordShouldNotBeFound("salary.equals=" + UPDATED_SALARY); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary not equals to DEFAULT_SALARY defaultEmployeeRecordShouldNotBeFound("salary.notEquals=" + DEFAULT_SALARY); // Get all the employeeRecordList where salary not equals to UPDATED_SALARY defaultEmployeeRecordShouldBeFound("salary.notEquals=" + UPDATED_SALARY); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary in DEFAULT_SALARY or UPDATED_SALARY defaultEmployeeRecordShouldBeFound("salary.in=" + DEFAULT_SALARY + "," + UPDATED_SALARY); // Get all the employeeRecordList where salary equals to UPDATED_SALARY defaultEmployeeRecordShouldNotBeFound("salary.in=" + UPDATED_SALARY); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary is not null defaultEmployeeRecordShouldBeFound("salary.specified=true"); // Get all the employeeRecordList where salary is null defaultEmployeeRecordShouldNotBeFound("salary.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary is greater than or equal to DEFAULT_SALARY defaultEmployeeRecordShouldBeFound("salary.greaterThanOrEqual=" + DEFAULT_SALARY); // Get all the employeeRecordList where salary is greater than or equal to UPDATED_SALARY defaultEmployeeRecordShouldNotBeFound("salary.greaterThanOrEqual=" + UPDATED_SALARY); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsLessThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary is less than or equal to DEFAULT_SALARY defaultEmployeeRecordShouldBeFound("salary.lessThanOrEqual=" + DEFAULT_SALARY); // Get all the employeeRecordList where salary is less than or equal to SMALLER_SALARY defaultEmployeeRecordShouldNotBeFound("salary.lessThanOrEqual=" + SMALLER_SALARY); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsLessThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary is less than DEFAULT_SALARY defaultEmployeeRecordShouldNotBeFound("salary.lessThan=" + DEFAULT_SALARY); // Get all the employeeRecordList where salary is less than UPDATED_SALARY defaultEmployeeRecordShouldBeFound("salary.lessThan=" + UPDATED_SALARY); } @Test @Transactional public void getAllEmployeeRecordsBySalaryIsGreaterThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where salary is greater than DEFAULT_SALARY defaultEmployeeRecordShouldNotBeFound("salary.greaterThan=" + DEFAULT_SALARY); // Get all the employeeRecordList where salary is greater than SMALLER_SALARY defaultEmployeeRecordShouldBeFound("salary.greaterThan=" + SMALLER_SALARY); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate equals to DEFAULT_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.equals=" + DEFAULT_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate equals to UPDATED_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.equals=" + UPDATED_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate not equals to DEFAULT_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.notEquals=" + DEFAULT_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate not equals to UPDATED_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.notEquals=" + UPDATED_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate in DEFAULT_CONTRACT_START_DATE or UPDATED_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.in=" + DEFAULT_CONTRACT_START_DATE + "," + UPDATED_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate equals to UPDATED_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.in=" + UPDATED_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate is not null defaultEmployeeRecordShouldBeFound("contractStartDate.specified=true"); // Get all the employeeRecordList where contractStartDate is null defaultEmployeeRecordShouldNotBeFound("contractStartDate.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate is greater than or equal to DEFAULT_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.greaterThanOrEqual=" + DEFAULT_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate is greater than or equal to UPDATED_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.greaterThanOrEqual=" + UPDATED_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsLessThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate is less than or equal to DEFAULT_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.lessThanOrEqual=" + DEFAULT_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate is less than or equal to SMALLER_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.lessThanOrEqual=" + SMALLER_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsLessThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate is less than DEFAULT_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.lessThan=" + DEFAULT_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate is less than UPDATED_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.lessThan=" + UPDATED_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractStartDateIsGreaterThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractStartDate is greater than DEFAULT_CONTRACT_START_DATE defaultEmployeeRecordShouldNotBeFound("contractStartDate.greaterThan=" + DEFAULT_CONTRACT_START_DATE); // Get all the employeeRecordList where contractStartDate is greater than SMALLER_CONTRACT_START_DATE defaultEmployeeRecordShouldBeFound("contractStartDate.greaterThan=" + SMALLER_CONTRACT_START_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate equals to DEFAULT_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.equals=" + DEFAULT_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate equals to UPDATED_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.equals=" + UPDATED_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate not equals to DEFAULT_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.notEquals=" + DEFAULT_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate not equals to UPDATED_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.notEquals=" + UPDATED_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate in DEFAULT_CONTRACT_END_DATE or UPDATED_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.in=" + DEFAULT_CONTRACT_END_DATE + "," + UPDATED_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate equals to UPDATED_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.in=" + UPDATED_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate is not null defaultEmployeeRecordShouldBeFound("contractEndDate.specified=true"); // Get all the employeeRecordList where contractEndDate is null defaultEmployeeRecordShouldNotBeFound("contractEndDate.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate is greater than or equal to DEFAULT_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.greaterThanOrEqual=" + DEFAULT_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate is greater than or equal to UPDATED_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.greaterThanOrEqual=" + UPDATED_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsLessThanOrEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate is less than or equal to DEFAULT_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.lessThanOrEqual=" + DEFAULT_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate is less than or equal to SMALLER_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.lessThanOrEqual=" + SMALLER_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsLessThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate is less than DEFAULT_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.lessThan=" + DEFAULT_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate is less than UPDATED_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.lessThan=" + UPDATED_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByContractEndDateIsGreaterThanSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where contractEndDate is greater than DEFAULT_CONTRACT_END_DATE defaultEmployeeRecordShouldNotBeFound("contractEndDate.greaterThan=" + DEFAULT_CONTRACT_END_DATE); // Get all the employeeRecordList where contractEndDate is greater than SMALLER_CONTRACT_END_DATE defaultEmployeeRecordShouldBeFound("contractEndDate.greaterThan=" + SMALLER_CONTRACT_END_DATE); } @Test @Transactional public void getAllEmployeeRecordsByBankNameIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankName equals to DEFAULT_BANK_NAME defaultEmployeeRecordShouldBeFound("bankName.equals=" + DEFAULT_BANK_NAME); // Get all the employeeRecordList where bankName equals to UPDATED_BANK_NAME defaultEmployeeRecordShouldNotBeFound("bankName.equals=" + UPDATED_BANK_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBankNameIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankName not equals to DEFAULT_BANK_NAME defaultEmployeeRecordShouldNotBeFound("bankName.notEquals=" + DEFAULT_BANK_NAME); // Get all the employeeRecordList where bankName not equals to UPDATED_BANK_NAME defaultEmployeeRecordShouldBeFound("bankName.notEquals=" + UPDATED_BANK_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBankNameIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankName in DEFAULT_BANK_NAME or UPDATED_BANK_NAME defaultEmployeeRecordShouldBeFound("bankName.in=" + DEFAULT_BANK_NAME + "," + UPDATED_BANK_NAME); // Get all the employeeRecordList where bankName equals to UPDATED_BANK_NAME defaultEmployeeRecordShouldNotBeFound("bankName.in=" + UPDATED_BANK_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBankNameIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankName is not null defaultEmployeeRecordShouldBeFound("bankName.specified=true"); // Get all the employeeRecordList where bankName is null defaultEmployeeRecordShouldNotBeFound("bankName.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByBankNameContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankName contains DEFAULT_BANK_NAME defaultEmployeeRecordShouldBeFound("bankName.contains=" + DEFAULT_BANK_NAME); // Get all the employeeRecordList where bankName contains UPDATED_BANK_NAME defaultEmployeeRecordShouldNotBeFound("bankName.contains=" + UPDATED_BANK_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBankNameNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankName does not contain DEFAULT_BANK_NAME defaultEmployeeRecordShouldNotBeFound("bankName.doesNotContain=" + DEFAULT_BANK_NAME); // Get all the employeeRecordList where bankName does not contain UPDATED_BANK_NAME defaultEmployeeRecordShouldBeFound("bankName.doesNotContain=" + UPDATED_BANK_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBranchNameIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where branchName equals to DEFAULT_BRANCH_NAME defaultEmployeeRecordShouldBeFound("branchName.equals=" + DEFAULT_BRANCH_NAME); // Get all the employeeRecordList where branchName equals to UPDATED_BRANCH_NAME defaultEmployeeRecordShouldNotBeFound("branchName.equals=" + UPDATED_BRANCH_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBranchNameIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where branchName not equals to DEFAULT_BRANCH_NAME defaultEmployeeRecordShouldNotBeFound("branchName.notEquals=" + DEFAULT_BRANCH_NAME); // Get all the employeeRecordList where branchName not equals to UPDATED_BRANCH_NAME defaultEmployeeRecordShouldBeFound("branchName.notEquals=" + UPDATED_BRANCH_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBranchNameIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where branchName in DEFAULT_BRANCH_NAME or UPDATED_BRANCH_NAME defaultEmployeeRecordShouldBeFound("branchName.in=" + DEFAULT_BRANCH_NAME + "," + UPDATED_BRANCH_NAME); // Get all the employeeRecordList where branchName equals to UPDATED_BRANCH_NAME defaultEmployeeRecordShouldNotBeFound("branchName.in=" + UPDATED_BRANCH_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBranchNameIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where branchName is not null defaultEmployeeRecordShouldBeFound("branchName.specified=true"); // Get all the employeeRecordList where branchName is null defaultEmployeeRecordShouldNotBeFound("branchName.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByBranchNameContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where branchName contains DEFAULT_BRANCH_NAME defaultEmployeeRecordShouldBeFound("branchName.contains=" + DEFAULT_BRANCH_NAME); // Get all the employeeRecordList where branchName contains UPDATED_BRANCH_NAME defaultEmployeeRecordShouldNotBeFound("branchName.contains=" + UPDATED_BRANCH_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBranchNameNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where branchName does not contain DEFAULT_BRANCH_NAME defaultEmployeeRecordShouldNotBeFound("branchName.doesNotContain=" + DEFAULT_BRANCH_NAME); // Get all the employeeRecordList where branchName does not contain UPDATED_BRANCH_NAME defaultEmployeeRecordShouldBeFound("branchName.doesNotContain=" + UPDATED_BRANCH_NAME); } @Test @Transactional public void getAllEmployeeRecordsByBankAccountIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankAccount equals to DEFAULT_BANK_ACCOUNT defaultEmployeeRecordShouldBeFound("bankAccount.equals=" + DEFAULT_BANK_ACCOUNT); // Get all the employeeRecordList where bankAccount equals to UPDATED_BANK_ACCOUNT defaultEmployeeRecordShouldNotBeFound("bankAccount.equals=" + UPDATED_BANK_ACCOUNT); } @Test @Transactional public void getAllEmployeeRecordsByBankAccountIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankAccount not equals to DEFAULT_BANK_ACCOUNT defaultEmployeeRecordShouldNotBeFound("bankAccount.notEquals=" + DEFAULT_BANK_ACCOUNT); // Get all the employeeRecordList where bankAccount not equals to UPDATED_BANK_ACCOUNT defaultEmployeeRecordShouldBeFound("bankAccount.notEquals=" + UPDATED_BANK_ACCOUNT); } @Test @Transactional public void getAllEmployeeRecordsByBankAccountIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankAccount in DEFAULT_BANK_ACCOUNT or UPDATED_BANK_ACCOUNT defaultEmployeeRecordShouldBeFound("bankAccount.in=" + DEFAULT_BANK_ACCOUNT + "," + UPDATED_BANK_ACCOUNT); // Get all the employeeRecordList where bankAccount equals to UPDATED_BANK_ACCOUNT defaultEmployeeRecordShouldNotBeFound("bankAccount.in=" + UPDATED_BANK_ACCOUNT); } @Test @Transactional public void getAllEmployeeRecordsByBankAccountIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankAccount is not null defaultEmployeeRecordShouldBeFound("bankAccount.specified=true"); // Get all the employeeRecordList where bankAccount is null defaultEmployeeRecordShouldNotBeFound("bankAccount.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByBankAccountContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankAccount contains DEFAULT_BANK_ACCOUNT defaultEmployeeRecordShouldBeFound("bankAccount.contains=" + DEFAULT_BANK_ACCOUNT); // Get all the employeeRecordList where bankAccount contains UPDATED_BANK_ACCOUNT defaultEmployeeRecordShouldNotBeFound("bankAccount.contains=" + UPDATED_BANK_ACCOUNT); } @Test @Transactional public void getAllEmployeeRecordsByBankAccountNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where bankAccount does not contain DEFAULT_BANK_ACCOUNT defaultEmployeeRecordShouldNotBeFound("bankAccount.doesNotContain=" + DEFAULT_BANK_ACCOUNT); // Get all the employeeRecordList where bankAccount does not contain UPDATED_BANK_ACCOUNT defaultEmployeeRecordShouldBeFound("bankAccount.doesNotContain=" + UPDATED_BANK_ACCOUNT); } @Test @Transactional public void getAllEmployeeRecordsByInsuranceRegistrationNumberIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where insuranceRegistrationNumber equals to DEFAULT_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldBeFound("insuranceRegistrationNumber.equals=" + DEFAULT_INSURANCE_REGISTRATION_NUMBER); // Get all the employeeRecordList where insuranceRegistrationNumber equals to UPDATED_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldNotBeFound("insuranceRegistrationNumber.equals=" + UPDATED_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByInsuranceRegistrationNumberIsNotEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where insuranceRegistrationNumber not equals to DEFAULT_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldNotBeFound("insuranceRegistrationNumber.notEquals=" + DEFAULT_INSURANCE_REGISTRATION_NUMBER); // Get all the employeeRecordList where insuranceRegistrationNumber not equals to UPDATED_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldBeFound("insuranceRegistrationNumber.notEquals=" + UPDATED_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByInsuranceRegistrationNumberIsInShouldWork() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where insuranceRegistrationNumber in DEFAULT_INSURANCE_REGISTRATION_NUMBER or UPDATED_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldBeFound("insuranceRegistrationNumber.in=" + DEFAULT_INSURANCE_REGISTRATION_NUMBER + "," + UPDATED_INSURANCE_REGISTRATION_NUMBER); // Get all the employeeRecordList where insuranceRegistrationNumber equals to UPDATED_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldNotBeFound("insuranceRegistrationNumber.in=" + UPDATED_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByInsuranceRegistrationNumberIsNullOrNotNull() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where insuranceRegistrationNumber is not null defaultEmployeeRecordShouldBeFound("insuranceRegistrationNumber.specified=true"); // Get all the employeeRecordList where insuranceRegistrationNumber is null defaultEmployeeRecordShouldNotBeFound("insuranceRegistrationNumber.specified=false"); } @Test @Transactional public void getAllEmployeeRecordsByInsuranceRegistrationNumberContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where insuranceRegistrationNumber contains DEFAULT_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldBeFound("insuranceRegistrationNumber.contains=" + DEFAULT_INSURANCE_REGISTRATION_NUMBER); // Get all the employeeRecordList where insuranceRegistrationNumber contains UPDATED_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldNotBeFound("insuranceRegistrationNumber.contains=" + UPDATED_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByInsuranceRegistrationNumberNotContainsSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); // Get all the employeeRecordList where insuranceRegistrationNumber does not contain DEFAULT_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldNotBeFound("insuranceRegistrationNumber.doesNotContain=" + DEFAULT_INSURANCE_REGISTRATION_NUMBER); // Get all the employeeRecordList where insuranceRegistrationNumber does not contain UPDATED_INSURANCE_REGISTRATION_NUMBER defaultEmployeeRecordShouldBeFound("insuranceRegistrationNumber.doesNotContain=" + UPDATED_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void getAllEmployeeRecordsByAttachmentsIsEqualToSomething() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); Attachment attachments = AttachmentResourceIT.createEntity(em); em.persist(attachments); em.flush(); employeeRecord.addAttachments(attachments); employeeRecordRepository.saveAndFlush(employeeRecord); Long attachmentsId = attachments.getId(); // Get all the employeeRecordList where attachments equals to attachmentsId defaultEmployeeRecordShouldBeFound("attachmentsId.equals=" + attachmentsId); // Get all the employeeRecordList where attachments equals to attachmentsId + 1 defaultEmployeeRecordShouldNotBeFound("attachmentsId.equals=" + (attachmentsId + 1)); } @Test @Transactional public void getAllEmployeeRecordsByDepartmentIsEqualToSomething() throws Exception { // Get already existing entity Department department = employeeRecord.getDepartment(); employeeRecordRepository.saveAndFlush(employeeRecord); Long departmentId = department.getId(); // Get all the employeeRecordList where department equals to departmentId defaultEmployeeRecordShouldBeFound("departmentId.equals=" + departmentId); // Get all the employeeRecordList where department equals to departmentId + 1 defaultEmployeeRecordShouldNotBeFound("departmentId.equals=" + (departmentId + 1)); } @Test @Transactional public void getAllEmployeeRecordsByEmployeeTypeIsEqualToSomething() throws Exception { // Get already existing entity EmploymentCategory employeeType = employeeRecord.getEmployeeType(); employeeRecordRepository.saveAndFlush(employeeRecord); Long employeeTypeId = employeeType.getId(); // Get all the employeeRecordList where employeeType equals to employeeTypeId defaultEmployeeRecordShouldBeFound("employeeTypeId.equals=" + employeeTypeId); // Get all the employeeRecordList where employeeType equals to employeeTypeId + 1 defaultEmployeeRecordShouldNotBeFound("employeeTypeId.equals=" + (employeeTypeId + 1)); } @Test @Transactional public void getAllEmployeeRecordsByDesignationIsEqualToSomething() throws Exception { // Get already existing entity Carder designation = employeeRecord.getDesignation(); employeeRecordRepository.saveAndFlush(employeeRecord); Long designationId = designation.getId(); // Get all the employeeRecordList where designation equals to designationId defaultEmployeeRecordShouldBeFound("designationId.equals=" + designationId); // Get all the employeeRecordList where designation equals to designationId + 1 defaultEmployeeRecordShouldNotBeFound("designationId.equals=" + (designationId + 1)); } @Test @Transactional public void getAllEmployeeRecordsByFacilityIsEqualToSomething() throws Exception { // Get already existing entity Facility facility = employeeRecord.getFacility(); employeeRecordRepository.saveAndFlush(employeeRecord); Long facilityId = facility.getId(); // Get all the employeeRecordList where facility equals to facilityId defaultEmployeeRecordShouldBeFound("facilityId.equals=" + facilityId); // Get all the employeeRecordList where facility equals to facilityId + 1 defaultEmployeeRecordShouldNotBeFound("facilityId.equals=" + (facilityId + 1)); } @Test @Transactional public void getAllEmployeeRecordsByProjectIsEqualToSomething() throws Exception { // Get already existing entity Project project = employeeRecord.getProject(); employeeRecordRepository.saveAndFlush(employeeRecord); Long projectId = project.getId(); // Get all the employeeRecordList where project equals to projectId defaultEmployeeRecordShouldBeFound("projectId.equals=" + projectId); // Get all the employeeRecordList where project equals to projectId + 1 defaultEmployeeRecordShouldNotBeFound("projectId.equals=" + (projectId + 1)); } /** * Executes the search, and checks that the default entity is returned. */ private void defaultEmployeeRecordShouldBeFound(String filter) throws Exception { restEmployeeRecordMockMvc.perform(get("/api/employee-records?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(employeeRecord.getId().intValue()))) .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME))) .andExpect(jsonPath("$.[*].middleName").value(hasItem(DEFAULT_MIDDLE_NAME))) .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME))) .andExpect(jsonPath("$.[*].address").value(hasItem(DEFAULT_ADDRESS))) .andExpect(jsonPath("$.[*].gender").value(hasItem(DEFAULT_GENDER))) .andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString()))) .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL))) .andExpect(jsonPath("$.[*].cellPhone").value(hasItem(DEFAULT_CELL_PHONE))) .andExpect(jsonPath("$.[*].telephone").value(hasItem(DEFAULT_TELEPHONE))) .andExpect(jsonPath("$.[*].maritalStatus").value(hasItem(DEFAULT_MARITAL_STATUS))) .andExpect(jsonPath("$.[*].pictureContentType").value(hasItem(DEFAULT_PICTURE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].picture").value(hasItem(Base64Utils.encodeToString(DEFAULT_PICTURE)))) .andExpect(jsonPath("$.[*].employeeNumber").value(hasItem(DEFAULT_EMPLOYEE_NUMBER))) .andExpect(jsonPath("$.[*].active").value(hasItem(DEFAULT_ACTIVE.booleanValue()))) .andExpect(jsonPath("$.[*].dateJoining").value(hasItem(DEFAULT_DATE_JOINING.toString()))) .andExpect(jsonPath("$.[*].salary").value(hasItem(DEFAULT_SALARY.doubleValue()))) .andExpect(jsonPath("$.[*].contractStartDate").value(hasItem(DEFAULT_CONTRACT_START_DATE.toString()))) .andExpect(jsonPath("$.[*].contractEndDate").value(hasItem(DEFAULT_CONTRACT_END_DATE.toString()))) .andExpect(jsonPath("$.[*].bankName").value(hasItem(DEFAULT_BANK_NAME))) .andExpect(jsonPath("$.[*].branchName").value(hasItem(DEFAULT_BRANCH_NAME))) .andExpect(jsonPath("$.[*].bankAccount").value(hasItem(DEFAULT_BANK_ACCOUNT))) .andExpect(jsonPath("$.[*].insuranceRegistrationNumber").value(hasItem(DEFAULT_INSURANCE_REGISTRATION_NUMBER))); // Check, that the count call also returns 1 restEmployeeRecordMockMvc.perform(get("/api/employee-records/count?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(content().string("1")); } /** * Executes the search, and checks that the default entity is not returned. */ private void defaultEmployeeRecordShouldNotBeFound(String filter) throws Exception { restEmployeeRecordMockMvc.perform(get("/api/employee-records?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").isEmpty()); // Check, that the count call also returns 0 restEmployeeRecordMockMvc.perform(get("/api/employee-records/count?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(content().string("0")); } @Test @Transactional public void getNonExistingEmployeeRecord() throws Exception { // Get the employeeRecord restEmployeeRecordMockMvc.perform(get("/api/employee-records/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateEmployeeRecord() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); int databaseSizeBeforeUpdate = employeeRecordRepository.findAll().size(); // Update the employeeRecord EmployeeRecord updatedEmployeeRecord = employeeRecordRepository.findById(employeeRecord.getId()).get(); // Disconnect from session so that the updates on updatedEmployeeRecord are not directly saved in db em.detach(updatedEmployeeRecord); updatedEmployeeRecord .firstName(UPDATED_FIRST_NAME) .middleName(UPDATED_MIDDLE_NAME) .lastName(UPDATED_LAST_NAME) .address(UPDATED_ADDRESS) .gender(UPDATED_GENDER) .birthDate(UPDATED_BIRTH_DATE) .email(UPDATED_EMAIL) .cellPhone(UPDATED_CELL_PHONE) .telephone(UPDATED_TELEPHONE) .maritalStatus(UPDATED_MARITAL_STATUS) .picture(UPDATED_PICTURE) .pictureContentType(UPDATED_PICTURE_CONTENT_TYPE) .employeeNumber(UPDATED_EMPLOYEE_NUMBER) .active(UPDATED_ACTIVE) .dateJoining(UPDATED_DATE_JOINING) .salary(UPDATED_SALARY) .contractStartDate(UPDATED_CONTRACT_START_DATE) .contractEndDate(UPDATED_CONTRACT_END_DATE) .bankName(UPDATED_BANK_NAME) .branchName(UPDATED_BRANCH_NAME) .bankAccount(UPDATED_BANK_ACCOUNT) .insuranceRegistrationNumber(UPDATED_INSURANCE_REGISTRATION_NUMBER); EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(updatedEmployeeRecord); restEmployeeRecordMockMvc.perform(put("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isOk()); // Validate the EmployeeRecord in the database List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeUpdate); EmployeeRecord testEmployeeRecord = employeeRecordList.get(employeeRecordList.size() - 1); assertThat(testEmployeeRecord.getFirstName()).isEqualTo(UPDATED_FIRST_NAME); assertThat(testEmployeeRecord.getMiddleName()).isEqualTo(UPDATED_MIDDLE_NAME); assertThat(testEmployeeRecord.getLastName()).isEqualTo(UPDATED_LAST_NAME); assertThat(testEmployeeRecord.getAddress()).isEqualTo(UPDATED_ADDRESS); assertThat(testEmployeeRecord.getGender()).isEqualTo(UPDATED_GENDER); assertThat(testEmployeeRecord.getBirthDate()).isEqualTo(UPDATED_BIRTH_DATE); assertThat(testEmployeeRecord.getEmail()).isEqualTo(UPDATED_EMAIL); assertThat(testEmployeeRecord.getCellPhone()).isEqualTo(UPDATED_CELL_PHONE); assertThat(testEmployeeRecord.getTelephone()).isEqualTo(UPDATED_TELEPHONE); assertThat(testEmployeeRecord.getMaritalStatus()).isEqualTo(UPDATED_MARITAL_STATUS); assertThat(testEmployeeRecord.getPicture()).isEqualTo(UPDATED_PICTURE); assertThat(testEmployeeRecord.getPictureContentType()).isEqualTo(UPDATED_PICTURE_CONTENT_TYPE); assertThat(testEmployeeRecord.getEmployeeNumber()).isEqualTo(UPDATED_EMPLOYEE_NUMBER); assertThat(testEmployeeRecord.isActive()).isEqualTo(UPDATED_ACTIVE); assertThat(testEmployeeRecord.getDateJoining()).isEqualTo(UPDATED_DATE_JOINING); assertThat(testEmployeeRecord.getSalary()).isEqualTo(UPDATED_SALARY); assertThat(testEmployeeRecord.getContractStartDate()).isEqualTo(UPDATED_CONTRACT_START_DATE); assertThat(testEmployeeRecord.getContractEndDate()).isEqualTo(UPDATED_CONTRACT_END_DATE); assertThat(testEmployeeRecord.getBankName()).isEqualTo(UPDATED_BANK_NAME); assertThat(testEmployeeRecord.getBranchName()).isEqualTo(UPDATED_BRANCH_NAME); assertThat(testEmployeeRecord.getBankAccount()).isEqualTo(UPDATED_BANK_ACCOUNT); assertThat(testEmployeeRecord.getInsuranceRegistrationNumber()).isEqualTo(UPDATED_INSURANCE_REGISTRATION_NUMBER); } @Test @Transactional public void updateNonExistingEmployeeRecord() throws Exception { int databaseSizeBeforeUpdate = employeeRecordRepository.findAll().size(); // Create the EmployeeRecord EmployeeRecordDTO employeeRecordDTO = employeeRecordMapper.toDto(employeeRecord); // If the entity doesn't have an ID, it will throw BadRequestAlertException restEmployeeRecordMockMvc.perform(put("/api/employee-records").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(employeeRecordDTO))) .andExpect(status().isBadRequest()); // Validate the EmployeeRecord in the database List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteEmployeeRecord() throws Exception { // Initialize the database employeeRecordRepository.saveAndFlush(employeeRecord); int databaseSizeBeforeDelete = employeeRecordRepository.findAll().size(); // Delete the employeeRecord restEmployeeRecordMockMvc.perform(delete("/api/employee-records/{id}", employeeRecord.getId()).with(csrf()) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List<EmployeeRecord> employeeRecordList = employeeRecordRepository.findAll(); assertThat(employeeRecordList).hasSize(databaseSizeBeforeDelete - 1); } }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>JMRI: Engine Driver Throttle for Android</title> </head> <h1>JMRI: Engine Driver Throttle for Android</h1> <img src="file:///android_asset/engine_driver_icon.png" height="144" width="166" style="float:left;padding:0 8px 8px 0"/> <p>Engine Driver version 2.9-test2 includes: update to available JMRI systems for turnouts, don't show loco until acquired by JMRI, text and icon sizing enhancements, fix issue with volume button controlling wrong loco, added missing default function button 28, prevent crash reported to Store. <br /><em><a href="http://sourceforge.net/p/jmri/code/HEAD/tree/trunk/EngineDriver/changelog-and-todo-list.txt" target="_blank" title="View complete EngineDriver changelog">[view complete changelog]</a></em></p> <p>This free application can connect to a <a href="http://jmri.sourceforge.net/help/en/package/jmri/jmrit/withrottle/UserInterface.shtml" target="_blank">JMRI WiThrottle</a> server running on a computer, and in turn control your DCC locomotives and other devices. Speed, direction, and up to 29 DCC functions are supported for one to three locos or consists. You can create and edit consists (software-defined). You can also control layout power, turnouts and routes, and display panels and other JMRI windows using the web views.</p> <p>For more details, visit <a href="http://enginedriver.rrclubs.org" target="_blank">[EngineDriver&nbsp;site]</a>. For screenshots, click <a href="http://enginedriver.rrclubs.org/content/screenshots" target="_blank">[here]</a>.</p> <h3>Prerequisites:</h3> <p>Verify your Android device can connect to your PC network via WiFi and obtain an IP address.<br />Make sure you are running one of the latest versions of <a href="http://jmri.sourceforge.net/" target="_blank">JMRI</a> (2.8 works, 3.0+ works much better) on your PC, connected to your layout.&nbsp; Start up JMRI and verify you can use the included "Throttle" app to control a loco on your layout.</p> <p>Start the <a href="http://jmri.sourceforge.net/help/en/package/jmri/jmrit/withrottle/UserInterface.shtml" target="_blank">WiThrottle</a> function of JMRI, located in DecoderPro under Tools, Throttles.&nbsp; It is also hghly recommended that you start the <a href="http://jmri.sourceforge.net/help/en/html/web/index.shtml" target="_blank" title="Learn more about JMRI Web Server">JMRI Web Server</a> function (Tools, Start JMRI Web Server).&nbsp; Both of these should be added to Preferences, Start Up as well.</p> <h3>Operation:</h3> <p>On your phone, start the Engine Driver app and wait for your PC's address to show up in "Discovered Services".&nbsp;</p> <p>Click on the discovered address, or you can enter the address and port of your WiThrottle server directly.&nbsp; (Using the values shown on the WiThrottle window.)<br /> There is also a "demo" server at jmri.mstevetodd.com, port 44444 that you can connect to for testing.</p> <p>On the throttle screen, click on the "Press to Select" loco button for each loco.<br />On the next screen, click on a loco from the roster list, or enter the loco address (verify short or long), and press "Acquire".&nbsp; You will be returned to the Throttle screen.<br /> Repeat using 2nd and 3rd "Press to Select" button to acquire a 2nd loco or 3rd loco.<br /> Note: press and hold a roster item to see additional details from the roster.</p> <p>Operate your loco using the slider (or volume control) (or arrow buttons) for speed, and the reverse, stop and forward buttons to control direction. <br /> To release all locos, just press the Back button and exit the app. This will also stop your locos (can be overridden in preferences). You can reassign the volume control by clicking on the speed indicator (the small "v" shows which has control).</p> <p>To create a consist "on-the-fly", simply select additional locos for the same throttle. Direction and speed will be sent for all. Release will release all for that throttle.</p> <p>Press your phone's Menu button to access screens for Turnout, Route and Power control, as well as adjust settings and set numerous preferences.</p> <p>You can also "fling" left or right to jump quickly back and forth between the Throttle, Routes and Turnouts pages.</p> <h3>Configuration:</h3> <p>Under Preferences, there is an extensive list of options where you can customize the screens and actions of EngineDriver to work best with your device, your layout and your personal style. These include web views, button size, additional buttons, slider size and behavior, number of throttles to display, stop on release, allow/disallow on-the-fly consisting, autoconnect, and many more. </p> <p>If you have entered function labels for a roster entry in JMRI, these labels will be used. If not, you can use the Function Defaults menu option to set default labels and function numbers to display.&nbsp; Remove buttons by blanking out the labels.&nbsp; </p> <p>On the JMRI computer side, check your WiThrottle preferences to insure you allow or disallow the control features desired.&nbsp; If you've defined your turnouts and routes in a panel, make sure to specify "user names" for those you'd like to see listed on your throttle.&nbsp; You can also "filter" the turnouts shown using the WiThrottle-&gt;Filter Controls option in the WiThrottle window.&nbsp; Turning on "Use eStop" and "Use fixed port#" are also recommended.</p> <p>Entering roster entries, and defining routes and turnouts in JMRI will all make your Engine Driver throttle more powerful and easier to use (though not required).&nbsp; EngineDriver will show additional info if the JMRI Web Server is started (such as roster details and icon images).</p> <p>You can browse the current development source code (with tags for earlier releases) <a href="http://sourceforge.net/p/jmri/code/HEAD/tree/trunk/EngineDriver/" target="_blank">[HERE].</a></p> <p><a href="http://enginedriver.rrclubs.org" target="_blank">[Homepage for EngineDriver]</a></p> </body> </html>
import { useEffect, useState } from 'react'; import { getAuth, onAuthStateChanged } from 'firebase/auth'; const UserInfo = () => { const [user, setUser] = useState(null); useEffect(() => { const auth = getAuth(); const unsubscribe = onAuthStateChanged(auth, (user) => { if (user) { // El usuario está autenticado setUser(user); } else { // El usuario no está autenticado setUser(null); } }); // Asegúrate de desuscribirte cuando el componente se desmonte return () => unsubscribe(); }, []); if (user) { // El usuario está autenticado, puedes acceder a sus datos, incluido el nombre const { displayName, email } = user; return ( <div> <p>Nombre de usuario: {displayName}</p> <p>Correo electrónico: {email}</p> </div> ); } else { // El usuario no está autenticado return <div>No hay usuario autenticado</div>; } }; export default UserInfo;
/* eslint-disable react/react-in-jsx-scope */ import './App.scss'; import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom'; import { Booking, Detail, HomePage, Login, Register } from './pages'; import 'bootstrap/dist/css/bootstrap.min.css'; const App = () => { return ( <BrowserRouter> <Switch> <Route exact path="/login" render={(props) => <Login {...props} />} /> <Route exact path="/register" render={(props) => <Register {...props} />} /> <Route exact path="/detail/:id" render={(props) => <Detail {...props} />} /> <Route exact path="/booking" render={(props) => <Booking {...props} />} /> <Route exact path="/home" render={(props) => <HomePage {...props} />} /> <Redirect to="/home" /> </Switch> </BrowserRouter> ); }; export default App;
package malkongpudding.configserver.jasypt; import org.jasypt.encryption.StringEncryptor; import org.jasypt.encryption.pbe.PooledPBEStringEncryptor; import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.beans.factory.annotation.Value; @Configuration public class JasyptConfig { @Bean("jasyptStringEncryptor") public StringEncryptor stringEncryptor(@Value(value = "${jasypt.secrete-key}") String secreteKey) { PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); SimpleStringPBEConfig config = new SimpleStringPBEConfig(); config.setPassword(secreteKey); config.setAlgorithm("PBEWithMD5AndDES"); config.setPoolSize(2); config.setStringOutputType("base64"); encryptor.setConfig(config); return encryptor; } }
import {Component, EventEmitter, HostListener, OnInit, Output} from '@angular/core'; import {IWord, userWord} from "../../../../../types"; import {AudioService} from "../../../../services/audio.service"; import {ApiService} from "../../../../services/api.service"; @Component({ selector: 'app-audio-game-play', templateUrl: './audio-game-play.component.html', styleUrls: ['./audio-game-play.component.scss'] }) export class AudioGamePlayComponent implements OnInit { @Output() display: EventEmitter<number>; @HostListener('document: keyup', ['$event.key']) onKeyUp(key: number) { if (key > 0 && key < 6 && !this.disabled) { this.answer(this.currentWords[key-1]); } } public words: IWord[]; public wordsForGame: IWord[]; public wrongWords: IWord[]; public index: number; public currentWords: IWord[]; public sound: HTMLAudioElement; public wrongSound: HTMLAudioElement; public correctSound: HTMLAudioElement; private userWords: userWord[]; public wrongAnswers: IWord[]; public correctAnswers: IWord[]; public disabled: boolean; constructor(private audioService: AudioService, private api: ApiService) { this.display = new EventEmitter<number>(); this.words = this.audioService.words; this.wordsForGame = []; this.index = 0; this.currentWords = []; this.wrongSound = new Audio('assets/mistake.mp3'); this.correctSound = new Audio('assets/rigthanswe.mp3'); this.wrongAnswers = []; this.correctAnswers = []; this.disabled = false; } ngOnInit(): void { this.userWords = this.audioService.userWords; this.getWordsForGame(); this.getCurrentWords(); } private getIdx(): number { return Math.floor(Math.random() * this.words.length); } public getWordsForGame(): void { for (let i = 0; i < 10; i++) { let word: IWord[] = this.words.splice(this.getIdx(), 1); this.wordsForGame.push(...word); } this.wordsForGame.map(elem => elem.isHidden = false); } public getWrongWords(): void { this.wrongWords = []; for (let i = 0; i < 4; i++) { let word: IWord[] = this.words.splice(this.getIdx(), 1); this.wrongWords.push(...word); } } public getCurrentWords(): void { this.currentWords = []; this.getWrongWords(); this.currentWords.push(this.wordsForGame[this.index], ...this.wrongWords); this.currentWords.sort(() => Math.random() - 0.5); this.sound = new Audio(`https://app-learnwords-rslang.herokuapp.com/${this.wordsForGame[this.index].audio}`); this.sound.play(); this.index++; } public answer(word: IWord): void { this.disabled = true; let userWord = this.userWords.find((word: userWord) => word.wordId === this.wordsForGame[this.index - 1].id); if (word.id === this.wordsForGame[this.index - 1].id) { this.correctAnswers.push(word); this.correctSound.play(); if (!userWord) { this.api.createUserWord(localStorage.getItem('userId')!, this.wordsForGame[this.index - 1].id, {difficulty: 'false', optional: {}}).subscribe(); this.updateStudiedWords(true); } else if (userWord.difficulty === 'true') { this.api.updateUserWord(localStorage.getItem('userId')!, this.wordsForGame[this.index - 1].id, {difficulty: 'false', optional: {}}).subscribe(); this.updateStudiedWords(true); } } else { this.wrongAnswers.push(word); this.wrongSound.play(); if (!userWord) { this.api.createUserWord(localStorage.getItem('userId')!, this.wordsForGame[this.index - 1].id, {difficulty: 'true', optional: {}}).subscribe(); } else if (userWord.difficulty === 'false') { this.api.deleteUserWord(localStorage.getItem('userId')!, this.wordsForGame[this.index - 1].id).subscribe(); this.updateStudiedWords(false); } } this.wordsForGame[this.index - 1].isHidden = true; if (this.index < 10) { setTimeout(() => this.getCurrentWords(), 1000); } else { this.audioService.wrongAnswers = this.wrongAnswers; this.audioService.correctAnswers = this.correctAnswers; setTimeout(() => this.display.emit(3), 1000); } setTimeout(() => this.disabled = false, 1000); } notToKnow() { let userWord = this.userWords.find((word: userWord) => word.wordId === this.wordsForGame[this.index - 1].id); if (!userWord) { this.api.createUserWord(localStorage.getItem('userId')!, this.wordsForGame[this.index - 1].id, {difficulty: 'true', optional: {}}).subscribe(); } else if (userWord.difficulty === 'false') { this.api.deleteUserWord(localStorage.getItem('userId')!, this.wordsForGame[this.index - 1].id).subscribe(); this.updateStudiedWords(false); } this.wordsForGame[this.index - 1].isHidden = true; if (this.index < 10) { setTimeout(() => this.getCurrentWords(), 1000); } else { this.audioService.wrongAnswers = this.wrongAnswers; this.audioService.correctAnswers = this.correctAnswers; setTimeout(() => this.display.emit(3), 1000); } } public playSound() { this.sound.play(); } private updateStudiedWords(add: boolean) { if (add) { localStorage.setItem('studWordsA', `${(+localStorage.getItem('studWordsA')! || 0) + 1}`) } else { localStorage.setItem('studWordsA', `${+localStorage.getItem('studWordsA')! - 1}`) } } }
Python urinishdan tashqari Blok trysizga kod blokini xatolar uchun tekshirish imkonini beradi. Blok exceptsizga xatoni hal qilishga imkon beradi. Blok elsexato bo'lmaganda kodni bajarishga imkon beradi. Blok finally, sinash natijasidan qat'i nazar, kodni bajarishga imkon beradi- va bloklardan tashqari. Istisno bilan ishlash Xato yoki biz uni istisno qilganda, Python odatda to'xtab qoladi va xato xabarini yaratadi. Ushbu istisnolar bayonot yordamida hal qilinishi mumkin try: Misol Blok tryistisno hosil qiladi, chunki xaniqlanmagan: try: print(x) except: print("An exception occurred") ERROR Sinab ko'rish bloki xatoga yo'l qo'yganligi sababli, istisno bloki bajariladi. Sinab ko'rish bloki bo'lmasa, dastur ishdan chiqadi va xatoga yo'l qo'yadi: Misol Ushbu bayonot xatoga olib keladi, chunki xaniqlanmagan: print(x) Ko'p istisnolar Siz xohlagancha istisno bloklarini belgilashingiz mumkin, masalan, agar siz maxsus xatolik uchun maxsus kod blokini bajarmoqchi bo'lsangiz: Misol Agar try bloki a NameErrorva boshqa xatolarni ko'tarsa, bitta xabarni chop eting: try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Boshqa elseHech qanday xatolik yuzaga kelmasa, bajariladigan kod blokini aniqlash uchun kalit so'zdan foydalanishingiz mumkin : Misol Ushbu misolda tryblok hech qanday xato yaratmaydi: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") Nihoyat Blok finally, belgilangan bo'lsa, urinib ko'rish bloki xatolik tug'diradimi yoki yo'qmi, qat'iy nazar bajariladi. Misol try: print(x) except: print("Something went wrong") finally: print("The 'try except' is finished") Bu ob'ektlarni yopish va resurslarni tozalash uchun foydali bo'lishi mumkin: Misol Yozish mumkin bo'lmagan faylni ochishga va unga yozishga harakat qiling: try: f = open("demofile.txt") try: f.write("Lorum Ipsum") except: print("Something went wrong when writing to the file") finally: f.close() except: print("Something went wrong when opening the file") Dastur fayl ob'ektini ochiq qoldirmasdan davom etishi mumkin. Istisno ko'taring Python dasturchisi sifatida, agar biror holat yuzaga kelsa, istisno qilishni tanlashingiz mumkin. Istisnoni tashlash (yoki oshirish) uchun raisekalit so'zdan foydalaning. Misol Xatoni ko'taring va agar x 0 dan past bo'lsa, dasturni to'xtating: x = -1 if x < 0: raise Exception("Sorry, no numbers below zero") Kalit raiseso'z istisno qilish uchun ishlatiladi. Siz qanday xatoni ko'tarishni va matnni foydalanuvchiga chop etishni belgilashingiz mumkin. Misol Agar x butun son bo'lmasa, TypeErrorni ko'taring: x = "hello" if not type(x) is int: raise TypeError("Only integers are allowed")
using ApiCommons.DTOs; using System.Text.Json; using JsonSerializer = System.Text.Json.JsonSerializer; using System.Net; namespace RecipesUI.Services; public class RecipeService : ApiService<RecipeResponse>, IRecipeService { public RecipeService(IConfiguration configuration, ILogger<RecipeService> logger) : base(configuration, logger) { } public async Task<List<RecipeResponse>> GetRecipes( string? userId = null, string? search = null, List<int>? ingredientIds = null, int page = 1, int pageSize = 9, string? orderBy = null, string sorting = "asc") { var queryParams = new List<string>(); if (!string.IsNullOrEmpty(userId)) { queryParams.Add($"UserId={Uri.EscapeDataString(userId)}"); } if (!string.IsNullOrEmpty(search)) { queryParams.Add($"Search={Uri.EscapeDataString(search)}"); } if (ingredientIds != null && ingredientIds.Any()) { queryParams.AddRange(ingredientIds.Select(id => $"IngredientId={id}")); } queryParams.Add($"Page={page}"); queryParams.Add($"PageSize={pageSize}"); if (!string.IsNullOrEmpty(orderBy)) { queryParams.Add($"OrderBy={Uri.EscapeDataString(orderBy)}"); } if (!string.IsNullOrEmpty(sorting)) { queryParams.Add($"Sorting={Uri.EscapeDataString(sorting)}"); } string queryString = string.Join("&", queryParams); string endpoint = $"recipes?{queryString}"; _logger.LogInformation("Fetching recipes from {Endpoint}", endpoint); try { string requestUrl = $"{_httpClient.BaseAddress}{endpoint}"; _logger.LogInformation("Request URL: {RequestUrl}", requestUrl); var response = await _httpClient.GetAsync(endpoint); var responseBody = await response.Content.ReadAsStringAsync(); _logger.LogInformation("Response Body: {ResponseBody}", responseBody); if (!response.IsSuccessStatusCode) { _logger.LogError("HTTP {StatusCode} error occurred while fetching recipes from {Endpoint}. Response Body: {ResponseBody}", response.StatusCode, endpoint, responseBody); throw new ApplicationException($"HTTP error occurred while fetching recipes from {endpoint}. Status Code: {response.StatusCode}"); } var recipes = JsonSerializer.Deserialize<List<RecipeResponse>>(responseBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (recipes == null || !recipes.Any()) { _logger.LogInformation("No recipes were found at the endpoint: {Endpoint}", endpoint); return new List<RecipeResponse>(); } return recipes; } catch (HttpRequestException httpEx) { _logger.LogError(httpEx, "HTTP error occurred while fetching recipes from {Endpoint}", endpoint); throw new ApplicationException($"HTTP error occurred while fetching recipes from {endpoint}", httpEx); } catch (Exception ex) { _logger.LogError(ex, "An unexpected error occurred while fetching recipes from {Endpoint}", endpoint); throw new ApplicationException($"An unexpected error occurred while fetching recipes from {endpoint}", ex); } } public async Task<RecipeResponse> GetRecipeById(long id) { string endpoint = $"recipe/{id}"; _logger.LogInformation("Fetching recipe with ID {Id} from {Endpoint}", id, endpoint); try { string requestUrl = $"{_httpClient.BaseAddress}{endpoint}"; _logger.LogInformation("Request URL: {RequestUrl}", requestUrl); var response = await _httpClient.GetAsync(endpoint); var responseBody = await response.Content.ReadAsStringAsync(); //_logger.LogInformation("Response Body: {ResponseBody}", responseBody); if (!response.IsSuccessStatusCode) { if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { _logger.LogWarning("Recipe with ID {Id} was not found.", id); return null; } _logger.LogError("HTTP {StatusCode} error occurred while fetching recipe with ID {Id} from {Endpoint}. Response Body: {ResponseBody}", response.StatusCode, id, endpoint, responseBody); throw new ApplicationException($"HTTP error occurred while fetching recipe with ID {id} from {endpoint}. Status Code: {response.StatusCode}"); } var recipe = JsonSerializer.Deserialize<RecipeResponse>(responseBody, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); if (recipe == null) { _logger.LogInformation("No recipe was found at the endpoint: {Endpoint}", endpoint); return null; } return recipe; } catch (HttpRequestException httpEx) { _logger.LogError(httpEx, "HTTP error occurred while fetching recipe with ID {Id} from {Endpoint}", id, endpoint); throw new ApplicationException($"HTTP error occurred while fetching recipe with ID {id} from {endpoint}", httpEx); } catch (Exception ex) { _logger.LogError(ex, "An unexpected error occurred while fetching recipe with ID {Id} from {Endpoint}", id, endpoint); throw new ApplicationException($"An unexpected error occurred while fetching recipe with ID {id} from {endpoint}", ex); } } public async Task<bool> CreateRecipe(RecipeRequest recipeRequest = null) { try { if (recipeRequest == null) { _logger.LogError("RecipeRequest is null."); return false; } _logger.LogInformation("Sending POST request to create a new recipe."); var response = await _httpClient.PostAsJsonAsync("recipe", recipeRequest); if (response.IsSuccessStatusCode) { _logger.LogInformation("Recipe created successfully."); return true; } else { var responseContent = await response.Content.ReadAsStringAsync(); _logger.LogError("Failed to create recipe. Status Code: {StatusCode}, Response: {Response}", response.StatusCode, responseContent); return false; } } catch (Exception ex) { _logger.LogError(ex, "An error occurred while creating the recipe."); return false; } } public async Task<HttpStatusCode> UpdateRecipe(long id, RecipeRequest recipeRequest = null) { try { if (recipeRequest == null) { _logger.LogError("RecipeRequest is null."); return HttpStatusCode.BadRequest; } _logger.LogInformation("Sending PUT request to update recipe with ID {Id}.", id); var response = await _httpClient.PutAsJsonAsync($"recipe/{id}", recipeRequest); if (response.IsSuccessStatusCode) { _logger.LogInformation("Recipe updated successfully."); return response.StatusCode; } else { var responseContent = await response.Content.ReadAsStringAsync(); _logger.LogError("Failed to update recipe. Status Code: {StatusCode}, Response: {Response}", response.StatusCode, responseContent); return response.StatusCode; } } catch (Exception ex) { _logger.LogError(ex, "An error occurred while updating the recipe."); return HttpStatusCode.InternalServerError; } } }
# EmergingTechnologies # Tasks & Project This repository is for Emerging Technologies, where we study the use of Quantum Computing as an emerging technology. The tasks in this repository are mainly mathematical operations in Python, while the project is a study on Deutsch's algorithm, which is a fundamental concept in quantum computing. By *Owen Casey* # Prerequisites The main contents of this repository are Jupyter notebooks. To run these notebooks, you will need the following: **Python**: Downloading the most recent version of Python is recommended. You can download python from the official Python site [here](https://www.python.org/downloads/). However, I recommend installing Python through [Miniconda](https://docs.conda.io/projects/miniconda/en/latest/) or [Anaconda](https://www.anaconda.com/download), as it provides an all in one installation and management for Python. - Miniconda (Recommended): Minimal installer, low storage usage - Anaconda: Full installer, high storage usage **Jupyter Notebook**: Jupyter Notebook support should come with Anaconda/Miniconda, but you can also install it through a VSCode extension. **Required Libraries**: Any required libraries will be mentioned in the relevant section they are used in the notebooks. **VSCode**: If you intend to execute code in your own environment, VSCode is recommended, as it's the standard. # Anaconda and Miniconda The use of Anaconda or Miniconda is *heavily* encouraged for this repository. Anaconda is a **full** installer while Miniconda is a **minimal** installer. They both have an easy to follow installer, which you can use to set up your environment. However, there are some things I'd like to mention. - When you install Anaconda/Miniconda, ensure that you have the correct environment set up in the interpreter for VSCode. To do this, you can: - Open VSCode - Install Python extension (if not already installed) - Open the command palette (Ctrl+Shift+P on windows / Cmd+Shift+P on Mac) - Enter "Python:Select Interpreter" and select it - Choose the correct Anaconda/Miniconda environment - If you haven't be sure to activate your environment through the command line. To do this, open the Anaconda/Miniconda command line and enter the following command: ``` conda activate myenv ``` Ensure that you replace "myenv" with your environment name. - If you wish to install packages, extensions, etc, directly to your environment, you can use the following command: ``` conda install *package name* ``` - If required, ensure that you read any relevant documentation needed for [Anaconda](https://docs.anaconda.com/index.html) or [Miniconda](https://docs.conda.io/projects/miniconda/en/latest/). # How to run This section provides a step-by-step guide on how to set up and run the Jupyter notebooks ### Step 1: Install Python Ensure you have Python installed on your system. You can install it through the methods I outlined above. ### Step 2: Clone the Repository Clone this repository to your local machine using Git. You can do this by running the following command in your terminal: ``` git clone https://github.com/Owen-kc/EmergingTechnologies.git ``` ### Step 3: Install required libraries The relevant libraries will be defined in the notebooks, ensure these are installed for the notebooks to run properly. Depending on how you have your own environment set up, you may want to install these locally in your Anaconda/Miniconda/VSCode terminal. Here is a list of extensions and libraries that are used in the notebooks: - Qiskit - Qiskit Aer - Matplotlib - Pandas - Pylatexenc - Itertools - Numpy ### Step 4: Run Jupyter Notebook If you have installed Anaconda or Miniconda, Jupyter Notebook should already be installed. Otherwise, install it using the following command: ``` pip install notebook ``` or you can install it through the VSCode extension. ### Step 5: Start Jupyter notebook You can start the jupyter notebook you can run the following command: ``` jupyter notebook ``` You can use this command to open a navigation tree where you can select a specific notebook. **Note**: Depending on your own install, you may need to run this from your Anaconda/Miniconda terminal. If you are encountering errors launching the notebook in something like VSCode, you should open the Anaconda/Miniconda terminal, navigate to the repository using the following code command: ``` cd *path to repo on your system* ``` By following these steps, you should be able to run the contents of the repository. # Tasks ### Overview **Task 1: Collatz Conjuncture** This task covers the famous unsolved Collatz Conjuncutre problem through Python. **Task 2: Square Roots** This task covers square roots in Python through Newtons method. **Task 3: Four Bit Functions** This task covers a function that takes four input bits. **Task 4: Matrix Multiplication** This task covers matrix multiplication in Python. # Project ### Overview The project covers Deutsch's Algorithm, which is a foundational algorithm in quantum computing. The algorithm is the first representation of quantum advantage, which is when a quantum computer has an advantage over a classical computer. The project introduces quantum computing and gives a detailed explanation on all of the essential components for understanding and implementing Deutsch's algorithm. In the project notebook, we create the quantum circuit for Deutsch's algorithm using Qiskit. Qiskit is an open source piece of software, developed by IBM for the purpose of quantum computing. You can find in depth documentation regarding Qiskit [here](https://www.ibm.com/quantum/qiskit). ### Purpose The purpose of this project is to analyze Deutsch's algorithm and what purpose it serves in quantum computing. We aim to demonstrate Deutsch's algorithm being implemented in Qiskit, and simulate the quantum circuit we implement. ## Section Breakdown Here, I will go over the main points of the project, and explain the purpose each of these sections represent. ### Introduction to Quantum Computing Introduction to Quantum Computing covers the historical context and fundamentals of quantum computing. These aspects are essential to understanding the context of quantum computing before implementing Deutsch's algorithm. This section goes over the main points that we are interested in, qubits, superposition, entaglement and gates/circuits. ### Deutsch's Algorithm This section introdices the concept of Deutsch's algorithm and what problem it aims to achieve. It provides context on balanced and constant functions, and introduces the oracle and the quantum circuit to the project. ### Qiskit The Qiskit section introduces Qiskit, how to install it, and how it works. It provides a detailed explanation on Qiskit, including the components of Qiskit that we use in the implementation of Deutsch's algorithm, and provides a brief example of a simple cirucit. ### Deutsch's Algorithm in Qiskit This is considered the main section of the notebook. Here, we implement Deutsch's algorithm in qiskit, and simulate the quantum circuit. This is the section we have been building towards with the previous sections. ### Results In the results section, we provide an analysis of the results, as well as some scientifc graph representations of our results. ### Conclusion Finally, we conclude our results and thoughts on Deutsch's algorithm in the conclusion section.
#!/usr/bin/env python3 from typing import Callable, Optional, NamedTuple, Iterable from pyre_extensions import none_throws from sch import codex, command, Command, format_doc, query_args TAGS = ["public", "code"] class Repo(NamedTuple): name: str docs: str errors: Optional[str] = None tags: Optional[Iterable[str]] = None repos = { "invoke": Repo( name="pyinvoke/invoke", docs="https://docs.pyinvoke.org/en/stable", ), "click": Repo( name="pallets/click", docs="https://click.palletsprojects.com/en/8.1.x", ), "flask": Repo( name="pallets/flask", docs="https://flask.palletsprojects.com/en/3.0.x", ), "luigi": Repo( name="spotify/luigi", docs="https://flask.palletsprojects.com/en/3.0.x", ), "hammerspoon": Repo( name="Hammerspoon/hammerspoon", docs="https://www.hammerspoon.org/docs", ), "buck": Repo( name="facebook/buck2", docs="https://buck2.build/docs", ), "sapling": Repo( name="facebook/sapling", docs="https://sapling-scm.com/docs/introduction" ), "pyre": Repo( name="facebook/pyre-check", docs="https://pyre-check.org/docs/getting-started/", errors="https://pyre-check.org/docs/errors/", ), "beets": Repo(name="beetbox/beets", docs="https://beets.readthedocs.io/en/stable"), "rockbox": Repo( name="Rockbox/rockbox", docs="https://download.rockbox.org/daily/manual/rockbox-ipod6g/rockbox-build.html", ), "anytree": Repo( name="c0fec0de/anytree", docs="https://anytree.readthedocs.io/en/stable/" ), "tup": Repo(name="gittup/tup", docs="https://gittup.org/tup/"), "jupyterlab": Repo( name="jupyterlab/jupyterlab", docs="https://jupyterlab.readthedocs.io/en/latest/", ), "logisim": Repo( name="logisim-evolution/logisim-evolution", docs="https://github.com/logisim-evolution/logisim-evolution/blob/main/docs/docs.md", tags=["6502"], ), } def github_search_url(repo: str, *args: str) -> str: query = query_args(f"repo:{repo}", *args) return f"https://github.com/search?type=code&q={query}" @codex.command("gh", tags=TAGS) def github(repo: Optional[str] = None) -> str: """go to github or a view a repo if repo: return https://github.com/{repo} else: return https://github.com """ if repo: return f"https://github.com/{repo}" else: return "https://github.com" @github.command("search") def github_search(repo: str, *args: str) -> str: """search a github repo return https://github.com/search?type=code&q=repo:{repo}+{*args} """ return github_search_url(repo, *args) @github_search.command("all") def github_search_all(*args: str) -> str: """search all of github return https://github.com/search?type=code&q={*args} """ return f"https://github.com/search?type=code&q={query_args(*args)}" def code_command( repo_name: str, repo_docs: str, repo_errors: Optional[str] = None, repo_tags: Optional[Iterable[str]] = None, ) -> Command: if repo_tags: tags = set(repo_tags) tags.add("public") tags.add("code") else: tags = TAGS @command(tags=tags) @format_doc(repo_name=repo_name) def code_repo(*args: str) -> str: """{repo_name} on github if args: return https://github.com/search?type=code&q=repo:{repo_name}+{{*args}} else: return https://github.com/{repo_name} """ if args: return github_search_url(repo_name, *args) else: return f"https://github.com/{repo_name}" @code_repo.command("docs") @format_doc(repo_docs=repo_docs) def code_repo_docs() -> str: """hosted docs return {repo_docs} """ return repo_docs @code_repo.command("file") @format_doc(repo_name=repo_name) def code_repo_file(file_str: str) -> str: """file search return https://github.com/{repo_name}/tree/main/{{file_str}} """ return f"https://github.com/{repo_name}/tree/main/{file_str}" @code_repo.command("prs") @format_doc(repo_name=repo_name) def code_repo_pr(pr: Optional[str] = None) -> str: """go to pr or view prs if pr: return https://github.com/{repo_name}/pull/{{pr}} else: return https://github.com/{repo_name}/pulls """ if pr: return f"https://github.com/{repo_name}/pull/{pr}" else: return f"https://github.com/{repo_name}/pulls" @code_repo.command("issues") @format_doc(repo_name=repo_name) def code_repo_issue(issue: Optional[str] = None) -> str: """go to issue or view issues if issue: return https://github.com/{repo_name}/issues/{{issue}} else: return https://github.com/{repo_name}/issues """ if issue: return f"https://github.com/{repo_name}/issues/{issue}" else: return f"https://github.com/{repo_name}/issues" if repo_errors is not None: @code_repo.command("errors") @format_doc(repo_name=repo_name, repo_errors=repo_errors) def code_repo_errors(issue: Optional[str] = None) -> str: """main error troubleshooting page return {repo_errors} """ return none_throws(repo_errors) return code_repo for name, config in repos.items(): codex.add_command(code_command(*config), name) codex.add_bookmark("sourcehut", "https://sr.ht/", "sourcehut git host", tags=TAGS) @codex.command("commonmark", tags=TAGS) def commonmark() -> str: """commonmark spec All md -> html/txt formatting in sch is done via the commonmark_x engine in pandoc, so this is the spec which all md docs should adhere to. For info on pandoc's use of CommonMark, see sch pandoc commonmark_x return https://spec.commonmark.org/current/ """ return "https://spec.commonmark.org/current/" pandoc: Command = codex.add_command( code_command("jgm/pandoc", "https://pandoc.org"), "pandoc" ) @pandoc.command("commonmark_x") def pandoc_commonmark_x() -> str: """commonmark_x extension definition commonmark_x is separate from the commonmark engine in that it includes several useful pandoc extensions which add more functionality than what is provided in commonmark. This is the list of extensions currently enabled, which can also be used when rendering pages in sch. Search the extension name in the manual (sch pandoc manual) to learn more about extension functionality. return https://github.com/jgm/pandoc/blob/509cc3ac8765f3d531f953e5ef7a24901bce0ec7/src/Text/Pandoc/Extensions.hs#L410 """ return "https://github.com/jgm/pandoc/blob/509cc3ac8765f3d531f953e5ef7a24901bce0ec7/src/Text/Pandoc/Extensions.hs#L410" pandoc.add_bookmark( "manual", "https://pandoc.org/MANUAL.html", "pandoc CLI manual", tags=TAGS ) codex.add_bookmark("regex", "https://regex101.com", "regex 101 regex tester", tags=TAGS) solarized: Command = codex.add_bookmark( "solarized", "https://en.wikipedia.org/wiki/Solarized", "solarized color pallette", tags=TAGS, ) solarized.add_bookmark( "css", "https://thomasf.github.io/solarized-css/", "css stylesheet", ) python: Command = codex.add_search( "python", "https://docs.python.org/3/search.html?q=", "https://docs.python.org/3/", "python programming language", ) python.add_bookmark("match", "https://peps.python.org/pep-0636/", "pattern matching") python.add_bookmark( "functional", "https://docs.python.org/3/howto/functional.html", "functional howto" ) pypi: Command = codex.add_search( "pypi", "https://pypi.org/search/?q=", "https://pypi.org/", "python_package_index" ) pypi.add_bookmark( "classifiers", "https://pypi.org/classifiers/", "python package classifiers" ) jupyter: Command = codex.add_command( code_command( "jupyter/notebook", "https://jupyter-notebook.readthedocs.io/en/stable/" ), "jupyter", )
import { View, Text, TextInput, StyleSheet, TouchableOpacity, Image, ToastAndroid, } from 'react-native'; import React, {useState, useEffect} from 'react'; import {Addbooks} from '../utils/firestoredatabase'; import { requestUserPermission, notificationListner, LocalNotification, createChannel, getChannels, } from '../utils/notification'; import PushNotification from 'react-native-push-notification'; const logoimage = '/home/mambhore/React Native/RNnotificationdemo/src/assets/download.png'; // import firebase from '../utils/Firebase'; const AddPost = ({navigation}) => { const [title, setTitle] = useState(''); const [author, setAuthor] = useState(''); const [price, setPrice] = useState(''); useEffect(() => { requestUserPermission(); notificationListner(); createChannel(); getChannels(); }, []); const handlesubmit = () => { if (title != '' && author != '' && price != '') { Addbooks(title, author, price); console.log('title -->', title, 'author -->', author, 'price -->', price); LocalNotification(); } else { console.log('error'); ToastAndroid.show('Required all field !!', ToastAndroid.LONG); } }; return ( <View style={styles.container}> <Image style={styles.logo} source={require(logoimage)} /> <View style={{ justifyContent: 'center', alignItems: 'center', textAlign: 'center', }}> </View> <View style={styles.formcontainer}> <TextInput style={styles.textinput} placeholder="Title" onChangeText={value => setTitle(value)} /> <TextInput style={styles.textinput} placeholder="Author name" onChangeText={value => setAuthor(value)} /> <TextInput style={styles.textinput} onChangeText={value => setPrice(value)} placeholder="price" /> <TouchableOpacity style={styles.submit} onPress={handlesubmit}> <Text style={styles.submittext}>SUBMIT</Text> </TouchableOpacity> </View> </View> ); }; const styles = StyleSheet.create({ container: { marginTop: 40, margin: 20, justifyContent: 'center', alignItems: 'center', }, formcontainer: { marginTop: 50, width: '100%', justifyContent: 'center', alignItems: 'center', }, logo: { width: 150, height: 150, marginBottom: 20, marginTop: 10, }, submit: { backgroundColor: '#6a994e', borderRadius: 10, width: '50%', margin: 10, padding: 10, }, submittext: { fontSize: 20, textAlign: 'center', color: 'white', fontWeight: '500', }, textinput: { fontSize: 20, backgroundColor: '#e9ecef', marginBottom: 10, borderRadius: 10, padding: 10, width: '100%', justifyContent: 'center', }, }); export default AddPost;
#include <bits/stdc++.h> using namespace std; #define ll long long #define pii pair<int, int> #define pll pair<long long, long long> #define vi vector<int> #define vvi vector<vector<int>> #define vvvi vector<vector<vector<int>>> #define vll vector<long long> #define mii map<int, int> #define pb push_back #define f first #define s second #define nl "\n" #define MOD 1000000007 #define PI 3.1415926535897932384626433832795 #define INF 1e9 int recursive_Burst_Balloons(int i,int j,vi &v){ // Time Complexity: O(2^(N^2)) // Space Complexity: O(N) if(i>j)return 0; int cuts = 0; for(int k=i;k<=j;k++){ cuts=max(cuts,v[j+1]*v[i-1]*v[k]+ recursive_Burst_Balloons(i,k-1,v)+recursive_Burst_Balloons(k+1,j,v)); } return cuts; } int memoization_Burst_Balloons(int i,int j,vi &v,vvi &dp){ // Time Complexity: O(N^3) // Space Complexity: O(N^2) if(i>j)return 0; if(dp[i][j]!=-1)return dp[i][j]; int cuts = 0; for(int k=i;k<=j;k++){ cuts=max(cuts,v[j+1]*v[i-1]*v[k]+memoization_Burst_Balloons(i,k-1,v,dp)+memoization_Burst_Balloons(k+1,j,v,dp)); } return dp[i][j]=cuts; } int dynamic_programming_Burst_Balloons(int n,vi &v){ // Time Complexity: O(N^3) // Space Complexity: O(N^2) vvi dp(n+2, vi(n+2,0)); for (int i = n; i >=1; i--) { for (int j = i; j <=n; j++) { for(int k=i;k<=j;k++){ int cuts=dp[i][k-1]+dp[k+1][j]+v[j+1]*v[i-1]*v[k]; dp[i][j]=max(cuts,dp[i][j]); } } } return dp[1][n]; } int main() { // your code goes here ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n; cin >> n ; vi v(n+1); v[0]=1; for(int i=1;i<=n;i++)cin>>v[i]; v.push_back(1); vvi dp(n+2, vi(n+2,-1)); int result_recursive = recursive_Burst_Balloons(1,n,v); int result_memoization = memoization_Burst_Balloons(1,n,v,dp); int result_dynamic = dynamic_programming_Burst_Balloons(n,v); cout << "Burst_Balloons using Recursive: " << result_recursive << endl; cout << "Burst_Balloons using Memoization: " << result_memoization << endl; cout << "Burst_Balloons using Dynamic Programming: " << result_dynamic << endl; return 0; }
// // CGpathMapper.swift // Dollani // // Created by Layan Alwadie on 27/06/1444 AH. // import SwiftUI // // CGPathMapper.swift // Dollani // // Created by Layan Alwadie on 27/06/1444 AH. // import SwiftUI struct CGPathMapperContentView: View { init(place_:Place,hallways_:[DirectionalHallway],source_:CGPoint) { self.hallways = hallways_ self.selectedClassroom = Classroom(name: place_.name, entrancePoint: CGPoint(x: place_.x, y: place_.y)) youAreHerePoint = source_ if let route = self.shortestRouteTo(classroom: self.selectedClassroom) { withAnimation { self.resultDistance = route.distance self.mapPathVertices = route.path self.mapPathDrawnPercentage = 1 } } } // MARK: - Constants let youAreHerePoint : CGPoint /// ### 3B i. (Row 2) - list of hallways var hallways = [DirectionalHallway]() // MARK: - User Input Storage let selectedClassroom:Classroom // MARK: - Output Storage var resultDistance = CGFloat(0) var mapPathVertices = [Vertex]() var mapPathDrawnPercentage = CGFloat(0) // MARK: - User Interface var body: some View { VStack { ZStack { Image("مبنى كلية الحاسب الدور الأرضي").resizable() /// the map image (made by myself) // MARK: - Visual Output, path drawn on top of map Path { path in if mapPathVertices.isEmpty == false { path.move(to: mapPathVertices.first!.point) for vertex in mapPathVertices { path.addLine(to: vertex.point) } } } .trim(from: 0, to: 0.01) /// animate path drawing .stroke(Color.red, style: StrokeStyle(lineWidth: 10, lineCap: .round)) .shadow(color: Color.black.opacity(0.3), radius: 3).overlay( Path { path in if mapPathVertices.isEmpty == false { path.move(to: mapPathVertices.first!.point) for vertex in mapPathVertices { path.addLine(to: vertex.point) } } } .trim(from: 0.02, to: mapPathDrawnPercentage) .stroke(Color.blue, style: StrokeStyle(lineWidth:6)) ) } VStack { HStack { Text("\(selectedClassroom.name)\n").lineLimit(2) Spacer() Text("الوجهة المختارة:").fontWeight(.bold) // MARK: - Text Input via dropdown } .padding(10) .background(Color(.secondarySystemBackground)) .cornerRadius(16) // MARK: - Text Output, show the distance and approximate time needed if resultDistance != 0 { HStack { Text("\(numberToMinutes(number: resultDistance)) دقيقة")// Concatenate strings Spacer() Text("الوقت المتوقع:").fontWeight(.bold) } .padding() .background(Color(.secondarySystemBackground)) .cornerRadius(16) } /// tap button to call main procedure } // VStack{ // Text(" ") // // } // VStack{ // Text(" ") // // } .font(.system(size: 20, weight: .medium)) .padding(.horizontal, 20) Spacer() } /// remove results if selected classroom changed } // MARK: - Procedures /// get list of vertices (represents all possible paths) to a destination func getVerticesTo(destinationPoint: CGPoint) -> [Vertex] { /// ### 3B ii. (Row 2) - create `vertices` list from `hallways` list var vertices = [Vertex]() /// get and append a hallway's corresponding vertex to `vertices`, then append the hallway to the vertex's `touchingHallways` func configureVertexWith(hallway: DirectionalHallway) { var vertex: Vertex if let existingVertex = vertices.first(where: { $0.point == hallway.start }) { vertex = existingVertex /// prevent duplicates, get existing vertex in the `vertices` list } else { vertex = Vertex(point: hallway.start) /// create new vertex vertices.append(vertex) /// append to `vertices` list } vertex.touchingHallways.append(hallway) } var hallwaysCopy = hallways /// create mutable copy for i in hallwaysCopy.indices { if PointIsOnLine(lineStart: hallwaysCopy[i].start, lineEnd: hallwaysCopy[i].end, point: destinationPoint) { hallwaysCopy[i] = DirectionalHallway(start: hallwaysCopy[i].start, end: destinationPoint) /// replace full hallway with a portion configureVertexWith(hallway: DirectionalHallway(start: destinationPoint, end: destinationPoint)) /// final hallway, length of 0 } configureVertexWith(hallway: hallwaysCopy[i]) } return vertices } /// ### 3C i. (Row 4) - main procedure, get shortest route (distance and path) to classroom func shortestRouteTo(classroom: Classroom) -> Route? { if classroom != nil { /// classroom name is made of numbers (normal classroom) /// **sequencing** let vertices = getVerticesTo(destinationPoint: classroom.entrancePoint) if let shortestRoute = ShortestRouteFromVertices(vertices: vertices, start: youAreHerePoint, end: classroom.entrancePoint) { return shortestRoute } } else { /// no classroom was selected let alert = UIAlertController(title: "Select a classroom", message: "You must select a classroom first", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) UIApplication.shared.windows.first { $0.isKeyWindow }?.rootViewController?.present(alert, animated: true) /// present error alert } return nil /// return nothing when if check fell through - no shortest path was found } } // MARK: - Helper Procedures
package com.dan.test.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import com.dan.test.webobjects.WebTable1; public class WebDB { private Connection connection; private Logger logger; public WebDB() throws WebDBException { try { Context context = new InitialContext(); DataSource dataSource = (DataSource)context.lookup("jdbc/web"); this.connection = dataSource.getConnection(); } catch (NamingException ex) { throw new WebDBException("Couldn't locate database.",ex); } catch (SQLException ex) { throw new WebDBException("Couldn't connect to database.",ex); } logger = Logger.getLogger(WebDB.class.getName()); } public List<WebTable1> getWebTable1s() throws WebDBException { List<WebTable1> webTable1s = null; PreparedStatement ps = null; StringBuffer buffer = new StringBuffer(); buffer.append("SELECT `id`, `set`, `key`, `value`"); buffer.append(" FROM web_table_1 " ); try { ps = this.connection.prepareStatement(buffer.toString()); ResultSet rs = ps.executeQuery(); if (rs != null) { webTable1s = new ArrayList<WebTable1>(); while (rs.next()) { WebTable1 webTable1 = new WebTable1(); webTable1.setSet(rs.getString("set")); webTable1.setKey(rs.getString("key")); webTable1.setValue(rs.getString("value")); webTable1s.add(webTable1); } } } catch (SQLException ex) { logger.severe("SQL Exception: " + ex.toString()); throw new WebDBException("Failed to select data.",ex); } finally { try { if (ps != null) ps.close(); } catch (SQLException ex) { } } return webTable1s; } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; if(root==NULL) { return result; } else { stack<TreeNode*> s; TreeNode* cur=root; while(!s.empty() || cur) { if(cur) { s.push(cur); cur=cur->left; } else { TreeNode* node=s.top(); s.pop(); result.push_back(node->val); cur = node->right; } } } return result; } };
class Animals: def __init__(self, typeOfAn, area, typeFeed, numberOfPaws): self.typeOfAn = typeOfAn self.area = area self.typeFeed = typeFeed self._numberOfPows = numberOfPaws def presentation(self): return f'I am a {self.typeOfAn}. I live in {self.area} and like eat {self.typeFeed}' def feed(self): return f'I am animal. Feed me. I like {self.typeFeed}. I have {self._numberOfPows} paws' def set_area(self, new_area): self.area = new_area bird = Animals('bird', 'Europe', 'grain', 2) print(bird.presentation()) bird.set_area('Africa') print(bird.presentation()) cat = Animals('cat', 'home', 'whiskas', 4) print(cat.presentation()) print(cat.feed()) class Mammals(Animals): def __init__(self, typeOfAn, area, typeFeed, numberOfPaws, environment): super().__init__(typeOfAn, area, typeFeed, numberOfPaws) self.environment = environment def hello(self): return 'I am mammal' elephant = Mammals('elephant', 'Africa', 'grass', 4, 'jungles') print(elephant.hello()) print(cat._numberOfPows) print(cat.__dict__) class Birds(Animals): def __int__(self, typeOfAn, area, typeFeed, numberofPaws, numberOfWings): super().__init__(typeOfAn, area, typeFeed, numberofPaws) self.numberOfWings = numberOfWings def hello_bird(self): return '!!!I am bird!!! I can fly'
import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import "/src/styles.css"; function App() { return ( <div className="card"> <Avatar /> <div className="data"> <Intro /> <SkillList /> </div> </div> ); } function Avatar() { return <img className="avatar" src="1.jpg" alt="Mahir" />; } function Intro() { return ( <div className="intro"> <h1>Mahir Demir</h1> <p>Hello, ı am learning react. I hope ı will be a frontend developer</p> </div> ); } function SkillList() { return ( <div className="skill-list"> <Skill skill="HTML/CSS" color="blue" emoji="💪" /> <Skill skill="Javascript" color="red" emoji="💪" /> <Skill skill="Tailwind" color="skyBlue" emoji="💪" /> <Skill skill="React" color="orange" emoji="💪" /> </div> ); } function Skill(props) { return ( <div className="skill" style={{ backgroundColor: props.color }}> <span>{props.skill}</span> <span>{props.emoji}</span> </div> ); } const rootElement = document.getElementById("root"); const root = createRoot(rootElement); root.render( <StrictMode> <App /> </StrictMode> );
package Schema::Data; use strict; use warnings; use Class::Utils qw(set_params); use English; use Error::Pure qw(err); use Perl6::Slurp qw(slurp); our $VERSION = 0.07; sub new { my ($class, @params) = @_; # Create object. my $self = bless {}, $class; # Version. $self->{'version'} = undef; # Process parameters. set_params($self, @params); # Load file with versions. $self->{'_versions_file'} = $self->_versions_file; my @versions = slurp($self->{'_versions_file'}, {'chomp' => 1}); $self->{'_versions'} = \@versions; # Set version to last if isn't defined. if (! defined $self->{'version'}) { $self->{'version'} = $self->{'_versions'}->[-1]; } if ($self->{'version'} !~ /^([0-9]+)\.([0-9]+)\.([0-9]+)$/) { err 'Schema data version has bad format.', 'Schema data version', $self->{'version'}, ; } # Load schema. $self->{'_schema_data_module'} = $class.'::'."$1\_$2\_$3"; eval 'require '.$self->{'_schema_data_module'}; if ($EVAL_ERROR) { err 'Cannot load Schema data module.', 'Module name', $self->{'_schema_data_module'}, 'Error', $EVAL_ERROR, ; } return $self; } sub list_versions { my $self = shift; return sort @{$self->{'_versions'}}; } sub schema_data { my $self = shift; return $self->{'_schema_data_module'}; } sub version { my $self = shift; return $self->{'version'}; } sub _versions_file { my $self = shift; err "We need to implement distribution file with Schema data versions."; return; } 1; __END__ =pod =encoding utf8 =head1 NAME Schema::Data - Abstract class for versioned DB schema datasets. =head1 SYNOPSIS package Schema::Data::Foo; use base qw(Schema::Data); sub _versions_file { return 'versions.txt'; } package main; my $obj = Schema::Data::Foo->new; my @versions = $obj->list_versions; my $schema_data = $obj->schema_data; my $version = $obj->version; =head1 DESCRIPTION This is abstract class for versioned schema dataset modules. =head1 METHODS =head2 C<new> my $obj = Schema::Data->new(%params); Constructor. Returns instance of object. =over 8 =item * C<version> Selected schema data version. Default value is last version. =back =head2 C<list_versions> my @versions = $obj->list_versions; Get sorted list of versions. Returns array of versions. =head2 C<schema_data> my $schema_data = $obj->schema_data; Get schema data module name. Returns string. =head2 C<version> my $version = $obj->version; Get version of schema data, which is actial set. Returns string. =head1 ERRORS new(): Cannot load Schema data module. Module name: %s Error: %s Schema data version has bad format. Schema data version: %s From Class::Utils::set_params(): Unknown parameter '%s'. (only in this abstract class) We need to implement distribution file with Schema data versions. =head1 EXAMPLE =for comment filename=list_data_versions.pl use strict; use warnings; use File::Path qw(make_path); use File::Spec::Functions qw(catfile); use File::Temp qw(tempdir tempfile); use IO::Barf qw(barf); # Temp directory for generated module my $temp_dir = tempdir(CLEANUP => 1); # File with versions. my (undef, $versions_file) = tempfile(); make_path(catfile($temp_dir, 'Schema', 'Data', 'Foo')); my $package_schema_foo = catfile($temp_dir, 'Schema', 'Data', 'Foo.pm'); barf($package_schema_foo, <<"END"); package Schema::Data::Foo; use base qw(Schema::Data); use IO::Barf qw(barf); sub _versions_file { barf('$versions_file', "0.2.0\\n0.1.0\\n0.1.1"); return '$versions_file'; } 1; END my $package_schema_foo_0_1_0 = catfile($temp_dir, 'Schema', 'Data', 'Foo', '0_1_0.pm'); barf($package_schema_foo_0_1_0, <<'END'); package Schema::Data::Foo::0_1_0; 1; END my $package_schema_foo_0_1_1 = catfile($temp_dir, 'Schema', 'Data', 'Foo', '0_1_1.pm'); barf($package_schema_foo_0_1_1, <<'END'); package Schema::Data::Foo::0_1_1; 1; END my $package_schema_foo_0_2_0 = catfile($temp_dir, 'Schema', 'Data', 'Foo', '0_2_0.pm'); barf($package_schema_foo_0_2_0, <<'END'); package Schema::Data::Foo::0_2_0; 1; END unshift @INC, $temp_dir; require Schema::Data::Foo; my $obj = Schema::Data::Foo->new; my @versions = $obj->list_versions; print join "\n", @versions; unlink $versions_file; # Output: # 0.1.0 # 0.1.1 # 0.2.0 =head1 DEPENDENCIES L<Class::Utils>, L<English>, L<Error::Pure>, L<Perl6::Slurp>. =head1 REPOSITORY L<https://github.com/michal-josef-spacek/Schema-Data> =head1 AUTHOR Michal Josef Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2022-2023 Michal Josef Špaček BSD 2-Clause License =head1 VERSION 0.07 =cut
// Given an array of strings, group anagrams together. let groupAnagrams = function(strs) { // create a new array that sorts the words in the array but keeps them at the same index // find all sorted words that are matching // group all matching words together let map = {} let sorted = [] // sort the letters in each word for(i in strs){ sorted.push(strs[i].split('').sort().join('')) } // add matching sorted words to map object for(i in sorted){ map[sorted[i]] ? map[sorted[i]].push(i) : map[sorted[i]] = [i] } // get all the grouped positions let positions = Object.values(map) // convert indexes to actual words for(let i = 0; i < positions.length; i++){ for(let j = 0; j < positions[i].length; j++){ positions[i][j] = strs[positions[i][j]] } } return positions } Other people's solutions: // basically what I wanted to do but much cleaner and far less loops... const groupAnagrams = strs => { const map = {}; for (let str of strs) { const key = [...str].sort().join(''); if (!map[key]) { map[key] = []; } map[key].push(str); } return Object.values(map); };
// // EmojiMemoryGame.swift // Memorize // // Created by Jasper Wang on 2020-07-10. // Copyright © 2020 Jasper Wang. All rights reserved. // // ViewModel in MVVM import Foundation // ViewModel is always a class. ViewModel never stores the View; instead, View always stores an instance of ViewModel // For class type, the default initializer inits none of the vars // ObservableObject: needed for Reactive UI class EmojiMemoryGame: ObservableObject { // Explicit typing // private var memoryGame: MemoryGame<String> = MemoryGame<String>(numberOfPairsOfCard: 2, cardContentFactory: { (pairIndex: Int) -> String in // return "" // }) // function is inlined // // Implicit typing // private var memoryGame: MemoryGame<String> = MemoryGame<String>(numberOfPairsOfCard: 2, cardContentFactory: { pairIndex in ""}) // // Let the last argument float outside // private var memoryGame: MemoryGame<String> = MemoryGame<String>(numberOfPairsOfCard: 2) { pairIndex in ""} // // If pairIndex is not used, use _ instead // private var memoryGame: MemoryGame<String> = MemoryGame<String>(numberOfPairsOfCard: 2) { _ in ""} @Published // a property wrapper; call objectWillChange upon the object changes private var memoryGame: MemoryGame<String> = createMemoryGame() // Add static keyword to properly initialize class property private static func createMemoryGame() -> MemoryGame<String> { let emojis: Array<String> = ["👻", "🎃", "🕷"] return MemoryGame<String>(numberOfPairsOfCard: 3) {index in return emojis[index] } } // MARK: - Access to the model var cards: Array<MemoryGame<String>.Card> { memoryGame.cards } // MARK: - Intent(s) func chooseCard(card: MemoryGame<String>.Card) { memoryGame.choose(card: card) } }
module.exports = class NyzoMicropayConfiguration { constructor(clientUrl, receiverId, tag, displayName, amountMicroNyzos) { let cleanTag = (_tag) => { // This was previously called cleanTag in the extensionUtil // Previously, the tag was limited to 32 characters and non-word characters were removed. Now, the tag will be // limited to 67 characters to provide support for normalized sender-data strings, and all characters are allowed. // This allows new functionality without breaking previous functionality. if (typeof _tag !== "string") { _tag = ""; } return _tag.substring(0, 67); } let cleanDisplayName = (_displayName) => { if (typeof _displayName !== "string") { _displayName = ""; } return _displayName.replace(/[^\w_ ]/g, ""); } this.tag = cleanTag(tag); this.displayName = cleanDisplayName(displayName); this.clientUrl = NyzoUtil.IsValidClientURL(clientUrl) ? clientUrl : null; this.receiverId = NyzoUtil.IsValidPublicIdentifier(receiverId) ? receiverId : null; this.amountMicronyzos = amountMicroNyzos; } static GetClientURL(){ return this.clientUrl; } static GetReceiverID(){ return this.receiverId; } static GetTag(){ return this.tag; } static GetDisplayName(){ return this.displayName; } static GetAmountOfMicroNyzos(){ return this.amountMicronyzos; } static GetAmountOfNyzos(){ return Math.floor(this.amountMicronyzos / NyzoConstants.GetMicroNyzosPerNyzo()); } }
import React, { Component } from "react"; import Loading from "../components/Loading"; import Button from "../components/Button"; import getProject from "../services/getProject"; import "./project.css"; class Project extends Component { state = { isLoading: true, projectInfo: { id: "", title: "", description: [], smallDescription: "", techs: [], images: [], }, }; componentDidMount() { const { match: { params: { id }, }, } = this.props; const project = getProject(id); this.setState({ isLoading: false, projectInfo: project }); } render() { const { isLoading, projectInfo } = this.state; const { title, description, techs, images } = projectInfo; return ( <> {isLoading ? ( <Loading /> ) : ( <main className="project-main"> <aside className="project-aside"> {images.map(({ title, link }) => ( <section className="project-images"> <img src={link} alt={title} /> </section> ))} </aside> <article className="project-article"> <h2 className="project-h2">{title}</h2> <div className="project-description"> <h3 className="project-h3">Descrição</h3> {description.map((p) => ( <p className="p-description">{p}</p> ))} </div> <div className="project-techs"> <h3 className="project-h3">Ferramentas utilizadas</h3> {techs.map((tech) => ( <p className="p-techs">{tech}</p> ))} </div> <Button /> </article> </main> )} </> ); } } export default Project;
"use client"; import { createSlice } from "@reduxjs/toolkit"; export const tripsSlice = createSlice({ name: "trips", initialState: { trips: [ { id: 2341234, city: "Boston", state: "MA", country: "USA", startDate: "2020-06-01", endDate: "2020-06-03", hotel: { name: "Marriott", address: "1000 Boylston St, Boston, MA 02116", lat: 42.346741, lon: -71.078049, rating: 4, link: "https://www.marriott.com/hotels/travel/bosco-boston-marriott-copley-place/", }, meals: [ { id: 12345, name: "breakfast", startTime: "8:00am", endTime: "9:00am", date: "2020-06-01", }, { id: 12346, name: "lunch", startTime: "12:00pm", endTime: "1:00pm", date: "2020-06-01", }, { id: 12347, name: "dinner", startTime: "6:00pm", endTime: "7:00pm", date: "2020-06-01", }, ], attraction: { id: 1234, name: "Fenway Park", startTime: "10:00", endTime: "12:00", distance: 2, rating: 5, address: "4 Yawkey Way, Boston, MA 02215", link: "https://www.mlb.com/redsox/ballpark", }, }, ], }, reducers: { addAttraction: (state, action) => { state.trips[0].attraction = action.payload; }, }, }); export default tripsSlice.reducer;
import React from "react"; import { useState } from "react"; import { certifsD } from "../../utils/certif"; import "./Add.css"; const Add = () => { const [diploma, setDiploma] = useState({ nom_univesrite: "USTHB", mat_etudiant: null, nom_etudiant: "", prenom_etudiant: "", date_naissance: "", lieu_naissance: "", date: "", niveau: "", domaine: "", filiere: "", specialite: "", departement: "INFORMATIQUE", }); return ( <div className='add'> <div className='container'> <h2>Ajouter Un Diplôme</h2> <form> <label>Matricule</label> <input type='text' maxLength='12' value={diploma.mat_etudiant} onChange={(e) => { setDiploma({ ...diploma, mat_etudiant: e.target.value, }); }} /> <div className='wrapper'> <div className='box'> <label>Nom</label> <input type='text' value={diploma.nom_etudiant} onChange={(e) => { setDiploma({ ...diploma, nom_etudiant: e.target.value.toUpperCase(), }); }} /> </div> <div className='box'> <label>Prénom</label> <input type='text' value={diploma.prenom_etudiant} onChange={(e) => { setDiploma({ ...diploma, prenom_etudiant: e.target.value.toUpperCase(), }); }} /> </div> </div> <div className='wrapper'> <div className='box'> <label>Date de Naissance</label> <input type='date' value={diploma.date_naissance} onChange={(e) => { setDiploma({ ...diploma, date_naissance: e.target.value, }); }} /> </div> <div className='box'> <label>Lieu de Naissance</label> <input type='text' value={diploma.lieu_naissance} onChange={(e) => { setDiploma({ ...diploma, lieu_naissance: e.target.value.toUpperCase(), }); }} /> </div> </div> <div className='wrapper'> <div className='box'> {" "} <label>Diplôme</label> <select value={diploma.niveau} onChange={(e) => { setDiploma({ ...diploma, niveau: e.target.value, }); }} > <option></option> <option value='LICENCE'>Licence</option> <option value='MASTER'>Master</option> <option value='DOCTORAT'>Doctorat</option> </select> </div> <div className='box'> <label>Date de Délibération</label> <input type='date' value={diploma.date} onChange={(e) => { setDiploma({ ...diploma, date: e.target.value, }); }} /> </div> </div> <label>Domaine</label> <input type='text' value={diploma.domaine} onChange={(e) => { setDiploma({ ...diploma, domaine: e.target.value.toUpperCase(), }); }} /> <div className='wrapper'> <div className='box'> <label>Filière</label> <input type='text' value={diploma.filiere} onChange={(e) => { setDiploma({ ...diploma, filiere: e.target.value.toUpperCase(), }); }} /> </div> <div className='box'> <label>Spécialité</label> <input type='text' value={diploma.specialite} onChange={(e) => { setDiploma({ ...diploma, specialite: e.target.value.toUpperCase(), }); }} /> </div> </div> <div className='buttons'> <button className='save' onClick={async (e) => { e.preventDefault(); await certifsD.methods .addDiplome( diploma.nom_univesrite, diploma.mat_etudiant, diploma.nom_etudiant, diploma.prenom_etudiant, diploma.date_naissance, diploma.lieu_naissance, diploma.date, diploma.niveau, diploma.domaine, diploma.filiere, diploma.specialite, diploma.departement ) .send({ from: "0x1c06595F6E29d50eDc6eb6e84b87cf8Ade848B10", gas: "1000000", }); window.location.reload(); }} > Enregistrer </button> <button className='close' onClick={(e) => { e.preventDefault(); e.target.parentElement.parentElement.parentElement.parentElement.style.display = "none"; }} > Fermer </button> </div> </form> </div> </div> ); }; export default Add;
# DataBases Foundations This course is designed to introduce undergraduate students to foundations of __database systems__ and _good practices_ of databases design. This is __not__ a course fully focus on __software engineering__, but it is part of main concepts of software systems building. Classes will consist of lectures, __discussions__, practical examples, and workshops. Also, you must take some readings from _software architecture_. In addition, there will be a __semester-long project__, as well __three__ exams, __six__ workshops, and __twenty__ additional assignmens. - [DataBases Foundations](#databases-foundations) - [Goals](#goals) - [Pre-requisites](#pre-requisites) - [Tasks](#tasks) - [Grading](#grading) - [Rules](#rules) - [Code of Conduct](#code-of-conduct) - [Bibliography](#bibliography) ## Goals The main goal of this course is to provide undergraduate students with different **models** **concepts**, and **tools** for solving the data layer of software problems using **database systems** based on software application project requirements. At the end of this course you should be able to **create** a full software **database solution** with a good level of **quality** metrics. Also, you should be able to **design** robust database systems in an **agnostic** way. ## Pre-requisites This is a basic course, so you must have some knowledge in: - **Programming** in Python, or C++. - **Object-Oriented Programming** foundations. - UML and **Class Diagrams** basic concepts. - **Git** basic usage, and **GitHub** basic usage. - Use of **IDEs** like VS Code, Eclipse, or PyCharm. ## Tasks As follows the list of task of the course is described. Be careful with deadlines. | Deadline | Task ID | Task Description | | ---------- | -------- | --------------------------------------------------------------------------------- | | May 7th | T11 | What are Declarative Programming Languages? | | May 7th | T12 | What are Imputers and what are the recommended practices to built them? | | May 11th | T13 | Which ones are the common technical skills required for data engineer positions? | | May 11th | T14 | What are user grants for access into operative system context? | | May 14th | T15 | What is a Database Backups and what policies are recommended to handle them? | | May 14th | T16 | What is a database indexes and why is it important to apply them? | | May 18th | T17 | What is the difference between numerical and categorical columns in data context? | | May 18th | T18 | What are Encoders and why do they are important in neunal networks progress? | | May 21th | T19 | What are Vector Databases and why are they crucial for LLM development? | | May 21th | T20 | What is a Feature Store and what is Data Lineage? | ## Grading As follows there is a simple distribution of percentage of grades: | Period | Item | Percentage | | --------- | ---------------------- | ---------- | | Period I | Assignments | 10% | | | Workshops | 15% | | | Project Partial Delivery | 10% | | Period II | Assignments | 10% | | | Workshops | 15% | | | Test | 10% | | Period III| Workshop + Assignments | 5% | | | Final Test | 10% | | | Course Project | 15% | ## Rules Don't hate the player, hate the game: - All assignments must be submitted hand-written on **time** and in **English**. Grammar and spelling will **not** be evaluated. - Copying and pasting from the internet is **forbidden**. Please, **develop** your own solutions. - Class attendance is **not mandatory**. If you **miss** classes, you must _study by yourself_. - No cell-phones, no smartwatches, no WhatsApp, no Tinder, no smart anything. **Just you and your brain**. Pay attention in class. - Communications with me must be done by **email** or by **Slack**. I will **not** answer any question by _WhatsApp_. ## Code of Conduct - Always be **respectful** to your classmates and to me. You must be **kind** with everyone inside (_and outside_) the classroom. - There is no a better programming language, tool, or technology. There are only **better** or **worse** solutions. - You must be **honest** with your work. If you don't know something, just **ask** me. I will be glad to help you. - You must be **responsible** with your work. If you don't submit **on time**, please don't cry. - You must **not be annoying**, or affect the **classroom environment**. If you do, I will ask you to **leave** the classroom. ## Bibliography Recommended bibliography: - **Database Systems: The Complete Book**, by Hector Garcia-Molina, Jeffrey D. Ullman, and Jennifer Widom. - **Database Management Systems**, by Raghu Ramakrishnan and Johannes Gehrke. - **Fundamentals of Database Systems**, by Ramez Elmasri and Shamkant B. Navathe. - **Introducción a los Sistemas de Bases de Datos**, by Date C.J. - **Procesamiento de Bases de Datos, Fundamentos, Diseño e Implementación**, by David M. Kroenke. - **Sistemas de Bases de Datos: Conceptos Fundamentales**, by Elmasri, Navathe. - **Database System Implementation**, by Hector Garcia-Molina, Jeffrey D. Ullman, and Jennifer Widom. - **Fundamentos de Bases de Datos**, by Silberschtz A., Korth H.F, Sudershan S.
package com.example.shanti.presentation.home.book_session import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.shanti.data.database.SessionDatabase import com.example.shanti.data.database.TrainerDatabase import com.example.shanti.data.entity.SessionEntity import com.example.shanti.data.entity.TrainerEntity import com.example.shanti.data.model.PractiseType import com.example.shanti.data.repository.SessionRepository import com.example.shanti.data.repository.TrainerRepository import com.example.shanti.presentation.home.HomeScreenViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class BookSessionViewModel(trainerDatabase: TrainerDatabase, sessionDatabase: SessionDatabase, homeScreenViewModel: HomeScreenViewModel): ViewModel() { private var trainerDao = trainerDatabase.trainerDao() private var sessionDao = sessionDatabase.sessionDao() private val trainerRepository: TrainerRepository = TrainerRepository(this, trainerDao!!) private val sessionRepository: SessionRepository = SessionRepository(homeScreenViewModel, sessionDao!!) // Used only when Trainer Database is created fun init(){ trainerRepository.init() } fun insertSession(sessionEntity: SessionEntity){ viewModelScope.launch { sessionRepository.insertSession(sessionEntity) } } var selectedPractiseType = MutableStateFlow<PractiseType?>(PractiseType.YOGA) private set val trainersByPractiseType: StateFlow<List<TrainerEntity>> = selectedPractiseType .flatMapLatest { practiseType -> practiseType?.let { trainerRepository.getTrainersByPractiseType(it) } ?: flowOf(emptyList()) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList()) var openClearBookingDialog by mutableStateOf(false) fun selectPractiseType(practiseType: PractiseType) { selectedPractiseType.value = practiseType } }
// { Driver Code Starts //Initial template for C++ #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ // A : given string to search // B : vector of available strings class Solution { public: int wordBreak(string s, vector<string> &B) { int n=s.length(); int dp[n+1]; memset(dp,(0),sizeof(dp)); dp[0]=1; for(int i=1;i<=n;i++){ for(int j=0;j<i;j++){ if(dp[j]){ string sub=s.substr(j,i-j); auto it=find(B.begin(),B.end(),sub); if(it!=B.end()){ dp[i]=1; break; } } } } return dp[n]; } }; // { Driver Code Starts. int main(){ int t; cin>>t; while(t--){ int n; cin>>n; vector<string> dict; for(int i=0;i<n;i++){ string S; cin>>S; dict.push_back(S); } string line; cin>>line; Solution ob; cout<<ob.wordBreak(line, dict)<<"\n"; } } // } Driver Code Ends
import { AfterViewInit, Component, ViewChild } from '@angular/core'; import { MatPaginator } from '@angular/material/paginator'; import { MatSort } from '@angular/material/sort'; import { MatTableDataSource } from '@angular/material/table'; import { eListenChannels } from 'src/app/core/models/channels.enum'; import { eOrderStatus, iOrder } from 'src/app/core/models/order.model'; import { ApiService } from 'src/app/core/services/api.service'; import { PageInfoService } from 'src/app/core/services/page-info.service'; import { SocketService } from 'src/app/core/services/socket.service'; import { Router } from '@angular/router'; import { PageDataService } from 'src/app/core/services/page-data.service'; import { iOrderData, iTempOrder } from '../../models/order.model'; import { iRoom } from 'src/app/core/models/room.model'; import { iTable } from 'src/app/core/models/table.model'; import { DatabaseReferencesService, eArchivedStatus } from 'src/app/core/services/database-references.service'; import { Subscription } from 'rxjs'; import { NotifierComponent } from 'src/app/core/components/notifier/notifier.component'; @Component({ selector: 'app-orders-table', templateUrl: './orders-table.component.html', styleUrls: ['./orders-table.component.css'] }) export class OrdersTableComponent implements AfterViewInit { route = '/orders'; displayedColumns: string[] = ['room', 'tables', 'guests', 'status']; dataSource: MatTableDataSource<iOrderData>; roomReference: iRoom[] = []; tableReference: iTable[] = []; subscriptionRoom: Subscription | undefined; subscriptionTable: Subscription | undefined; orders: iOrder[] = []; @ViewChild(MatPaginator) paginator: MatPaginator | undefined; @ViewChild(MatSort) sort: MatSort | undefined; constructor(private api: ApiService, private sockerService: SocketService, private pageInfo: PageInfoService, private pageData: PageDataService, private router: Router, public references: DatabaseReferencesService, public notifier: NotifierComponent) { this.dataSource = new MatTableDataSource(); references.changeArchivedStatus(eArchivedStatus.notArchived); Promise.resolve().then(() => this.pageInfo.pageMessage = "📃🏃‍♀️Orders"); } ngOnDestroy(): void { this.subscriptionRoom?.unsubscribe(); this.subscriptionTable?.unsubscribe(); } ngOnInit(): void { this.subscriptionRoom = this.references.roomsReferenceObservable.subscribe((value) => { this.roomReference = value!; this.pushdataToSource(); }); this.subscriptionTable = this.references.tablesReferenceObservable.subscribe((value) => { this.tableReference = value!; this.pushdataToSource(); }); this.api.get(this.route).subscribe((responce) => { this.orders = responce.body.payload; this.pushdataToSource(); }); } pushdataToSource() { let ordersData: iOrderData[] = []; this.orders.forEach((order) => { let tables = ''; order.tables.forEach((table) => { tables += this.tableReference.find((tableReference) => tableReference._id === table)?.name + ', '; }); tables = tables.slice(0, -2); let orderData: iOrderData = { room: this.roomReference.find((room) => room._id === order.room)?.name!, tables: tables, guests: order.guests.toString(), status: order.status!, }; ordersData.push(orderData); }); this.dataSource = new MatTableDataSource<iOrderData>(ordersData); this.dataSource.paginator = this.paginator!; this.dataSource.sort = this.sort!; } ngAfterViewInit() { this.sockerService.listen(eListenChannels.orders).subscribe((responce) => { this.updateOrders(); }); } updateOrders() { this.api.get(this.route).subscribe((responce) => { this.orders = responce.body.payload; this.pushdataToSource(); this.dataSource.paginator = this.paginator!; this.dataSource.sort = this.sort!; }); } ngOndestroy() { this.subscriptionRoom?.unsubscribe(); this.subscriptionTable?.unsubscribe(); } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } sendData(data: any) { //find order by table id and send it to the order detail page let tempTable = data.tables.split(", ") as string[]; //note the tables is a string not array const table = this.tableReference.find((reference) => reference.name == tempTable[0]); if (table) { this.orders.forEach((order) => { order.tables.forEach((tableId) => { if (tableId == table._id) { if(order.status == eOrderStatus.ordering){ this.notifier.showError(400,"Order is taken by another waiter"); }else{ const tempOrder = { order: order, courses: [], } as iTempOrder; this.pageData.data = tempOrder; this.router.navigate(['/core/waiter/orders/detail']); } } }); }); } } }
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.BooksStore = void 0; const database_1 = __importDefault(require("../database")); class BooksStore { index() { return __awaiter(this, void 0, void 0, function* () { const conn = yield database_1.default.connect(); const sql = 'SELECT * FROM books'; const result = yield conn.query(sql); conn.release(); return result.rows; }); } bookExist(book) { return __awaiter(this, void 0, void 0, function* () { const allBooks = yield this.index(); for (const item of allBooks) { if (item.name === book.name && item.author === book.author && item.pages === book.pages) { return true; } } return false; }); } idExist(id) { return __awaiter(this, void 0, void 0, function* () { const allBooks = yield this.index(); for (const item of allBooks) { if (item.id === id) { return true; } } return false; }); } getById(id) { return __awaiter(this, void 0, void 0, function* () { const conn = yield database_1.default.connect(); const sql = 'SELECT * FROM books WHERE id=($1)'; const result = yield conn.query(sql, [id]); conn.release(); return result.rows[0]; }); } createBook(book) { return __awaiter(this, void 0, void 0, function* () { const conn = yield database_1.default.connect(); const sql = 'INSERT INTO books (name, author, pages) VALUES($1, $2, $3) RETURNING *'; const result = yield conn.query(sql, [ book.name, book.author, book.pages, ]); conn.release(); return result.rows[0]; }); } updateBook(id, book) { var _a, _b, _c, _d, _e, _f; return __awaiter(this, void 0, void 0, function* () { const getBookByID = yield this.getById(id); const name = getBookByID ? ((_b = (_a = book.name) !== null && _a !== void 0 ? _a : getBookByID.name) !== null && _b !== void 0 ? _b : '') : ''; const author = getBookByID ? ((_d = (_c = book.author) !== null && _c !== void 0 ? _c : getBookByID.author) !== null && _d !== void 0 ? _d : '') : ''; const pages = getBookByID ? ((_f = (_e = book.pages) !== null && _e !== void 0 ? _e : getBookByID.pages) !== null && _f !== void 0 ? _f : 0) : 0; const conn = yield database_1.default.connect(); const sql = 'UPDATE books SET name = ($1), author = ($2), pages = ($3) WHERE id = ($4) RETURNING *'; const result = yield conn.query(sql, [name, author, pages, id]); conn.release(); return result.rows[0]; }); } deleteBook(id) { return __awaiter(this, void 0, void 0, function* () { const conn = yield database_1.default.connect(); const sql = 'DELETE FROM books WHERE id = ($1) RETURNING *'; const result = yield conn.query(sql, [id]); conn.release(); return result.rows[0]; }); } } exports.BooksStore = BooksStore;
package Colletions.list.Pesquisa; import java.util.ArrayList; import java.util.List; public class CatalogoLivros { private List<Livro> livroList; public CatalogoLivros(){ this.livroList = new ArrayList<>(); } public void adicionarLivro(String titulo, String autor, int anoPublicacao){ livroList.add(new Livro(titulo,autor,anoPublicacao)); } public List<Livro> pesquisarPorAutor(String autor){ List<Livro> livrosPorAutor = new ArrayList<>(); if(!livroList.isEmpty()){ for (Livro l : livroList){ if(l.getAutor().equalsIgnoreCase(autor)){ livrosPorAutor.add(l); } } } return livrosPorAutor; } public List<Livro> pesquisarPorIntervaloAnos(int anoInicial, int anoFinal){ List<Livro> livrosPorAnos = new ArrayList<>(); if(!livroList.isEmpty()) { for (Livro l : livroList) { if (l.getAno() >= anoInicial && l.getAno() <= anoFinal) { livrosPorAnos.add(l); } } } return livrosPorAnos; } public Livro pesquisarPorTitulo(String titulo){ Livro livroTitulo = null; if(!livroList.isEmpty()){ for (Livro l: livroList){ if(l.getTitulo().equalsIgnoreCase(titulo)){ livroTitulo = l; break; } } } return livroTitulo; } public static void main(String[] args) { //psvm CatalogoLivros catalogoLivros = new CatalogoLivros(); catalogoLivros.adicionarLivro("lv 1", "eu 1", 2001); catalogoLivros.adicionarLivro("lv 2", "eu 2", 2002); catalogoLivros.adicionarLivro("lv 2", "eu 2", 2003); catalogoLivros.adicionarLivro("lv 3", "eu 3", 2003); catalogoLivros.adicionarLivro("lv 4", "eu 4", 2004); System.out.println(catalogoLivros.pesquisarPorAutor("eu 2")); System.out.println(catalogoLivros.pesquisarPorAutor("eu 1")); System.out.println("Livro por inteveralo de anos: "+catalogoLivros.pesquisarPorIntervaloAnos(2001,2002)); System.out.println("Titulo: "+ catalogoLivros.pesquisarPorTitulo("lv 2")); } }
import 'package:flutter/material.dart'; import 'package:pretty_gauge/pretty_gauge.dart'; import 'package:share_plus/share_plus.dart'; class ScoreScreen extends StatelessWidget { final double bmiScore; final int age; String? bmiStatus; String? bmiInterpretation; Color? bmiStatusColor; ScoreScreen({Key? key, required this.bmiScore, required this.age}) : super(key: key); @override Widget build(BuildContext context) { setBmiInterpretation(); return Scaffold( appBar: AppBar( centerTitle: true, title: const Text("RESULTADO IMC") ), body: Container( padding: const EdgeInsets.all(12), child: Card ( elevation: 12, shape: const RoundedRectangleBorder(), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Seu resultado", style: TextStyle( fontSize: 30, color: Colors.blue, ) ), const SizedBox( height: 10, ), PrettyGauge( gaugeSize: 300, minValue: 0, maxValue: 40, segments: [ GaugeSegment("UnderWeight", 18.5, Colors.red), GaugeSegment("Normal", 6.4, Colors.green), GaugeSegment("OverWeight", 5, Colors.orange), GaugeSegment("Obese", 10.1, Colors.pink) ], valueWidget: Text( bmiScore.toStringAsFixed(1), style: const TextStyle(fontSize: 40), ), currentValue: bmiScore.toDouble(), needleColor: Colors.blue, ), const SizedBox(height: 10,), Text( bmiStatus!, style: TextStyle( fontSize: 20, color: bmiStatusColor ), ), const SizedBox(height: 10,), Text( bmiInterpretation!, style: const TextStyle( fontSize: 20, ), ), const SizedBox(height: 10,), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text("Calcular novamente")), const SizedBox(width: 10,), ElevatedButton( onPressed: () { Share.share("Seu IMC é ${bmiScore.toStringAsFixed(1)} at age $age"); }, child: const Text("Compartilhar")) ], ) ] ) ) ), ); } void setBmiInterpretation() { if (bmiScore > 30) { bmiStatus = "Obeso"; bmiInterpretation = "Trabalhe para reduzir seu peso."; bmiStatusColor = Colors.pink; } else if (bmiScore >= 25) { bmiStatus = "Sobrepeso"; bmiInterpretation = "Faça exercícios regulares e reduza o peso."; bmiStatusColor = Colors.orange; } else if (bmiScore >= 18.5) { bmiStatus = "Normal"; bmiInterpretation = "Parabéns, você está no peso ideal."; bmiStatusColor = Colors.green; } else if (bmiScore < 18.5) { bmiStatus = "Abaixo do peso"; bmiInterpretation = "Abaixo do peso, tente consultar profissionais"; bmiStatusColor = Colors.red; } } }
package service import ( "bytes" "context" "io" "strconv" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/glacier" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/aws/aws-sdk-go-v2/service/s3/types" ) // https://docs.aws.amazon.com/amazonglacier/latest/dev/introduction.html // https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/using-glacier-with-go-sdk.html // https://docs.aws.amazon.com/cli/latest/reference/glacier/index.html type IAwsService interface { GlacierVaultList() *glacier.ListVaultsOutput GlacierUploadArchive(vaultName string, fileBuffer []byte) (*glacier.UploadArchiveOutput, error) S3PutObject(bucketName string, objectName string, fileBuffer io.Reader) (*manager.UploadOutput, error) Enabled() bool } type myAwsService struct { cfg aws.Config } func MyAwsService() IAwsService { cfg, _ := config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider( credentials.NewStaticCredentialsProvider(GetEnv("AWS_ACCESS_KEY_ID"), GetEnv("AWS_SECRET_ACCESS_KEY"), ""))) return &myAwsService{cfg: cfg} } func (as myAwsService) S3PutObject(bucketName string, objectName string, fileBuffer io.Reader) (*manager.UploadOutput, error) { client := s3.NewFromConfig(as.cfg) uploader := manager.NewUploader(client) return uploader.Upload(context.TODO(), &s3.PutObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(objectName), Body: fileBuffer, StorageClass: types.StorageClassGlacier, }) } func (as myAwsService) GlacierVaultList() *glacier.ListVaultsOutput { glacierCls := glacier.NewFromConfig(as.cfg) result, _ := glacierCls.ListVaults(context.Background(), &glacier.ListVaultsInput{}) /*for _, vault := range result.VaultList { fmt.Println(*vault.VaultName) }*/ return result } func (as myAwsService) GlacierUploadArchive(vaultName string, fileBuffer []byte) (*glacier.UploadArchiveOutput, error) { glacierCls := glacier.NewFromConfig(as.cfg) return glacierCls.UploadArchive(context.Background(), &glacier.UploadArchiveInput{ VaultName: &vaultName, Body: bytes.NewReader(fileBuffer), }) } func (as myAwsService) Enabled() bool { res, _ := strconv.ParseBool(GetEnv("AWS_ENABLED")) return res }