text
stringlengths
184
4.48M
import useSWR, { SWRConfiguration } from 'swr' import { User, UserDataInput } from '../../../types' import { createUserCacheKey } from '../../createCacheKeys' import getUserData from './getUserData' import constants from '../../../constants' import { collection, doc, getFirestore, serverTimestamp, updateDoc, } from 'firebase/firestore' import useAuth from '../../auth/useAuth' const { USERS_COLLECTION } = constants const DEFAULT_SWR_CONFIG: SWRConfiguration = { revalidateOnFocus: false, } type UseUser = (options?: { swrConfig?: SWRConfiguration; skip?: boolean }) => { error: unknown isLoading: boolean isValidating: boolean update: (data: UserDataInput) => Promise<void> user: User | null | undefined } const useUserData: UseUser = ({ swrConfig = {}, skip = false } = {}) => { const { uid } = useAuth() const userCacheKey = uid ? createUserCacheKey(uid) : undefined const { data, error, isLoading, isValidating, mutate } = useSWR( !skip ? userCacheKey : undefined, () => (uid ? getUserData(uid) : null), { ...DEFAULT_SWR_CONFIG, ...swrConfig, } ) const update = async (data: UserDataInput) => { if (!uid) { throw new Error('User is not authenticated') } const db = getFirestore() const collectionRef = collection(db, USERS_COLLECTION) const dbRef = doc(collectionRef, uid) await updateDoc(dbRef, { ...data, updatedAt: serverTimestamp(), }) await mutate() } return { error, isLoading, isValidating, update, user: data, } } export default useUserData
<div class="audit-jobs-details-collapse" *ngIf="isCollapseDetails" title="Expand the audit details form" (click)="openPlacesDetail()"> <mat-icon>filter_list</mat-icon> </div> <div class="audit-jobs-details" *ngIf="!isCollapseDetails"> <form [formGroup]="auditDetailForm" (ngSubmit)="onSubmit(auditDetailForm.value)"> <div fxLayout="row" fxLayoutAlign="center center" fxLayoutGap="20px" class="open-map-link"> <mat-icon class="collapse-icon" (click)="collapseDetails()" title="Collapse the audit details form">keyboard_arrow_left</mat-icon> <span fxFlex="1 1 auto"></span> <a class="link" (click)="searchInformation('search')">Google Search</a> <a class="link" (click)="searchInformation('street')">Street View</a> <span fxFlex="1 1 auto"></span> <mat-icon (click)="closeDetails()">close</mat-icon> </div> <div class="field-area" [ngStyle]="{'height.px': contentHeight}" (window:resize)="onResize()" [ngClass]="{'overflow-hidden': isOpenedHours}"> <input type="hidden" placeholder="Safegraph ID" formControlName="safegraphId"> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <div class="imx-form-field"> <mat-form-field> <input matInput placeholder="Place Name" [formControl]="searchTextCtrl"> <button type="button" class="search-icon" mat-button matSuffix mat-icon-button title="search" aria-label="search" (click)="onSearch('placeName', searchTextCtrl.value)"> <mat-icon class="link">search</mat-icon> </button> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.name.value && auditDetailForm.controls.name.value.length>0">Name</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <mat-label>name<span class="star ml-2">*</span></mat-label> <input matInput formControlName="name" #fName> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.street.value && auditDetailForm.controls.street.value.length>0">Street</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <mat-label>Street<span class="star ml-2">*</span></mat-label> <input matInput formControlName="street"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.city.value && auditDetailForm.controls.city.value.length>0">City</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <mat-label>City<span class="star ml-2">*</span></mat-label> <input matInput formControlName="city"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.state.value && auditDetailForm.controls.state.value.length>0">State</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <mat-label>State<span class="star ml-2">*</span></mat-label> <input matInput formControlName="state"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.zipcode.value && auditDetailForm.controls.zipcode.value.length>0">Zipcode</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <mat-label>Zipcode<span class="star ml-2">*</span></mat-label> <input matInput formControlName="zipcode"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.hereId.value && auditDetailForm.controls.hereId.value.length>0">Here ID</mat-checkbox> </div>--> <div class="imx-form-field" fxLayout="row" *ngIf="this.place['status'] !== 0"> <mat-form-field> <input matInput placeholder="Place ID" readonly="readonly" value="{{this.place['place_id'] && this.place['place_id'] || ''}}"> </mat-form-field> <!--<span fxFlex="1 1 auto"></span> <mat-icon class="link" title="search" (click)="onSearch('here_place_id',auditDetailForm.get('hereId').value)">search</mat-icon>--> </div> </div> <div class="imx-form-field" fxLayout="row" fxLayoutAlign="start center" *ngIf="this.place['status'] !== 0"> <mat-form-field> <input matInput placeholder="Parent Place ID" formControlName="parentPlaceID" appNumberOnly > </mat-form-field> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <div class="imx-form-field" fxLayout="row"> <mat-form-field > <mat-label>Place Type</mat-label> <mat-select formControlName="placeType"> <mat-option *ngFor="let type of placeTypes$ | async" [value]="type.place_type_id">{{type.name | titlecase}}</mat-option> </mat-select> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="column" fxLayoutAlign="start start" formGroupName="hours"> <div fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox>Hours</mat-checkbox> </div> <div> <mat-form-field> <mat-select formControlName="label"> <mat-option *ngFor="let hour of hoursData" [value]="hour.name"> {{hour.name}} </mat-option> </mat-select> </mat-form-field> </div> <a class="link imx-ml-10" #overlayOrigin="cdkOverlayOrigin" cdkOverlayOrigin (click)="onOpenHours()">Add</a> <app-dropdown [overlayOrigin]="overlayOrigin" (close)="isOpenedHours = false" (open)="isOpenedHours = true" [dialogClass]="'imx-add-audit-hours'"> <div fxLayout="column" fxLayoutAlign="start center"> <div class="width100"> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <div class="imx-field-check imx-mr-10"> Name </div> <div class="imx-form-field"> <mat-form-field> <input matInput formControlName="hoursName"> </mat-form-field> </div> </div> </div> <div> <p>Select date for Hours</p> <div fxLayout="row" fxLayoutAlign="start center"> <sat-calendar [rangeMode]="true" [beginDate]="dateInlineRange['begin']" [endDate] = "dateInlineRange['end']" (dateRangesChange)="inlineRangeChange($event)"> </sat-calendar> </div> <div class="hours-save-btn"> <button type="button" mat-raised-button color="primary" (click)="onSaveHours()"> Save </button> </div> </div> </div> </app-dropdown>--> </div> <div div fxLayout="row" fxLayoutAlign="end center" class='action-link-div'> <a class="link imx-mlr-20" title="Copy to weekdays" (click)="copyValues(duration.WEEKDAYS)">Apply to weekdays</a> <a class="link imx-mlr-20" title="Copy to all days" (click)="copyValues(duration.ALL)">Apply to all</a> <a class="link imx-mlr-20" title="Clear all feilds" (click)="clearAllTimeData();">Clear all</a> </div> <div class="imx-time-field"> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="mo"> <div class="imx-time-label custom-labels"><label>Monday</label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="tu"> <div class="imx-time-label custom-labels"><label>Tuesday</label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="we"> <div class="imx-time-label custom-labels"><label>Wednesday</label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="th"> <div class="imx-time-label custom-labels"><label >Thursday</label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="fr"> <div class="imx-time-label custom-labels"><label>Friday</label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="sa"> <div class="imx-time-label custom-labels"><label>Saturday</label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> <div fxLayout="row" fxLayoutAlign="start center" formGroupName="su"> <div class="imx-time-label custom-labels"><mat-label>Sunday</mat-label></div> <mat-form-field class="time-field mr-10"> <mat-select formControlName="from"> <mat-option *ngFor="let time of times" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="time-field mr-10"> <mat-select formControlName="to"> <mat-option *ngFor="let time of timesnextday" [value]="time.value">{{time.label}}</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field class="time-field ext-time-field"> <mat-select formControlName="ext"> <mat-option [value]=""></mat-option> <ng-container *ngFor="let time of times; let i = index;"> <mat-option [value]="time" *ngIf="i > 0 && i < 13">+{{i}}</mat-option> </ng-container> </mat-select> </mat-form-field> --> </div> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.floors.value && auditDetailForm.controls.floors.value.length>0">Floors</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <input matInput placeholder="Floors" formControlName="floors"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.entrances.value && auditDetailForm.controls.entrances.value.length>0">Entrances</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <input matInput placeholder="Entrances" formControlName="entrances"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.concourses.value && auditDetailForm.controls.concourses.value.length>0">Concourses</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <input matInput placeholder="Concourses" formControlName="concourses"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.platforms.value && auditDetailForm.controls.platforms.value.length>0">Platforms</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <input matInput placeholder="Platforms" formControlName="platforms"> </mat-form-field> </div> </div> <div class="imx-field" fxLayout="row" fxLayoutAlign="start center"> <!--<div class="imx-field-check"> <mat-checkbox [checked]="auditDetailForm.controls.gates.value && auditDetailForm.controls.gates.value.length>0">Gates</mat-checkbox> </div>--> <div class="imx-form-field"> <mat-form-field> <input matInput placeholder="Gates" formControlName="gates"> </mat-form-field> </div> </div> <!-- building area--> <div class="imx-field imx-mtb-20" fxLayout="column" fxLayoutAlign="start start"> <div class="imx-field-check width100" fxLayout="row" fxLayoutAlign="space-around center"> <div class="imx-time-label"> <div class="custom-labels">Building Area<span class="star ml-2">*</span></div> </div> <span fxFlex="1 1 auto"></span> <a class="link" (click)="addNewArea('building')" *ngIf="!buildingAreaPolygon['type']"> Add Building Area </a> </div> <div class="building-area-main" *ngIf="buildingAreaPolygon['type']"> <div class="building-area-map" (click)="onOpenFacilityMap('building')" > <app-display-map [properties]="buildAreaProperties"></app-display-map> </div> </div> </div> <!-- Property area--> <div class="imx-field imx-mtb-20" fxLayout="column" fxLayoutAlign="start start"> <div class="imx-field-check width100" fxLayout="row" fxLayoutAlign="space-around center"> <div class="custom-labels">Property Area<span class="star ml-2">*</span></div> <span fxFlex="1 1 auto"></span> <a class="link" (click)="addNewArea('property')" *ngIf="!propertyArea['type']"> Add Property Area </a> </div> <div class="building-area-main" *ngIf= "propertyArea['type']"> <div class="building-area-map" (click)="onOpenFacilityMap('property')" > <app-display-map [properties]="propertyAreaProperties"></app-display-map> </div> </div> </div> <div> <p>Last updated at: {{updatedDate | date:'MMM dd, yyyy hh:mm aaa'}}</p> <p>Last updated by: {{updatedBy}}</p> </div> <!--<div class="imx-field imx-mtb-20" fxLayout="column" fxLayoutAlign="start start"> &lt;!&ndash; Note list &ndash;&gt; <h4>Notes</h4> <div *ngFor="let note of notes" fxLayout="column wrap" class="notes-area width100"> <p class="note-details">{{note.note}}</p> <p class="link">{{note.name}}</p> <mat-divider></mat-divider> </div> <div formGroupName="notes" class="width100"> <div class="width100"> <mat-form-field fxFlex="60%"> <input matInput placeholder="Name" formControlName="name"> </mat-form-field> </div> <div class="width100" > <mat-form-field class="width100"> <textarea matInput placeholder="Note" formControlName="note"></textarea> </mat-form-field> </div> </div> <div class="width100" fxLayout="row" fxLayoutAlign="end"> <a class="link" (click)="onAddNoteField()">Add Note</a> </div> </div> <div class="imx-field" fxLayout="column" fxLayoutAlign="start start"> <div class="imx-field-check width100" fxLayout="row" fxLayoutAlign="start"> <a class="link" (click)="onAddCustomField()"> Add Custom Field </a> </div> <div class="custom-field" formArrayName="customFields" *ngFor="let item of auditDetailForm.get('customFields')['controls']; let i = index;"> <div fxLayout="row" fxLayoutAlign="start center" [formGroupName]="i"> <div class="imx-field" fxLayout="column" fxLayoutAlign="start"> <div fxLayout="row" fxLayoutAlign="start center"> <div class="fx-width-100"> <label>Field Name</label> </div> <mat-form-field> <input matInput placeholder="Field Name" formControlName="name"> </mat-form-field> </div> <div fxLayout="row" fxLayoutAlign="start center"> <div class="fx-width-100"> <label>Field value</label> </div> <mat-form-field> <input matInput placeholder="Field value" formControlName="value"> </mat-form-field> </div> </div> <span fxFlex="1 1 auto"></span> <div class="delete"> <span><mat-icon class="delete-icon" (click)="onRemoveCustomField(i)">delete</mat-icon></span> </div> </div> &lt;!&ndash; dynamic field area &ndash;&gt; </div> </div>--> </div> <mat-divider></mat-divider> <div class="field-action-area auditedControls" *ngIf="this.place['status'] === 0; else auditedControls;"> <div class="auditedControlButton" fxLayout="row" fxLayoutAlign="flex-end center"> <button mat-raised-button type="submit" color="primary">Request Insights</button> </div> </div> <ng-template #auditedControls> <div class="field-action-area auditedControls" > <div> <mat-form-field > <mat-label class="imx-primary-color">Audit Status</mat-label> <mat-select formControlName="placeStatus" (selectionChange)="selectAuditStatus($event)"> <mat-option *ngFor="let status of statuses$ | async" [value]="status.audit_status_cd" >{{status.status}} </mat-option> </mat-select> </mat-form-field> <mat-form-field *ngIf="isRequiredReview"> <mat-label>Audit Outcome</mat-label> <mat-select formControlName="outcome"> <mat-option *ngFor="let outcome of outcomes$ | async" [value]="outcome.audit_outcome_id">{{outcome.outcome | titlecase}}</mat-option> </mat-select> </mat-form-field> </div> <div class="auditedControlButton" fxLayout="row" fxLayoutAlign="space-between center"> <button mat-raised-button class="saveAuditBtn" type="submit" (click)="saveChangesFlag = true">Save Changes</button> <button mat-raised-button color="primary" type="submit">Next Place</button> </div> </div> </ng-template> </form> </div>
import React from 'react'; import "./testContext" import TestContext from "./testContext"; /* 使用方式一: 1、引入context 2、使用xxx.Consumer 组件创建元素 Consumer的标签需要一个回调函数 会将Context设置回调函数的参数,通过参数就可以访问到context中存储的数据 */ const A = () => { return ( <div style={{fontSize:"12px"}}> <TestContext.Consumer> {/*里面是回调函数*/} {(ctx)=>{ return <div>{ctx.name} - {ctx.age}</div> }} </TestContext.Consumer> </div> ); }; export default A;
<div class="content-wrapper"> <section class="content-header"> <h1> Tài liệu <small>Lập trình viên quốc tế-BKAP</small> </h1> <ol class="breadcrumb"> <li><a [routerLink]="['/admin/tai-lieu']" routerLinkActive="router-link-active"><i class="fa fa-dashboard"></i>{{ title }}</a></li> <li class="active">Danh sách</li> </ol> </section> <!-- Main content --> <section class="content container-fluid"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <mat-toolbar color="primary"> <mat-toolbar-row> <h1 class="text-uppercase">Danh sách {{ title }}</h1> </mat-toolbar-row> </mat-toolbar> <mat-card class="example-card"> <mat-card-content> <div class="action-bar"> <button mat-button mat-flat-button color="primary" [routerLink]="['/admin/tai-lieu-hoc-tap/them-moi']" routerLinkActive="router-link-active">Thêm mới</button> <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Lọc"> </mat-form-field> </div> <div class="mat-elevation-z8"> <table mat-table [dataSource]="dataSource" matSort> <!-- STT Column --> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef mat-sort-header> STT </th> <td mat-cell *matCellDef="let row; let i=index" style="width: 30px; text-align: center"> {{ i +1 }} </td> </ng-container> <!-- newsCatalog Column --> <ng-container matColumnDef="documentsName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Tiêu đề </th> <td mat-cell *matCellDef="let row" style="width: 100px"> {{row.DocName}} </td> </ng-container> <!-- newsCatalog Column --> <ng-container matColumnDef="documentsCate"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Danh mục </th> <td mat-cell *matCellDef="let row" style="width: 80px"> {{row.DocTypeName}} </td> </ng-container> <!-- newsContent Column --> <ng-container matColumnDef="documentsDescription"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Nội dung </th> <td mat-cell *matCellDef="let row " style="width: 250px" innerHTML="{{ row.DocDescription | shortPipe:0:150 }} "></td> </ng-container> <!-- image Column --> <ng-container matColumnDef="thumpnail"> <th mat-header-cell *matHeaderCellDef mat-sort-header style="width: 70px; text-align: center"> Hình đại diện </th> <td mat-cell *matCellDef="let row" style="width: 70px; text-align: center"> <img src="{{ imgURL }}/{{ row.DocImage }}" style="width: 50px; height: 50px"> </td> </ng-container> <!-- Download File Column --> <ng-container matColumnDef="documentsFile"> <th mat-header-cell *matHeaderCellDef mat-sort-header style="text-align: center"> Tải về </th> <td style="width: 70px; text-align: center" mat-cell *matCellDef="let row"> <a href="{{ row.DocLink }}" target="_blank"> <img src="assets/img/icon_download.png" class="img-fluid" style="width: 30px;" alt="download"> </a> </td> </ng-container> <!-- Status Column --> <ng-container matColumnDef="status"> <th mat-header-cell *matHeaderCellDef mat-sort-header style="width: 30px; text-align: center"> Trạng thái </th> <td mat-cell *matCellDef="let row" style="width: 30px; text-align: center"> <span (click)="apply(row.DocId, row.DocStatus)"> <i class="fa text-green" [class.fa-check-circle]='row.DocStatus==1' style='font-size:24px' data-toggle="tooltip" title="Ngừng kích hoạt!"></i> <i class="fa text-red" [class.fa-times-circle]="row.DocStatus==0" style='font-size:24px' data-toggle="tooltip" title="Kích hoạt!"></i> </span> </td> </ng-container> <!-- Action Column --> <ng-container matColumnDef="action" style="width: 50px; text-align: center"> <th mat-header-cell *matHeaderCellDef mat-sort-header style="text-align: center"> Hành động </th> <td mat-cell *matCellDef="let row" style="width: 30px; padding: 10 !important; text-align: center; vertical-align: center"> <a [routerLink]="['/admin/tai-lieu-hoc-tap/sua', row.DocId]" routerLinkActive="router-link-active" data-toggle="tooltip" title="Sửa!" style="margin-right: 15px;"> <mat-icon class="menu-icon" style="color: orange; font-size: 26px;">edit</mat-icon> </a>| <a (click)="deleteDocument(row.DocId)" routerLinkActive="router-link-active delete" data-toggle="tooltip" title="Xóa!" class="delete"> <mat-icon class="menu-icon" style="color: red; font-size: 26px;">delete</mat-icon> </a> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"> </tr> </table> <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator> </div> </mat-card-content> </mat-card> </div> </div> </section> <!-- /.content --> </div>
import React from 'react'; import {Col, Container, Row} from 'reactstrap'; import useGetData from '../custom-hooks/useGetData'; import {db} from '../firebase.config'; import {doc, deleteDoc} from 'firebase/firestore'; import {toast} from 'react-toastify'; const AllProducts = () => { const {data:productsData, loading} = useGetData('products'); const deleteProduct = async(id) => { await deleteDoc(doc(db, 'products', id)); toast.success('Deleted!'); } return ( <section> <Container> <Row> <Col lg="12"> <table className="table"> <thead> <tr> <th>Image</th> <th>Title</th> <th>Category</th> <th>Price</th> <th>Action</th> </tr> </thead> <tbody> {loading ? ( <h3 className="py-5 text-center fw-bold">Loading...</h3> ) : ( productsData.map((item, index)=>( <tr key={index}> <td> <img src={item.imgUrl} alt="" /> </td> <td>item.title</td> <td>item.category</td> <td>$.{item.price}</td> <td> <button onClick={()=>{ deleteProduct(item.id); }} className='btn btn-danger' > Delete </button> </td> </tr> )) )} </tbody> </table> </Col> </Row> </Container> </section> ) } export default AllProducts
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat with GPT</title> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f9; color: #333; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .chat-container { width: 100%; max-width: 600px; padding: 20px; border: 1px solid #ddd; border-radius: 8px; background-color: #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } .messages { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; border-radius: 4px; background-color: #fafafa; display: flex; flex-direction: column; } .input-container { display: flex; margin-top: 10px; } .message-input { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 4px; margin-right: 10px; } .send-button { padding: 10px 20px; border: none; border-radius: 4px; background-color: #007bff; color: #fff; cursor: pointer; } .send-button:hover { background-color: #0056b3; } .message { margin: 5px 0; padding: 10px; border-radius: 4px; max-width: 70%; word-wrap: break-word; } .user-message { background-color: #d1e7dd; align-self: flex-end; } .bot-message { background-color: #f8d7da; align-self: flex-start; } </style> </head> <body> <div class="chat-container"> <div class="messages" id="messages"></div> <div class="input-container"> <input type="text" id="messageInput" class="message-input" placeholder="Type a message..."> <button id="sendButton" class="send-button">Send</button> </div> </div> <script> document.addEventListener('DOMContentLoaded', () => { const messagesContainer = document.getElementById('messages'); const messageInput = document.getElementById('messageInput'); const sendButton = document.getElementById('sendButton'); async function sendMessageToChatGPT(message) { try { console.log('Sending message to server:', message); const response = await fetch('https://api.coze.com/open_api/v2/chat', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer pat_zpdrntrHUgMyleyVye5j4JbjXUflkFo6L1Yv1nWbzPzHfUIVLRiKjx6SbIPruOLE' // Add the token here }, body: JSON.stringify({ message }) }); if (!response.ok) { const errorText = await response.text(); console.error(`Error ${response.status}: ${errorText}`); throw new Error(`Failed to retrieve response: ${response.statusText}`); } const data = await response.json(); console.log('Received response from server:', data); appendMessage(data.message, 'bot-message'); } catch (error) { console.error('Error fetching chatbot response:', error); appendMessage('Failed to retrieve response. Please try again later.', 'bot-message'); } } function appendMessage(message, className) { const messageElement = document.createElement('div'); messageElement.className = `message ${className}`; messageElement.textContent = message; messagesContainer.appendChild(messageElement); messagesContainer.scrollTop = messagesContainer.scrollHeight; } sendButton.addEventListener('click', () => { const userMessage = messageInput.value.trim(); if (userMessage !== '') { appendMessage(userMessage, 'user-message'); sendMessageToChatGPT(userMessage); messageInput.value = 'pat_zpdrntrHUgMyleyVye5j4JbjXUflkFo6L1Yv1nWbzPzHfUIVLRiKjx6SbIPruOLE'; } }); messageInput.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); sendButton.click(); } }); }); </script> </body> </html>
<div class="col-md-12"> <nb-card> <toaster-container></toaster-container> <nb-card-header>{{id ? 'Edit' : 'Add'}} Enquiry Details</nb-card-header> <nb-card-body> <form [formGroup]="AddEnquiryForm" class="form-horizontal" (ngSubmit)="addNas();"> <div class="modal-body"> <div class="form-group row"> <div class="col-sm-4"> <label>Reseller Name*</label> <select name="reseller_name" formControlName="reseller_name" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.reseller_name.invalid&&submit}"> <small *ngIf="AddEnquiryForm.hasError('required','reseller_name')&&submit" class="form-text error">Reseller name is required! </small> <option value="" selected> Select Reseller</option> <option *ngFor="let item of resell" [ngValue]="item.user_id">{{item.user_login_id}}</option> </select> </div> <div class="col-sm-4"> <label>Select Location*</label> <select name="enq_loc" formControlName="enq_loc" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.enq_loc.invalid&&submit}"> <small *ngIf="AddEnquiryForm.hasError('required','enq_loc')&&submit" class="form-text error">Location is required! </small> <option value="" selected>Select City</option> <option value="4">Chennai</option> <option value="5">Madurai</option> <option value="6">Nagari</option> <option value="7">Cochin</option> </select> </div> <div class="col-sm-4"> <label>Select Branch*</label> <select name="branch" formControlName="branch" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.branch.invalid&&submit}"> <small *ngIf="AddEnquiryForm.hasError('required','branch')&&submit" class="form-text error">Branch is required! </small> <option value="" selected> Select Branch</option> <option value="1" selected> Kilpauk</option> <option value="2" selected> Kolathur</option> <option value="3" selected> Urapakkam</option> </select> </div> </div> <div class="form-group row"> <div class="col-sm-4"> <label>Select Area</label> <select name="area" formControlName="area" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.area.invalid&&submit}"> <small *ngIf="AddEnquiryForm.hasError('required','area')&&submit" class="form-text error">Area is required! </small> <option value="" selected> Select Area</option> <option value="1" selected> chennai</option> <option value="2" selected> Nagari</option> <option value="3" selected> kerala</option> </select> </div> <div class="col-sm-4"> <label>Assign to Employee</label> <select name="assign_emp" formControlName="assign_emp" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.assign_emp.invalid&&submit}"> <option value="" selected> Select Employee</option> <option value="1" selected> chennai</option> <option value="2" selected> Nagari</option> <option value="3" selected> kerala</option> </select> </div> <div class="col-sm-4"> <label>Customer Name</label> <input type="text" name="cust_name" formControlName="cust_name" placeholder="customer name" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.cust_name.invalid&&submit}"/> <small *ngIf="AddEnquiryForm.hasError('required','cust_name')&&submit" class="form-text error">Customer Name is required ! </small> </div> </div> <div class="form-group row"> <div class="col-sm-4"> <label>Status</label> <select name="enq_status" formControlName="enq_status" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.enq_status.invalid&&submit}"> <small *ngIf="AddEnquiryForm.hasError('required','enq_status')&&submit" class="form-text error">Status is required! </small> <option value="" selected> Select status</option> <option value="1" selected> Open</option> <option value="2" selected> Confirmed</option> <option value="3" selected> Interested</option> </select> </div> <div class="col-sm-4"> <label>Lead Type*</label> <select name="enq_lead" formControlName="enq_lead" placeholder="" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.enq_lead.invalid&&submit}"> <small *ngIf="AddEnquiryForm.hasError('required','enq_lead')&&submit" class="form-text error">Lead type is required! </small> <option value="" selected> Select Lead</option> <option value="1" selected> New Connection</option> <option value="2" selected> General Enquiry</option> </select> </div> <div class="col-sm-4"> <label>Address</label> <textarea name="enq_address" formControlName="enq_address" placeholder=" Address" [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.enq_address.invalid&&submit}"></textarea> <small *ngIf="AddEnquiryForm.hasError('required','enq_address')&&submit" class="form-text error">Address is required! </small> </div> </div> <div class="form-group row"> <div class="col-sm-4"> <label>Mobile No*</label> <input [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.enq_mobnum.invalid&&submit}" formControlName="enq_mobnum" name="enq_mobnum" type="text" placeholder="Phone No * " size="30" maxlength="60"> <small *ngIf="AddEnquiryForm.controls.enq_mobnum.invalid&&submit" class="form-text error"> Mobile number is required! </small> </div> <div class="col-sm-4"> <label>Email</label> <input type="email" name="enq_mail" formControlName="enq_mail" placeholder="Email " [ngClass]="{'form-control' : true,'form-control-danger':AddEnquiryForm.controls.enq_mail.invalid&&submit}"/> <small *ngIf="AddEnquiryForm.controls.enq_mail.invalid&&submit" class="form-text error"> Mail id is required! </small> </div> <div class="col-sm-4"> <label>Notes</label> <textarea name="notes" formControlName="notes" class="form-control"> </textarea> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-md btn-success">{{id ? 'Update' : 'Submit'}}</button> <button class="btn btn-md btn-danger" [routerLink]="['/pages/enquiry/list_enquiry']">Back</button> </div> </form> </nb-card-body> </nb-card> </div>1
package java8Topics.streamAPI; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Stream; public class StreamCreation { public static void main(String[] args) { System.out.println("------------------------ Source is Collection -----------------------------"); Collection<String> collection = Arrays.asList("Rohit", "Gill", "Kohli", "Shreyas", "Rahul", "Hardik", "Jadeja"); Stream<String> stream = collection.stream(); stream.forEach(System.out::println); // :: is called as Method reference System.out.println(""); System.out.println("------------------------ Source is List -----------------------------"); List<String> list = Arrays.asList("Bengaluru", "Hyderabad", "Dharmashala", "Mumbai", "Lucknow", "Delhi"); Stream<String> streamObj = list.stream(); streamObj.forEach(System.out::println); System.out.println(""); System.out.println("------------------------ Converting List into Set -----------------------------"); Set<String> setObj = new HashSet<String>(list); Stream<String> streamObj1 = setObj.stream(); streamObj1.forEach(System.out::println); } }
import React, { useState, useEffect } from "react"; import "./shopping-cart.css"; import "bootstrap/dist/css/bootstrap.min.css"; import { Link } from "react-router-dom"; import { endPoint } from "../../api/clientAPI"; import ClientAPI from "../../api/clientAPI"; import MySecurity from "../../api/mySecurity"; export const ShoppingCart = () => { const [cartItems, setCartItems] = useState(null); const [totalPrice, setTotalPrice] = useState(0.0); const [refresh, setRefresh] = useState(0.0); //inital data useEffect(() => { async function fetchData() { try { const data = { nothing: "nothing" }; const respond = await ClientAPI.post("getCartItem", data); //console.log("From ShoppingCart.jsx: ", respond.data); setCartItems(MySecurity.decryptedData(respond.data)); // Calculate total price based on quantity const total = respond.data.items.reduce((acc, product) => acc + product.price * product.quantity, 0); setTotalPrice(total); } catch (err) { //console.log("From ShoppingCart.jsx: ", err); } } fetchData(); }, [refresh]); // update item in shooping cart const handleOrderItemChange = async (orderItemID, quantity) => { try { const data = { orderID: cartItems.orderID, orderItemID: orderItemID, quantity: quantity }; await ClientAPI.post("updateCartItem", data); //console.log(`From ${caller}.jsx: `, respond.data); window.dispatchEvent(new Event("cartUpdated")); setRefresh(Math.random()); } catch (err) { //console.log(`From ${caller}.jsx: `, err); } } return ( <main className="cart-rabbit-en py-5"> <div id="layout-cart"> <div className="wrapper-mainCart"> <div className="content-bodyCart"> <div className="container"> <div className="row"> <div className="header-page"> <h1>Cart</h1> </div> {cartItems!==null && cartItems.items.length > 0 ? ( <div className="mainCart-detail"> <div className="list-pageform-cart"> <div className="cart-row"> <table className="table-cart"> <thead> <tr className="content-cart"> <th className="media-title">PRODUCT</th> <th className="item-qty">QUANTITY</th> <th className="item-total-price">PRICE</th> <th className="item-total-price">ACTION</th> </tr> </thead> <tbody> {cartItems.items.map((product, index) => ( <tr className="product-quantity" key={index}> <td className="media-title"> <div className="item-img"> <a title={product.name} href={"/product/"+product.productId}> <img src={endPoint+product.image} alt={product.name} /> </a> </div> <div className="item-info"> <h3 className="item--title"> <a href={"/product/" + product.productId}>{product.name}</a> </h3> <div className="item--variant"> <span> <strong>SIZE</strong> {product.selectedSize} </span> <br /> </div> </div> </td> <td className="item-qty"> <div className="qty"> <div className="quantity-box"> <button type="button" className="qty-btn plus" onClick={() => handleOrderItemChange(product.orderItemID, (parseInt(product.quantity) + 1 > 10 ? 10 : parseInt(product.quantity) + 1))} > + </button> <input type="text" size="2" name="updates[]" max="10" value={product.quantity} className="tc line-item-qty item-quantity" onChange={(e) => handleOrderItemChange(product.orderItemID, (parseInt(e.target.value) < 1 && parseInt(e.target.value) > 10 ? parseInt(product.quantity) : parseInt(e.target.value,1)))} /> <button type="button" className="minus qty-btn stop" onClick={() => handleOrderItemChange(product.orderItemID, (parseInt(product.quantity) - 1 < 1 ? 1 : parseInt(product.quantity) - 1))} > - </button> </div> </div> </td> <td className="item-total-price"> <span>${(product.price * product.quantity).toFixed(2)}</span> </td> <td className="item-remove"> <a href="#" onClick={() => handleOrderItemChange(product.orderItemID, 0)} > <img src="//theme.hstatic.net/1000351433/1001138941/14/delete.png?v=243" /> </a> </td> </tr> ))} </tbody> </table> </div> <div className="col-lg-4 col-md-12 col-sm-12 col-12 order-summary-block"> <h4 className="summary-title">TOTAL BILLINGS</h4> <div className="summary-total"> <span>${totalPrice.toFixed(2)}</span> </div> <div className="summary-action"> <div className="summary-button"> <Link to="/checkout"> <a id="btnCart-checkout" className="checkout-btn" > CHECK OUT </a> </Link> </div> <a className="button" href="/product?page=1"> CONTINUE SHOPPING </a> </div> </div> </div> <br /><br /> <div className="cart-row"> <div className="order-noted-block"> <div className="checkout-buttons clearfix"> <label htmlFor="note" className="note-label h4 font-weight-bold" > ORDER NOTES </label> <textarea className="form-control" id="note" name="note" rows="5" ></textarea> </div> <button type="submit" id="update-cart" className="btn-update button d-none" name="update" value="" > Cập nhật </button> <button type="submit" id="checkout" className="btn-checkout button d-none " name="checkout" value="" > Check out </button> </div> </div> </div> ) : ( <div className="col-lg-12 col-md-12 col-sm-12 col-12 contentCart-detail"> <div className="mainCart-detail"> <div className="expanded-message text-center font-weight-bold"> <p>YOUR CART is empty</p> <img className="cart_icon" src={endPoint +"default/cart_icon.jpg"} alt="WebP rules." ></img> </div> </div> </div> )} </div> </div> </div> </div> </div> </main> ); };
import { EXTENSION_PAYMENT_TOKEN_API } from 'constants/check-nft.constants'; import { post } from 'helpers/axios.helper'; import { fromWei } from 'helpers/big-number.helpers'; import { useMemo } from 'react'; import useSWR from 'swr'; export declare type PaymentTokenEntity = { id: number; createdAt: string; updatedAt: string; symbol: string; address: string; imageUrl: string; name: string; decimals: number; }; export const useTokenPrice = (tokenAddress: string, weiAmount: string) => { const { data, error } = useSWR<PaymentTokenEntity[]>( [EXTENSION_PAYMENT_TOKEN_API, tokenAddress], () => post(EXTENSION_PAYMENT_TOKEN_API, { addresses: [tokenAddress] }), ); const tokenInfo = data ? data[0] : null; const price = useMemo(() => (tokenInfo ? fromWei(weiAmount, tokenInfo?.decimals) : null), [tokenInfo, error, weiAmount]); return { price, symbol: tokenInfo?.symbol || '', loading: !data && !error, decimals: tokenInfo?.decimals || null, }; };
import { parseISO } from 'date-fns'; import { Granule } from '../index'; const configJSON = { chirps_global_month_data: { dataType: 'RASTER', units: 'mm', period: 'month', continuous: false, start: { granule_start: '1981-01-01', granule_end: '1981-01-31', }, end: { granule_start: '2020-01-01', granule_end: '2020-01-31', }, }, chirps_global_pentad_data: { dataType: 'RASTER', units: 'mm', period: 'pentad', continuous: false, start: { granule_start: '1981-01-01', granule_end: '1981-01-05', }, end: { granule_start: '2020-01-26', granule_end: '2020-01-31', }, }, chirps_global_2month_data: { dataType: 'RASTER', units: 'mm', period: '2month', continuous: false, start: { granule_start: '1981-01-01', granule_end: '1981-02-28', }, end: { granule_start: '2019-12-01', granule_end: '2020-01-31', }, }, chirps_global_3month_data: { dataType: 'RASTER', units: 'mm', period: '3month', continuous: false, start: { granule_start: '1981-01-01', granule_end: '1981-03-31' }, end: { granule_start: '2019-12-01', granule_end: '2020-02-29' }, }, emodisndvic6v2_africa_dekad_data: { dataType: 'RASTER', units: 'mm', period: 'dekad', continuous: false, start: { granule_start: '2002-07-01', granule_end: '2002-07-10' }, end: { granule_start: '2020-02-11', granule_end: '2020-02-20' }, }, swe_asia_day_data: { dataType: 'RASTER', units: 'mm', period: 'day', continuous: false, start: { granule_start: '2000-10-02', granule_end: '2000-10-02' }, end: { granule_start: '2020-02-23', granule_end: '2020-02-23' }, }, eviirsndvi_camcar_pentad_pctm: { dataType: 'RASTER', published: true, units: null, region: 'camcar', period: 'pentad_10daycomposite', continuous: false, start: { granule_start: '2012-01-26', granule_end: '2012-02-05' }, end: { granule_start: '2022-04-11', granule_end: '2022-04-20' }, }, }; describe('Generates NON-CONTINUOUS granules', () => { it('Day Granules', () => { const config = configJSON.swe_asia_day_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: true, granuleReference: 'start', } ); expect(granule.intervals.length).toBeGreaterThan(0); const currentGranule = granule.activeInterval; granule.next(); expect(granule.activeInterval).toEqual(currentGranule); granule.prev(); expect(granule.activeInterval).toEqual(granule.intervals[granule.intervals.length - 2]); }); it('Dekad Granules', () => { const config = configJSON.emodisndvic6v2_africa_dekad_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: true, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('Pentad Granules', () => { const config = configJSON.chirps_global_pentad_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: true, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it(`Pentadal 10-Day Composite`, () => { const config = configJSON.eviirsndvi_camcar_pentad_pctm; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { granuleReference: 'start', weekStartsOn: 0, ignoreLeapYear: false, } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('Month Granules', () => { const config = configJSON.chirps_global_month_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: true, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('2-Month Granules', () => { const config = configJSON.chirps_global_2month_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: true, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('3-Month Granules', () => { const config = configJSON.chirps_global_3month_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: true, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); }); describe('Generates CONTINUOUS granules', () => { it('Day Granules', () => { const config = configJSON.swe_asia_day_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: true, }, { weekStartsOn: 1, ignoreLeapYear: false, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('Dekad Granules', () => { const config = configJSON.emodisndvic6v2_africa_dekad_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: true, }, { weekStartsOn: 1, ignoreLeapYear: false, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('Pentad Granules', () => { const config = configJSON.chirps_global_pentad_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: true, }, { weekStartsOn: 1, ignoreLeapYear: false, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('Month Granules', () => { const config = configJSON.chirps_global_month_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: false, }, { weekStartsOn: 1, ignoreLeapYear: false, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('2-Month Granules', () => { const config = configJSON.chirps_global_2month_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: false, }, { weekStartsOn: 1, ignoreLeapYear: false, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); it('3-Month Granules', () => { const config = configJSON.chirps_global_3month_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: false, }, { weekStartsOn: 1, ignoreLeapYear: false, granuleReference: 'start', } ); console.log(granule); expect(granule.intervals.length).toBeGreaterThan(0); }); }); describe(`Interval Filtering`, () => { const config = configJSON.swe_asia_day_data; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { weekStartsOn: 0, ignoreLeapYear: false, granuleReference: 'start', } ); it(`Returns the interval based on an index.`, () => { const test = { start: '2000-10-02', end: '2000-10-02' }; expect(granule.getIntervalByIndex(0)).toMatchObject(test); }); it(`Returns the intervals in a given year`, () => { // granule end date is 2-23, with a leap year on a daily product === 54 intervals. expect(granule.getIntervalsInYear(2020)).toBeArray().toBeArrayOfSize(54); }); it(`Gets the available months within the granules of a given year`, () => { const test = [ { text: 'Jan', value: 1, }, { text: 'Feb', value: 2, }, ]; expect(granule.getMonthsInIntervalInYear(2020)).toBeArray().toStrictEqual(test); }); it(`Gets the year of a given interval`, () => { const interval = { start: '2020-01-01', end: '2020-01-05', }; expect(granule.getYearOfInterval(interval)).toEqual(2020); }); it(`Gets the year of the active interval.`, () => { expect(granule.getYearOfActiveInterval()).toEqual(2020); }); it(`Sets the selected month index`, () => { const newIndex = 0; // January granule.setSelectedMonthIndex(newIndex); expect(granule.selectedMonthIndex).toEqual(0); }); it(`Sets the selected year index`, () => { // const years = ['2020', '2019', '2018'] granule.setSelectedYearIndex(2); // 2019 expect(granule.selectedYearIndex).toEqual(2); }); it(`Gets the selectable months for the selected month, and year`, () => { // month is 0 - January // year is 2019 expect(granule.getSelectableMonths()).toBeArray().toBeArrayOfSize(12); }); }); describe(`Interval Filtering -- 10Day Composite`, () => { const config = configJSON.eviirsndvi_camcar_pentad_pctm; const granule = new Granule( { start: parseISO(config.start.granule_start), end: parseISO(config.end.granule_end), periodType: config.period, continuous: config.continuous, }, { granuleReference: 'start', weekStartsOn: 0, ignoreLeapYear: false, } ); let intervals = granule.getIntervalsWithinSelectedMonthYear(); granule.setSelectedMonthIndex(0); intervals = granule.getIntervalsWithinSelectedMonthYear(); console.log(granule); });
package cn.realtime.config.netty; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; /** * WebSocket服务 */ @Component @Slf4j public class WsServer { /**静态内部类创建单例*/ private static class SingletonWsServer{ static final WsServer INSTANCE = new WsServer(); } public static WsServer getInstance(){ return SingletonWsServer.INSTANCE; } private EventLoopGroup mainGroup; private EventLoopGroup subGroup; private ServerBootstrap bootstrap; private ChannelFuture channelFuture; /**初始化配置*/ public WsServer(){ mainGroup = new NioEventLoopGroup(); subGroup = new NioEventLoopGroup(); bootstrap = new ServerBootstrap(); bootstrap.group(mainGroup,subGroup) .channel(NioServerSocketChannel.class) .childHandler(new WsServerInitializer()); } /**启动Websocket服务并绑定端口*/ public void start(){ this.channelFuture = bootstrap.bind(8888); log.info("################### WebSocket启动[端口8888] #######################"); log.info("################### WebSocket启动[端口8888] #######################"); log.info("################### WebSocket启动[端口8888] #######################"); } }
// // ViewController.swift // kalkulaThor // // Created by Daniel Djakam on 31/01/2022. // import UIKit class ViewController: UIViewController { @IBOutlet weak var operationLabel: UILabel!; @IBOutlet weak var resultLabel: UILabel!; var operation:String = ""; override func viewDidLoad() { super.viewDidLoad(); clearAll(); } func clearAll(){ operation = ""; operationLabel.text = "0"; resultLabel.text = operation; } func addCaracterToOperation(value: String) { operation = operation + value; operationLabel.text = operation } func formatEqual(result: Double) -> String{ if (result.truncatingRemainder(dividingBy: 1) == 0) { return String(format: "%.0f", result) }else{ return String(format: "%.0f", result) } } // Touch's operations @IBAction func clearOne(_ sender: Any) { if (!operation.isEmpty) { operation.removeLast(); operationLabel.text = operation } } @IBAction func pressClear(_ sender: Any) { clearAll(); } @IBAction func pressPercent(_ sender: Any) { addCaracterToOperation(value: "%") } @IBAction func pressDivision(_ sender: Any) { addCaracterToOperation(value: "/") } @IBAction func pressMultiplication(_ sender: Any) { addCaracterToOperation(value: "*") } @IBAction func pressSoustraction(_ sender: Any) { addCaracterToOperation(value: "-") } @IBAction func pressAddition(_ sender: Any) { addCaracterToOperation(value: "+") } @IBAction func pressEqual(_ sender: Any) { if validInput() { let checkOperationForPercent = operation.replacingOccurrences(of: "%", with: "*0.01") let expression = NSExpression(format: checkOperationForPercent) let result = expression.expressionValue(with: nil, context: nil) as! Double let resutString = formatEqual(result: result) resultLabel.text = resutString }else{ let alert = UIAlertController( title: "Erreur de calcul", message: "Une erreur est survenue lors du calcul", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } } func validInput() -> Bool { var count = 0; var funcCharIndexes = [Int]() for char in operation { if(specialCharacter(char: char)){ funcCharIndexes.append(count) } count += 1; } var previous: Int = -1 for index in funcCharIndexes { if (index == 0) { return false } if (index == operation.count - 1) { return false } if(previous != -1) { if (index - previous == 1){ return false } } previous = index } return true; } func specialCharacter(char: Character) -> Bool { if (char == "*") { return true; } if (char == "/") { return true; } if (char == "+") { return true; } if (char == "-") { return true; } return false; } // Touch's numbers @IBAction func pressZero(_ sender: Any) { addCaracterToOperation(value: "0") } @IBAction func pressOne(_ sender: Any) { addCaracterToOperation(value: "1") } @IBAction func pressTwo(_ sender: Any) { addCaracterToOperation(value: "2") } @IBAction func pressThree(_ sender: Any) { addCaracterToOperation(value: "3") } @IBAction func pressFour(_ sender: Any) { addCaracterToOperation(value: "4") } @IBAction func pressFive(_ sender: Any) { addCaracterToOperation(value: "5") } @IBAction func pressSix(_ sender: Any) { addCaracterToOperation(value: "6") } @IBAction func pressSeven(_ sender: Any) { addCaracterToOperation(value: "7") } @IBAction func pressEigth(_ sender: Any) { addCaracterToOperation(value: "8") } @IBAction func pressNine(_ sender: Any) { addCaracterToOperation(value: "9") } @IBAction func pressPoint(_ sender: Any) { addCaracterToOperation(value: ".") } }
package dev.ebyrdeu.movie_jakarta.repository; import dev.ebyrdeu.movie_jakarta.entity.Movie; import jakarta.enterprise.context.ApplicationScoped; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.transaction.Transactional; import jakarta.ws.rs.NotFoundException; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; @ApplicationScoped public class MovieRepository { @PersistenceContext(unitName = "mysql") private EntityManager em; @Transactional public Movie saveMovie(Movie movie) { em.persist(movie); return movie; } public Optional<Movie> findById(UUID id) { Movie movie = em.find(Movie.class, id); return Optional.ofNullable(movie); } public List<Movie> findAll() { return em.createQuery("SELECT m FROM Movie m", Movie.class).getResultList(); } @Transactional public void deleteMovie(UUID id) { var existingMovie = em.find(Movie.class, id); if (existingMovie == null) { throw new NotFoundException("Movie with id: " + id + " not found"); } em.remove(existingMovie); } @Transactional public Movie updateMovie(UUID id, Movie movieDetails) { Movie movieToUpdate = em.find(Movie.class, id); if (movieToUpdate == null) { throw new NotFoundException("Movie with id: " + id + " not found"); } checkOnNull(movieToUpdate::setTitle, movieDetails.getTitle()); checkOnNull(movieToUpdate::setReleaseYear, movieDetails.getReleaseYear()); checkOnNull(movieToUpdate::setDirector, movieToUpdate.getDirector()); return em.merge(movieToUpdate); } private <T> void checkOnNull(Consumer<T> consumer, T value) { if (value != null) consumer.accept(value); } }
import { Game, Project, Subscription, SubscriptionType } from '@prisma/client' import { FC, useCallback, useEffect, useMemo, useState } from 'react' import { Button, Toggle } from 'react-daisyui' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faTrash } from '@fortawesome/free-solid-svg-icons' import { Modal } from './common/modal' import { SaveButton } from './common/form' import { requestNotificationPermission } from '@/hooks/notification-hooks' import { mutationToToastStatus, useStatusToast, useToast, } from '@/context/toast-context' import { getIconForSubscriptionType, getTextForSubscriptionType, } from '@/utils/subscription-type' import { trpc } from '@/utils/trpc' type HelpTextProps = { name: string text: string } const HelpText: FC<HelpTextProps> = ({ name, text }) => ( <> <span className='italic'>{text}</span> <span className='font-bold text-primary'>{name}</span> </> ) export type SubscriptionModalProps = { open: boolean onClose: () => void subscription?: Subscription project?: Project game?: Game onChange: () => void hasVerifiedEmail: boolean receiveEmails: boolean } export const SubscriptionModal: FC<SubscriptionModalProps> = ({ open, onClose, subscription, project, game, onChange, hasVerifiedEmail, receiveEmails, }) => { const [checkedTypes, setCheckedTypes] = useState<Set<SubscriptionType>>( new Set(subscription?.type ?? []) ) const gameOrProjectName = project?.name ?? game?.name ?? '' const { mutateAsync: upsertSubscription, status: upsertStatus } = trpc.subscription.upsert.useMutation() const { mutateAsync: deleteSubscription, status: deleteStatus } = trpc.subscription.delete.useMutation() useStatusToast(mutationToToastStatus(deleteStatus), { success: { title: `Unsubscribed from ${gameOrProjectName}`, }, error: { title: 'Could not Unsubscribe', }, }) useStatusToast(mutationToToastStatus(upsertStatus), { success: { title: subscription ? `Updated your subscription to ${gameOrProjectName}` : `Subscribed to ${gameOrProjectName}`, }, error: { title: subscription ? 'Could not subscribe' : 'Could not update subscription', }, }) const onUnsubscribe = () => { if (subscription?.id) { deleteSubscription({ subscriptionId: subscription?.id }).then(onChange) } } const onSave = () => upsertSubscription({ projectId: project?.id, gameId: game?.id, type: [...checkedTypes], }).then(onChange) useEffect(() => { if (subscription) { setCheckedTypes(new Set(subscription.type)) } }, [subscription]) const { showToast } = useToast() const toggleType = useCallback( async (t: SubscriptionType) => { const isActivatingPush = t === 'PUSH_NOTIFICATION' && !checkedTypes.has('PUSH_NOTIFICATION') if (isActivatingPush) { const granted = await requestNotificationPermission() if (!granted) { showToast({ title: 'Could not activate push notifications', message: 'Please try again and allow push notifications when asked.', status: 'error', }) return } } const newSet = new Set(checkedTypes) if (newSet.has(t)) { newSet.delete(t) } else { newSet.add(t) } setCheckedTypes(newSet) }, [checkedTypes, showToast] ) const noTypesSelected = checkedTypes.size === 0 const emailDisabledText = useMemo(() => { if (hasVerifiedEmail && !receiveEmails) { return 'You need to enable email receipt in your profile settings to receive email notifications.' } if (!hasVerifiedEmail) { return 'You have to verify your email to receive email notifications.' } return undefined }, [hasVerifiedEmail, receiveEmails]) const toggle = useCallback( (type: SubscriptionType, disabledText?: string) => ( <div className='flex flex-col gap-y-2'> <div className='flex flex-row items-center gap-x-3'> <label className='flex cursor-pointer flex-row items-center gap-x-3'> <Toggle color='primary' checked={checkedTypes.has(type)} onChange={() => toggleType(type)} disabled={!!disabledText} /> <FontAwesomeIcon icon={getIconForSubscriptionType(type)} /> {getTextForSubscriptionType(type)} </label> </div> {disabledText && <span className='text-error'>{disabledText}</span>} </div> ), [checkedTypes, toggleType] ) return ( <Modal open={open} onClose={onClose} title={ subscription ? 'Manage subscription' : `Subscribe to ${gameOrProjectName}` } actions={ <> {subscription && ( <Button onClick={onUnsubscribe} color='error' startIcon={<FontAwesomeIcon icon={faTrash} />} loading={deleteStatus === 'loading'} > Unsubscribe </Button> )} <SaveButton onClick={onSave} disabled={noTypesSelected} loading={upsertStatus === 'loading'} > {subscription ? 'Save Changes' : 'Subscribe'} </SaveButton> </> } > {game && ( <HelpText name={game.name} text='Get notified whenever a new project is published for ' /> )} {project && ( <HelpText name={project.name} text='Get notified whenever a new post is published for ' /> )} <div className='my-4 flex flex-col gap-y-5'> {toggle('PUSH_NOTIFICATION')} {toggle('EMAIL', emailDisabledText)} </div> {noTypesSelected && ( <span className='text-error'> Please select at least one notification type. </span> )} </Modal> ) }
from unittest import TestCase from app import app from flask import session, jsonify from boggle import Boggle class FlaskTests(TestCase): def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() app.config['TESTING'] = True def test_index_route(self): with self.client: response = self.client.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'<table id="boggle-board">', response.data) def test_set_board_size_route(self): with self.client: response = self.client.get('/set_board_size') self.assertEqual(response.status_code, 200) self.assertIn(b'Enter the size of the Boggle board:', response.data) def test_check_word_route_valid_word(self): with self.client: with app.test_request_context(): # Set up a mock board in the session boggle_game = Boggle(size=3) session['board'] = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] # Mock a valid word in the session session['words'] = ['ABC'] response = self.client.post('/check_word', json={'word': 'ABC'}) data = response.get_json() self.assertEqual(response.status_code, 200) self.assertEqual(data['result'], 'ok') self.assertIn(b'Valid word on the board!', response.data) def test_check_word_route_invalid_word(self): with self.client: with app.test_request_context(): # Set up a mock board in the session boggle_game = Boggle(size=3) session['board'] = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] # Mock an invalid word in the session session['words'] = ['XYZ'] response = self.client.post('/check_word', json={'word': 'XYZ'}) data = response.get_json() self.assertEqual(response.status_code, 200) self.assertEqual(data['result'], 'not-on-board') self.assertIn(b'Word is not on the board.', response.data) def test_end_game_route(self): with self.client: with app.test_request_context(): # Set up a mock score in the session session['score'] = 10 response = self.client.post('/end_game', json={'score': 10}) data = response.get_json() self.assertEqual(response.status_code, 200) self.assertEqual(data['message'], 'Game ended successfully') self.assertEqual(session['num_played'], 1) self.assertEqual(session['highest_score'], 10)
# -*- coding: utf-8 -*- """ Created on Fri Dec 23 17:53:04 2022 @author: rebec """ #Fig. 21. Average total system costs per unit of generated energy as a function of the CO2 emission limit defined as fraction of the emission level of the year 1990, i.e. 1.55 Gtonne-CO2, for the zero, compromise, and optimal transmis-sion grid (left to right panels). #%% “green field” (simple network) unconstrained # -*- coding: utf-8 -*- import pypsa import pandas as pd from pypsa.linopt import get_var, linexpr, define_constraints import logging import numpy as np logger = logging.getLogger(__name__) def solve_network(n, renewable_carriers, *args, **kwargs): """Solve the network. Args: n (PyPSA Network): PyPSA network to be solved. """ def storage_restriction(n, snapshots): """Define the constraint that ensure that energy generated by renewable resources that has been stored in storage units a fictious storage unit was added for each normal storage unit that would only allow charging using generation units with the carrier "Renewable" (this is defined in the function storage_restriction(n,snapshots)). Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ renewable_generators = n.generators[n.generators.carrier.isin(renewable_carriers)].index renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index storage_units = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers))].index renewable_generators_feed_in = (linexpr((1, get_var(n, "Generator", "p")[renewable_generators]))).sum(axis=1) renewable_storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))).sum(axis=1) renewable_storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))).sum(axis=1) define_constraints( n, renewable_generators_feed_in +renewable_storage_units_store, ">=", 0, "Generator", "restrict_renewable_storages_share" ) def storage_variables_constraints(n, snapshots): """Define the constraint that coupple the fictious and real storage variables together To ensure the fictious storage units do not extent the normal (conventional) storage units or in other words provide more storage possibility to the system and stay purely fictious, the optimization variables of the normal (conventional) storage units and the fictious storage units are coupled. This means that the sum of both storage units (fictious + conventional) is limited by the maximum/minimum properties of the corresponding normal storage unit. Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index renewable_storage_units_ext = n.storage_units[n.storage_units.carrier.isin(renewable_carriers) & n.storage_units.p_nom_extendable].index storage_units = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers))].index storage_units_ext = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers)) & n.storage_units.p_nom_extendable].index storage_units_non_ext = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers)) & ~(n.storage_units.p_nom_extendable)].index renewable_storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))) storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[storage_units]))) renewable_storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))) storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[storage_units]))) renewable_storage_units_soc = (linexpr((1, get_var(n, "StorageUnit", "state_of_charge")[renewable_storage_units]))) storage_units_soc = (linexpr((1, get_var(n, "StorageUnit", "state_of_charge")[storage_units]))) storage_units_store_max_non_ext = (linexpr((-1, (n.storage_units.p_nom*n.storage_units.p_max_pu)[storage_units_non_ext]))) try: storage_units_store_max_ext = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom")*n.storage_units.p_max_pu)[storage_units_ext]))) storage_units_dispatch_max_ext = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom")*n.storage_units.p_min_pu)[storage_units_ext]))) storage_units_soc_max_ext = (linexpr((-n.storage_units.max_hours[storage_units_ext], (get_var(n, "StorageUnit", "p_nom"))[storage_units_ext]))) except KeyError: storage_units_store_max_ext = None storage_units_dispatch_max_ext = None storage_units_soc_max_ext = None storage_units_dispatch_max_non_ext = (linexpr((-1, (n.storage_units.p_nom*n.storage_units.p_min_pu)[storage_units_non_ext]))) storage_units_soc_max_non_ext = (linexpr((-n.storage_units.max_hours[storage_units_non_ext], (n.storage_units.p_nom)[storage_units_non_ext]))) try: renewable_storage_units_extension = (linexpr((1, (get_var(n, "StorageUnit", "p_nom"))[renewable_storage_units_ext]))) storage_units_extension = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom"))[storage_units_ext]))) except KeyError: logger.warning("No storage unit extension is allowed.") for s, name in enumerate(storage_units): if name in storage_units_ext: define_constraints( n, renewable_storage_units_store[renewable_storage_units[s]] + storage_units_store[storage_units[s]] + storage_units_store_max_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_store" ) define_constraints( n, renewable_storage_units_dispatch[renewable_storage_units[s]] + storage_units_dispatch[storage_units[s]] + storage_units_dispatch_max_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_dispatch" ) define_constraints( n, storage_units_soc_max_ext[storage_units[s]] + renewable_storage_units_soc[renewable_storage_units[s]] + storage_units_soc[storage_units[s]], "<=", 0, "StorageUnit", "state_of_charge_restriction" ) define_constraints( n, renewable_storage_units_extension[renewable_storage_units[s]] + storage_units_extension[storage_units[s]], "==", 0, "StorageUnit", "storage_extension" ) else: define_constraints( n, renewable_storage_units_store[renewable_storage_units[s]] + storage_units_store[storage_units[s]] + storage_units_store_max_non_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_store" ) define_constraints( n, renewable_storage_units_dispatch[renewable_storage_units[s]] + storage_units_dispatch[storage_units[s]] + storage_units_dispatch_max_non_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_dispatch" ) define_constraints( n, storage_units_soc_max_non_ext[storage_units[s]] + renewable_storage_units_soc[renewable_storage_units[s]] + storage_units_soc[storage_units[s]], "<=", 0, "StorageUnit", "state_of_charge_restriction" ) def extra_functionalities(n, snapshots): storage_restriction(n,snapshots) storage_variables_constraints(n,snapshots) def create_fictious_storage_units(n): """Create fictious storage units for each storage unit. The fictious storage units are created in order to be able to model the share of renewable storage units in the system. The share of renewable storage units is defined by the user and is used to limit the share of renewable storage units in the system. Args: n (PyPSA Network): PyPSA network to which the new storage units are added. """ n.madd('StorageUnit', n.storage_units.index, suffix='_Renewable', carrier='Renewable_Storage', **n.storage_units.drop('carrier', axis=1)) create_fictious_storage_units(n) if 'Renewable_Storage' not in renewable_carriers: renewable_carriers.append('Renewable_Storage') n.lopf( n.snapshots[:6], solver_name='gurobi', pyomo=False, extra_functionality=extra_functionalities, ) if __name__=="__main__": DE_1node = pypsa.Network() DE_1node.set_snapshots(pd.date_range('2019-01-01', periods=5, freq='H')) snapshot = 5 load= 40000 # Create carriers for which CO2 emissions unequal 0 co2_emissions_coal=0.34 DE_1node.add('Carrier', 'Coal', co2_emissions = co2_emissions_coal) DE_1node.add('Bus','DE') DE_1node.add('Generator', 'Solar', bus = 'DE', carrier='Renewable', p_max_pu=[1, 0, 0, 0, 0], p_nom = 0, marginal_cost=0.010, capital_cost=35602, p_nom_extendable=True) DE_1node.add('Generator', 'Wind', bus = 'DE', carrier='Renewable', p_max_pu=[1, 0, 0, 0, 0], p_nom = 0, marginal_cost=0.015, capital_cost=96085, p_nom_extendable=True) DE_1node.add('StorageUnit', 'Storage_1', bus='DE', carrier='Others', p_nom=0, max_hours=5,marginal_cost=1,capital_cost=177345, p_nom_extendable=True) DE_1node.add('StorageUnit', 'Storage_2', bus='DE', carrier='Others', p_nom=0, max_hours=5, marginal_cost=1,capital_cost=177345, p_nom_extendable=True) DE_1node.add('Generator', 'Coal', bus = 'DE', carrier='Coal', p_nom = 14830, marginal_cost=28.197, capital_cost=349977) DE_1node.add('Load', 'DE_Load', bus='DE', p_set = [load for _ in range(snapshot)]) storage_map = {} list_renewable_carriers = ['Renewable','Solar', 'solar','offwind-ac', 'Wind', 'onwind', 'biomass','ror', 'geothermal','hydro', 'offwind-ac', 'offwind-dc', 'Renewable_Storage'] #['Solar','solar', 'onwind', 'biomass', 'geothermal', 'ror', 'offwind-ac', 'hydro', 'offwind-dc', 'PHS', 'Renewable_Storage','Wind'] solve_network(DE_1node, renewable_carriers = list_renewable_carriers) DE_1node.generators_t.p.plot() # Evaluate the share of renewable energy ax = DE_1node.generators_t.p.plot() DE_1node.storage_units_t.p.plot(ax=ax) DE_1node.loads_t.p.plot(ax=ax) cap_installed = DE_1node.generators.p_nom_opt cap_installed_storage = DE_1node.storage_units.p_nom_opt production = pd.concat([DE_1node.generators_t.p, DE_1node.storage_units_t.p], axis=1) production_total = production.sum() production_share = production_total/production_total.sum() co2_emissions_t=np.nansum((DE_1node.snapshot_weightings.generators @ DE_1node.generators_t.p) / DE_1node.generators.efficiency * DE_1node.generators.carrier.map(DE_1node.carriers.co2_emissions)) print("CO2 emissions unconstrained green field: ", co2_emissions_t) print("installed capacity:\n", cap_installed) print("installed storage:\n", cap_installed_storage) print("total production per carrier:\n", production_total) print("production share per carrier:\n", production_share) system_cost=DE_1node.objective/(snapshot*load) print("System cost [euro/MWh]", system_cost) #%% “green field” constrained (co2 cap.) import pypsa import pandas as pd from pypsa.linopt import get_var, linexpr, define_constraints import logging logger = logging.getLogger(__name__) import numpy as np def solve_network(n, renewable_carriers,co2_emissions, *args, **kwargs): """Solve the network. Args: n (PyPSA Network): PyPSA network to be solved. """ def storage_restriction(n, snapshots): """Define the constraint that ensure that energy generated by renewable resources that has been stored in storage units a fictious storage unit was added for each normal storage unit that would only allow charging using generation units with the carrier "Renewable" (this is defined in the function storage_restriction(n,snapshots)). Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ renewable_generators = n.generators[n.generators.carrier.isin(renewable_carriers)].index renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index storage_units = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers))].index renewable_generators_feed_in = (linexpr((1, get_var(n, "Generator", "p")[renewable_generators]))).sum(axis=1) renewable_storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))).sum(axis=1) renewable_storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))).sum(axis=1) define_constraints( n, renewable_generators_feed_in +renewable_storage_units_store, ">=", 0, "Generator", "restrict_renewable_storages_share" ) def storage_variables_constraints(n, snapshots): """Define the constraint that coupple the fictious and real storage variables together To ensure the fictious storage units do not extent the normal (conventional) storage units or in other words provide more storage possibility to the system and stay purely fictious, the optimization variables of the normal (conventional) storage units and the fictious storage units are coupled. This means that the sum of both storage units (fictious + conventional) is limited by the maximum/minimum properties of the corresponding normal storage unit. Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index renewable_storage_units_ext = n.storage_units[n.storage_units.carrier.isin(renewable_carriers) & n.storage_units.p_nom_extendable].index storage_units = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers))].index storage_units_ext = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers)) & n.storage_units.p_nom_extendable].index storage_units_non_ext = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers)) & ~(n.storage_units.p_nom_extendable)].index renewable_storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))) storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[storage_units]))) renewable_storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))) storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[storage_units]))) renewable_storage_units_soc = (linexpr((1, get_var(n, "StorageUnit", "state_of_charge")[renewable_storage_units]))) storage_units_soc = (linexpr((1, get_var(n, "StorageUnit", "state_of_charge")[storage_units]))) storage_units_store_max_non_ext = (linexpr((-1, (n.storage_units.p_nom*n.storage_units.p_max_pu)[storage_units_non_ext]))) try: storage_units_store_max_ext = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom")*n.storage_units.p_max_pu)[storage_units_ext]))) storage_units_dispatch_max_ext = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom")*n.storage_units.p_min_pu)[storage_units_ext]))) storage_units_soc_max_ext = (linexpr((-n.storage_units.max_hours[storage_units_ext], (get_var(n, "StorageUnit", "p_nom"))[storage_units_ext]))) except KeyError: storage_units_store_max_ext = None storage_units_dispatch_max_ext = None storage_units_soc_max_ext = None storage_units_dispatch_max_non_ext = (linexpr((-1, (n.storage_units.p_nom*n.storage_units.p_min_pu)[storage_units_non_ext]))) storage_units_soc_max_non_ext = (linexpr((-n.storage_units.max_hours[storage_units_non_ext], (n.storage_units.p_nom)[storage_units_non_ext]))) try: renewable_storage_units_extension = (linexpr((1, (get_var(n, "StorageUnit", "p_nom"))[renewable_storage_units_ext]))) storage_units_extension = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom"))[storage_units_ext]))) except KeyError: logger.warning("No storage unit extension is allowed.") for s, name in enumerate(storage_units): if name in storage_units_ext: define_constraints( n, renewable_storage_units_store[renewable_storage_units[s]] + storage_units_store[storage_units[s]] + storage_units_store_max_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_store" ) define_constraints( n, renewable_storage_units_dispatch[renewable_storage_units[s]] + storage_units_dispatch[storage_units[s]] + storage_units_dispatch_max_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_dispatch" ) define_constraints( n, storage_units_soc_max_ext[storage_units[s]] + renewable_storage_units_soc[renewable_storage_units[s]] + storage_units_soc[storage_units[s]], "<=", 0, "StorageUnit", "state_of_charge_restriction" ) define_constraints( n, renewable_storage_units_extension[renewable_storage_units[s]] + storage_units_extension[storage_units[s]], "==", 0, "StorageUnit", "storage_extension" ) else: define_constraints( n, renewable_storage_units_store[renewable_storage_units[s]] + storage_units_store[storage_units[s]] + storage_units_store_max_non_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_store" ) define_constraints( n, renewable_storage_units_dispatch[renewable_storage_units[s]] + storage_units_dispatch[storage_units[s]] + storage_units_dispatch_max_non_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_dispatch" ) define_constraints( n, storage_units_soc_max_non_ext[storage_units[s]] + renewable_storage_units_soc[renewable_storage_units[s]] + storage_units_soc[storage_units[s]], "<=", 0, "StorageUnit", "state_of_charge_restriction" ) def extra_functionalities(n, snapshots): storage_restriction(n,snapshots) storage_variables_constraints(n,snapshots) def create_fictious_storage_units(n): """Create fictious storage units for each storage unit. The fictious storage units are created in order to be able to model the share of renewable storage units in the system. The share of renewable storage units is defined by the user and is used to limit the share of renewable storage units in the system. Args: n (PyPSA Network): PyPSA network to which the new storage units are added. """ n.madd('StorageUnit', n.storage_units.index, suffix='_Renewable', carrier='Renewable_Storage', **n.storage_units.drop('carrier', axis=1)) create_fictious_storage_units(n) if 'Renewable_Storage' not in renewable_carriers: renewable_carriers.append('Renewable_Storage') n.add("GlobalConstraint", "CO2Limit",carrier_attribute="co2_emissions", sense="<=", constant=co2_emissions) n.lopf( n.snapshots[:6], solver_name='gurobi', pyomo=False, extra_functionality=extra_functionalities, ) if __name__=="__main__": DE_1node = pypsa.Network() DE_1node.set_snapshots(pd.date_range('2018-01-01', periods=5, freq='H')) snapshot = 5 load= 40000 # Create carriers for which CO2 emissions unequal 0 co2_emissions_coal=0.34 DE_1node.add('Carrier', 'Coal', co2_emissions = co2_emissions_coal) DE_1node.add('Bus','DE') DE_1node.add('Generator', 'Solar', bus = 'DE', carrier='Renewable', p_max_pu=[1, 0, 0, 0, 0], p_nom = 0, marginal_cost=0.010, capital_cost=35602, p_nom_extendable=True) DE_1node.add('Generator', 'Wind', bus = 'DE', carrier='Renewable', p_max_pu=[1, 0, 0, 0, 0], p_nom = 0, marginal_cost=0.015, capital_cost=96085, p_nom_extendable=True) DE_1node.add('StorageUnit', 'Storage_1', bus='DE', carrier='Others', p_nom=0, max_hours=5,marginal_cost=1,capital_cost=177345, p_nom_extendable=True) DE_1node.add('StorageUnit', 'Storage_2', bus='DE', carrier='Others', p_nom=0, max_hours=5, marginal_cost=1,capital_cost=177345, p_nom_extendable=True) DE_1node.add('Generator', 'Coal', bus = 'DE', carrier='Coal', p_nom = 14830, marginal_cost=28.197, capital_cost=349977) DE_1node.add('Load', 'DE_Load', bus='DE', p_set = [load for _ in range(snapshot)]) storage_map = {} list_renewable_carriers = ['Renewable','Solar', 'solar','offwind-ac', 'Wind', 'onwind', 'biomass','ror', 'geothermal','hydro', 'offwind-ac', 'offwind-dc', 'Renewable_Storage'] #['Solar','solar', 'onwind', 'biomass', 'geothermal', 'ror', 'offwind-ac', 'hydro', 'offwind-dc', 'PHS', 'Renewable_Storage','Wind'] co2_emissions=0.1*25211 solve_network(DE_1node, renewable_carriers = list_renewable_carriers,co2_emissions = co2_emissions) DE_1node.generators_t.p.plot() # Evaluate the share of renewable energy ax = DE_1node.generators_t.p.plot() DE_1node.storage_units_t.p.plot(ax=ax) DE_1node.loads_t.p.plot(ax=ax) cap_installed = DE_1node.generators.p_nom_opt cap_installed_storage = DE_1node.storage_units.p_nom_opt production = pd.concat([DE_1node.generators_t.p, DE_1node.storage_units_t.p], axis=1) production_total = production.sum() production_share = production_total/production_total.sum() co2_emissions_t=np.nansum((DE_1node.snapshot_weightings.generators @ DE_1node.generators_t.p) / DE_1node.generators.efficiency * DE_1node.generators.carrier.map(DE_1node.carriers.co2_emissions)) print("CO2 emissions CO2 cap green field:\n", co2_emissions_t) print("installed capacity:\n", cap_installed) print("installed storage:\n", cap_installed_storage) print("total production per carrier:\n", production_total) print("production share per carrier:\n", production_share) system_cost =DE_1node.objective/(snapshot*load) print("System cost [euro/MWh]", system_cost) #%% “green field” constrained (cert.) import pypsa import pandas as pd from pypsa.linopt import get_var, linexpr, define_constraints import logging logger = logging.getLogger(__name__) import numpy as np def solve_network(n, renewable_shares, renewable_carriers, *args, **kwargs): """Solve the network. Args: n (PyPSA Network): PyPSA network to be solved. """ def fix_bus_production(n, snapshots): """Define the constraint that the sum of the renewable generation in each snapshot must be equal to the minimum required renewable share. Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ demand_at_t = n.loads_t.p_set.loc[snapshots].sum(axis=1) renewable_generators = n.generators[n.generators.carrier.isin(renewable_carriers)].index renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index renewable_storage_units_store = (linexpr((-1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))).sum(axis=1) renewable_generation = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))).sum(axis=1) + (linexpr((1, get_var(n, "Generator", "p")[renewable_generators]))).sum(axis=1) define_constraints( n, renewable_generation + renewable_storage_units_store, ">=", demand_at_t *renewable_shares , "Generator", "production_share" ) def storage_restriction(n, snapshots): """Define the constraint that ensure that energy generated by renewable resources that has been stored in storage units a fictious storage unit was added for each normal storage unit that would only allow charging using generation units with the carrier "Renewable" (this is defined in the function storage_restriction(n,snapshots)). Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ renewable_generators = n.generators[n.generators.carrier.isin(renewable_carriers)].index renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index storage_units = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers))].index renewable_generators_feed_in = (linexpr((1, get_var(n, "Generator", "p")[renewable_generators]))).sum(axis=1) renewable_storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))).sum(axis=1) renewable_storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))).sum(axis=1) define_constraints( n, renewable_generators_feed_in +renewable_storage_units_store, ">=", 0, "Generator", "restrict_renewable_storages_share" ) def storage_variables_constraints(n, snapshots): """Define the constraint that coupple the fictious and real storage variables together To ensure the fictious storage units do not extent the normal (conventional) storage units or in other words provide more storage possibility to the system and stay purely fictious, the optimization variables of the normal (conventional) storage units and the fictious storage units are coupled. This means that the sum of both storage units (fictious + conventional) is limited by the maximum/minimum properties of the corresponding normal storage unit. Args: n (PyPSA Network): PyPSA network to which the constraint is added. snapshots (list or pandas.Index): List of snapshots or time steps. All time-dependent series quantities are indexed by network.snapshots. """ renewable_storage_units = n.storage_units[n.storage_units.carrier.isin(renewable_carriers)].index renewable_storage_units_ext = n.storage_units[n.storage_units.carrier.isin(renewable_carriers) & n.storage_units.p_nom_extendable].index storage_units = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers))].index storage_units_ext = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers)) & n.storage_units.p_nom_extendable].index storage_units_non_ext = n.storage_units[~(n.storage_units.carrier.isin(renewable_carriers)) & ~(n.storage_units.p_nom_extendable)].index renewable_storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[renewable_storage_units]))) storage_units_store = (linexpr((1, get_var(n, "StorageUnit", "p_store")[storage_units]))) renewable_storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[renewable_storage_units]))) storage_units_dispatch = (linexpr((1, get_var(n, "StorageUnit", "p_dispatch")[storage_units]))) renewable_storage_units_soc = (linexpr((1, get_var(n, "StorageUnit", "state_of_charge")[renewable_storage_units]))) storage_units_soc = (linexpr((1, get_var(n, "StorageUnit", "state_of_charge")[storage_units]))) storage_units_store_max_non_ext = (linexpr((-1, (n.storage_units.p_nom*n.storage_units.p_max_pu)[storage_units_non_ext]))) storage_units_store_max_ext = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom")*n.storage_units.p_max_pu)[storage_units_ext]))) storage_units_dispatch_max_ext = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom")*n.storage_units.p_min_pu)[storage_units_ext]))) storage_units_dispatch_max_non_ext = (linexpr((-1, (n.storage_units.p_nom*n.storage_units.p_min_pu)[storage_units_non_ext]))) storage_units_soc_max_ext = (linexpr((-n.storage_units.max_hours[storage_units_ext], (get_var(n, "StorageUnit", "p_nom"))[storage_units_ext]))) storage_units_soc_max_non_ext = (linexpr((-n.storage_units.max_hours[storage_units_non_ext], (n.storage_units.p_nom)[storage_units_non_ext]))) renewable_storage_units_extension = (linexpr((1, (get_var(n, "StorageUnit", "p_nom"))[renewable_storage_units_ext]))) storage_units_extension = (linexpr((-1, (get_var(n, "StorageUnit", "p_nom"))[storage_units_ext]))) for s, name in enumerate(storage_units): if name in storage_units_ext: define_constraints( n, renewable_storage_units_store[renewable_storage_units[s]] + storage_units_store[storage_units[s]] + storage_units_store_max_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_store" ) define_constraints( n, renewable_storage_units_dispatch[renewable_storage_units[s]] + storage_units_dispatch[storage_units[s]] + storage_units_dispatch_max_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_dispatch" ) define_constraints( n, storage_units_soc_max_ext[storage_units[s]] + renewable_storage_units_soc[renewable_storage_units[s]] + storage_units_soc[storage_units[s]], "<=", 0, "StorageUnit", "state_of_charge_restriction" ) define_constraints( n, renewable_storage_units_extension[renewable_storage_units[s]] + storage_units_extension[storage_units[s]], "==", 0, "StorageUnit", "storage_extension" ) else: define_constraints( n, renewable_storage_units_store[renewable_storage_units[s]] + storage_units_store[storage_units[s]] + storage_units_store_max_non_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_store" ) define_constraints( n, renewable_storage_units_dispatch[renewable_storage_units[s]] + storage_units_dispatch[storage_units[s]] + storage_units_dispatch_max_non_ext[storage_units[s]], "<=", 0, "StorageUnit", "max_dispatch" ) define_constraints( n, storage_units_soc_max_non_ext[storage_units[s]] + renewable_storage_units_soc[renewable_storage_units[s]] + storage_units_soc[storage_units[s]], "<=", 0, "StorageUnit", "state_of_charge_restriction" ) def extra_functionalities(n, snapshots): fix_bus_production(n, snapshots) storage_restriction(n,snapshots) storage_variables_constraints(n,snapshots) def create_fictious_storage_units(n): """Create fictious storage units for each storage unit. The fictious storage units are created in order to be able to model the share of renewable storage units in the system. The share of renewable storage units is defined by the user and is used to limit the share of renewable storage units in the system. Args: n (PyPSA Network): PyPSA network to which the new storage units are added. """ n.madd('StorageUnit', n.storage_units.index, suffix='_Renewable', carrier='Renewable_Storage', **n.storage_units.drop('carrier', axis=1)) def define_RE_share(n, renewable_share): """Define the share of renewable storage units in the system. and check if the length of the share is equal to the number of snapshots, and has similar index as the snapshots.""" if len(renewable_share) > len(n.snapshots): logger.warning( "The length of passed renewable share per snapshots is greater than the number of snapshots." ) logger.warning( f"Only taking the first {len(n.snapshots)} values." ) temp_renewable_share = pd.Series(renewable_share[:len(n.snapshots)], index=n.snapshots) elif len(renewable_share) < len(n.snapshots): logger.warning( "The length of passed renewable share per snapshots is less than the number of snapshots." ) logger.warning("Filling the missing values with 0s.") temp_renewable_share = pd.Series(0, index=n.snapshots) temp_renewable_share[:len(renewable_share)] = pd.Series(renewable_share, index=n.snapshots[:len(renewable_share)]) else: temp_renewable_share = pd.Series(renewable_share, index=n.snapshots) return temp_renewable_share renewable_shares = define_RE_share(n, renewable_shares) create_fictious_storage_units(n) if 'Renewable_Storage' not in renewable_carriers: renewable_carriers.append('Renewable_Storage') n.lopf( n.snapshots[:6], solver_name='gurobi', pyomo=False, extra_functionality=extra_functionalities, ) if __name__=="__main__": DE_1node = pypsa.Network() DE_1node.set_snapshots(pd.date_range('2018-01-01', periods=5, freq='H')) snapshot = 5 load= 40000 # Create carriers for which CO2 emissions unequal 0 co2_emissions_coal=0.34 DE_1node.add('Carrier', 'Coal', co2_emissions = co2_emissions_coal) DE_1node.add('Bus','DE') DE_1node.add('Generator', 'Solar', bus = 'DE', carrier='Renewable', p_max_pu=[1, 0, 0, 0, 0], p_nom = 0, marginal_cost=0.010, capital_cost=35602, p_nom_extendable=True) DE_1node.add('Generator', 'Wind', bus = 'DE', carrier='Renewable', p_max_pu=[1, 0, 0, 0, 0], p_nom = 0, marginal_cost=0.015, capital_cost=96085, p_nom_extendable=True) DE_1node.add('StorageUnit', 'Storage_1', bus='DE', carrier='Others', p_nom=0, max_hours=5,marginal_cost=1,capital_cost=177345, p_nom_extendable=True) DE_1node.add('StorageUnit', 'Storage_2', bus='DE', carrier='Others', p_nom=0, max_hours=5, marginal_cost=1,capital_cost=177345, p_nom_extendable=True) DE_1node.add('Generator', 'Coal', bus = 'DE', carrier='Coal', p_nom = 14830, marginal_cost=28.197, capital_cost=349977, p_nom_extendable=False) DE_1node.add('Load', 'DE_Load', bus='DE', p_set = [load for _ in range(snapshot)]) storage_map = {} list_renewable_carriers = ['Renewable','Solar', 'solar','offwind-ac', 'Wind', 'onwind', 'biomass','ror', 'geothermal','hydro', 'offwind-ac', 'offwind-dc', 'Renewable_Storage'] #['Solar','solar', 'onwind', 'biomass', 'geothermal', 'ror', 'offwind-ac', 'hydro', 'offwind-dc', 'PHS', 'Renewable_Storage','Wind'] renewable_Shares = pd.Series([0.97 for _ in range(len(DE_1node.snapshots))], index=DE_1node.snapshots) solve_network(DE_1node, renewable_shares= renewable_Shares, renewable_carriers = list_renewable_carriers) DE_1node.generators_t.p.plot() ax = DE_1node.generators_t.p.plot() DE_1node.storage_units_t.p.plot(ax=ax) DE_1node.loads_t.p.plot(ax=ax) cap_installed = DE_1node.generators.p_nom_opt cap_installed_storage = DE_1node.storage_units.p_nom_opt # Evaluate the share of renewable energy production = pd.concat([DE_1node.generators_t.p, DE_1node.storage_units_t.p], axis=1) production_total = production.sum() production_share = production_total/production_total.sum() co2_emissions_t=np.nansum((DE_1node.snapshot_weightings.generators @ DE_1node.generators_t.p) / DE_1node.generators.efficiency * DE_1node.generators.carrier.map(DE_1node.carriers.co2_emissions)) print("CO2 emissions certificate green field: ", co2_emissions_t) print("installed capacity:\n", cap_installed) print("installed storage:\n", cap_installed_storage) print("total production per carrier:\n", production_total) print("production share per carrier:\n", production_share) system_cost=DE_1node.objective/(snapshot*load) print("System cost [euro/MWh]", system_cost)
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; use App\Models\Cpl; use App\Models\Kdm; use App\Models\Screen; class KdmFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Kdm::class; /** * Define the model's default state. */ public function definition(): array { return [ 'uuid' => $this->faker->uuid(), 'name' => $this->faker->name(), 'AnnotationText' => $this->faker->name(), 'ContentKeysNotValidBefore' => $this->faker->name(), 'ContentKeysNotValidAfter' => $this->faker->name(), 'SubjectName' => $this->faker->name(), 'DeviceListDescription' => $this->faker->name(), 'SerialNumber' => $this->faker->name(), 'path_file' => $this->faker->name(), 'server_name' => $this->faker->name(), 'file_type' => $this->faker->name(), 'id_server' => $this->faker->name(), 'file_size' => $this->faker->randomFloat(2, 0, 999999.99), 'file_progress' => $this->faker->randomFloat(2, 0, 999999.99), 'tms_path' => $this->faker->name(), 'last_update' => $this->faker->dateTime(), 'screen_id' => Screen::factory(), 'cpl_id' => Cpl::factory(), ]; } }
<?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Validator; class UserController extends Controller { public function Reg(Request $request) { $validation = Validator::make($request->all(), [ 'fio'=>['required', 'regex:/[А-Яа-яЁё-]/u'], 'birthday'=>['required'], 'passport'=>['required', 'numeric'], 'login'=>['required', 'unique:users', 'regex:/[A-Za-z0-9-]/u'], 'phone'=>['required', 'numeric'], 'email'=>['required', 'unique:users', 'email:frc'], 'password'=>['required', 'min:6', 'confirmed'], 'password_confirmation'=>['required'], 'rules'=>['required'], ], [ 'fio.required'=>'Поле обязательно для заполнения', 'fio.regex'=>'Разрешенные символы: кириллица, пробел и тире', 'birthday.required'=>'Поле обязательно для заполнения', 'passport.required'=>'Поле обязательно для заполнения', 'passport.numeric'=>'Разрешены только цифры', 'login.required'=>'Поле обязательно для заполнения', 'login.unique'=>'Пользователь с таким логином уже существует', 'login.regex'=>'Разрешенные символы: латиница, цифры и тире', 'phone.required'=>'Поле обязательно для заполнения', 'phone.numeric'=>'Разрешены только цифры', 'email.required'=>'Поле обязательно для заполнения', 'email.unique'=>'Пользователь с такой почтой уже существует', 'email.email'=>'Тип должен соответстовать почте', 'password.required'=>'Поле обязательно для заполнения', 'password.min'=>'Минимальное количество симмолов - 6', 'password.confirmed'=>'Пароли не совпадают', 'password_confirmation.required'=>'Поле обязательно для заполнения', 'rules.required'=>'Поле обязательно для заполнения', ]); if ($validation->fails()) { return response()->json($validation->errors(), 400); } $user = new User(); $user->fio = $request->fio; $user->birthday = $request->birthday; $user->passport = $request->passport; $user->email = $request->email; $user->phone = $request->phone; $user->login = $request->login; $user->password = md5($request->password); $user->save(); return redirect()->route('AuthPage'); } public function Auth(Request $request) { $validation = Validator::make($request->all(), [ 'login'=>['required'], 'password'=>['required'], ], [ 'login.required'=>'Поле обязательно для заполнения', 'password.required'=>'Поле обязательно для заполнения', ]); if ($validation->fails()) { return response()->json($validation->errors(), 400); } $user = User::query() ->where('login', $request->login) ->where('password', md5($request->password)) ->first(); if ($user) { Auth::login($user); return redirect()->route('HomePage'); } else { return response()->json('Неверный логин или пароль!', 403); } } public function Logout() { Auth::logout(); return redirect()->route('HomePage'); } public function EditProfile(Request $request) { $validation = Validator::make($request->all(), [ 'fio'=>['required', 'regex:/[А-Яа-яЁё-]/u'], 'birthday'=>['required'], 'passport'=>['required', 'numeric'], 'login'=>['required', 'regex:/[A-Za-z0-9-]/u'], 'phone'=>['required', 'numeric'], 'email'=>['required', 'email:frc'], 'password'=>['nullable', 'confirmed'], 'old_password'=>['required', 'min:6'], ], [ 'fio.required'=>'Поле обязательно для заполнения', 'fio.regex'=>'Разрешенные символы: кириллица, пробел и тире', 'birthday.required'=>'Поле обязательно для заполнения', 'passport.required'=>'Поле обязательно для заполнения', 'passport.numeric'=>'Разрешены только цифры', 'login.required'=>'Поле обязательно для заполнения', 'login.unique'=>'Пользователь с таким логином уже существует', 'login.regex'=>'Разрешенные символы: латиница, цифры и тире', 'phone.required'=>'Поле обязательно для заполнения', 'phone.numeric'=>'Разрешены только цифры', 'email.required'=>'Поле обязательно для заполнения', 'email.unique'=>'Пользователь с такой почтой уже существует', 'email.email'=>'Тип должен соответстовать почте', 'password.required'=>'Поле обязательно для заполнения', 'password.min'=>'Минимальное количество симмолов - 6', 'password.confirmed'=>'Пароли не совпадают', 'password_confirmation.required'=>'Поле обязательно для заполнения', 'rules.required'=>'Поле обязательно для заполнения', ]); if ($validation->fails()) { return response()->json($validation->errors(), 400); } $user = User::query() ->where('id', Auth::id()) ->first(); dd(md5($request->old_password)); if ($user->password == md5($request->old_password)) { $user->fio = $request->fio; $user->birthday = $request->birthday; $user->passport = $request->passport; $user->email = $request->email; $user->phone = $request->phone; $user->login = $request->login; if ($user->password) { $user->password = md5($request->password); } } else { return response()->json('Неверный пароль!', 403); } $user->update(); return redirect()->route('UserProfile'); } }
import { db } from "@/lib/db"; import { $notes } from "@/lib/db/schema"; import { eq } from "drizzle-orm"; import { NextResponse } from "next/server"; import { z } from "zod"; const UpdateNoteSchema = z.object({ editorState: z .string({ required_error: "Editor state is required" }) .min(1, { message: "Editor state is required" }), }); type UpdateNote = z.infer<typeof UpdateNoteSchema>; export async function GET( _: Request, { params }: { params: { note_id: string } }, ) { try { const note_id = params?.note_id; if (isNaN(Number(note_id))) { return NextResponse.json({ message: "Invalid note id" }, { status: 500 }); } const notes = await db .select() .from($notes) .where(eq($notes?.id, Number(note_id))); if (notes.length === 0) { return NextResponse.json( { message: `Note with id ${note_id} is not found` }, { status: 404 }, ); } if (notes.length > 1) { return NextResponse.json( { message: "Multiple notes are found" }, { status: 500 }, ); } const note = notes[0]; return NextResponse.json( { data: note, }, { status: 200, }, ); } catch (error) { if (error instanceof TypeError) { return NextResponse.json( { message: "error getting the note", error: String(error), }, { status: 500 }, ); } return NextResponse.json( { message: "error getting the note", error, }, { status: 500 }, ); } } export async function PUT( req: Request, { params }: { params: { note_id: string } }, ) { try { const note_id = params?.note_id; if (isNaN(Number(note_id))) { return NextResponse.json({ message: "Invalid note id" }, { status: 500 }); } const body = (await req.json()) as UpdateNote; if (!body) { return NextResponse.json( { message: "Missing note_id or editor state" }, { status: 400 }, ); } const { editorState } = await UpdateNoteSchema.parseAsync(body); if (!Number(note_id) || !editorState) { return NextResponse.json( { message: "Missing note_id or editor state" }, { status: 400 }, ); } const notes = await db .select() .from($notes) .where(eq($notes.id, Number(note_id))); if (notes.length === 0) { return NextResponse.json( { message: "Note does not exists" }, { status: 404 }, ); } if (notes.length > 1) { return NextResponse.json( { message: "Multiple notes are found" }, { status: 500 }, ); } const note = notes[0]; if (note.editorState !== editorState) { await db .update($notes) .set({ editorState }) .where(eq($notes.id, Number(note_id))); } return NextResponse.json( { success: true, message: "Note state updated successfully" }, { status: 200 }, ); } catch (error) { if (error instanceof TypeError) { return NextResponse.json( { message: "error updating note state", error: String(error), }, { status: 500 }, ); } return NextResponse.json( { message: "error updating note state", error, }, { status: 500 }, ); } } export async function DELETE( _: Request, { params }: { params: { note_id: string } }, ) { try { const note_id = params?.note_id; if (isNaN(Number(note_id))) { return NextResponse.json({ message: "Invalid note id" }, { status: 500 }); } await db.delete($notes).where(eq($notes.id, Number(note_id))); return NextResponse.json( { message: `Note with id ${note_id} is successfully deleted`, success: true, }, { status: 200, }, ); } catch (error) { if (error instanceof TypeError) { return NextResponse.json( { message: "error deleting the note", error: String(error), }, { status: 500 }, ); } return NextResponse.json( { message: "error deleting the note", error, }, { status: 500 }, ); } }
import { RequestHandler, Router } from 'express' import asyncMiddleware from '../../../middleware/asyncMiddleware' import validationMiddleware from '../../../middleware/validationMiddleware' import emptyJourneyHandler from '../../../middleware/emptyJourneyHandler' import StartJourneyRoutes from './handlers/startJourney' import { Services } from '../../../services' import CheckAnswersRoutes from './handlers/checkAnswers' import ConfirmationRoutes from './handlers/confirmation' export default function Index({ activitiesService, prisonService, metricsService }: Services): Router { const router = Router({ mergeParams: true }) const get = (path: string, handler: RequestHandler, stepRequiresSession = false) => router.get(path, emptyJourneyHandler('createJourney', stepRequiresSession), asyncMiddleware(handler)) const post = (path: string, handler: RequestHandler, type?: new () => object) => router.post(path, validationMiddleware(type), asyncMiddleware(handler)) const startHandler = new StartJourneyRoutes(metricsService) const checkAnswersHandler = new CheckAnswersRoutes(activitiesService, prisonService, metricsService) const confirmationHandler = new ConfirmationRoutes() get('/start', startHandler.GET) get('/check-answers', checkAnswersHandler.GET, true) post('/check-answers', checkAnswersHandler.POST) get('/confirmation/:id', confirmationHandler.GET, true) return router }
package study.project.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; @Entity @Getter @Setter public class Member { @Id @GeneratedValue @Column(name = "MEMBER_ID") private Long id; private String name; @Embedded private Address address; @JsonIgnore @OneToMany(mappedBy = "member") private List<Order> orders = new ArrayList<>(); public static Member createMember(String name, Address address) { Member member = new Member(); member.setName(name); member.setAddress(address); return member; } public Long getId() { return id; } public String getName() { return name; } public Address getAddress() { return address; } public List<Order> getOrders() { return orders; } }
""" Copyright (c) 2021, Consortium Board ROXANNE All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the ROXANNE nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY CONSORTIUM BOARD ROXANNE ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CONSORTIUM BOARD TENCOMPETENCE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # helper functions for ROXANNE's first field test import ast import itertools import networkx as nx import numpy as np import os import sys tokens = os.path.abspath(__file__).split('/') path2root = '/'.join(tokens[:-2]) if path2root not in sys.path: sys.path.append(path2root) print('fft_helpters: path2root = ', path2root) if path2root not in sys.path: sys.path.append(path2root) from storage.kit.VBx import diarization_lib from storage.builtin_datasets import BuiltinDataset ''' 1. Setting up the path: - It uses os.path.abspath(__file__) to get the absolute path of the current file. - It splits the path into tokens using / as the delimiter. - It constructs the path2root by joining all tokens except the last two with /. - It checks if path2root is already in the sys.path system variable, which defines the search path for importing modules. - If not, it adds path2root to sys.path. - Finally, it prints the value of path2root for information. 2. Importing modules: - It checks again if path2root is in sys.path, presumably for safety. - It imports the diarization_lib module from the storage.kit.VBx package. - It imports the BuiltinDataset class from the storage.builtin_datasets package. ''' def _generate_channels_and_index(wp5_outputs): channels = {} for con in wp5_outputs['conversations']: for channel in con['channels']: channels[channel['id']] = channel # build channel-2-index map channel2index = {} for con in wp5_outputs['conversations']: for channel in con['channels']: channel2index[channel['id']] = len(channel2index) return channels, channel2index ''' - Creates two dictionaries: - channels: Maps channel IDs to their corresponding channel information (extracted from wp5_outputs). - channel2index: Maps channel IDs to unique numerical indices, representing their order in the data. Functionality: - Iterate through conversations: - Loops through each conversation in the wp5_outputs['conversations'] list. - Extract channels: - For each conversation, iterates through its channels list. - Build channels dictionary: - For each channel, adds an entry to the channels dictionary with: - Key: The channel's ID. - Value: The channel's information dictionary (presumably from channel). - Build channel to index map: - Creates an empty channel2index dictionary. - Assign unique indices: - Loops through each conversation and its channels again. - For each channel, adds an entry to the channel2index dictionary with: - Key: The channel's ID. - Value: The current length of the channel2index dictionary (acting as a unique index). - Return results: -Returns a tuple containing both the channels and channel2index dictionaries. ''' def _cluster_from_voice_prints_matrix(channel2index, wp5_outputs, threhold, calibration): # cluster voiceprintsMatrix = np.zeros((len(channel2index), len(channel2index))) for u, row in wp5_outputs['voiceprintsMatrix'].items(): u_index = channel2index[u] for v, s in row.items(): v_index = channel2index[v] voiceprintsMatrix[u_index, v_index] = s for con in wp5_outputs['conversations']: channel_ids = [channel['id'] for channel in con['channels']] for s in channel_ids: for l in channel_ids: if s != l: s_index = channel2index[s] l_index = channel2index[l] voiceprintsMatrix[s_index, l_index] = -np.inf if calibration: thr, scr_cal = diarization_lib.twoGMMcalib_lin(voiceprintsMatrix[np.where(np.isfinite(voiceprintsMatrix))]) else: thr = 0 labels = diarization_lib.AHC(voiceprintsMatrix, thr + threhold) return labels ''' Takes a voice print matrix representing pairwise similarities between channels and conversation information as input. Applies a clustering algorithm (AHC) to group channels (speakers) based on their voice prints. Employs a thresholding strategy to improve clustering accuracy. Steps: - Initialize voice print matrix: - Creates a square matrix (voiceprintsMatrix) of zeros with dimensions equal to the number of channels. - Populate voice print matrix: - Iterates through each entry in the voiceprintsMatrix provided in wp5_outputs. - Looks up the indices of the corresponding channels using channel2index. - Sets the value at the corresponding matrix indices to the similarity score. - Set self-similarity and inter-conversation similarity to negative infinity: - Iterates through each conversation in wp5_outputs. - Extracts channel IDs from the conversation. - Iterates through all pairs of channel IDs within the conversation and sets their similarity in the matrix to negative infinity. - Threshold calibration (optional): - If calibration is True, uses a specific function (diarization_lib.twoGMMcalib_lin) to calculate a calibrated threshold based on the non-infinite values in the matrix. - Otherwise, sets the threshold to 0. - Apply clustering: - Uses the diarization_lib.AHC function to perform Agglomerative Hierarchical Clustering (AHC) on the voice print matrix with the chosen threshold. - Return cluster labels: - Returns the cluster labels assigned to each channel by the clustering algorithm. This function relies on the channel2index dictionary created in another function for efficient indexing. It uses a specific heuristic to handle self-similarity and inter-conversation similarity. The calibration step (if enabled) aims to adjust the threshold based on data characteristics. ''' def _generate_nodes(channels, channel2index, labels): nodes = {} for channel in channels: index = channel2index[channel] channel_info = channels[channel] if 'transcription' in channel_info: del channel_info['transcription'] # ignore the transcription in first field test c = labels[index] if c in nodes: nodes[c].append(channel_info) else: nodes[c] = [channel_info] return nodes ''' Takes information about channels (speakers), their indices, and clustering labels as input. Generates a dictionary where each key represents a cluster and the value is a list of channel information dictionaries belonging to that cluster. Steps: - Initialize empty nodes dictionary: - Creates an empty dictionary called nodes to store the generated clusters. - Iterate through channels: - Loops through each channel (speaker) information dictionary in the channels input. - Extract index and channel info: - Looks up the corresponding index of the channel using channel2index. - Extracts the actual channel information dictionary from the channels dictionary. - Process transcription (optional): - Checks if the channel information contains a key named "transcription". - If present, it removes the "transcription" key-value pair (presumably for this specific test scenario). - Get cluster label: - Retrieves the cluster label for the current channel from the labels list. - Add channel info to cluster: - Checks if the current cluster label already exists as a key in the nodes dictionary. - If yes, appends the current channel information to the existing list of channels within that cluster. - If no, creates a new list with the current channel information and adds it to nodes with the cluster label as the key. - Return nodes dictionary: -Returns the generated nodes dictionary containing the clustered speaker information. This function assumes the presence of pre-processed channel information and clustering results. It filters out "transcription" information for the current test scenario but this might be relevant in other contexts. It generates a simple cluster representation using a dictionary structure. ''' def _generate_nodes_aegis(channels, channel2index, labels): nodes = {} for channel in channels: index = channel2index[channel] channel_info = channels[channel] if 'transcription' in channel_info: del channel_info['transcription'] # ignore the transcription in first field test c = labels[index] if c in nodes: nodes[c].append(channel_info) else: nodes[c] = [channel_info] return nodes ''' Creates a network representation by organizing channels (speakers) into nodes based on clustering results. Specifically designed for the Aegis system or a similar context where transcriptions are temporarily excluded. Steps: - Initializes empty nodes dictionary: - Creates a dictionary named nodes to store the generated nodes. - Iterates through channels: - Loops through each channel (speaker) information dictionary in the channels input. - Extracts index and channel info: - Retrieves the channel's index from channel2index. - Obtains the channel's information from the channels dictionary. - Removes transcription (specific to Aegis): - Deletes the "transcription" key-value pair from the channel information, likely due to a temporary constraint in the Aegis system or test setup. - Gets cluster label: - Retrieves the cluster label assigned to the current channel from the labels list. - Groups channels into nodes: - Checks if the cluster label already exists as a key in the nodes dictionary. - If yes, appends the channel information to the existing list of channels within that node. - If no, creates a new list with the channel information and adds it to nodes with the cluster label as the key. - Returns nodes dictionary: - Returns the generated nodes dictionary, where each key represents a node (cluster) and the value is a list of channel information dictionaries belonging to that node. Relies on pre-processed channel information and clustering results. Excludes transcriptions for Aegis-specific reasons. Creates a network representation with nodes as clusters of channels. ''' # def _generate_nodes_aegis(channels): # nodes = {} # for channel in channels: # channel_info = channels[channel] # if 'transcription' in channel_info: # del channel_info['transcription'] # ignore the transcription in first field test # node_id = channel_info['number'] # nodes[node_id] = channel_info # return nodes def _generate_edges(channel2index, labels, wp5_outputs, directed): edges = {} for con in wp5_outputs['conversations']: channel_ids = [channel['id'] for channel in con['channels']] if 'date' in con: con_date = con['date'] else: con_date = None # print(con_date) # print(channel_ids) for i in range(len(channel_ids)): s = channel_ids[i] for j in range(len(channel_ids)): if j == i: continue l = channel_ids[j] if i < j or not directed: s_cid = labels[channel2index[s]] l_cid = labels[channel2index[l]] if s_cid in edges: if l_cid in edges[s_cid]: edges[s_cid][l_cid]['weight'] += 1 if 'timestamps' in edges[s_cid][l_cid]: temp_timestamps = edges[s_cid][l_cid]['timestamps'] temp_timestamps.append(con_date) edges[s_cid][l_cid]['timestamps'] = temp_timestamps else: if con_date is not None: edges[s_cid][l_cid] = {'weight' : 1, 'timestamps': [con_date]} else: edges[s_cid][l_cid] = {'weight' : 1} else: if con_date is not None: edges[s_cid] = {l_cid: {'weight' : 1, 'timestamps': [con_date]}} else: edges[s_cid] = {l_cid: {'weight' : 1}} return edges ''' Creates a network representation by defining edges between nodes (clusters of channels) based on their co-occurrence in conversations. Allows for both directed and undirected edge creation. Optionally includes timestamps for edges based on conversation dates. Steps: - Initializes empty edges dictionary: - Creates a dictionary named edges to store the generated edges. - Iterates through conversations: - Loops through each conversation in the wp5_outputs['conversations'] list. - Extracts channel IDs and date: - Retrieves the IDs of channels involved in the current conversation. - Extracts the conversation date if available, otherwise sets it to None. - Iterates through channel pairs: - Loops through all possible pairs of channels within the conversation. - Creates edges based on conditions: - If the network is directed, only creates edges from the first channel to the second (i < j). - If the network is undirected, creates edges in both directions (i < j or not directed). - Retrieves the cluster labels for the current channel pair using labels. - Checks if an edge already exists between those cluster labels: - If yes, increments the edge weight and appends the conversation date to the timestamps list (if applicable). - If no, creates a new edge with weight 1 and optionally includes the conversation date. - Returns edges dictionary: - Returns the generated edges dictionary, where keys represent source nodes (cluster labels), values are dictionaries with keys as target nodes, and each inner dictionary contains edge weight and optional timestamps. Relies on pre-processed channel information, clustering results, and conversation data. Captures co-occurrence relationships between clusters as edges. Supports both directed and undirected networks. Allows for inclusion of temporal information (timestamps) for edges. ''' def _generate_edges_aegis(channel2index, labels, wp5_outputs, directed): edges = {} for con in wp5_outputs['conversations']: channel_ids = [channel['id'] for channel in con['channels']] if 'date' in con: con_date = con['date'] else: con_date = None print(con_date) print(channel_ids) for i in range(len(channel_ids)): s = channel_ids[i] for j in range(len(channel_ids)): if j == i: continue l = channel_ids[j] if i < j or not directed: s_cid = labels[channel2index[s]] l_cid = labels[channel2index[l]] # timestamp_val = (con_date, channel_ids) timestamp_val = con_date if s_cid in edges: if l_cid in edges[s_cid]: edges[s_cid][l_cid]['weight'] += 1 if 'timestamps' in edges[s_cid][l_cid]: temp_timestamps = edges[s_cid][l_cid]['timestamps'] temp_timestamps = temp_timestamps.append(timestamp_val) edges[s_cid][l_cid]['timestamps'] = temp_timestamps else: if con_date is not None: edges[s_cid][l_cid] = {'weight' : 1, 'timestamps': [timestamp_val]} else: edges[s_cid][l_cid] = {'weight' : 1} else: if con_date is not None: edges[s_cid] = {l_cid: {'weight' : 1, 'timestamps': [timestamp_val]}} else: edges[s_cid] = {l_cid: {'weight' : 1}} return edges ''' - Builds a network representation for the Aegis system or a similar context. - Creates edges between nodes (clusters of channels) based on co-occurrence in conversations. - Allows for directed or undirected edges. - Includes timestamps for edges based on conversation dates. - Potentially prints debugging information. Steps: - Initializes edges dictionary: - Creates an empty dictionary edges to store the edges. - Iterates through conversations: - Loops through each conversation in wp5_outputs['conversations']. - Extracts channel IDs and date: - Retrieves channel IDs from the current conversation. - Extracts the conversation date if available, otherwise sets it to None. - Prints the date and channel IDs (likely for debugging). - Iterates through channel pairs: - Loops through all possible pairs of channels within the conversation. - Creates edges based on conditions: - If directed, creates edges only from the first channel to the second (i < j). - If undirected, creates edges in both directions (i < j or not directed). - Retrieves cluster labels for the channel pair using labels. - Checks if an edge already exists between those labels: - If yes, increments weight and appends the date to timestamps. - If no, creates a new edge with weight 1 and includes the date (if available). - Returns edges dictionary: - Returns the generated edges dictionary representing the network. - Similar to _generate_edges but potentially for Aegis-specific use. - Prints debugging information (date and channel IDs). ''' def _generate_phone_number_edges_aegis(wp5_outputs, directed): edges = {} for con in wp5_outputs['conversations']: channel_ids = [channel['id'] for channel in con['channels']] channel_numbers = [channel['number'] for channel in con['channels']] if 'date' in con: con_date = con['date'] else: con_date = None for i in range(len(channel_numbers)): s = channel_numbers[i] for j in range(len(channel_numbers)): if j == i: continue l = channel_numbers[j] if i < j or not directed: s_cid = s l_cid = l # timestamp_val = (con_date, channel_ids) timestamp_val = con_date if s_cid in edges: if l_cid in edges[s_cid]: edges[s_cid][l_cid]['weight'] += 1 if 'timestamps' in edges[s_cid][l_cid]: temp_timestamps = edges[s_cid][l_cid]['timestamps'] temp_timestamps.append(timestamp_val) edges[s_cid][l_cid]['timestamps'] = temp_timestamps else: if con_date is not None: edges[s_cid][l_cid] = {'weight' : 1, 'timestamps': [timestamp_val]} else: edges[s_cid][l_cid] = {'weight' : 1} else: if con_date is not None: edges[s_cid] = {l_cid: {'weight' : 1, 'timestamps': [timestamp_val]}} else: edges[s_cid] = {l_cid: {'weight' : 1}} return edges ''' - Builds a network representation (similar to previous functions) but connects nodes based on phone number co-occurrence in conversations. - Designed for the Aegis system or a similar context. - Allows for directed or undirected edges. - Includes timestamps based on conversation dates (if available). Steps: - Initializes empty edges dictionary: - Creates an empty dictionary edges to store the edges. - Iterates through conversations: - Loops through each conversation in wp5_outputs['conversations']. - Extracts phone numbers and date: - Retrieves phone numbers and conversation date (if available) for each channel in the conversation. - Iterates through phone number pairs: - Loops through all possible pairs of phone numbers within the conversation. - Creates edges based on conditions: - Similar to previous functions, considers directed/undirected edges and checks for existing edges. - Uses phone numbers directly as node identifiers (s_cid and l_cid). - Includes conversation date (if available) in timestamps. - Returns edges dictionary: - Returns the generated edges dictionary representing the network based on phone number co-occurrence. Differs from previous functions by using phone numbers for node identification and edge creation. Maintains similar structure for edge construction and timestamp handling. Likely for specific use cases like analyzing phone call networks. ''' def _construct_network(nodes, edges): network = [] for node in nodes: network.append({'type': 'node', 'id': 'speaker_{}'.format(node), 'properties': {'type': 'cluster', 'channels': nodes[node]} }) for u in edges: for v in edges[u]: edge_properties = dict() edge_properties['type'] = 'conversations' edge_properties['weight'] = edges[u][v]['weight'] if 'timestamps' in edges[u][v]: edge_properties['timestamps'] = edges[u][v]['timestamps'] network.append({'type': 'edge', 'source': 'speaker_{}'.format(u), 'target': 'speaker_{}'.format(v), 'properties': edge_properties }) return network ''' Takes nodes (speaker clusters) and edges (connections between them) as input. Creates a network representation in a specific format likely suitable for visualization or network analysis tools. Steps: - Initializes empty network list: - Creates an empty list network to store the network elements. - Processes nodes: - Iterates through each node (speaker cluster) in the nodes dictionary. - Adds a node element to the network list with the following properties: - type: Set to "node" indicating the element represents a node in the network. - id: Formatted as "speaker_{node_id}" where node_id is the original cluster identifier. - properties: A dictionary with information about the node: - type: Set to "cluster" indicating the node represents a cluster of speakers. - channels: A list containing the channel information associated with the cluster (extracted from nodes[node]). - Processes edges: - Iterates through each source node (u) in the edges dictionary. - For each source node, iterates through its target nodes (v) in the corresponding inner dictionary. - Creates an edge element for each source-target pair and adds it to the network list with the following properties: - type: Set to "edge" indicating the element represents a connection between nodes. - source: Set to "speaker_{source_id}" where source_id is the original cluster identifier of the source node. - target: Set to "speaker_{target_id}" where target_id is the original cluster identifier of the target node. - properties: A dictionary with information about the edge: - type: Set to "conversations" indicating the edge represents co-occurrence in conversations. - weight: Set to the weight of the edge retrieved from edges[u][v]['weight']. - timestamps (optional): If present in edges[u][v], includes a list of timestamps associated with the edge. - Returns network: - Returns the constructed network representation stored in the network list. Converts speaker clusters and their connections into a network format with nodes and edges. Uses specific naming conventions for node and edge identifiers. Includes edge weight and optional timestamps for detailed analysis. ''' def _construct_network_aegis(nodes, speaker_edges, phone_number_edges, directed): if directed == True: nx_graph = nx.DiGraph() else: nx_graph = nx.Graph() dict_node_phone_number = dict() for node in nodes: channels = nodes[node] phone_numbers = [] for idx, channel in enumerate(channels): channel_info = channel # number = channel_info.pop('number', 'phone_number_{}'.format(node)) number = channel_info['number'] channels[idx] = channel_info phone_numbers.append(number) # print('phone_numbers:', phone_numbers) # print('channels:', channels) dict_node_phone_number[node] = phone_numbers # dict_node_phone_number[node] = list(set(phone_numbers)) node_properties = {'type': 'cluster', 'channels': channels} nx_graph.add_node('speaker_{}'.format(node), type='node', properties=node_properties) for phone_number in phone_numbers: phone_node_properties = {'type': 'phone_number', 'channels': channels} nx_graph.add_node(phone_number, type='node', properties=phone_node_properties) print(dict_node_phone_number) # for node in nx_graph.nodes(data=True): # print(node) for u in speaker_edges: for v in speaker_edges[u]: timestamps = speaker_edges[u][v]['timestamps'] # timestamps_no_channel_id = [] # for timestamp in timestamps: # date = timestamp[0] # channel_id_1 = timestamp[1][0] # channel_id_2 = timestamp[1][1] # print(timestamp[0], timestamp[1][0], timestamp[1][1]) u_phone_numbers = dict_node_phone_number[u] for u_phone_number in u_phone_numbers: temp_edge = ('speaker_{}'.format(u), u_phone_number) temp_edge_properties = { 'type': 'calling' } if temp_edge not in nx_graph.edges(): temp_edge_properties['weight'] = 1 temp_edge_properties['timestamps'] = timestamps nx_graph.add_edge(temp_edge[0], temp_edge[1], type='edge', properties=temp_edge_properties) else: temp_weight = nx_graph[temp_edge[0]][temp_edge[1]]['properties']['weight'] temp_weight = temp_weight + 1 nx_graph[temp_edge[0]][temp_edge[1]]['properties']['weight'] = temp_weight temp_timestamps = [ts for ts in nx_graph[temp_edge[0]][temp_edge[1]]['properties']['timestamps']] temp_timestamps = temp_timestamps + timestamps nx_graph[temp_edge[0]][temp_edge[1]]['properties']['timestamps'] = temp_timestamps v_phone_numbers = dict_node_phone_number[v] for v_phone_number in v_phone_numbers: temp_edge = (v_phone_number, 'speaker_{}'.format(v)) temp_edge_properties = { 'type': 'receiving' } if temp_edge not in nx_graph.edges(): temp_edge_properties['weight'] = 1 temp_edge_properties['timestamps'] = timestamps nx_graph.add_edge(temp_edge[0], temp_edge[1], type='edge', properties=temp_edge_properties) else: temp_weight = nx_graph[temp_edge[0]][temp_edge[1]]['properties']['weight'] temp_weight = temp_weight + 1 nx_graph[temp_edge[0]][temp_edge[1]]['properties']['weight'] = temp_weight temp_timestamps = nx_graph[temp_edge[0]][temp_edge[1]]['properties']['timestamps'] temp_timestamps = temp_timestamps + timestamps nx_graph[temp_edge[0]][temp_edge[1]]['properties']['timestamps'] = temp_timestamps for u in phone_number_edges: for v in phone_number_edges[u]: temp_edge = (u, v) timestamps = phone_number_edges[u][v]['timestamps'] temp_edge_properties = { 'type': 'conversations' } if temp_edge not in nx_graph.edges(): temp_edge_properties['weight'] = phone_number_edges[u][v]['weight'] temp_edge_properties['timestamps'] = phone_number_edges[u][v]['timestamps'] nx_graph.add_edge(temp_edge[0], temp_edge[1], type='edge', properties=temp_edge_properties) else: temp_weight = nx_graph[temp_edge[0]][temp_edge[1]]['properties']['weight'] temp_weight = temp_weight + phone_number_edges[u][v]['weight'] nx_graph[temp_edge[0]][temp_edge[1]]['properties']['weight'] = temp_weight temp_timestamps = nx_graph[temp_edge[0]][temp_edge[1]]['properties']['timestamps'] temp_timestamps.append(timestamps) nx_graph[temp_edge[0]][temp_edge[1]]['properties']['timestamps'] = temp_timestamps network = [] for node_id, node_data in nx_graph.nodes(data=True): node = { 'type': node_data['type'], 'id': node_id, 'properties': node_data['properties'] } network.append(node) for source_id, target_id, edge_data in nx_graph.edges(data=True): edge = { 'type': edge_data['type'], 'source': source_id, 'target': target_id, 'properties': edge_data['properties'] } network.append(edge) weight = edge_data['properties']['weight'] if weight > 1: print(edge) # for edge in nx_graph.edges(data=True): # u = edge[0] # v = edge[1] # # print(edge, nx_graph[u]['properties']['channels']['id'], nx_graph[v]['properties']['channels']['id']) # print(edge) # # print(nx_graph.nodes(data=True)[u]['properties']['channels'], nx_graph.nodes(data=True)[v]['properties']['channels']) # for u in edges: # for v in edges[u]: # print('nodes[v]', nodes[v]) # edge_properties = dict() # edge_properties['type'] = 'conversations' # u_v_weight = edges[u][v]['weight'] # edge_properties['weight'] = edges[u][v]['weight'] # timestamps = edges[u][v]['timestamps'] # print('timestamps', timestamps) # for timestamp in timestamps: # print(timestamp[0], timestamp[1][0], timestamp[1][1]) # if 'timestamps' in edges[u][v]: # edge_properties['timestamps'] = edges[u][v]['timestamps'] # u_phone_numbers = dict_node_phone_number[u] # # print(u, u_phone_numbers) # for u_phone_number in u_phone_numbers: # network.append({'type': 'edge', # 'source': 'speaker_{}'.format(u), # 'target': u_phone_number, # 'properties': edge_properties # }) # v_phone_numbers = dict_node_phone_number[v] # # print(v, v_phone_numbers) # for v_phone_number in v_phone_numbers: # network.append({'type': 'edge', # 'source': v_phone_number, # 'target': 'speaker_{}'.format(v), # 'properties': edge_properties # }) # for i, j in itertools.product(u_phone_numbers, v_phone_numbers): # network.append({'type': 'edge', # 'source': i, # 'target': j, # 'properties': edge_properties # }) return network ''' Takes nodes (speaker clusters), speaker-to-speaker edges, phone number-to-phone number edges, and a directed/undirected flag as input. Creates a network representation in a specific format likely suitable for visualization or network analysis tools, incorporating both speaker and phone number nodes and edges. Includes edge weights and timestamps based on conversation data. Steps: - Initializes network based on directed/undirected flag: - Creates a nx_graph object as either a directed or undirected graph based on the directed parameter. - Creates a dictionary mapping nodes to phone numbers: - Iterates through each node and extracts its associated channels. - For each channel, extracts the phone number and adds it to a list for that node. - Stores the mapping between nodes and their phone numbers in a dictionary dict_node_phone_number. - Adds speaker nodes and their properties: - Iterates through each node: - Creates a node element with properties: - type: Set to "node" indicating a network node. - id: Formatted as "speaker_{node_id}" where node_id is the original cluster identifier. - properties: A dictionary containing information about the node: - type: Set to "cluster" indicating the node represents a cluster of speakers. - channels: The list of channels associated with the speaker cluster. - Adds the node element to the nx_graph. - Adds phone number nodes and their properties: - Iterates through each node and its associated phone numbers: - Creates a node element for each phone number with properties: - type: Set to "phone_number" indicating the node represents a phone number. - channels: The list of channels associated with the speaker cluster (inherited from the corresponding speaker node). - Adds the phone number node element to the nx_graph. - Adds speaker-to-speaker edges with calling/receiving directions: - Iterates through each speaker-to-speaker edge (speaker_edges): - For each source and target speaker: - Retrieves the associated phone numbers for both speakers. - For each source phone number: - Creates an edge between the source phone number and the target speaker: - type: Set to "calling" indicating the source initiated the call. - properties: Dictionary containing: - weight: Initial weight of 1. - timestamps: List of timestamps associated with the conversations. - Adds the edge element to the nx_graph if it doesn't exist, otherwise updates its weight and timestamps. - Similarly, creates and adds edges in the opposite direction (target speaker to source phone number) with "receiving" type. - Adds phone number-to-phone number edges: - Iterates through each phone number-to-phone number edge (phone_number_edges): - For each source and target phone number: - Creates an edge between the source and target phone numbers: - type: Set to "conversations" indicating co-occurrence in conversations. - properties: Dictionary containing: - weight: Edge weight from the input dictionary. - timestamps: List of timestamps associated with the conversations. - Adds the edge element to the nx_graph if it doesn't exist, otherwise updates its weight and timestamps. - Converts networkx graph to desired format: - Iterates through nodes and edges in the nx_graph: - Creates node and edge dictionaries with relevant information extracted from the networkx elements. - Appends these dictionaries to a network list. - Prints edges with weight greater than 1 (potentially for debugging): - Iterates through edges and prints those with weight greater than 1. - Returns the constructed network representation: - Returns the network list containing node and edge dictionaries. Combines speaker-based and phone number-based network representations. Captures calling/receiving relationships for speaker-to-speaker edges. Includes edge weights and timestamps for detailed analysis. Uses specific naming conventions for nodes and edges. ''' # def _construct_network_aegis(nodes, edges): # network = [] # for node in nodes: # network.append({'type': 'node', # 'id': nodes[node]['number'], # 'properties': {'type': 'phone_number', # 'channels': nodes[node]} # }) # for u in edges: # for v in edges[u]: # edge_properties = dict() # edge_properties['type'] = 'conversations' # edge_properties['weight'] = edges[u][v]['weight'] # if 'timestamps' in edges[u][v]: # edge_properties['timestamps'] = edges[u][v]['timestamps'] # network.append({'type': 'edge', # 'source': u, # 'target': v, # 'properties': edge_properties # }) # return network def parse_wp5_output(wp5_outputs, threhold=50, calibration=False, directed=False): """ build network from output of wp5 :param wp5_outputs: dictionary converted from WP5's JSON object :param threhold: :param calibration: :param directed: :return: """ # build channel-2-index map channels, channel2index = _generate_channels_and_index(wp5_outputs) # print(channels) # cluster labels = _cluster_from_voice_prints_matrix(channel2index, wp5_outputs, threhold, calibration) # print(labels) # generate nodes nodes = _generate_nodes(channels, channel2index, labels) # print(nodes) # generate edges: edges = _generate_edges(channel2index, labels, wp5_outputs, directed) # print(edges) # construct network network = _construct_network(nodes, edges) # print(network) return network ''' Takes the output of WP5 (likely a system for voice analysis and speaker identification) as input. Constructs a network representation based on identified speaker clusters and their relationships. Parameters: - wp5_outputs: A dictionary containing WP5's output data. - threshold: A threshold value used for clustering (likely based on voice similarity). - calibration: A boolean flag indicating whether to apply calibration to the data. - directed: A boolean flag specifying whether to create a directed or undirected network. Steps: - Creates a channel-to-index mapping: - Processes wp5_outputs to generate a list of channels (channels) and a dictionary mapping channels to indices (channel2index). - Performs clustering: - Calls _cluster_from_voice_prints_matrix to create speaker clusters based on voice similarity using the threshold and calibration settings. - Stores the cluster labels for each channel in the labels list. - Generates nodes: - Calls _generate_nodes to create a list of nodes (nodes) representing speaker clusters, likely using information from channels, channel2index, and labels. - Generates edges: - Calls _generate_edges to create a list of edges (edges) representing relationships between speakers, likely based on co-occurrence in conversations or calls. - The directed flag determines whether to create directed edges (indicating caller-callee relationships) or undirected edges (representing general connections). - Constructs the network: - Calls _construct_network (presumably a separate function) to build the final network structure using the generated nodes and edges. - The specific implementation of _construct_network would determine the format and properties of the network (e.g., graph data structure, edge weights, etc.). - Returns the network: - Returns the constructed network representation for further analysis or visualization. Relies on other functions for clustering, node/edge generation, and network construction. Creates a network based on speaker clusters and their relationships. Allows for directed or undirected network representation. Can be customized through parameters for clustering and edge creation. ''' def parse_wp5_output_for_aegis(wp5_outputs, threhold=50, calibration=False, directed=False): """ build network from output of wp5 :param wp5_outputs: dictionary converted from WP5's JSON object :param directed: :return: """ # build channel-2-index map channels, channel2index = _generate_channels_and_index(wp5_outputs) # print(channels) # cluster labels = _cluster_from_voice_prints_matrix(channel2index, wp5_outputs, threhold, calibration) print('labels:', labels) # generate nodes nodes = _generate_nodes_aegis(channels, channel2index, labels) print(nodes) # generate edges: # edges = _generate_edges(channel2index, labels, wp5_outputs, directed) edges = _generate_edges_aegis(channel2index, labels, wp5_outputs, directed) print(edges) phone_number_edges = _generate_phone_number_edges_aegis(wp5_outputs, directed) print(phone_number_edges) # construct network network = _construct_network_aegis(nodes, edges, phone_number_edges, directed) # print(network) return network ''' Processes the output of WP5 (voice analysis and identification system) to build a network representation suitable for Aegis. This network incorporates both speaker clusters and phone numbers as nodes, along with different types of edges based on speaker co-occurrence and phone number co-occurrence in conversations. Parameters: - wp5_outputs: A dictionary containing WP5's output data. - threshold: Threshold value for speaker clustering (likely based on voice similarity). - calibration: Boolean flag for applying calibration to data. - directed: Boolean flag for creating directed or undirected network. Steps: - Channel-to-index mapping: - Similar to parse_wp5_output, generates a list of channels (channels) and a dictionary mapping channels to indices (channel2index). - Speaker clustering: - Calls _cluster_from_voice_prints_matrix to create speaker clusters using the threshold and calibration settings. - Stores cluster labels for each channel in labels. - Generating speaker nodes: - Calls _generate_nodes_aegis to create a list of nodes (nodes) representing speaker clusters, potentially considering additional information like channels. - Generating speaker-to-speaker edges: - Calls _generate_edges_aegis (different from _generate_edges) to create speaker-to-speaker edges (edges) based on co-occurrence in conversations. - Considers directed/undirected based on the directed flag. - This function likely focuses on speaker relationships and might consider factors like call direction. - Generating phone number edges: - Calls _generate_phone_number_edges_aegis to create edges (phone_number_edges) based on phone number co-occurrence in conversations. - Considers directed/undirected based on the directed flag. - This function likely builds connections between phone numbers themselves. - Constructing Aegis network: - Calls _construct_network_aegis (different from _construct_network) to build the final network incorporating: - Speaker nodes from nodes. - Speaker-to-speaker edges from edges. - Phone number edges from phone_number_edges. - The specific network format and properties depend on the implementation of _construct_network_aegis. - Returning the network: - Returns the constructed network representation for further analysis or visualization within Aegis. Builds a network with speaker clusters, phone numbers, and different edge types for Aegis analysis. Leverages separate functions for speaker clustering, node/edge generation, and network construction. Allows for directed/undirected networks based on the directed flag. Likely uses speaker co-occurrence, phone number co-occurrence, and potentially call direction information. ''' def dataset_from_wp5_output(network): """ :param network: list of dictionary, each is a node or an edge :return: """ dataset = BuiltinDataset(path_2_data=None, uploaded=False, from_file=False) dataset.nodes = {} dataset.edges = [] dataset.adj_list = {} dataset.in_adj_list = {} dataset.node_types = {} dataset.edge_types = {} dataset.recent_changes = [] for element in network: if element['type'] == 'node': node = element['properties'] if 'community' in element: node['community'] = element['community'] node['community_confidence'] = element['community_confidence'] if 'social_influence_score' in element: node['social_influence_score'] = element['social_influence_score'] node['normalized_social_influence'] = element['normalized_social_influence'] dataset.nodes[element['id']] = node if 'type' in node: node_type = node['type'] if node_type in dataset.node_types: dataset.node_types[node_type] += 1 else: dataset.node_types[node_type] = 1 elif element['type'] == 'edge': edge = {'source': element['source'], 'target': element['target'], 'observed': True, 'properties': element['properties']} if 'observed' in element: if element['observed'] == 'false': edge['observed'] = 'false' dataset.edges.append(edge) e_index = len(dataset.edges) - 1 source = edge['source'] if source in dataset.adj_list: dataset.adj_list[source].append(e_index) else: dataset.adj_list[source] = [e_index] target = edge['target'] if target in dataset.in_adj_list: dataset.in_adj_list[target].append(e_index) else: dataset.in_adj_list[target] = [e_index] if 'type' in element['properties']: edge_type = element['properties']['type'] if edge_type in dataset.edge_types: dataset.edge_types[edge_type] += 1 else: dataset.edge_types[edge_type] = 1 else: continue return dataset ''' Takes a network representation generated from WP5 output (speaker clusters and relationships) as input. Constructs a BuiltinDataset object, likely for use within a specific analysis framework. Organizes the network data into a structured format with nodes, edges, and additional metadata for efficient analysis. Steps: - Creates a BuiltinDataset object: - Initializes a BuiltinDataset instance to hold the network data. - Sets appropriate attributes indicating the data is not uploaded from a file or external source. - Populates node and edge data: - Iterates through each element in the input network: - Extracts node properties and adds them to the dataset.nodes dictionary. - Optionally adds community and social influence information if available in the element. - Updates the dataset.node_types dictionary to count the frequency of each node type. - If the element is an edge: - Extracts edge properties and adds them to the dataset.edges list. - Updates the dataset.adj_list and dataset.in_adj_list dictionaries to create adjacency lists for efficient edge lookup. - Updates the dataset.edge_types dictionary to count the frequency of each edge type. - Returns the dataset: - Returns the constructed BuiltinDataset object containing the organized network data for further analysis. Converts a network representation into a specific dataset format. Stores nodes, edges, and metadata for analysis. Creates adjacency lists for efficient edge traversal. Maintains counts of node and edge types. '''
export interface IGeocodeData { lat: string; lon: string; } export interface ILocation { address: { city: string; municipality: string; city_district: string; state: string; } } export interface IWeather { current_weather: { is_day: number; temperature: number; time: string; weathercode: number; winddirection: number; windspeed: number; }, daily: { sunrise: Array<string>; sunset: Array<string>; temperature_2m_max: Array<number>; temperature_2m_min: Array<number>; time: Array<string>; uv_index_max: Array<number>; weathercode: Array<number>; } } export interface IWeathercode { [key: number]: { title: string; icon: string; }; } export interface IAddress { address: string } export type AddressContextType = { address: IAddress; setAddress: (address: IAddress) => void; }
import React, {useState} from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardHeader from "@material-ui/core/CardHeader"; import Avatar from "@material-ui/core/Avatar"; import IconButton from "@material-ui/core/IconButton"; import { ButtonBase, CardActionArea } from "@material-ui/core"; import {Typography} from "@material-ui/core"; import ViewReferralDialog from "./ViewReferralDialog"; function ReferralCard(props) { //Handle dialogs const [openDialogName, setOpenDialog] = React.useState(null); const closeDialog = () => { setOpenDialog(false); }; const openViewReferralDialog = () => { setOpenDialog(true); }; return(<div> <Card > <CardActionArea onClick= {openViewReferralDialog} > <CardHeader avatar={ <Avatar aria-label="recipe" style={{ margin: "10px", width: "100px", height: "100px", align: "center" }} src={props.img}> </Avatar> } title= {props.name} titleTypographyProps={{variant:'h5' }} subheader={props.position} subheaderTypographyProps={{variant: 'subtitle1'}} action='' /> <Typography style={{padding: "20px"}}>{props.description}</Typography> </CardActionArea> </Card> <ViewReferralDialog open={openDialogName === true} handleClose={closeDialog} name={props.name} position={props.position} email={props.email} description={props.description}></ViewReferralDialog> </div>); } export default ReferralCard;
import React from 'react'; import InventoryIcon from '@mui/icons-material/Inventory'; import { Link } from 'react-router-dom'; import "./Home.scss"; import heroImg from "../../assets/inventory.jpg"; import { ShowOnLogin, ShowOnLogout } from '../../components/protect/HiddenLink'; const Home = () => { return ( <div className='home'> <nav className='container --flex-between'> <div className="logo"> <InventoryIcon /> </div> <ul className="home-links"> <ShowOnLogout> <li> <Link to="/register" > Register </Link> </li> </ShowOnLogout> <ShowOnLogout> <li> <button className="--btn --btn-primary"> <Link to="/login"> Login </Link> </button> </li> </ShowOnLogout> <ShowOnLogin> <li> <button className="--btn --btn-primary"> <Link to="/dashboard"> Dashboard </Link> </button> </li> </ShowOnLogin> </ul> </nav> {/* HERO SECTION */} <section className="container hero"> <div className="hero-text"> <h2> Inventory & Stock Management Solution </h2> <p> Inventory system to control and manage products in the warehouse in real time and integrated to make it easier to develop your business. </p> <div className="hero-buttons"> <button className="--btn --btn-secondary"> <Link to="/subscribe"> Free Trial 1 Month </Link> </button> </div> <div className="--flex-start"> <NumberText num="14K" text="Brand Owners" /> <NumberText num="23K" text="Active Users" /> <NumberText num="500+" text="Partners" /> </div> </div> <div className="hero-image"> <img style={{height:"100%", width:"100%"}} src={heroImg} alt="inventory" /> </div> </section> </div> ) } const NumberText = ({num, text}) => { return ( <div className="--mr"> <h3 className='--color-white'>{num}</h3> <p className='--color-white'>{text}</p> </div> ) } export default Home
<?php use Auth0\Laravel\Facade\Auth0; use Illuminate\Support\Facades\Route; use Inertia\Inertia; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ // 以下のURLは、Auth0 のSDKが自動で生成・登録してくれている。 /* /login /logout /callback */ // 動作確認用の仮々実装 Route::get('/', function () { $message = 'You are not logged in.'; $user = null; if (auth()->check()) { $user = auth()->user(); $name = $user->name ?? 'User'; $email = $user->email ?? ''; $message = "Hello {$name}! Your email address is {$email}."; } $payload = [ 'message' => $message, 'user' => $user, ]; return Inertia::render('IndexPage', $payload); }); // Auth0 sample // see https://auth0.com/docs/quickstart/webapp/laravel/interactive Route::middleware('auth')->group(function () { // 認可が必要なページのサンプル Route::get('/private', function () { // \Log::debug(var_export(auth()->user(), true)); return response('Welcome! You are logged in.'); }); // Auth0 上で設定した権限の有無をチェックするサンプル Route::get('/scope', function () { return response('You have `read:messages` permission, and can therefore access this resource.'); })->can('read:messages'); // Auth0 のユーザの設定を更新するサンプル Route::get('/colors', function () { $endpoint = Auth0::management()->users(); $colors = [ 'red', 'blue', 'green', 'black', 'white', 'yellow', 'purple', 'orange', 'pink', 'brown', ]; $endpoint->update( id: auth()->id(), body: [ 'user_metadata' => [ 'color' => $colors[random_int(0, count($colors) - 1)] ] ] ); $metadata = $endpoint->get(auth()->id()); $metadata = Auth0::json($metadata); $color = $metadata['user_metadata']['color'] ?? 'unknown'; $name = auth()->user()->name; return response("Hello {$name}! Your favorite color is {$color}."); }); });
// Palette $primary: #414C3C; $primary-white: #C1CBBD; $primary-light: #939E8E; $primary-dark: #262D23; // Breakpoints and sizes $bp-s: 600px; $bp-m: 1200px; $bp-l: 1600px; $border-radius: 2px; $fixed-margin: 10px; $drop: 0.3rem; // Curves $duration-s: 0.08s; $duration-m: 0.27s; $in-s: $duration-s ease-in; $out-s: $duration-s ease-out; $inout-s: $duration-s ease-in-out; $in-m: $duration-m ease-in; $out-m: $duration-m ease-out; $inout-m: $duration-m ease-in-out; /* Width is divided into breakpoints: ] 1 ] [ 2 ] [ 3 ] [ 4 [ ^ ^ ^ ------ S ----- M ----- L -----> The first breakpoint also includes devices with a height under S */ // Breakpoint-focused behaviour // /!\ Queries are not complementary: 1 + 234 = 1234 but 1 + 23 != 123 @mixin breakpoint($bp) { @if $bp == 1 { @media (max-width: $bp-s), (max-height: $bp-s) { @content; }} @else if $bp == 12 { @media (max-width: $bp-m) { @content; }} @else if $bp == 123 { @media (max-width: $bp-l) { @content; }} @else if $bp == 4 { @media (min-width: $bp-l) { @content; }} @else if $bp == 34 { @media (min-width: $bp-m) { @content; }} @else if $bp == 234 { @media (min-width: $bp-s), (min-height: $bp-s) { @content; }} @else if $bp == 2 { @media (min-width: $bp-s) and (max-width: $bp-m) { @content; }} @else if $bp == 3 { @media (min-width: $bp-m) and (max-width: $bp-l) { @content; }} @else if $bp == 23 { @media (min-width: $bp-s) and (max-width: $bp-l) { @content; }} } // Property-focused behaviour @mixin responsive($properties) { @media (max-width: $bp-s), (max-height: $bp-s) { @each $p in $properties { #{nth($p, 1)}: nth($p, 2); } } @media (min-width: $bp-s) and (min-height: $bp-s) and (max-width: $bp-m) { @each $p in $properties { #{nth($p, 1)}: nth($p, 3); } } @media (min-width: $bp-m) and (max-width: $bp-l) { @each $p in $properties { #{nth($p, 1)}: nth($p, 4); } } @media (min-width: $bp-l) { @each $p in $properties { #{nth($p, 1)}: nth($p, 5); } } } // Vanilla full-size element @mixin full() { height: 100%; left: 0; position: absolute; top: 0; width: 100%; } // Flex column or row @mixin flex($dir, $center: true) { display: flex; @if $dir == col { flex-flow: column; } @if $dir == row { flex-flow: row; } @if $center { align-items: center; justify-content: center; } } @mixin modal() { background-color: white; border: 1px solid $grayscale-light; border-radius: $border-radius; } @mixin highlight() { border: 1px solid transparent; @include breakpoint(1) { &:active { background-color: $primary-light; border-color: $primary-dark; } } @include breakpoint(234) { &:hover, &:active { background-color: $primary-light; } &:active { border-color: $primary-dark; } } } @mixin input-base() { background-color: transparent; border: 1px solid transparent; border-radius: $border-radius; box-shadow: none; box-sizing: border-box; color: $primary-dark; display: block; font-size: 1rem; font-weight: inherit; margin: 0; min-width: 0; outline: none; padding: 0 0.5rem; -webkit-appearance: none; &:hover, &:active { border-color: $primary; } &::placeholder { opacity: 0.5; } &::-moz-focus-inner { border: none; } } // Reset and basic styling of inputs @mixin input-flat() { @include input-base(); border-color: $primary; box-shadow: $soft-shadow; padding: 0.7rem 1rem; &[type=text], &[type=email], &[type=password] &[type=tel] { background-color: white; color: $primary-dark; &:hover, &:active, &:focus { background-color: $primary-white; } } &[type=button], &[type=submit], &[type=reset] { @include highlight(); background-color: $primary; color: white; cursor: pointer; } } @mixin round-children() { & > *:first-child { border-bottom-left-radius: $border-radius; border-top-left-radius: $border-radius; } & > *:not(:first-child) { border-bottom-left-radius: 0; border-top-left-radius: 0; } & > *:last-child { border-bottom-right-radius: $border-radius; border-top-right-radius: $border-radius; } & > *:not(:last-child) { border-bottom-right-radius: 0; border-top-right-radius: 0; } }
require 'rails_helper' RSpec.describe Comment, type: :model do describe 'validation check' do let(:comment) { build(:comment) } context 'validation success' do it 'passes all validations' do expect(comment).to be_valid expect(comment.errors).to be_empty end end context 'validation failed' do it 'fails validation when body is nil' do comment.body = nil expect(comment).to be_invalid expect(comment.errors[:body]).to include("を入力してください") end it 'fails validation when body length is over 65,535 characters' do comment.body = 'a' * (Comment.validators_on(:body).find { |v| v.options[:maximum] }.options[:maximum] + 1) expect(comment).to be_invalid expect(comment.errors[:body]).to include("は65535文字以内で入力してください") end end end end
#!/usr/bin/python3 import sys def is_safe(board, row, col, N, result): for i in range(col): if board[i] == row or board[i] - i == row - col or board[i] + i == row + col: return False return True def solve_nqueens(board, col, N, result): if col == N: result.append(board[:]) return for i in range(N): if is_safe(board, i, col, N, result): board[col] = i solve_nqueens(board, col + 1, N, result) def nqueens(N): if not isinstance(N, int): print("N must be a number") sys.exit(1) if N < 4: print("N must be at least 4") sys.exit(1) board = [-1] * N result = [] solve_nqueens(board, 0, N, result) for res in result: print([[i, res[i]] for i in range(N)]) if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: nqueens N") sys.exit(1) try: N = int(sys.argv[1]) nqueens(N) except ValueError: print("N must be a number") sys.exit(1)
<div class="class"> <div class="form-card" style="margin-top: 120px;"> <h2> NOUVEAU SITE </h2> <form [formGroup]="sites"> <div class="form-group"> <label for="titre">Titre</label> <input id="titre" type="text" formControlName="titre"> </div> <div class="form-group"> <label for="description">Contenu</label> <textarea id="description" type="text" formControlName="contenu" rows="4"> </textarea> </div> <div class="form-group"> <label for="imageUrl">URL de l'image</label> <input id="imageUrl" type="text" formControlName="imageUrl"> </div> <div class="form-group"> <label for="adresse">Adresse</label> <input id="adresse" type="text" formControlName="adresse"> </div> <div class="form-group"> <label for="region">Region</label> <!--<input id="region" type="text" formControlName="region">--> <select id="region" type="text" formControlName="region" style="width: 50%;"><!--requetes back--> <option>Centre</option> <option>Littoral</option> <option>Est</option> <option>Ouest</option> <option>Sud</option> <option>Nord</option> <option>Extreme-Nord</option> <option>Adamaoua</option> <option>Sud-Ouest</option> <option>Nord-Ouest</option> </select> </div> <div class="form-group"> <label for="ville">Ville</label><!--requetes back--> <input id="ville" type="text" formControlName="ville"> </div> <div class="form-group"> <label for="categorie">Categorie</label><!--requetes back--> <input id="categorie" type="text" formControlName="categorie"> </div> <div class="form-group"> <label for="type">Type</label><!--requetes back--> <input id="type" type="text" formControlName="type"> </div> <div class="form-group"> <label for="latitude">Latitude</label> <input id="latitude" type="text" formControlName="latitude"> </div> <div class="form-group"> <label for="longitude">Longitude</label> <input id="longitude" type="text" formControlName="longitude"> </div> <div class="action-buttons"> <button type="submit" (click)="onSubmitForm()">Enregistrer</button> </div> </form> </div> <div class="site-view-card" *ngIf="sitePreview$ | async as sites"> <!--<p>Mis en ligne {{ sites.createDate | date: 'à HH:mm, le d MMMM yyyy' }}</p>--> <img [src]='sites.imageUrl' [alt]="sites.titre"> <h2>{{ sites.titre | uppercase }}</h2> <p>{{ sites.contenu }}</p> <p *ngIf="sites.adresse">Photo prise à {{ sites.adresse }}</p> </div> </div>
@extends('layouts.settings') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-sm-12 offset-md-2 mt-5"> <div class="card card-shadow"> <div class="card-header"> <div class="d-flex justify-content-between"> <h5 class="mt-2">Change Password </h5> <a href="{{route('setting.user_index')}}" style="margin-right: 10px"> <img src="/image/list.png" alt="" height="25px"> </a> </div> </div> <div class="card-body"> <form id="userFrom"> <div class="row"> <div class="col-lg-12 col-md-6 col-sm-12 mb-3"> <div class="form-group"> <label>Old Password <span class="text-danger">*</span></label> <input type="text" class="form-control" v-model="user.old_password" placeholder="Enter Old Password" required> <span class="text-danger" v-if="errors.old_password" v-text="errors.old_password[0]"></span> </div> </div> <div class="col-lg-12 col-md-6 col-sm-12 mb-3"> <div class="form-group"> <label>New Password <span class="text-danger">*</span></label> <input type="text" class="form-control" v-model="user.password" placeholder="Enter New Password" required> <span class="text-danger" v-if="errors.password" v-text="errors.password[0]"></span> </div> </div> <div class="col-lg-12 col-md-6 col-sm-12 mb-3"> <div class="form-group"> <label> Confirm Password <span class="text-danger">*</span></label> <input type="text" class="form-control" v-model="user.password_confirmation" placeholder="Enter Confirm Password" required> </div> </div> </div> </form> </div> <div class="card-footer"> <div class="form-group d-flex justify-content-end"> <button type="submit" class="btn-submit" @click.prevent='storeData'>Submit</button> </div> </div> </div> </div> </div> </div> <script type="text/javascript"> $(document).ready(function () { $(document).ready(function() { $('#role_id').select2(); }); var vue = new Vue({ el: '#app', data: { config: { base_path: "{{ env('APP_URL') }}", token: "{{ session('token') }}", }, user:{ old_password: '', password: '', password_confirmation: '', }, errors:[], }, methods: { storeData() { let token = this.config.token; axios.post(`${this.config.base_path}/setting/change_password?token=${token}`, this.user).then((response) => { toastr.success(response.data.message); }).catch((error) => { if (error.response.status == 422) { console.log(error.response.data.errors); this.errors = error.response.data.errors toastr.error('Validation error'); return false; } if (error.response.status == 400) { toastr.error(error.response.data.error); return false; } toastr.error("Something went wrong"); }); }, }, }); }); </script> @endsection
import "./profile.css"; import { useEffect, useState } from "react"; import Followers from "../../assets/img/followers.png"; import { NavLink } from "react-router-dom"; export const Profile = () => { const [myData, setMyData] = useState([]); const [pro, setPro] = useState("muhammadali0666"); useEffect(() => { async function getData() { const res = await fetch(`https://api.github.com/users/${pro}`) .then((res) => res.json()) .then((data) => setMyData(data)); } getData(); }, []); return ( <div> <img className="profile-img mt-4" src={myData.avatar_url} alt="logo" /> <p className="profile-user-name my-3">{myData.login}</p> <button className="profile-btn rounded-2 py-1 fw-semibold">Edit profile</button> <div className="profile-box mt-3"> <div className="profile-box-in d-flex align-items-center"> <img className="me-2" src={Followers} alt="img" width={20} height={20} /> <NavLink to="/follower" className="profile-follower text-dark"> <p className="profile-follower "> <span className="profile-span fw-bold me-2"> {myData.followers} </span> followers </p> </NavLink> <NavLink to="/following" className="profile-follower text-dark"> <p className="profile-follower ms-2"> <span className="profile-span fw-bold me-2"> {myData.following} </span> following </p> </NavLink> </div> </div> </div> ); };
// ignore_for_file: prefer_const_literals_to_create_immutables, prefer_const_constructors, use_build_context_synchronously import 'package:fluttertoast/fluttertoast.dart'; import 'package:provider/provider.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:whatsapp_clone/data/models/user_model.dart'; import 'package:whatsapp_clone/providers/auth_provider.dart'; import 'package:whatsapp_clone/providers/user_provider.dart'; import 'package:whatsapp_clone/screens/home.dart'; import 'package:whatsapp_clone/tabs/home_tab.dart'; import 'package:whatsapp_clone/screens/signup.dart'; import 'package:whatsapp_clone/utils/helper.dart'; import 'package:whatsapp_clone/utils/necessary_methods.dart'; import 'package:whatsapp_clone/widgets/primary_button.dart'; import 'package:whatsapp_clone/widgets/title_widget.dart'; class LogIn extends StatefulWidget { const LogIn({super.key}); @override State<LogIn> createState() => _LogInState(); } class _LogInState extends State<LogIn> { bool showPassword = true; late IconData lockIcon = Icons.visibility; TextEditingController email = TextEditingController(text: 'minhaz@gmail.com'); TextEditingController password = TextEditingController(text: '12345678'); handleSignInwithemailPassword() async { final FirebaseAuthProvider sb = Provider.of<FirebaseAuthProvider>(context, listen: false); var ub = context.read<UserProvider>(); SharedPreferences sp = await SharedPreferences.getInstance(); NecessaryMethods.showLoaderDialog(context: context, title: 'Loading...'); try { await sb .signInwithEmailPassword(email.text, password.text) .then((_) async { if (sb.hasError == false) { ub .saveUserData( UserModel( userId: 'ksdf', userName: 'userName', emailId: email.text, phone: 'phone', ), 'email') .then((_) async { await sp.setBool("isSignedIn", true); Helper.nextScreenCloseOthers( context, Home(), ); }); } else { NecessaryMethods.showMessage(sb.errorCode.toString()); } }); } catch (e) { Fluttertoast.showToast(msg: 'Error: $e'); } } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar(), body: GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: Padding( padding: const EdgeInsets.all(18.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 10, ), TitleWidget( title: 'Log In', subTitle: 'Welcome to the Whatsapp Clone', ), SizedBox( height: 45, ), TextFormField( controller: email, keyboardType: TextInputType.emailAddress, onEditingComplete: handleSignInwithemailPassword, decoration: InputDecoration( prefixIcon: Icon( Icons.email_outlined, ), hintText: 'E-mail'), ), SizedBox(height: 15), TextFormField( controller: password, obscureText: showPassword, onEditingComplete: handleSignInwithemailPassword, decoration: InputDecoration( suffixIcon: CupertinoButton( padding: EdgeInsets.all(0), onPressed: () { setState(() { showPassword = !showPassword; lockIcon = lockIcon == Icons.visibility ? Icons.visibility_off : Icons.visibility; }); }, child: Icon( lockIcon, color: Colors.grey, ), ), prefixIcon: Icon( Icons.lock_open_outlined, ), hintText: 'Password'), ), SizedBox(height: 35), PrimaryButton( title: 'Log In', onPressed: handleSignInwithemailPassword, ), // CustomRoundedLoadingButton2( // doSomething: () async { // handleSignInwithemailPassword; // }, // title: 'Log In', // ), SizedBox(height: 18), Center(child: Text('Do not have an account?')), SizedBox(height: 0), Center( child: CupertinoButton( padding: EdgeInsets.all(0), onPressed: () { Helper.toScreen(context, SignUp()); }, child: Text( 'create account', style: TextStyle(color: Theme.of(context).primaryColor), ), ), ), ], ), ), ), ); } }
import React, { useState } from 'react'; import PropTypes from 'prop-types'; import '../App/App.css'; const initialValues = { meterNumber: '', amount: '', } const PowerCash = ({ change }) => { const [state, setState] = useState(initialValues); const handleChange = e => { let { value, name } = e.target; setState({ ...state, [name]: value, }); }; const handleSubmit = () => { change(state); setState(initialValues); }; return ( <> <div className="row"> <div> <label htmlFor="meterNumber">Meter Number</label> <input id="meterNumber" name="meterNumber" type="number" min="999999" max="999999" placeholder="Enter the meter number" value={state.meterNumber} onChange={handleChange} /> </div> <div> <label htmlFor="amount">Rwf Amount</label> <input id="amount" name="amount" type="number" min="100" max="9000000" placeholder="Enter your amount payment" value={state.amount} onChange={handleChange} /> </div> </div> <div className="center"> <button id="bmi-btn" className="calculate-btn" type="button" disabled={state.meterNumber === '' || state.amount === ''} onClick={handleSubmit} > Buy Electricity </button> </div> </> ); }; PowerCash.propTypes = { change: PropTypes.func.isRequired }; export default PowerCash;
import 'dart:convert'; import 'dart:developer'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:food_app/controllers/create_post_controller.dart'; import 'package:food_app/controllers/login_controller.dart'; import 'package:food_app/controllers/photo_upload_controller.dart'; import 'package:food_app/controllers/signin_controller.dart'; import 'package:food_app/screens/auth_screen.dart'; import 'package:get/get.dart'; import 'firebase_options.dart'; void main()async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform,); runApp(const FoodApp()); } class FoodApp extends StatelessWidget { const FoodApp({super.key}); @override Widget build(BuildContext context) { return GetMaterialApp( theme: ThemeData( primarySwatch: Colors.teal, inputDecorationTheme: InputDecorationTheme( filled: true, hintStyle: TextStyle(color: Colors.grey.shade400), border: OutlineInputBorder(borderRadius: BorderRadius.circular(8),), enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(8),), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Colors.teal, width: 2)), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.teal, padding: const EdgeInsets.symmetric(horizontal: 60,vertical: 15), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ) ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( textStyle: const TextStyle(fontWeight: FontWeight.w400,fontSize: 16) ) ), outlinedButtonTheme: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( padding: EdgeInsets.symmetric(horizontal: 30,vertical: 20) ) ) ), home: AuthScreen(), initialBinding: BindingController(), ); } } class BindingController extends Bindings{ @override void dependencies() { Get.put(SignInController()); Get.put(LoginController()); Get.put(PhotoUploadController()); Get.put(CreatePostController()); } }
import { PackType } from 'src/service-pack/enums/pack.enum'; import { Lessor } from '../../../entities/lessor.entity'; import { LessorRank, LessorStatus } from '../../../enums/lessor.enum'; import { UserResDto } from './user.res.dto'; export class LessorResDto { id: number; name: string; email: string; status: LessorStatus; rank: LessorRank; address: string; phoneNumber: string; user?: UserResDto; avatar?: string; package: PackType; static mapProperty(dto: LessorResDto, data: Lessor) { dto.id = data.id; dto.name = data.name; dto.email = data.email; dto.address = data.address; dto.phoneNumber = data.phoneNumber; dto.avatar = data.avatar?.path ? data.avatar?.path : null; dto.package = data.packType; } static forLessor(data?: Lessor) { const result = new LessorResDto(); if (!data) return result; this.mapProperty(result, data); result.user = UserResDto.forLessor(data.user); return result; } static forAdmin(data?: Lessor) { const result = new LessorResDto(); if (!data) return result; this.mapProperty(result, data); result.status = data.status; result.rank = data.rank; result.user = UserResDto.forAdmin(data.user); // result.avatar = FileResDto.forAdmin(data.avatar); return result; } }
<?php namespace Database\Factories; use App\Models\ContactPeople; use App\Models\People; use Illuminate\Database\Eloquent\Factories\Factory; class ContactPeopleFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = ContactPeople::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'people_id' => People::factory()->create()->id, 'contact_id' => 1, 'contato' => $this->faker->email, ]; } }
/** * SPDX-FileCopyrightText: (c) 2000 Liferay, Inc. https://liferay.com * SPDX-License-Identifier: LGPL-2.1-or-later OR LicenseRef-Liferay-DXP-EULA-2.0.0-2023-06 */ package com.liferay.jethr0.git.branch; import com.liferay.jethr0.entity.factory.BaseEntityFactory; import com.liferay.jethr0.event.github.client.GitHubClient; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; /** * @author Michael Hashimoto */ @Configuration public class GitBranchEntityFactory extends BaseEntityFactory<GitBranchEntity> { @Override public String getEntityPluralLabel() { return "Git Branches"; } @Override public GitBranchEntity newEntity(JSONObject jsonObject) { GitBranchEntity gitBranchEntity = null; GitBranchEntity.Type type = GitBranchEntity.Type.get( jsonObject.getJSONObject("type")); if (type == GitBranchEntity.Type.SENDER) { gitBranchEntity = new SenderGitBranchEntity(jsonObject); } else if (type == GitBranchEntity.Type.UPSTREAM) { gitBranchEntity = new UpstreamGitBranchEntity(jsonObject); } else { gitBranchEntity = new DefaultGitBranchEntity(jsonObject); } gitBranchEntity.setGitHubClient(_gitHubClient); return gitBranchEntity; } protected GitBranchEntityFactory() { super(GitBranchEntity.class); } @Autowired private GitHubClient _gitHubClient; }
# C刷题:找两个数之间位数为偶数的个数 **目录** [toc] **Git项目地址**:[LeetCodeUsingC刷题笔记](https://github.com/ioMayday/leetcode_sol) ## 题目描述 --- **题目:** > 给定正整数N、M,均介于1~10^9之间,N<=M,找出两者之间(含N、M)的位数为偶数的数有多少个。 **测试用例:** > 输入:N = 1, M = 100 > 输出:90 > 样例说明:[1,100]区间上,有10~99元素的位数是2位,是偶数,这些整数的数量为90。 > 输入:N = 1, M = 1000 > 输出:91 > 样例说明:在上个样例结果上,加上一个1000这个位数为偶数的数,即90 + 1 = 91。 ## 分析 ---- 数据输入小于`2^31=2,147,483,648`,可以用int来保存。 ### 方法一 该方法是最容易想到的方法,易推广。 - 得到n,m的位数 - 若n,m位数相同: - 为偶数,则返回 `m - n + 1` - 为奇数,则返回0 - 若n,m位数不同: - 分别判断起止区间n和m位数 - 若n的位数为偶数,则 `位数的末端数 - n + 1`;如位数是`2`,则 `99 - n + 1` (`99 = 10^2 - 1`) - 若m的位数为偶数,则 `m - 位数的起始数 + 1`;如位数是`2`,则 `m - 10 + 1` (`10 = 10^(2 - 1)`) - 其他情况,则不处理 - 从n的位数+1遍历到m的位数-1 - 若位数为偶数,则直接乘对应整段区间数 ### 方法二 该方法代码精简,思路清晰。 - 10^9范围有限,直接划分出位数为偶数的区间 - 遍历所有区间,检测n,m落在这些区间的情况 - 找到m归属情况后可退出遍历 ## C代码 ---- 方法一: ```c #define BASE_OCT 10 #define STEP 2 #define EVEN_BASE 2 int GetBitsNum(int val) { int bit = 0; while (val != 0) { val /= BASE_OCT; bit++; } return bit; } int mostDouble2(int n, int m) { int even = 0; int bitN = GetBitsNum(n); int bitM = GetBitsNum(m); if (bitN == bitM) { if (bitN % 2 == 0) { return m - n + 1; } return 0; } if (bitN % EVEN_BASE == 0) { even += (int)pow(10, bitN) - 1 - n + 1; // 9999 = 10000 - 1 } else { bitN++; // 调整为偶数起 } if (bitM % EVEN_BASE == 0) { even += m - (int)pow(10, bitM - 1) + 1; } int i; for (i = bitN; i < bitM; i += STEP) { even += (int)pow(10, i) - 1 - (int)pow(10, i - 1) + 1; } return even; } ``` 方法二: ```c #define ROW 5 #define COL 2 const int g_evenRanges[ROW][COL] = { {10, 99}, {1000, 9999}, {100000, 999999}, {10000000, 9999999}, {1000000000, 1000000001}, }; int mostDouble2(int n, int m) { int even = 0; int i; for (i = 0; i < ROW; i++) { // n, m落在区间内 if (n >= g_evenRanges[i][0] && m <= g_evenRanges[i][1]) { return even = m - n + 1; } // n 落在区间左侧 if (n >= g_evenRanges[i][0] && n <= g_evenRanges[i][0] && m > g_evenRanges[i][1]) { even += g_evenRanges[i][1] - n + 1; } // n, m 中间的区间数累加 if (n < g_evenRanges[i][0] && m > g_evenRanges[i][1]) { even += g_evenRanges[i][1] - g_evenRanges[i][0] + 1; } // m 落在区间右侧 if (n < g_evenRanges[i][0] && m >= g_evenRanges[i][0] && m <= g_evenRanges[i][1]) { even += m - g_evenRanges[i][0] + 1; break; // 已检测完[n, m]范围 } } return even; } ``` ## LeetCode相关题目 --- [1295. 统计位数为偶数的数字 (简单)](https://leetcode-cn.com/problems/find-numbers-with-even-number-of-digits/) 实现思路: - 直接遍历数组,循环调用方法一中的`GetBitsNum()`函数 - 记录调用结果能被2整除的次数即可
<!doctype html> <html ng-app="jsonApp"> <head> <title>BONJOUR</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> <style media="screen"> .sortorder:after { content: '\25b2'; } .sortorder.reverse:after { content: '\25bc'; } </style> </head> <body> <div ng-controller="jsonController"> <input type="text" ng-model="searchPerson" placeholder="Chercher dans la liste" autofocus> <table style="text-align:center"> <tr> <th><a ng-click="order('id')">id</a></th> <span class="sortorder" ng-show="predicate === 'id'" ng-class="{reverse:reverse}"></span> <th><a ng-click="order('firstname')">Prenom</a></th> <span class="sortorder" ng-show="predicate === 'firstname'" ng-class="{reverse:reverse}"></span> <th><a ng-click="order('surname')">Nom</a></th> <span class="sortorder" ng-show="predicate === 'surname'" ng-class="{reverse:reverse}"></span> <th><a ng-click="order('gender')">Sexe</a></th> <span class="sortorder" ng-show="predicate === 'gender'" ng-class="{reverse:reverse}"></span> <th><a ng-click="order('birthday')">Anniverssaire</a></th> <span class="sortorder" ng-show="predicate === 'birthday'" ng-class="{reverse:reverse}"></span> <th><a ng-click="order('height')">Taille</a></th> <span class="sortorder" ng-show="predicate === 'height'" ng-class="{reverse:reverse}"></span> </tr> <tr ng-repeat="people in person | filter:searchPerson | orderBy:predicate:reverse"> <td>{{people.id}}</td> <td>{{people.firstname}}</td> <td>{{people.surname}}</td> <td>{{people.gender}}</td> <td>{{people.birthday}}</td> <td>{{people.height}}</td> </tr> </table> </div> <script src="app.js"></script> </body> </html>
import React, { useState } from 'react'; import { Pencil, Trash } from 'phosphor-react'; import { Button } from '../../ui'; import Pagination from './OrderManagement/Pagination'; import InitialOrders from './OrderManagement/InitialOrders'; import getStatusColor from './OrderManagement/StatusColor'; const ITEMS_PER_PAGE = 6; const OrderManagement = () => { const initialOrders = InitialOrders(); const [orders, setOrders] = useState(initialOrders); const [editingOrderId, setEditingOrderId] = useState(null); const [editedOrders, setEditedOrders] = useState({}); const [currentPage, setCurrentPage] = useState(1); const handleEdit = (orderId, field, value) => { setEditedOrders((prevEditedOrders) => ({ ...prevEditedOrders, [orderId]: { ...prevEditedOrders[orderId], [field]: value }, })); setEditingOrderId(orderId); }; const handleSave = () => { setOrders((prevOrders) => prevOrders.map((order) => editedOrders[order.orderId] ? { ...order, ...editedOrders[order.orderId] } : order ) ); setEditedOrders({}); setEditingOrderId(null); }; const handleDelete = (orderId) => { setOrders((prevOrders) => prevOrders.filter((order) => order.orderId !== orderId)); }; const handlePageChange = (pageNumber) => { setCurrentPage(pageNumber); }; const indexOfLastOrder = currentPage * ITEMS_PER_PAGE; const indexOfFirstOrder = indexOfLastOrder - ITEMS_PER_PAGE; const currentOrders = orders.slice(indexOfFirstOrder, indexOfLastOrder); const totalPages = Math.ceil(orders.length / ITEMS_PER_PAGE); return ( <div className="md:mx-5 md:px-4 container mt-5 overflow-hidden"> <div className="flex md:flex-row flex-col bg-white justify-between items-center"> <div className="flex flex-col"> <h1 className="text-textPrimary font-playfair text-lg">Orders Management</h1> <p className="text-left md:text-sm mb-3 text-zinc-400">Order list</p> </div> <div className="flex gap-x-2 mb-4"> <Button variant="secondary" className="text-sm p-1 w-[140px] md:w-[180px]"> Filter </Button> <Button variant="primary" className="text-sm p-1 w-[140px] md:w-[180px]" onClick={handleSave}> Save Changes </Button> </div> </div> <div className="flex border border-[#F5F7FE] p-4 bg-[#F5F7FE] rounded-xl table-container md:overflow-x-hidden overflow-x-auto w-full"> <table className="min-w-full "> <thead className="text-black text-left"> <tr> <th className="py-3 px-2 uppercase font-semibold text-sm border-b">Order ID</th> <th className="py-3 px-2 uppercase font-semibold text-sm border-b">Name</th> <th className="py-3 px-2 uppercase font-semibold text-sm border-b">Address</th> <th className="py-3 px-2 uppercase font-semibold text-sm border-b">Pickup Location</th> <th className="py-3 px-2 uppercase font-semibold text-sm border-b">Drop Location</th> <th className="py-3 px-2 uppercase font-semibold text-sm border-b">Status</th> <th className="py-3 px-6 uppercase font-semibold text-sm border-b">Action</th> </tr> </thead> <tbody className="text-gray-600 text-sm"> {currentOrders.map((order, index) => ( <React.Fragment key={order.orderId}> <tr className='px-15' style={{ border: editingOrderId === order.orderId ? '2px solid #1F51FF' : '0px solid #F5F7FE', borderRadius: editingOrderId === order.orderId ? '9px' : '0px', fontWeight: editingOrderId === order.orderId ? 'bold' : 'normal', }}> <td className="py-5 px-2">{order.orderId}</td> <td className="py-3 px-2"> {editingOrderId === order.orderId ? ( <input type="text" className='p-2 w-[8rem]' value={(editedOrders[order.orderId]?.name !== undefined ? editedOrders[order.orderId].name : order.name) || ''} onChange={(e) => handleEdit(order.orderId, 'name', e.target.value)} style={{ backgroundColor: editingOrderId === order.orderId ? 'transparent' : '', }} /> ) : ( order.name )} </td> <td className="py-3 px-2"> {editingOrderId === order.orderId ? ( <input type="text" className='p-2 w-[8rem]' value={(editedOrders[order.orderId]?.address !== undefined ? editedOrders[order.orderId].address : order.address) || ''} onChange={(e) => handleEdit(order.orderId, 'address', e.target.value)} style={{ backgroundColor: editingOrderId === order.orderId ? 'transparent' : '', // Add this line for transparent background }} /> ) : ( order.address )} </td> <td className="py-3 px-2">{editingOrderId === order.orderId ? ( <input type="text" className='p-2 w-[8rem]' value={(editedOrders[order.orderId]?.pickupLocation !== undefined ? editedOrders[order.orderId].pickupLocation : order.pickupLocation) || ''} onChange={(e) => handleEdit(order.orderId, 'pickupLocation', e.target.value)} style={{ backgroundColor: editingOrderId === order.orderId ? 'transparent' : '', // Add this line for transparent background }} /> ) : ( order.pickupLocation )} </td> <td className="py-3 px-2">{editingOrderId === order.orderId ? ( <input type="text" className='p-2 w-[8rem]' value={(editedOrders[order.orderId]?.dropLocation !== undefined ? editedOrders[order.orderId].dropLocation : order.dropLocation) || ''} onChange={(e) => handleEdit(order.orderId, 'dropLocation', e.target.value)} style={{ backgroundColor: editingOrderId === order.orderId ? 'transparent' : '', // Add this line for transparent background }} /> ) : ( order.dropLocation )}</td> <td style={{ color: getStatusColor(order.status) }}>{editingOrderId === order.orderId ? ( <input type="text" className='p-2 w-[8rem]' value={(editedOrders[order.orderId]?.status !== undefined ? editedOrders[order.orderId].status : order.status) || ''} onChange={(e) => handleEdit(order.orderId, 'status', e.target.value)} style={{ backgroundColor: editingOrderId === order.orderId ? 'transparent' : '', // Add this line for transparent background }} /> ) : ( order.status )}</td> <td className="py-3 px-2"> {editingOrderId === order.orderId ? ( <button className="px-4 py-1 mr-2 text-sm text-green-600 bg-green-200 rounded-full" onClick={handleSave} > Save </button> ) : ( <div className="flex justify-center space-x-2"> <button className="px-2 py-1 text-sm rounded-full" onClick={() => setEditingOrderId(order.orderId)} > <Pencil size={20} /> </button> <button className="px-2 py-1 text-sm rounded-full" onClick={() => handleDelete(order.orderId)} > <Trash size={20} /> </button> </div> )} </td> </tr> {index < currentOrders.length - 1 && ( <tr> <td colSpan="7" className="border-t"></td> </tr> )} </React.Fragment> ))} </tbody> </table> </div> <Pagination totalPages={totalPages} currentPage={currentPage} onPageChange={handlePageChange} /> </div> ); }; export default OrderManagement;
import { Controller, Post, Body, HttpCode, HttpStatus, NotFoundException, BadRequestException, InternalServerErrorException } from '@nestjs/common'; import { ApiTags, ApiOperation } from '@nestjs/swagger'; import { CreateOrderDTO } from './market.dto'; import { BitfinexApiService } from '@shared/services/bitfinex-api.service'; @ApiTags('Market') @Controller('market') export class MarketController { // Limit operation (in USD) // We should persist this property dynamically in a BBDD private limit = 100_000; constructor( private readonly api: BitfinexApiService ) {} @Post('order') @ApiOperation({ summary: 'Get effective price of an order' }) @HttpCode(HttpStatus.CREATED) async postPriceAVG(@Body() payload: CreateOrderDTO) { // Step 1: Validate pair const pairsAvailable = await this.api.getPairsList(); let validatePair = null; if (pairsAvailable.data && pairsAvailable.data[0]) validatePair = pairsAvailable.data[0].findIndex((p: string) => { return p == payload.pair; }); if (validatePair == null || validatePair == -1) throw new NotFoundException(`The pair ${payload.pair} has not been found.`); // Step 2: Calculate effective price let currentPairPrice = null; let totalPrice = null; let response = null; if (payload.type == 'buy') { // Get price for Buy const order = await this.api.postPriceAVG(payload.pair, payload.amount); currentPairPrice = order.data[0]; totalPrice = currentPairPrice * payload.amount; if (totalPrice > this.limit) { const maxAvailable = this.limit / currentPairPrice; throw new BadRequestException(`The order exceeds the maximum amount available for a trade. Max available to BUY: ${maxAvailable} ${payload.pair}`); } response = { pair: payload.pair, typeOperation: payload.type, amount: payload.amount, currentPairPrice, totalToPay: totalPrice, expirationTime: '5s' } } else if (payload.type == 'sell') { // Get price for Sell const order = await this.api.postPriceAVG(payload.pair, payload.amount); currentPairPrice = order.data[0]; totalPrice = currentPairPrice * payload.amount; if (totalPrice > this.limit) { const maxAvailable = this.limit / currentPairPrice; throw new BadRequestException(`The order exceeds the maximum amount available for a trade. Max available to SELL: ${maxAvailable} ${payload.pair}`); } response = { pair: payload.pair, typeOperation: payload.type, amount: payload.amount, currentPairPrice, totalToReceive: totalPrice, expirationTime: '5s' } } else { throw new InternalServerErrorException(`Something went wrong.`); } return { statusCode: HttpStatus.CREATED, result: { data: response } } } }
using AnBlog.Api; using AnBlog.Api.Authorization; using AnBlog.Api.Filters; using AnBlog.Api.Services; using AnBlog.Core.ConfigOptions; using AnBlog.Core.Domain.Identity; using AnBlog.Core.Models.Content; using AnBlog.Core.SeedWorks; using AnBlog.Core.Services; using AnBlog.Data; using AnBlog.Data.SeedWorks; using AnBlog.Data.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System.Reflection; using System.Text; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c => { c.CustomOperationIds(apiDesc => { return apiDesc.TryGetMethodInfo(out MethodInfo methodInfo) ? methodInfo.Name : null; }); c.SwaggerDoc("AdminAPI", new OpenApiInfo { Version = "v1", Title = "API for Administrators", Description = "API for CMS core domain. This domain keeps track of campaigns, campaign rules, and campagin execution." }); c.ParameterFilter<SwaggerNullableParameterFilter>(); }); var AnBlogCorsPolicy = "AnPolicy"; builder.Services.AddCors(o => o.AddPolicy(AnBlogCorsPolicy, builderCors => { var origins = builder.Configuration["AllowedOrigins"]; builderCors .AllowAnyMethod() .WithOrigins(origins!) .AllowAnyHeader() .AllowCredentials(); })); builder.Services.AddDbContext<AnBlogContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddIdentity<AppUser, AppRole>(options => options.SignIn.RequireConfirmedAccount = false) .AddEntityFrameworkStores<AnBlogContext>() .AddDefaultTokenProviders(); builder.Services.Configure<IdentityOptions>(options => { // Password settings. options.Password.RequireDigit = true; options.Password.RequireLowercase = true; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 1; // Lockout settings. options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; // User settings. options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; }); builder.Services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = builder.Configuration["JwtTokenSettings:Issuer"], ValidAudience = builder.Configuration["JwtTokenSettings:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtTokenSettings:Key"]!)) }; }); builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>(); builder.Services.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>(); builder.Services.AddScoped(typeof(IRepository<,>), typeof(RepositoryBase<,>)); builder.Services.AddScoped<IUnitOfWork, UnitOfWork>(); // business services and repositories builder.Services.DynamicRegisterRepositories(); builder.Services.AddAutoMapper(typeof(PostInListDto)); builder.Services.Configure<JwtTokenSettings>(builder.Configuration.GetSection("JwtTokenSettings")); builder.Services.Configure<MediaSettings>(builder.Configuration.GetSection("MediaSettings")); builder.Services.AddScoped<ITokenService, TokenService>(); builder.Services.AddScoped<IRoyaltyService, RoyaltyService>(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("AdminAPI/swagger.json", "Admin API"); c.DisplayOperationId(); c.DisplayRequestDuration(); }); app.MigrateDatabase(); } app.UseStaticFiles(); app.UseCors(AnBlogCorsPolicy); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();
import 'package:actual/common/const/data.dart'; import 'package:actual/shop/component/shop_card.dart'; import 'package:actual/shop/model/shop_model.dart'; import 'package:actual/shop/view/shop_detailed_screen.dart'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; class ShopScreen extends StatelessWidget { Future<List> paginationShop() async { final dio = Dio(); final accessToken = await storage.read(key: ACCESS_TOKEN_KEY); final resp = await dio.get( "http://$ip/restaurant", options: Options( headers: { "authorization": "Bearer $accessToken", }, ), ); return resp.data["data"]; } const ShopScreen({super.key}); @override Widget build(BuildContext context) { return Container( child: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: FutureBuilder<List>( future: paginationShop(), builder: (context, AsyncSnapshot<List> snapshot) { if (!snapshot.hasData) { return Center( child: CircularProgressIndicator(), ); } return ListView.separated( itemBuilder: (_, index) { final item = snapshot.data![index]; final model = ShopModel.fromJson(item); return GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (_) => ShopDetailedScreen( id: model.id, ), ), ); }, child: ShopCard.fromModel( model: model, ), ); }, separatorBuilder: (_, index) { return SizedBox(height: 20.0); }, itemCount: snapshot.data!.length, ); }, ), ), ), ); } }
package ex0125; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Scanner; public class ex02login { public static void main(String[] args) { // 로그인 프로그램 PreparedStatement psmt = null; Connection conn = null; ResultSet rs = null; // 1. id,pw 입력받기 Scanner sc = new Scanner(System.in); System.out.print("ID입력: "); String id = sc.next(); System.out.print("PW입력: "); String pw = sc.next(); // 2. id, pw가 DB에 저장된 정보와 일치하는지 체크 // 1) try-catch 구문 try { // 2) driver 동적로딩 Class.forName("oracle.jdbc.driver.OracleDriver"); // 3) db 연결 통로 생성 String url = "jdbc:oracle:thin:@localhost:1521:xe"; String user_id = "hr"; String user_pw = "hr"; conn = DriverManager.getConnection(url, user_id, user_pw); // 4) sql문 준비 String sql = "select * from big_member where id = ? and pw = ?"; // 5) sql문 실행 준비 상태 만들기 psmt = conn.prepareStatement(sql); psmt.setString(1, id); psmt.setString(2, pw); // 6) sql문 실행 // executeUpdate(): insert,delete,update 에만 적용가능 // >> 결과가 몇 행 변경일어났는지 // executeQuery(): select문을 실행할 때만 사용 // ResultSet 타입으로 리턴 (조회한 표 모양을 그대로 갖고 있음) // ResultSet로 역시 마지막에 닫아줘야함 rs = psmt.executeQuery(); // 7) 결과를 이용한 작업처리 // ResultSet // 행을 가리키는 커서를 갖고 있다 // 처음에는 열 이름을 가르킴. // rs.next(): 커서 한칸 내리면서 해당하는 행에 // 데이터가 있으면 true 없으면 false 리턴 // id: primary key 이므로 id같으면서 pw 같은 경우 한가지 유일>> 한칸만 내리면 됨 if (rs.next()) { System.out.println("로그인 성공"); // 커서가 가리키고 있는 행에서 데이터 꺼내기 // rs.get...으로 숫자로 열순서(int)써서 꺼내거나 "컬럼이름"(String) 써서 꺼내기 String uid = rs.getString(1); String upw = rs.getString(2); // 데이터 오버로딩, 대소문자는 상관없음 String uname = rs.getString("name"); String utel = rs.getString("tel"); System.out.printf("%s님 환영합니다", uname); } else { System.out.println("로그인 실패"); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 8) 나중에 만들어진 것부터 사용했던 객체들 닫기 if (rs != null) rs.close(); if (psmt != null) psmt.close(); if (conn != null) conn.close(); } catch (Exception e2) { e2.printStackTrace(); } } } }
package com.bankapp.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.bankapp.entity.Account; import com.bankapp.service.AccountService; @RestController @RequestMapping("/account") public class AccountController { @Autowired AccountService service; @PostMapping("/create") public ResponseEntity <Account> createAccount(@RequestBody Account account) { Account createAccount= service.createAccount(account); return ResponseEntity.status(HttpStatus.CREATED).body(createAccount); } @GetMapping("/{acc_no}") public Account getAccountByAccountNo(@PathVariable Integer acc_no) { Account getaccount=service.getAccountByAccountNo(acc_no); return getaccount; } @GetMapping("/read") public List <Account> getAllAccountDetails() { List <Account> acc_list = service.getAllAccountDetails(); return acc_list; } @PutMapping("/deposit/{acc_no}/{amount}") public Account depositAmount(@PathVariable Integer acc_no,@PathVariable Double amount) { // TODO Auto-generated method stub Account acc = service.depositAmount(acc_no, amount); return acc; } @PutMapping("/withdraw/{acc_no}/{amount}") public Account withdrawAmount(@PathVariable Integer acc_no,@PathVariable Double amount) { // TODO Auto-generated method stub Account acc=service.withdrawAmount(acc_no, amount); return acc; } @DeleteMapping("/delete/{acc_no}") public ResponseEntity<String> closeAccount(@PathVariable Integer acc_no) { // TODO Auto-generated method stub service.closeAccount(acc_no); return ResponseEntity.status(HttpStatus.ACCEPTED).body("Account closed"); } }
import React, { useState,useEffect } from 'react' import Nav from './Nav'; export default function CallCenter({doLogoutCC}) { const doLogout = () => { // for logging user out doLogoutCC(); } const temp = (arg) => { console.log(arg); if(window.confirm(`Are you sure that the complaint is resolved?`)){ fetch("http://localhost:3000/delete_complaint" , { method : "POST", headers : { 'Content-Type' : 'application/json', }, body: JSON.stringify( { complaintID : arg, } ) }) .then((res) => res.json()) .then((data) => { alert(data.data); get_data(); }) } else{ } } // ------------------------------------------------------------------------- // data section code // START const [data , setData]= useState([]); // for table data const [options,setOptions] = useState([]); // for search options function fillData(){ // for filling data var table = document.getElementById('complaints-table'); // use id of page's table table.innerHTML = ""; if (data.length==0){ var table_row = document.createElement('tr'); var table_row_d = document.createElement('td'); table_row_d.innerHTML = "Please refresh to see data"; table_row.appendChild(table_row_d); table.appendChild(table_row); return; } if ("No Results" in data[0]){ var table_row = document.createElement('tr'); var table_row_d = document.createElement('td'); table_row_d.innerHTML = "No data was found corresponding to the search"; table_row.appendChild(table_row_d); table.appendChild(table_row); return; } var col_names = []; var table_row = document.createElement('tr'); for(var key in data[0]){ if (key == '_id') continue; var table_row_d = document.createElement('td'); table_row_d.innerHTML = key; table_row.appendChild(table_row_d); col_names.push(key); } setOptions(col_names); var table_row_d = document.createElement('td'); table_row_d.innerHTML = 'Status'; table_row.appendChild(table_row_d); table_row.classList.add('tr-head'); table.appendChild(table_row); col_names.push('Status'); for(var i = 0 ; i<data.length ; i++){ table_row = document.createElement('tr'); for(var j = 0; j<col_names.length ; j++){ if(col_names[j] == 'Status'){ var td = document.createElement('td'); var button = document.createElement('button'); button.innerHTML = 'Resolve'; const id_doc = data[i]._id; button.onclick=(()=>{temp(id_doc);}) td.appendChild(button); table_row.appendChild(td); continue; } var td = document.createElement('td'); td.innerHTML = data[i][col_names[j]]; table_row.appendChild(td); } table.appendChild(table_row); } } useEffect(()=>{ // for refreshing the table as the data gets updated fillData(); },[data]) const get_data = () => { // for getting data from database fetch('http://localhost:3000/call_center') .then(response => response.json()) .then(response => { setData(response.Complaints); }).catch(err => { console.log(err); }); } // data section code // END // ----------------------------------------------------------------------- // ------------------------------------------------------------------------- // search and dropdown code // START const [searchText,setSearchText] = useState(''); // for search const handleSearchChange = (v) => { // for search text setSearchText(v.target.value); } const [isOpen, setIsOpen] = useState(false); // for dropdown const [selectedOption, setSelectedOption] = useState(null); // for selected option const handleSelect = (option) => { // for handling the selections setSelectedOption(option); }; const handleDropdown = () => { // for opening dropdowns setIsOpen((isOpen) => !isOpen); } const find = () => { // search function if (searchText=='' && selectedOption==null){ alert('Please enter some text and select a field to search'); } else if (searchText==''){ alert('Please enter some text to search'); } else if (selectedOption==null){ alert('Please select a field to search from'); } else{ fetch('http://localhost:3000/call_center_search',{ method : 'POST', headers: { 'Content-Type' : 'application/json' }, body: JSON.stringify({ 'attribute': selectedOption, 'search_text':searchText }), }) .then(response => response.json()) .then(response => { if (response.Results.length==0){ setData([{"No Results":"No data corresponding to search was found"}]); } else{ setData(response.Results); } }).catch(err => { console.log(err); }); } } // search and dropdown code // END // ----------------------------------------------------------------------- return ( <div className='data-table'> <Nav doLogout={doLogout}/> { (options.length==0) ? <p></p> : <> <input type="text" className='search-input' onChange={handleSearchChange} value={searchText} placeholder=' Search' /> <button onClick={find} className='find-button'> &#128269; </button> <button onClick={handleDropdown} className='dropdown'> <div>&#x25BC;&nbsp;&nbsp;&nbsp;&nbsp;{selectedOption || "Select a field"}</div> {isOpen && ( <ul> {options.map((option) => ( <li key={option} className='option-field' onClick={() => handleSelect(option)}> {option} </li> ))} </ul> )} </button> </> } <button onClick={get_data} className='right refresh'> Refresh </button> <center> <table id='complaints-table'></table> </center> </div> ) }
<?php namespace App\Model\Entity; use \WilliamCosta\DatabaseManager\Database; class Employee { /** * id do funcionario(a) * @var integer */ public int $id; /** * nome do funcionario(a) * @var string */ public string $name; /** * pis do funcionario(a) * @var string */ public string $pis; /** * cargo do funcionario(a) * @var string */ public string $office; /** * departamento do funcionario(a) * @var string */ public string $departament; /** * livraria do funcionario(a) * @var string */ public string $library_id; /** * método responsável por cadastrar funcionario(a) com a instancia atual * @return boolean */ public function register(): bool { //inseri um funcionario(a) no banco de dados $this->id = (new Database('employees'))->insert([ 'name' => $this->name, 'pis' => $this->pis, 'office' => $this->office, 'departament' => $this->departament, 'library_id' => $this->library_id, ]); //sucesso return true; } /** * método responsável por atualizar um funcionario com a instancia atual * @return boolean */ public function update(): bool { //atualiza um consumidor no banco de dados return (new Database('employees'))->update('id = ' . $this->id, [ 'name' => $this->name, 'pis' => $this->pis, 'office' => $this->office, 'departament' => $this->departament, 'library_id' => $this->library_id, ]); //sucesso return true; } /** * método responsável por deletar um funcionário no banco de dados * @return boolean */ public function delete(): bool { //deletar um funcionario no banco de dados return (new Database('employees'))->delete('id = ' . $this->id); } /** * metodo responsável por retornar um funcionario com base no seu id * @param integer $id * @return Employee */ public static function getEmployeeById(int $id): Employee { return self::getEmployee('id =' . $id)->fetchObject(self::class); } /** * @param string $where * @param string $order * @param string $limit * @param string $field * @return PDOStatement */ public static function getEmployee(string $where = null, string $order = null, string $limit = null, string $fields = '*') { return (new Database('employees'))->select($where, $order, $limit, $fields); } }
export interface SolarSystemPlanetDataType { name: string, neo: boolean, pha: boolean, absmag: number, diameter: number, albedo: number, eccentricity: number, semimajor_axis: number, perihelion: number, inclination: number, asc_node_long: number, arg_periapsis: number, mean_anomaly: number, true_anomaly: number, className: string } export const solarSystemPlanetData = { 'Mercury': { name: 'Mercury', neo: false, pha: false, absmag: 0.0, diameter: 4880, //km albedo: 0.088, eccentricity: 0.20563, semimajor_axis: 0.387098, //au perihelion: 0.307499, //au inclination: 7.005, //deg asc_node_long: 48.331, //deg arg_periapsis: 29.124, mean_anomaly: 0, true_anomaly: 0, className: "Airless Subferra" }, 'Venus': { name: 'Venus', neo: false, pha: false, absmag: 0.0, diameter: 6051.800*2, //km albedo: 0.689, eccentricity: 0.006772, semimajor_axis: 0.723332, //au perihelion: 0.718440, //au inclination: 3.39458, //deg asc_node_long: 76.680, //deg arg_periapsis: 54.884, mean_anomaly: 0, true_anomaly: 0, className: "Aria Terra" }, 'Earth': { name: 'Earth', neo: false, pha: false, absmag: 0.0, diameter: 6371*2, //km albedo: 0.367, eccentricity: 0.0167086, semimajor_axis: 1.0, //au perihelion: 0.983292404576, //au inclination: 7.155, //deg asc_node_long: -11.26064, //deg arg_periapsis: 114.20783, mean_anomaly: 0, true_anomaly: 0, className: "Marine Terra" }, 'Mars': { name: 'Mars', neo: false, pha: false, absmag: 0.0, diameter: 3389.500*2, //km albedo: 0.170, eccentricity: 0.0934, semimajor_axis: 1.52368055, //au perihelion: 1.3814, //au inclination: 1.850, //deg asc_node_long: 49.57854, //deg arg_periapsis: 286.5, mean_anomaly: 0, true_anomaly: 0, className: "Arid Subterra" }, 'Jupiter': { name: 'Jupiter', neo: false, pha: false, absmag: 0.0, diameter: 69911*2, //km albedo: 0.503, eccentricity: 0.0489, semimajor_axis: 5.2038, //au perihelion: 4.9506, //au inclination: 1.303, //deg asc_node_long: 100.464, //deg arg_periapsis: 273.867, mean_anomaly: 0, true_anomaly: 0, className: "Jupiter" }, 'Saturn': { name: 'Saturn', neo: false, pha: false, absmag: 0.0, diameter: 58232*2, //km albedo: 0.342, eccentricity: 0.0565, semimajor_axis: 9.5826, //au perihelion: 9.0412, //au inclination: 2.485, //deg asc_node_long: 113.665, //deg arg_periapsis: 339.392, mean_anomaly: 0, true_anomaly: 0, className: "Subjupiter" }, 'Uranus': { name: 'Uranus', neo: false, pha: false, absmag: 0.0, diameter: 25362*2, //km albedo: 0.300, eccentricity: 0.04717, semimajor_axis: 19.19126, //au perihelion: 18.2861, //au inclination: .773, //deg asc_node_long: 74.006, //deg arg_periapsis: 96.998857, mean_anomaly: 0, true_anomaly: 0, className: "Neptune" }, 'Neptune': { name: 'Neptune', neo: false, pha: false, absmag: 0.0, diameter: 24622*2, //km albedo: 0.290, eccentricity: 0.008678, semimajor_axis: 30.07, //au perihelion: 29.81, //au inclination: 1.770, //deg asc_node_long: 131.783, //deg arg_periapsis: 273.187, mean_anomaly: 0, true_anomaly: 0, className: "Nuptune" }, 'Pluto': { name: 'Pluto', neo: false, pha: false, absmag: 0.0, diameter: 1188.3*2, //km albedo: 0.52, eccentricity: 0.2488, semimajor_axis: 39.482, //au perihelion: 29.658, //au inclination: 17.16, //deg asc_node_long: 110.299, //deg arg_periapsis: 113.834, mean_anomaly: 0, true_anomaly: 0, className: "Arid Miniaquaria" }, // 'sample': { // name: 'Hyakutake', // neo: false, // pha: false, // absmag: 0.0, // diameter: 2.2, //km // albedo: 0.1, // eccentricity: 0.9998946, // semimajor_axis: 1700, // perihelion: 0.2301987, //au // inclination: 124.92246, //deg // asc_node_long: 188.05766, // arg_periapsis: 130.17218, // mean_anomaly: 0, // true_anomaly: 0, // className: "Asteroid" // } }
import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable, Subscription } from 'rxjs'; import * as fromApp from '../../store/app.reducer'; import * as ShoppingListActions from './store/shopping-list.actions'; import { State } from './store/shopping-list.reducer'; @Component({ selector: 'app-shopping-list', templateUrl: './shopping-list.component.html', styleUrls: ['./shopping-list.component.css'], providers: [] }) export class ShoppingListComponent implements OnInit { public ingredients: Observable<State>; public subscription: Subscription; constructor(private store: Store<fromApp.AppState>) { } ngOnInit(): void { this.ingredients = this.store.select('shoppingList'); } onEditIngredient(index: number): void { this.store.dispatch(new ShoppingListActions.StartEdit(index)); } }
'use client' import { useCallback, useMemo, useState } from "react"; import { Button } from "@/components/Button"; import { Input } from "@/components/Input"; import { ContentTask } from "@/components/Task"; import { TotalContent } from "@/components/Total"; import { EmptyContent } from "@/components/Empty"; import { HeaderContent } from "@/components/Header"; import { PlusCircleRegular } from "@/components/Icons/PlusCircleRegular"; export default function Home() { const [tasks, setTasks] = useState<TTask[]>([]) const [description, setDescription] = useState('') const addTask = () => { if (!description) return setTasks([...tasks, { id: new Date().getTime(), description, isFinished: false }]) setDescription('') } const handleUpdateTask = useCallback((id: number) => { const filteredTasks = tasks.map(task => ({ ...task, isFinished: (task.id === id ? !task.isFinished : task.isFinished) })) setTasks(filteredTasks) }, [setTasks, tasks]) const handleDeleteTask = useCallback((id: number) => { const filteredTasks = tasks.filter(task => task.id !== id) setTasks(filteredTasks) }, [setTasks, tasks]) const { totalFinished, totalCreated } = useMemo(() => { const totalFinished = tasks.filter(task => task.isFinished).length const totalCreated = tasks.filter(task => !task.isFinished).length return { totalFinished, totalCreated } }, [tasks]) return ( <main className="flex flex-col items-center min-h-screen bg-white"> <HeaderContent /> <div className="fixed sm:px-4 top-40 max-w-5xl w-full flex gap-2"> <Input maxLength={64} name='description' placeholder='Adicione uma nova tarefa' value={description} onChange={(e) => setDescription(e.target.value)} /> <Button name="addHandler" id="addHandler" onClick={addTask} disabled={!description}> <span className="mr-2">Criar</span> <PlusCircleRegular /> </Button> </div> <TotalContent totalCreated={totalCreated} totalFinished={totalFinished} /> {!tasks.length ? ( <EmptyContent /> ) : ( <div className="max-w-5xl sm:px-4 w-full h-full gap-3 items-center text-center justify-center flex flex-col"> {tasks.map(task => ( <ContentTask id={task.id} key={task.id} description={task.description} isFinished={task.isFinished} handleUpdate={() => handleUpdateTask(task.id)} handleDelete={() => handleDeleteTask(task.id)} /> ))} </div> )} </main> ); }
#include "fiber.h" #include "config.h" #include "macro.h" #include <ctime> #include "scheduler.h" #include <atomic> #include <exception> #include <ucontext.h> namespace bobliew { static Logger::ptr g_logger = BOBLIEW_LOG_NAME("system"); //协程只有两层, 主协程-子协程 static std::atomic<uint64_t> s_fiber_id {0}; static std::atomic<uint64_t> s_fiber_count {0}; static ConfigVar<uint32_t>::ptr g_fiber_stack_size = Config::Lookup<uint32_t>("fiber.stack_size", 1024 * 1024, "fiber stack size"); //子协程-记录当前协程 static thread_local Fiber* t_fiber = nullptr; //main协程 智能指针 static thread_local Fiber::ptr t_threadFiber = nullptr; class MallocStackAllocator { public: static void* ALloc(size_t size){ return malloc(size); } static void Dealloc(void* vp, size_t size) { return free(vp); } }; using StackAllocator = MallocStackAllocator; //把当前的线程变为我们协程的类 //主协程会作为全局变量历经整个函数的声明周期 Fiber::Fiber() { m_state = EXEC; SetThis(this); if(getcontext(&m_ctx)) { BOBLIEW_ASSERT2(false, "getcontext"); } ++s_fiber_count; BOBLIEW_LOG_DEBUG(g_logger) << "Fiber::main "; } //真正的创建(子协程)(需要分配栈空间和回调函数) //每个协程都有对应的栈 Fiber::Fiber(std::function<void()> cb, size_t stacksize, bool use_caller) :m_id(++s_fiber_id), m_cb(cb) { ++s_fiber_count; m_stacksize = stacksize ? stacksize : g_fiber_stack_size->getValue(); m_stack = StackAllocator::ALloc(m_stacksize); //如果取失败了会返回0 if(getcontext(&m_ctx)) { BOBLIEW_ASSERT2(false, "getcontext"); } //设置好协程的信息 m_ctx.uc_link =nullptr; m_ctx.uc_stack.ss_sp = m_stack; m_ctx.uc_stack.ss_size = m_stacksize; if(!use_caller) { makecontext(&m_ctx, &Fiber::MainFunc, 0); }else { makecontext(&m_ctx, &Fiber::CallerMainFunc, 0); } BOBLIEW_LOG_DEBUG(g_logger) << "Fiber::Fiber id:"<<m_id; } //后序可以用一个最小堆来维护m_id // Fiber::~Fiber(){ --s_fiber_count; //如果是子协程,这需要释放之前分配的内存空间 if(m_stack) { BOBLIEW_ASSERT(m_state == TERM || m_state==EXCEPT || m_state ==INIT); StackAllocator::Dealloc(m_stack, m_stacksize); } else { BOBLIEW_ASSERT(!m_cb); //析构的是子线程是没有m_cb的 BOBLIEW_ASSERT(m_state == EXEC); //如果是当前线程就是自己,那么就将t_fiber释放回去。 Fiber* cur = t_fiber; if(cur == this) { SetThis(nullptr); } } BOBLIEW_LOG_DEBUG(g_logger) << "Fiber::~Fiber id: " <<m_id; } //重置协程的回调函数,并重置状态 //协程相当于用户态的线程,虽然只有一个主协程,但是能确保当t_fiber是子线程的时候 //t_thread_fiber一定是主线程,所以可以在reset和构造函数中将uc_link指向&t_threadFiber //会避免上下文都是nullptr导致的线程直接结束。 //另一种方式就是在Mainfunc函数里面手动调回来,这样就不需要在每次reset和构造的时候进行交换了 void Fiber::reset(std::function<void()> cb){ BOBLIEW_ASSERT(m_stack); BOBLIEW_ASSERT(m_state==TERM || m_state == EXCEPT || m_state==INIT); m_cb = cb; if(getcontext(&m_ctx)) { BOBLIEW_ASSERT2(false,"getcontext"); } //m_ctx.uc_link = &t_threadFiber->m_ctx; m_ctx.uc_link = nullptr; m_ctx.uc_stack.ss_sp = m_stack; m_ctx.uc_stack.ss_size = m_stacksize; makecontext(&m_ctx, &Fiber::MainFunc, 0); m_state = INIT; } void Fiber::back() { SetThis(t_threadFiber.get()); if(swapcontext(&m_ctx, &t_threadFiber->m_ctx)) { BOBLIEW_ASSERT2(false, "swapcontext back()"); } } //切换到当前(main fiber)协程下的子协程运行 //相当于m_ctx和当前正在运行的ctx发生了交换。 //谁调用就换谁进去 void Fiber::swapIn() { SetThis(this); BOBLIEW_ASSERT(m_state != EXEC); m_state = EXEC; if(swapcontext(&Scheduler::GetMainFiber()->m_ctx, &m_ctx)){ BOBLIEW_ASSERT2(false,"swapcontextin"); } } void Fiber::call() { SetThis(this); m_state = EXEC; if(swapcontext(&t_threadFiber->m_ctx, &m_ctx)) { BOBLIEW_ASSERT2(false, "swapcontext"); } } //相当于两个状态 t_fiber记录确实在运行的 Scheduler::GetMainFiber()->m_ctx //t_threadFiber记录主协程,交换的时候正在运行的变为主协程, //然后子协程的地址就会发生交换。 void Fiber::swapOut() { SetThis(Scheduler::GetMainFiber()); if(swapcontext(&m_ctx,&Scheduler::GetMainFiber()->m_ctx)) { BOBLIEW_ASSERT2(false, "swapcontext out") } } //设置t_fiber 一般由其他函数调用。 void Fiber::SetThis(Fiber* f) { t_fiber = f; } uint64_t Fiber::GetFiberId() { if(t_fiber) { return t_fiber->getId(); } return 0; } //返回当前运行的协程 Fiber::ptr Fiber::Getthis() { if(t_fiber) { return t_fiber->shared_from_this(); } //Fiber::ptr就是智能指针的类。 Fiber::ptr main_fiber(new Fiber); BOBLIEW_ASSERT(t_fiber == main_fiber.get()); t_threadFiber = main_fiber; return t_threadFiber->shared_from_this(); } void Fiber::YieldToReady() { Fiber::ptr cur = Getthis(); cur->m_state = READY; cur->swapOut(); } void Fiber::YieldToHold() { Fiber::ptr cur = Getthis(); cur->m_state = HOLD; cur->swapOut(); } uint64_t TotalFibers() { return s_fiber_count; } void Fiber::MainFunc() { Fiber::ptr cur = Getthis(); BOBLIEW_ASSERT(cur); try { cur->m_cb(); cur->m_cb = nullptr;//防止一些参数的引用加一。 cur->m_state = TERM; } catch (std::exception& ex) { cur->m_state = EXCEPT; BOBLIEW_LOG_ERROR(g_logger)<<"Fiber Except:"<<ex.what(); } catch (...) { cur->m_state = EXCEPT; BOBLIEW_LOG_ERROR(g_logger)<<"Fiber Except"; } auto raw_ptr = cur.get(); cur.reset(); raw_ptr->swapOut(); BOBLIEW_ASSERT2(false, "never reach fiber_id=" + std::to_string(raw_ptr->getId())); } void Fiber::CallerMainFunc() { Fiber::ptr cur = Getthis(); BOBLIEW_ASSERT(cur); try { cur->m_cb(); cur->m_cb = nullptr;//防止一些参数的引用加一。 cur->m_state = TERM; } catch (std::exception& ex) { cur->m_state = EXCEPT; BOBLIEW_LOG_ERROR(g_logger)<<"Fiber Except:"<<ex.what(); } catch (...) { cur->m_state = EXCEPT; BOBLIEW_LOG_ERROR(g_logger)<<"Fiber Except"; } auto raw_ptr = cur.get(); cur.reset(); raw_ptr->back(); BOBLIEW_ASSERT2(false, "never reach fiber_id=" + std::to_string(raw_ptr->getId())); } }
package main import ( "context" "encoding/json" "fmt" "log" "os" "github.com/TFMV/GoDataStream/config" "github.com/apache/arrow/go/arrow/ipc" "github.com/apache/arrow/go/arrow/memory" "github.com/segmentio/kafka-go" ) func main() { config.LoadConfig() // Open Arrow file file, err := os.Open(config.AppConfig.Arrow.FilePath) if err != nil { log.Fatalf("failed to open arrow file: %v", err) } defer file.Close() // Initialize Arrow reader mem := memory.NewGoAllocator() reader, err := ipc.NewFileReader(file, ipc.WithAllocator(mem)) if err != nil { log.Fatalf("failed to create arrow reader: %v", err) } defer reader.Close() // Create a new Kafka producer writer := kafka.NewWriter(kafka.WriterConfig{ Brokers: config.AppConfig.Kafka.Brokers, Topic: config.AppConfig.Kafka.Topic, Balancer: &kafka.LeastBytes{}, }) defer writer.Close() // Read Arrow records and send to Kafka for i := 0; i < reader.NumRecords(); i++ { record, err := reader.Record(i) if err != nil { log.Fatalf("failed to read record: %v", err) } for j := 0; j < int(record.NumRows()); j++ { row := record.Column(j) value, err := json.Marshal(row) if err != nil { log.Printf("failed to marshal row: %v", err) continue } err = writer.WriteMessages(context.Background(), kafka.Message{ Key: []byte(fmt.Sprintf("%v", row)), // Adjust the key as per your schema Value: value, }, ) if err != nil { log.Printf("failed to write message to kafka: %v", err) } } } fmt.Println("Arrow data sent to Kafka") }
<?php /** * Professional Software Company functions and definitions * * @subpackage Professional Software Company * @since 1.0 */ include get_theme_file_path( 'vendor/wptrt/autoload/src/Professional_Software_Company_Loader.php' ); $Professional_Software_Company_Loader = new \WPTRT\Autoload\Professional_Software_Company_Loader(); $Professional_Software_Company_Loader->professional_software_company_add( 'WPTRT\\Customize\\Section', get_theme_file_path( 'vendor/wptrt/customize-section-button/src' ) ); $Professional_Software_Company_Loader->professional_software_company_register(); function professional_software_company_setup() { load_theme_textdomain( 'professional-software-company', get_template_directory() . '/languages' ); add_theme_support( 'automatic-feed-links' ); add_theme_support( 'title-tag' ); add_theme_support( 'responsive-embeds' ); add_theme_support( 'html5', array( 'comment-list', 'search-form', 'comment-form', ) ); add_theme_support( 'woocommerce' ); add_theme_support( 'post-thumbnails' ); add_theme_support( 'custom-background', $defaults = array( 'default-color' => '', 'default-image' => '', 'default-repeat' => '', 'default-position-x' => '', 'default-attachment' => '', 'wp-head-callback' => '_custom_background_cb', 'admin-head-callback' => '', 'admin-preview-callback' => '' )); $GLOBALS['content_width'] = 525; register_nav_menus( array( 'primary' => __( 'Primary Menu', 'professional-software-company' ), ) ); // Add theme support for Custom Logo. add_theme_support( 'custom-logo', array( 'width' => 250, 'height' => 250, 'flex-width' => true, ) ); // Add theme support for selective refresh for widgets. add_theme_support( 'customize-selective-refresh-widgets' ); /* * This theme styles the visual editor to resemble the theme style, * specifically font, colors, and column width. */ add_editor_style( array( 'assets/css/editor-style.css', professional_software_company_fonts_url() ) ); // Theme Activation Notice global $pagenow; if ( is_admin() && ('themes.php' == $pagenow) && isset( $_GET['activated'] ) ) { add_action( 'admin_notices', 'professional_software_company_activation_notice' ); } } add_action( 'after_setup_theme', 'professional_software_company_setup' ); // Notice after Theme Activation function professional_software_company_activation_notice() { echo '<div class="notice notice-success is-dismissible start-notice">'; echo '<h3>'. esc_html__( 'Welcome to Luzuk!!', 'professional-software-company' ) .'</h3>'; echo '<p>'. esc_html__( 'Thank you for choosing Professional Software Company theme. It will be our pleasure to have you on our Welcome page to serve you better.', 'professional-software-company' ) .'</p>'; echo '<p><a href="'. esc_url( admin_url( 'themes.php?page=professional_software_company_guide' ) ) .'" class="button button-primary">'. esc_html__( 'GET STARTED', 'professional-software-company' ) .'</a></p>'; echo '</div>'; } function professional_software_company_widgets_init() { register_sidebar( array( 'name' => __( 'Blog Sidebar', 'professional-software-company' ), 'id' => 'sidebar-1', 'description' => __( 'Add widgets here to appear in your sidebar on blog posts and archive pages.', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<div class="widget_container"><h2 class="widget-title">', 'after_title' => '</h2></div>', ) ); register_sidebar( array( 'name' => __( 'Sidebar 2', 'professional-software-company' ), 'id' => 'sidebar-2', 'description' => __( 'Add widgets here to appear in your pages and posts', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<div class="widget_container"><h2 class="widget-title">', 'after_title' => '</h2></div>', ) ); register_sidebar( array( 'name' => __( 'Sidebar 3', 'professional-software-company' ), 'id' => 'sidebar-3', 'description' => __( 'Add widgets here to appear in your pages and posts', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<div class="widget_container"><h2 class="widget-title">', 'after_title' => '</h2></div>', ) ); register_sidebar( array( 'name' => __( 'Footer 1', 'professional-software-company' ), 'id' => 'footer-1', 'description' => __( 'Add widgets here to appear in your footer.', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); register_sidebar( array( 'name' => __( 'Footer 2', 'professional-software-company' ), 'id' => 'footer-2', 'description' => __( 'Add widgets here to appear in your footer.', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); register_sidebar( array( 'name' => __( 'Footer 3', 'professional-software-company' ), 'id' => 'footer-3', 'description' => __( 'Add widgets here to appear in your footer.', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); register_sidebar( array( 'name' => __( 'Footer 4', 'professional-software-company' ), 'id' => 'footer-4', 'description' => __( 'Add widgets here to appear in your footer.', 'professional-software-company' ), 'before_widget' => '<section id="%1$s" class="widget %2$s">', 'after_widget' => '</section>', 'before_title' => '<h2 class="widget-title">', 'after_title' => '</h2>', ) ); } add_action( 'widgets_init', 'professional_software_company_widgets_init' ); function professional_software_company_fonts_url(){ $font_families = array( 'Roboto:ital,wght@0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900' ); $fonts_url = add_query_arg( array( 'family' => implode( '&family=', $font_families ), 'display' => 'swap', ), 'https://fonts.googleapis.com/css2' ); $contents = wptt_get_webfont_url( esc_url_raw( $fonts_url ) ); return $contents; } //Enqueue scripts and styles. function professional_software_company_scripts() { // Add custom fonts, used in the main stylesheet. wp_enqueue_style( 'professional-software-company-fonts', professional_software_company_fonts_url(), array(), null ); //Bootstarp wp_enqueue_style( 'bootstrap-css', esc_url( get_template_directory_uri() ).'/assets/css/bootstrap.css' ); // Theme stylesheet. wp_enqueue_style( 'professional-software-company-basic-style', get_stylesheet_uri() ); // Load the Internet Explorer 9 specific stylesheet, to fix display issues in the Customizer. if ( is_customize_preview() ) { wp_enqueue_style( 'professional-software-company-ie9', get_theme_file_uri( '/assets/css/ie9.css' ), array( 'professional-software-company-style' ), '1.0' ); wp_style_add_data( 'professional-software-company-ie9', 'conditional', 'IE 9' ); } // Load the Internet Explorer 8 specific stylesheet. wp_enqueue_style( 'professional-software-company-ie8', get_theme_file_uri( '/assets/css/ie8.css' ), array( 'professional-software-company-style' ), '1.0' ); wp_style_add_data( 'professional-software-company-ie8', 'conditional', 'lt IE 9' ); //font-awesome wp_enqueue_style( 'font-awesome-css', esc_url( get_template_directory_uri() ).'/assets/css/fontawesome-all.css' ); require get_parent_theme_file_path( '/lz-custom-style.php' ); wp_add_inline_style( 'professional-software-company-basic-style',$professional_software_company_custom_style ); wp_enqueue_script( 'professional-software-company-navigation-jquery', get_theme_file_uri( '/assets/js/navigation.js' ), array( 'jquery' ), '2.1.2', true ); wp_enqueue_script( 'bootstrap-js', esc_url( get_template_directory_uri() ). '/assets/js/bootstrap.js', array('jquery') ); wp_enqueue_script( 'jquery-superfish', esc_url( get_template_directory_uri() ). '/assets/js/jquery.superfish.js', array('jquery') ,'',true); if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) { wp_enqueue_script( 'comment-reply' ); } } add_action( 'wp_enqueue_scripts', 'professional_software_company_scripts' ); define('PROFESSIONAL_SOFTWARE_COMPANY_LIVE_DEMO',__('https://www.luzukdemo.com/demo/professional-software-company/','professional-software-company')); define('PROFESSIONAL_SOFTWARE_COMPANY_PRO_DOCS',__('https://www.luzukdemo.com/docs/professional-software-company/','professional-software-company')); define('PROFESSIONAL_SOFTWARE_COMPANY_BUY_NOW',__('https://www.luzuk.com/product/professional-software-wordpress-theme/','professional-software-company')); define('PROFESSIONAL_SOFTWARE_COMPANY_SUPPORT',__('https://wordpress.org/support/theme/professional-software-company/','professional-software-company')); define('PROFESSIONAL_SOFTWARE_COMPANY_CREDIT',__('https://www.luzuk.com/themes/free-software-wordpress-theme/','professional-software-company')); if ( ! function_exists( 'professional_software_company_credit' ) ) { function professional_software_company_credit(){ echo "<a href=".esc_url(PROFESSIONAL_SOFTWARE_COMPANY_CREDIT)." target='_blank'>".esc_html__('Software WordPress Theme','professional-software-company')."</a>"; } } function professional_software_company_front_page_template( $template ) { return is_home() ? '' : $template; } add_filter( 'frontpage_template', 'professional_software_company_front_page_template' ); function professional_software_company_sanitize_dropdown_pages( $page_id, $setting ) { // Ensure $input is an absolute integer. $page_id = absint( $page_id ); // If $page_id is an ID of a published page, return it; otherwise, return the default. return ( 'publish' == get_post_status( $page_id ) ? $page_id : $setting->default ); } function professional_software_company_sanitize_choices( $input, $setting ) { global $wp_customize; $control = $wp_customize->get_control( $setting->id ); if ( array_key_exists( $input, $control->choices ) ) { return $input; } else { return $setting->default; } } function professional_software_company_sanitize_checkbox( $input ) { return ( ( isset( $input ) && true == $input ) ? true : false ); } function professional_software_company_sanitize_float( $input ) { return filter_var($input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); } /* Excerpt Limit Begin */ function professional_software_company_string_limit_words($string, $word_limit) { $words = explode(' ', $string, ($word_limit + 1)); if(count($words) > $word_limit) array_pop($words); return implode(' ', $words); } // Change number or products per row to 3 add_filter('loop_shop_columns', 'professional_software_company_loop_columns'); if (!function_exists('professional_software_company_loop_columns')) { function professional_software_company_loop_columns() { return 3; // 3 products per row } } /* Breadcrumb Begin */ function professional_software_company_breadcrumb() { if (!is_home()) { echo '<a href="'; echo esc_url(home_url()); echo '">'; bloginfo('name'); echo "</a> "; if (is_category() || is_single()) { echo "&nbsp;&#187;&nbsp;"; the_category(', '); if (is_single()) { echo "&nbsp;&#187;&nbsp;"; echo "<span> "; the_title(); echo "</span>"; } } elseif (is_page()) { echo "&nbsp;&#187;&nbsp;"; echo "<span>"; the_title(); echo "</span> "; } } } function professional_software_company_banner_image( $image_url ){ global $post; if( is_singular() ){ $image_url = get_the_post_thumbnail_url( $post->ID, 'full' ); } return $image_url; } require get_parent_theme_file_path( '/inc/custom-header.php' ); require get_parent_theme_file_path( '/inc/template-tags.php' ); require get_parent_theme_file_path( '/inc/template-functions.php' ); require get_parent_theme_file_path( '/inc/customizer.php' ); require get_parent_theme_file_path( '/inc/font-awesome-icons.php' ); require get_parent_theme_file_path( '/inc/getting-started/getting-started.php' ); require get_parent_theme_file_path( '/inc/wptt-webfont-loader.php' );
#ifndef PICO_CLOCK_TYPES_H #define PICO_CLOCK_TYPES_H #include "pico/stdlib.h" typedef struct Rectangle { int32_t x; int32_t y; int32_t w; int32_t h; } Rectangle; typedef struct Color { uint8_t r; uint8_t g; uint8_t b; } Color; typedef enum { MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5, SATURDAY = 6, SUNDAY = 7, } WeekDay; typedef struct Date { WeekDay weekDay; uint8_t day; uint8_t month; // 1 -12 uint8_t year; } Date; typedef struct Time { uint8_t seconds; uint8_t minutes; uint8_t hours; } Time; typedef struct DateTime { Date date; Time time; } DateTime; typedef void (*DateChangedCallback)( const struct Date *const oldDate, const struct Date *const newDate); typedef void (*TimeChangedCallback)( const struct Time *const oldTime, const struct Time *const newTime); typedef void (*DateTimeChangedCallback)( const struct DateTime *const oldDateTime, const struct DateTime *const newDateTime); typedef void (*BatteryStateChangedCallback)(const bool oldIsCharging, const bool newIsCharging); typedef void (*BatteryPercentageChangedCallback)(const float oldPercentage, const float newPercentage); #endif //PICO_CLOCK_TYPES_H
import { OrderCreatedEvent, OrderStatus } from '@mrltickets/common'; import mongoose from 'mongoose'; import { Message } from 'node-nats-streaming'; import { Order } from '../../../models/order'; import { natsWrapper } from '../../../nats-wrapper'; import { OrderCreatedListener } from '../order-created-listener'; const setup = async () => { //create an instance of the listener const listener = new OrderCreatedListener(natsWrapper.client); //create a fake data object const data: OrderCreatedEvent['data'] = { id: new mongoose.Types.ObjectId().toHexString(), version: 0, expiresAt: new Date().toISOString(), userId: new mongoose.Types.ObjectId().toHexString(), status: OrderStatus.Created, ticket: { id: new mongoose.Types.ObjectId().toHexString(), price: 19, }, quantity: 10, }; //create a fake message object //@ts-ignore const msg: Message = { ack: jest.fn(), }; //return all the stuffs return { listener, data, msg }; }; it('replicates the order info', async () => { const { listener, data, msg } = await setup(); await listener.onMessage(data, msg); const order = await Order.findById(data.id); expect(order).toBeDefined(); expect(order!.price).toEqual(data.ticket.price * data.quantity); }); it('acks the message', async () => { const { listener, data, msg } = await setup(); await listener.onMessage(data, msg); expect(msg.ack).toHaveBeenCalled(); });
import React, { PropTypes } from 'react'; import { Result } from '../../utils/functional'; import T from '../misc/t'; import ShouldRenderMixin from '../../utils/should-render-mixin'; import HighCharts from 'highcharts'; import { Color } from '../../utils/colours'; import ChartDataLink from '../boilerplate/chart-data-link'; require('stylesheets/charts/family-barchart'); const FamilityBarChart = React.createClass({ propTypes: { data: PropTypes.array.isRequired, }, mixins: [ ShouldRenderMixin, ], componentDidMount() { this.getChart(); }, componentDidUpdate() { this.getChart(); }, componentWillUnmount() { if (this.chart) { this.chart.destroy(); delete this.chart; } }, getValue(values, metric) { return values.reduce((ret, item) => { if (item.hasOwnProperty(metric)) { ret.value = item[metric]; } return ret; }, {value: 0}).value; }, parseData(summary, keys, regions) { return keys.map(metric => { return { color: Color.getFacilityColor(metric), name: metric, data: regions.map(region => this.getValue(summary[region], metric)), }; }); }, getChart() { if (this.props.data.length === 0) { return false; } const keys = ['NEW CLIENTS', 'FAMILY PLANNING CONTINUIOUS']; const sum = Result.sumByGroupBy(this.props.data, 'REGION', keys); const regions = Object.keys(sum).filter(key => key !== 'total'); const stats = this.parseData(sum, keys, regions); this.chart = new HighCharts.Chart({ chart: { height: 400, type: 'column', renderTo: 'family-barchart', }, title: { text: '', }, xAxis: { categories: regions, }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y}</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true, }, plotOptions: { spline: { marker: { radius: 4, lineColor: '#666666', lineWidth: 1, }, }, }, series: stats, }); return this.chart; }, render() { if (this.props.data.length === 0) { return false; } return ( <div className="family-barchart"> <h3 className="chart-title"><T k="chart.family-barchart.title" /></h3> <span className="helptext"><ChartDataLink dataId="family-planing"/> <T k="chart.family-barchart.helptext" /></span> <div className="chart-container" id="family-barchart"></div> </div> ); }, }); export default FamilityBarChart;
import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class CellTest { @Test fun `cell should be alive when initialized as alive`() { val aliveCell = Cell(CellState.ALIVE) assertThat(aliveCell.isAlive()).isTrue } @Test fun `cell should be dead when initialized as dead`() { val deadCell = Cell(CellState.DEAD) assertThat(deadCell.isAlive()).isFalse } @Test fun `cell dies when it has less than 2 live neighbors`() { val aliveCell = Cell(CellState.ALIVE) val neighbours = listOf(Cell(CellState.ALIVE), Cell(CellState.DEAD), Cell(CellState.DEAD)) aliveCell.evolve(neighbours) assertThat(aliveCell.isAlive()).isFalse } @Test fun `cell dies when it has more than 3 live neighbors`() { val aliveCell = Cell(CellState.ALIVE) val neighbours = listOf(Cell(CellState.ALIVE), Cell(CellState.DEAD), Cell(CellState.DEAD), Cell(CellState.DEAD)) aliveCell.evolve(neighbours) assertThat(aliveCell.isAlive()).isFalse } @Test fun `cell stays alive when it has 2 live neighbors`() { val aliveCell = Cell(CellState.ALIVE) val neighbours = listOf(Cell(CellState.ALIVE), Cell(CellState.ALIVE)) aliveCell.evolve(neighbours) assertThat(aliveCell.isAlive()).isTrue } @Test fun `cell stays alive when it has 3 live neighbors`() { val aliveCell = Cell(CellState.ALIVE) val neighbours = listOf(Cell(CellState.ALIVE), Cell(CellState.ALIVE), Cell(CellState.ALIVE)) aliveCell.evolve(neighbours) assertThat(aliveCell.isAlive()).isTrue } @Test fun `dead cell becomes alive when it has exactly three live neighbors`() { val deadCell = Cell(CellState.DEAD) val neighbours = listOf(Cell(CellState.ALIVE), Cell(CellState.ALIVE), Cell(CellState.ALIVE)) deadCell.evolve(neighbours) assertThat(deadCell.isAlive()).isTrue } @Test fun `cell with 3 live neighbors survives to the next generation`() { //Given val aliveCell = Cell(CellState.ALIVE) val neighbors = List(3) { Cell(CellState.ALIVE) } val deadNeighbor = Cell(CellState.DEAD) //When neighbors.forEach { aliveCell.addNeighbor(it) } aliveCell.addNeighbor(deadNeighbor) aliveCell.evolve(neighbors) //Then assertThat(aliveCell.isAlive()).isTrue } @Test fun `must return all positions of the neighbours of the cell`() { // Given val grid = Grid(3, 3) val cellNeighbourPositions = grid.getNeighbourPositions(Position(1, 1), 1) // Then val expectedNeighbours = setOf( Position(0, 0), Position(0, 1), Position(0, 2), Position(1, 0), Position(1, 2), Position(2, 0), Position(2, 1), Position(2, 2) ) assertThat(expectedNeighbours.toSet()).isEqualTo(cellNeighbourPositions.toSet()) } @Test fun `au début du jeu game of life, si je n'ai aucune cellules vivantes alors le jeu est terminé`() { val grid = Grid(3, 3) val game = Game(grid, emptyList<Position>()) assertThat(game.isOver()).isTrue } @Test fun `au début du jeu game of life, si on a des cellules vivantes, le jeu continue`() { val grid = Grid(3, 3) val game = Game(grid, listOf(Position(0,0))) assertThat(game.isOver()).isFalse } @Test fun `au départ du jeu game of life, si j'ai une cellule vivante, alors au tour suivant, le jeu est fini`() { //Given val grid = Grid(3, 3) val game = Game(grid, listOf(Position(0,0))) // When game.play() //Then assertThat(game.isOver()).isTrue } }
import { Box, HStack, Heading, Table, TableContainer, Tbody, Td, Tfoot, Th, Thead, Tr, } from '@chakra-ui/react'; import { ReactNode, useContext } from 'react'; import { gql, useQuery } from '@apollo/client'; import { AuthContext } from '@/contexts/AuthContext'; import { Card } from '../templates'; import { ColorContext } from '@/contexts/ColorContext'; const ALL_ACTIVITIES = gql` query allActivities { allActivities { id name ytdSchedulesCount futureSchedulesCount expectedCost } } `; interface ActivitiesDashboardCardProps { children?: ReactNode; } type ActivitiesData = { allActivities: { id: string; name: string; ytdSchedulesCount: number; futureSchedulesCount: number; expectedCost: number; }[]; }; export function ActivitiesDashboardCard({}: ActivitiesDashboardCardProps) { const { token } = useContext(AuthContext); const { green } = useContext(ColorContext); const { data } = useQuery<ActivitiesData>(ALL_ACTIVITIES, { context: { headers: { authorization: `JWT ${token}`, }, }, }); return ( <Card> <HStack mb={4} w="full" justify="space-between"> <Heading size="md" color={green}> ATIVIDADES </Heading> </HStack> <TableContainer> <Table size="sm"> <Thead> <Tr> <Th>Atividade</Th> <Th isNumeric>Programações no ano</Th> <Th isNumeric>Programações agendadas</Th> <Th isNumeric>Custo esperado</Th> </Tr> </Thead> <Tbody> {data?.allActivities?.map((activity) => ( <Tr key={activity.id}> <Td>{activity.name}</Td> <Td isNumeric>{activity.ytdSchedulesCount}</Td> <Td isNumeric>{activity.futureSchedulesCount}</Td> <Td isNumeric>R$ ****</Td> </Tr> ))} </Tbody> <Tfoot visibility={'hidden'}> <Tr> <Td colSpan={4} isNumeric> <Box> <strong> Custo previsto: R$ {data?.allActivities?.reduce((acc, activity) => { return acc + activity.expectedCost; }, 0)} </strong> </Box> </Td> </Tr> </Tfoot> </Table> </TableContainer> </Card> ); }
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="rb" uri="http://www.springframework.org/tags" %> <!doctype html> <html lang="ko"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Favicon --> <link href="/resources/images/logo.PNG" rel="icon"> <title>memberView</title> <link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sidebars/"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <!-- Fontawesome Stylesheet --> <script src="https://kit.fontawesome.com/059fbc3cf8.js" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <style type="text/css"> label { font-size: large; } table { margin-left: auto; margin-right: auto; } th, td { border: 1px solid lightgray; height: 35px; } .listCheck { text-align: center; justify-content: center; } </style> <link href="/resources/xdmin/css/styles.css" rel="stylesheet"> <link href="/resources/xdmin/css/list.css" rel="stylesheet"> </head> <body> <form id="form" name="form" method="post" onkeydown="return captureReturnKey(event)" autocomplete="off" enctype="multipart/form-data"> <!-- *Vo.jsp s --> <%@include file="../common/memberVo.jsp"%> <!-- #-> --> <!-- *Vo.jsp e --> <!-- *header.jsp s --> <%@include file="../common/header.jsp"%> <!-- #-> --> <!-- *header.jsp e --> <div class="container-fluid"> <div class="row mt-4"> <!-- *sidebar.jsp s --> <%@include file="../common/sidebar.jsp"%> <!-- #-> --> <!-- *sidebar.jsp e --> <div class="col-10"> <div class="row"> <h4>회원 관리</h4> <div class="container-fluid"> <div class="row m-4"> <div class="col-6"> <label class="form-label" for="mmSeq">회원번호</label> <input type="text" class="form-control" id="mmSeq" value="<c:out value="${item.mmSeq }" />"> </div> <div class="col-6"> <label class="form-label" for="mmRank">회원등급</label> <input type="text" class="form-control" id="mmRank" name="mmRank" value="<c:out value="${item.mmRank }" />"> </div> </div> <div class="row m-4"> <div class="col-6"> <label class="form-label" for="mmEmail">이메일</label> <input type="text" class="form-control" id="mmEmail" name="mmEmail" value="<c:out value="${item.mmEmail }" />"> </div> <div class="col-6"> <label class="form-label" for="mmPw">비밀번호</label> <input type="text" class="form-control" id="mmPw" name="mmPw" value="<c:out value="${item.mmPw }" />"> </div> </div> <div class="row m-4"> <div class="col-6"> <label class="form-label" for="mmName">이름</label> <input type="text" class="form-control" id="mmName" name="mmName" value="<c:out value="${item.mmName }" />"> </div> <div class="col-6"> <label class="form-label" for="mmNickname">닉네임</label> <input type="text" class="form-control" id="mmNickname" name="mmNickname" value="<c:out value="${item.mmNickname }" />"> </div> </div> <div class="row m-4"> <div class="col mx-auto"> <label class="form-label" for="mmGender">성별</label> <input type="text" class="form-control" id="mmGender" name="mmGender" value="<c:out value="${item.mmGender }" />"> </div> <div class="col mx-auto"> <label class="form-label" for="mmBod">생일</label> <input type="text" class="form-control" id="mmBod" name="mmBod" value="<c:out value="${item.mmBod }" />"> </div> </div> <div class="row m-4"> <div class="col mx-auto"> <label class="form-label" for="mmEmail">Email</label> <input type="hidden" id="mmEmailAllowedNy" name="mmEmailAllowedNy" value="0"> <input type="text" class="form-control" id="mmEmail" name="mmEmail" <c:out value="${dto.mmEmail }"/> placeholder="이메일을 입력해 주세요."> <div class="invalid-feedback" id="mmEmailFeedback"></div> </div> <div class="col mx-auto"> <label class="form-label" for="ccgNameEng" style="display: block;">이메일 정보 마케팅 사용 동의</label> <input type="checkbox" class="form-check-input"> <label class="form-check-label" for="">동의합니다.</label> </div> </div> <div class="row m-4"> <div class="col mx-auto"> <div class="row"> <div class="col mx-auto"> <label class="form-label" for="ccgUseNy">통신사</label> <input type="text" class="form-control"> </div> <div class="col mx-auto"> <label class="form-label" for="ccgUseNy">모바일</label> <input type="text" class="form-control"> </div> </div> </div> <div class="col mx-auto"> <label class="form-label" for="ccgOrder" style="display: block;">핸드폰 정보 마케팅 사용 동의</label> <input type="checkbox" class="form-check-input"> <label class="form-check-label" for="">동의합니다.</label> </div> </div> <div class="row m-4"> <div class="col mx-auto"> <label class="form-label" for="ccgOrder">전화번호</label> <input type="text" class="form-control"> </div> </div> <div class="row m-4"> <div class="col-6"> <label class="form-label" for="mmPostcode">주소</label> <div class="row mb-2"> <div class="col-sm-5"> <div class="input-group"> <input class="form-control" type="text" id="mmPostcode" name="mmPostcode" placeholder="우편번호" readonly> <button class="btn btn-light btn-outline-secondary" type="button" onclick="mmExecDaumPostcode()"><i class="fa-solid fa-magnifying-glass"></i></button> <button class="btn btn-light btn-outline-secondary" type="button" id="btnAddressClear"><i class="fa-solid fa-x"></i></button> </div> </div> </div> <div class="row"> <div class="col mx-auto"> <input class="form-control" type="text" id="mmRoadAddress" placeholder="도로명주소" readonly> </div> </div> <div class="row mt-2"> <div class="col mx-auto"> <input class="form-control" type="text" id="mmJibunAddress" placeholder="지번주소" readonly> </div> </div> <span id="guide" style="color:#999;display:none"></span> <div class="row mt-2"> <div class="col mx-auto"> <input class="form-control" type="text" id="mmDetailAddress" placeholder="상세주소"> </div> </div> <div class="row mt-2"> <div class="col mx-auto"> <input class="form-control" type="text" id="mmExtraAddress" placeholder="참고항목" readonly> </div> </div> <div class="row mt-2"> <div class="col mx-auto"> <input type="hidden" name="place"> <input class="form-control" type="text" id="mmLat" name="lat" placeholder="위도" readonly> </div> <div class="col mx-auto"> <input class="form-control" type="text" id="mmLng" name="lng" placeholder="경도" readonly> </div> </div> </div> <div class="col mx-auto"> <label class="form-label" for="cgfExplain">설명</label> <textarea class="form-control" id="cgfExplain"></textarea> </div> </div> </div> <div class="row"> <div class="col px-5"> <button class="btn btn-secondary" type="button" id="btnList"> <i class="fa-solid fa-bars"></i> </button> </div> <div class="col px-4" style="text-align: right;"> <button class="btn btn-danger" type="button" id="btnUelete"> <i class="fa-duotone fa-x"></i> </button> <button class="btn btn-danger" type="button" id="btnDelete"> <i class="fa-regular fa-trash-can"></i> </button> <button class="btn btn-success" type="button" id="btnSave"> <i class="fa-regular fa-file-excel"></i> </button> </div> </div> </div> </div> </div> </div> <!-- Footer Start --> <div class="container-fluid bg-dark text-light footer mt-5 pt-5"> <div class="container"> <div class="copyright"> <div class="row"> <div class="col text-center"> Copyright &copy; 2022&nbsp;<a class="border-bottom" href="#">ISML</a>&nbsp;lnc, All Right Reserved. </div> </div> <div class="row"> <div class="col text-center"> Designed By <a class="border-bottom" href="#">HTML Codex</a> </div> </div> </div> </div> </div> <!-- Footer End --> </form> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script> <script src="//t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script> <script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=17e90af3c57fa367793d1f57799dd4c9&libraries=services,clusterer,drawing"></script> <script src="/resources/xdmin/js/list.js"></script> <script src="/resources/xdmin/js/sidebar.js"></script> <script src="/resources/xdmin/js/reg.js"></script> <script type="text/javascript"> var goUrlList = "/member/memberList"; var goUrlInst = "/member/memberInst"; var goUrlUpdt = "/member/memberUpdt"; var goUrlUele = "/member/memberUele"; var goUrlDele = "/member/memberDele"; var form = $("form[name=form]"); $("#btnSave").on("click", function(){ form.attr("action", goUrlInst).submit(); }); $("#btnList").on("click", function(){ form.attr("action", goUrlList).submit(); }); $("#btnUelete").on("click", function(){ $("input:hidden[name=mmDelNy]").val(1); $(".modal-title").text("확 인"); $(".modal-body").text("해당 데이터를 삭제하시겠습니까 ?"); $("#btnModalUelete").show(); $("#btnModalDelete").hide(); $("#modalConfirm").modal("show"); }); $("#btnDelete").on("click", function(){ $("input:hidden[name=mmDelNy]").val(0); $(".modal-title").text("확 인"); $(".modal-body").text("해당 데이터를 삭제하시겠습니까 ?"); $("#btnModalUelete").hide(); $("#btnModalDelete").show(); $("#modalConfirm").modal("show"); }); $("#btnModalUelete").on("click", function(){ $("#modalConfirm").modal("hide"); formVo.attr("action", goUrlUele).submit(); }); $("#btnModalDelete").on("click", function(){ $("#modalConfirm").modal("hide"); formVo.attr("action", goUrlDele).submit(); }); //카카오 지도 API //본 예제에서는 도로명 주소 표기 방식에 대한 법령에 따라, 내려오는 데이터를 조합하여 올바른 주소를 구성하는 방법을 설명합니다. function mmExecDaumPostcode() { new daum.Postcode({ oncomplete: function(data) { // 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분. // 도로명 주소의 노출 규칙에 따라 주소를 표시한다. // 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다. var roadAddr = data.roadAddress; // 도로명 주소 변수 var extraRoadAddr = ''; // 참고 항목 변수 // 법정동명이 있을 경우 추가한다. (법정리는 제외) // 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다. if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){ extraRoadAddr += data.bname; } // 건물명이 있고, 공동주택일 경우 추가한다. if(data.buildingName !== '' && data.apartment === 'Y'){ extraRoadAddr += (extraRoadAddr !== '' ? ', ' + data.buildingName : data.buildingName); } // 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다. if(extraRoadAddr !== ''){ extraRoadAddr = ' (' + extraRoadAddr + ')'; } // 우편번호와 주소 정보를 해당 필드에 넣는다. document.getElementById('mmPostcode').value = data.zonecode; document.getElementById("mmRoadAddress").value = roadAddr; document.getElementById("mmJibunAddress").value = data.jibunAddress; // 참고항목 문자열이 있을 경우 해당 필드에 넣는다. if(roadAddr !== ''){ document.getElementById("mmExtraAddress").value = extraRoadAddr; } else { document.getElementById("mmExtraAddress").value = ''; } var guideTextBox = document.getElementById("guide"); // 사용자가 '선택 안함'을 클릭한 경우, 예상 주소라는 표시를 해준다. if(data.autoRoadAddress) { var expRoadAddr = data.autoRoadAddress + extraRoadAddr; guideTextBox.innerHTML = '(예상 도로명 주소 : ' + expRoadAddr + ')'; guideTextBox.style.display = 'block'; } else if(data.autoJibunAddress) { var expJibunAddr = data.autoJibunAddress; guideTextBox.innerHTML = '(예상 지번 주소 : ' + expJibunAddr + ')'; guideTextBox.style.display = 'block'; } else { guideTextBox.innerHTML = ''; guideTextBox.style.display = 'none'; } /* lat and lng from address s */ var geocoder = new daum.maps.services.Geocoder(); // 주소로 좌표를 검색 geocoder.addressSearch(roadAddr, function(result, status) { // 정상적으로 검색이 완료됐으면, if (status == daum.maps.services.Status.OK) { document.getElementById("mmLat").value=result[0].y; document.getElementById("mmLng").value=result[0].x; } }); /* lat and lng from address e */ } }).open(); } $("#btnAddressClear").on("click", function(){ $("#mmPostcode").val(''); $("#mmRoadAddress").val(''); $("#mmJibunAddress").val(''); $("#mmDetailAddress").val(''); $("#mmExtraAddress").val(''); $("#mmLat").val(''); $("#mmLng").val(''); }); </script> <!-- <script type="text/javascript"> function mmExecDaumPostcode() { new daum.Postcode({ oncomplete: function(data) { // 주소-좌표 변환 객체를 생성 var geocoder = new daum.maps.services.Geocoder(); // 주소로 좌표를 검색 geocoder.addressSearch(roadAddr, function(result, status) { // 정상적으로 검색이 완료됐으면, if (status == daum.maps.services.Status.OK) { document.getElementById("mmLat").value=result[0].y; document.getElementById("mmLng").value=result[0].x; } }); /* lat and lng from address e */ } </script> --> </body> </html>
package com.kylecorry.procamera.ui import android.content.Context import android.view.View import android.widget.TextView import androidx.core.view.isVisible import com.kylecorry.andromeda.alerts.Alerts import com.kylecorry.andromeda.core.system.Resources import com.kylecorry.procamera.R import com.kylecorry.procamera.ui.views.DurationInputView import java.time.Duration object CustomUiUtils { fun pickDuration( context: Context, default: Duration? = null, title: String, message: String? = null, hint: String? = null, showSeconds: Boolean = false, onDurationPick: (duration: Duration?) -> Unit ) { val view = View.inflate(context, R.layout.view_duration_entry_prompt, null) var duration: Duration? = default val durationMessage = view.findViewById<TextView>(R.id.prompt_duration_message) val durationInput = view.findViewById<DurationInputView>(R.id.prompt_duration) durationMessage.isVisible = !message.isNullOrBlank() durationMessage.text = message durationInput.showSeconds = showSeconds if (!hint.isNullOrBlank()) { durationInput.hint = hint } durationInput?.setOnDurationChangeListener { duration = it } durationInput?.updateDuration(default) Alerts.dialog( context, title, contentView = view ) { cancelled -> if (cancelled) { onDurationPick.invoke(null) } else { onDurationPick.invoke(duration) } } } fun Resources.getPrimaryColor(context: Context): Int { return getAndroidColorAttr(context, com.google.android.material.R.attr.colorPrimary) } }
package com.qi.likou.a23; import com.qi.ListNode; // public class Leet23demo2 { public ListNode mergeKLists(ListNode[] lists) { MinHeap heap = new MinHeap(lists.length); // 1. 将链表的头节点加入小顶堆 for (ListNode listNode : lists) { if (listNode != null) { heap.offer(listNode); } } // 2. 不断从堆顶移除最小元素,加入新链表 ListNode s = new ListNode(-1, null); ListNode t = s; while (!heap.isEmpty()) { // 从队列头中删除元素 ListNode min = heap.poll(); t.next = min; t = min; if (min.next!=null) { heap.offer(min.next); } } return s.next; } public static void main(String[] args) { ListNode[] listNodes = {new ListNode(1, new ListNode(4, new ListNode(5, null))), new ListNode(1, new ListNode(3, new ListNode(4, null))), new ListNode(2, new ListNode(6, null)),}; System.out.println(new Leet23demo2().mergeKLists(listNodes)); } }
<template> <div class="map-grid-wrapper"> <div class="desc"> <span v-on:click="mode = 'Empty'" v-bind:class="{ selected: mode == 'Empty' }" > Empty </span> <span v-on:click="mode = 'Block'" v-bind:class="{ selected: mode == 'Block' }" > Block </span> <span v-on:click="mode = 'Wall'" v-bind:class="{ selected: mode == 'Wall' }" > Wall </span> <span v-on:click="mode = 'PowerUp'" v-bind:class="{ selected: mode == 'PowerUp' }" > PowerUp </span> </div> <div class="map-grid"> <div v-for="(row, rowIndex) in grid" :key="rowIndex" class="map-grid-row" > <div v-for="(block, blockIndex) in row" :key="blockIndex" class="map-grid-block" v-on:click="toggleBlock(block)" v-on:mousedown="mouseDown = true" v-on:mouseup="mouseDown = false" v-on:mousemove="mouseDown && toggleBlock(block)" > <div v-if="block.isEmpty" class="map-grid-block-empty" ></div> <div v-if="block.isBlock" class="map-grid-block-block"> B </div> <div v-if="block.isWall" class="map-grid-block-wall">W</div> <div v-if="block.hasPowerUp" class="map-grid-block-power-up" > P </div> </div> </div> <div class="buttons"> <button v-on:click="saveMap()">Save Map</button> <button v-on:click="loadMap()">Load Map</button> </div> <div class="buttons"> <button v-on:click="restart()">Restart</button> <button v-on:click="emptyMap()">Empty Map</button> </div> </div> </div> </template> <script setup lang="ts"> import { ref, reactive } from "vue"; // Define a block type (Types: Empty, Block, PowerUp, Wall) type block = { isEmpty?: boolean; isBlock?: boolean; isWall?: boolean; hasPowerUp?: boolean; }; const mode = ref<"Empty" | "Block" | "Wall" | "PowerUp">("Empty"); const mouseDown = ref(false); // Add this line // Create a 20x16 grid of blocks const grid = reactive( Array.from({ length: 16 }, () => Array.from({ length: 20 }, () => ({ isEmpty: false, isBlock: true, isWall: false, hasPowerUp: false, })) ) ); const toggleBlock = (block: block) => { // Toggle the block type based on the current mode switch (mode.value) { case "Empty": block.isEmpty = true; block.isBlock = false; block.isWall = false; block.hasPowerUp = false; break; case "Block": block.isEmpty = false; block.isBlock = true; block.isWall = false; block.hasPowerUp = false; break; case "Wall": block.isEmpty = false; block.isBlock = false; block.isWall = true; block.hasPowerUp = false; break; case "PowerUp": block.isEmpty = false; block.isBlock = false; block.isWall = false; block.hasPowerUp = true; break; } }; const saveMap = () => { // Save the map in a text file in the following format: // Structure: <Row>, <Col>, <IsWall>, <HasPowerup>, <IsEmpty> const map = grid.map((row, rowIndex) => { return row.map((block, blockIndex) => { return `${rowIndex},${blockIndex},${block.isWall ? "1" : "0"},${ block.hasPowerUp ? "1" : "0" },${block.isEmpty ? "0" : "1"}`; }); }); // Add "Structure: <Row>, <Col>, <IsWall>, <HasPowerup>" at the top of the file map.unshift([ "Structure: <Row>, <Col>, <IsWall>, <HasPowerup>, <IsAlive>", ]); // Join the map array with a new line (Include the newline) (Remove the comma at the end of each line) const mapString = map .map((row) => row.join("\n")) .join("\n") .replace(/,\n/g, "\n"); console.log(mapString); const blob = new Blob([mapString], { type: "text/plain;charset=utf-8", }); const a = document.createElement("a"); a.download = "map.txt"; a.href = window.URL.createObjectURL(blob); a.dataset.downloadurl = ["text/plain", a.download, a.href].join(":"); a.style.display = "none"; document.body.appendChild(a); a.click(); document.body.removeChild(a); }; const loadMap = () => { // Load the map from a text file in the following format: // Structure: <Row>, <Col>, <IsWall>, <HasPowerup> const fileInput = document.createElement("input"); fileInput.type = "file"; fileInput.accept = ".txt"; fileInput.onchange = (e) => { const file = (e.target as HTMLInputElement)?.files?.[0]; const reader = new FileReader(); reader.onload = (e) => { const mapString = (e.target as FileReader)?.result as string; const map = mapString .split("\n") .slice(1) .map((row) => row.split(",")); console.log(map); map.forEach((blockData) => { const rowIndex = parseInt(blockData[0]); const blockIndex = parseInt(blockData[1]); const isWall = blockData[2] === "1"; const hasPowerUp = blockData[3] === "1"; const isEmpty = blockData[4] === "1" ? false : true; const isBlock = !isWall && !hasPowerUp && !isEmpty; const block = { isEmpty, isBlock, isWall, hasPowerUp, }; if (!grid[rowIndex]) { grid[rowIndex] = []; } grid[rowIndex][blockIndex] = block; }); }; if (file) { reader.readAsText(file); } }; fileInput.click(); }; const restart = () => { // Restart the map grid.forEach((row) => { row.forEach((block) => { block.isEmpty = false; block.isBlock = true; block.isWall = false; block.hasPowerUp = false; }); }); }; const emptyMap = () => { // Empty the map grid.forEach((row) => { row.forEach((block) => { block.isEmpty = true; block.isBlock = false; block.isWall = false; block.hasPowerUp = false; }); }); }; </script> <style lang="scss"> .map-grid-wrapper { display: flex; justify-content: center; align-items: center; gap: 20px; .desc { display: flex; flex-direction: column; gap: 10px; font-size: 20px; font-weight: bold; span { padding: 5px 15px; border: 1px solid black; border-radius: 24px; cursor: pointer; &.selected { border: 3px solid black; } } span:nth-child(2) { color: #fff; background-color: blue; } span:nth-child(3) { color: #fff; background-color: gray; } span:nth-child(4) { color: #fff; background-color: red; } } } .map-grid { display: flex; flex-direction: column; height: 100%; margin: 20px 0; .buttons { display: flex; gap: 40px; justify-content: center; } button { width: auto; align-self: center; border-radius: 24px; padding: 0 20px; height: 50px; font-size: 20px; font-weight: bold; background-color: #fff; border: 1px solid black; cursor: pointer; margin-top: 20px; transition: 0.4s all; &:hover { background: black; color: white; } } } .map-grid-row { display: flex; flex-direction: row; justify-content: center; width: 100%; height: 100%; } .map-grid-block { width: 25px; height: 25px; background: black; border: 1px solid white; cursor: pointer; user-select: none; * { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; color: white; font-size: 20px; } } .map-grid-block-block { background-color: blue; } .map-grid-block-wall { background-color: gray; } .map-grid-block-power-up { background-color: red; } </style>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> /* Centers entire page */ html, body { height: 100%; } html { display: table; width: 100%; } body { display: table-cell; text-align: center; vertical-align: middle; } .btn { background-color: white; /* Green */ border: 2px solid black; color: black; padding: 15px 32px 15px 32px; margin: 5px 5px 5px 5px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; } .red { background-color: red; } .blue { background-color: blue; } </style> </head> <body> <button id="1" class="btn">&nbsp;</button> <button id="2" class="btn">&nbsp;</button> <button id="3" class="btn">&nbsp;</button><br /> <button id="4" class="btn">&nbsp;</button> <button id="5" class="btn">&nbsp;</button> <button id="6" class="btn">&nbsp;</button><br /> <button id="7" class="btn">&nbsp;</button> <button id="8" class="btn">&nbsp;</button> <button id="9" class="btn">&nbsp;</button> <script> // bind onClick event listener to all buttons const collection = document.getElementsByClassName("btn"); for (let i = 0; i < collection.length; i++) { collection[i].addEventListener("click", setSquare); } let turn = "red"; // red goes first let turn_symbol = "O"; // red is X let board = { 1: "", 2: "", 3: "", 4: "", 5: "", 6: "", 7: "", 8: "", 9: "", }; function setSquare() { console.log(this.id); board[this.id] = turn; if (turn == "red") { turn = "blue"; turn_symbol = "X"; this.classList.add("blue"); } else { turn = "red"; turn_symbol = "O"; this.classList.add("red"); } this.innerHTML = turn_symbol; let winner = getWinner(); if (winner !== false) { if (winner == "tie") { } else { alert("we have a winner ... " + turn); } } } function getWinner() { if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[4] == turn && board[5] == turn && board[6] == turn) return turn; if (board[7] == turn && board[8] == turn && board[9] == turn) return turn; if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[1] == turn && board[2] == turn && board[3] == turn) return turn; if (board[1] != "" && board[2] != "") { return "tie"; } for (var selection in board) { if (board[selection] == "") { return false; } } return "tie"; } </script> </body> </html>
import { getAllCountrys } from "../../API/getAllCountrys"; import { useState, useEffect } from "react"; import { Options } from "../Options/Options"; import "./CountryGame.css"; import { Link } from "wouter"; import { LoadPicture } from "../Loaders/LoadPicture"; export function CountryGame() { const [rand, setRand] = useState(Math.floor(Math.random() * 110)); const [countrys, setCountrys] = useState([]); const [load, setLoad] = useState(true); const [numQuestion, setnumQuestion] = useState(1); const [selected, setselected] = useState(false); const [numCorrect, setNumCorrect] = useState(0); useEffect(() => { setLoad(true); getAllCountrys().then((data) => { const result = data.filter( (country) => country.hasOwnProperty("borders") && country.borders.length >= 2 ); setCountrys(result[rand]); setLoad(false); }); }, [rand]); if (load) { return ( <div className="containerLoadPic"> <h1 className="gameTitle">What country is?</h1> <LoadPicture /> </div> ); } const codes = countrys.borders.slice(0, 2); codes.push(countrys.cca3); const OPcodes = codes.sort(); const handleBtnNext = () => { setRand(Math.floor(Math.random() * 110)); setnumQuestion((prev) => prev + 1); setselected(false); }; const handleClick = (resc, e) => { let selected = e.currentTarget; let correct = document.getElementById(resc); if (selected.innerText === resc) { selected.classList.add("correct"); setNumCorrect((prev) => prev + 1); setselected(true); return; } setselected(true); selected.classList.add("incorrect"); correct.classList.add("correct"); }; return ( <> <div className="containerHead"> <h1 className="gameTitle">What country is?</h1> <img className="countryImg" src={countrys.flags.png} alt={countrys.name.official} /> </div> <div className="containerOptions"> {OPcodes.map((op) => ( <Options key={op} code={op} resC={countrys.name.official} clickOptions={handleClick} /> ))} </div> <div className="containerBtn"> <p className="question"> Question: {numQuestion} <span className="questionTotal">/10</span> </p> {selected && (numQuestion === 10 ? ( <Link to={`/FlagQuiz/game/end/${numCorrect}`}> <button className="btnNext">Game Score</button> </Link> ) : ( <button className="btnNext" onClick={handleBtnNext}> Next Country </button> ))} </div> </> ); }
import { useState } from 'react'; import { Menu } from 'antd'; import { useTranslation } from 'react-i18next'; import FlaggedMessages from './Flag/FlaggedMessages'; import UserbanPanel from './Ban/UserBanPanel'; import './ModerationPanel.css'; export const Component = (): React.ReactElement => { const { t } = useTranslation('modcp', { keyPrefix: 'modcp' }); const menuMap = [ { key: 'banned', name: t('bannedUsers'), component: <UserbanPanel t={t} />, }, { key: 'flagged', name: t('flaggedMsg'), component: <FlaggedMessages t={t} />, }, ]; const [selectKey, setSelectKey] = useState('banned'); const items = menuMap.map((item) => ({ key: item.key, label: ( <div role="button" aria-label={item.key} onClick={() => { setSelectKey(item.key); }} > {item.name} </div> ), })); const menuItem = menuMap.find((k) => k.key === selectKey); const title = menuItem !== undefined ? menuItem.name : ''; const childComponent = menuItem !== undefined ? menuItem.component : ''; return ( <div className="info-main"> <div className="leftmenu"> <Menu mode="inline" selectedKeys={[selectKey]} items={items} /> </div> <div className="right"> <div className="title">{title}</div> {childComponent} </div> </div> ); };
#pragma once #ifndef DVMON_GTESTJSON_H #define DVMON_GTESTJSON_H #include <gtest/gtest.h> #include <gmock/gmock.h> #include "json.h" namespace dv { namespace json { namespace testing { template<typename T> class JsonEqualsMatcher : public ::testing::MatcherInterface<T> { public: template<typename JSONType=JSON, detail::enable_if_t<std::is_same<JSON, JSONType>::value> = 0> JsonEqualsMatcher( const JSONType &nexpected ) : expected( nexpected ) {} JsonEqualsMatcher( const std::string &json ) { JSONParser parser; parser.parseInto( expected, json ); } void DescribeTo( ::std::ostream *os ) const override { *os << "is equal to " << expected; } void DescribeNegationTo( ::std::ostream *os ) const override { *os << "is not equal to " << expected; } bool MatchAndExplain( T x, ::testing::MatchResultListener *listener ) const override { JSON other; JSONParser parser; parser.parseInto( other, x ); JSONDiffListenerImpl diffListener; bool rt = expected.compare( other, diffListener ); if ( !rt && listener->IsInterested() ) { *listener << diffListener; } return rt; } protected: JSON expected; }; template<typename T, typename Y> inline ::testing::Matcher<T> jsonEquals( Y value ) { return MakeMatcher( new JsonEqualsMatcher<T>( value ) ); } } } } #endif //DVMON_GTESTJSON_H
package selenium_demo.experiencing_selenium; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class XpathClassExample { static WebDriver d = null; public static void main(String[] args) throws Exception { idetxpathwithrelative(); } public static void loadapplication() throws Exception { d = new ChromeDriver(); d.manage().window().maximize(); d.get("https://demo.automationtesting.in/Register.html"); Thread.sleep(3000); } public static void idetxpathwithrelative() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//input[@ng-model='FirstName']")); ele.sendKeys("Chincholi"); System.out.println(ele.getAttribute("value")); Thread.sleep(3000); tearDown(); } public static void idetxpathwithrelativeAnd() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//input[@type='text' and @placeholder='Last Name']")); ele.sendKeys("Chincholi"); System.out.println(ele.getAttribute("value")); Thread.sleep(3000); tearDown(); } public static void idetxpathwithrelativeOR() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//input[@type='tex' or @placeholder='Last Name']")); ele.sendKeys("Chincholi"); System.out.println(ele.getAttribute("value")); Thread.sleep(3000); tearDown(); } public static void idetxpathwithrelativeIndex() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("(//input[@type='text'])[2]")); ele.sendKeys("Chincholi"); System.out.println(ele.getAttribute("value")); Thread.sleep(3000); tearDown(); } public static void idetxpathwithxpathText() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//label[text()='Email address*']")); System.out.println(ele.getText()); Thread.sleep(3000); tearDown(); } public static void idetxpathwithxpathContains() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//label[contains(@class,'checks')]")); System.out.println(ele.getText()); Thread.sleep(3000); tearDown(); } public static void idetxpathwithxpathContainstext() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//label[contains(text(),'Hoc')]")); System.out.println(ele.getText()); Thread.sleep(3000); tearDown(); } public static void idetxpathwithxpathStartswith() throws Exception { loadapplication(); WebElement ele = d.findElement(By.xpath("//textarea[starts-with(@ng-model,'Adr')]")); ele.sendKeys("My Address location is Hyderabad"); Thread.sleep(3000); tearDown(); } public static void identxpathnormalizespace() throws Exception { d = new ChromeDriver(); d.manage().window().maximize(); d.get("https://demo.automationtesting.in/Windows.html"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//button[text()[normalize-space()='click']]")); ele.click(); Thread.sleep(3000); tearDown(); } public static void identxpathnormalizespacewithChainedXpath() throws Exception { d = new ChromeDriver(); d.manage().window().maximize(); d.get("https://demo.automationtesting.in/Windows.html"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@id='Tabbed']//button[text()[normalize-space()='click']]")); ele.click(); Thread.sleep(3000); tearDown(); } public static void xapthParentAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//input[@id='twotabsearchtextbox']/parent::div[@class='nav-search-field ']")); highlightEle(ele); Thread.sleep(3000); tearDown(); } public static void xapthChildAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@id='nav-xshop']/child::a[position()=4]")); highlightEle(ele); Thread.sleep(3000); tearDown(); } public static void xapthAncestorAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//input[@id='twotabsearchtextbox']/ancestor::div[@class='nav-fill']")); highlightEle(ele); Thread.sleep(3000); tearDown(); } public static void xapthDescendantAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@class='nav-fill']/descendant::input[@id='twotabsearchtextbox']")); highlightEle(ele); ele.sendKeys("Bread toaster"); ele.submit(); Thread.sleep(3000); tearDown(); } public static void xapthFollowingSiblingAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@id='nav-xshop']/a[text()='Mobiles']/following-sibling::a")); highlightEle(ele); ele.click(); Thread.sleep(3000); tearDown(); } public static void xapthPrecedingSiblingAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@id='nav-xshop']/a[text()='Mobiles']/preceding-sibling::a[text()=\"Today's Deals\"]")); highlightEle(ele); ele.click(); Thread.sleep(3000); tearDown(); } public static void xapthFollowingAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@id='nav-xshop']/a[text()='Mobiles']/following::a[5]")); highlightEle(ele); Thread.sleep(3000); tearDown(); } public static void xapthPrecedingAxes() throws Exception { d = new ChromeDriver(); d.manage().deleteAllCookies(); d.manage().window().maximize(); d.get("https://www.amazon.in/"); Thread.sleep(3000); WebElement ele = d.findElement(By.xpath("//div[@id='nav-xshop']/a[text()='Mobiles']/preceding::a[4]")); highlightEle(ele); Thread.sleep(3000); tearDown(); } public static void highlightEle(WebDriver d, WebElement ele) { JavascriptExecutor js = (JavascriptExecutor) d; js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", ele); } public static void highlightEle(WebElement ele) { JavascriptExecutor js = (JavascriptExecutor) d; js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", ele); } public static void tearDown() throws InterruptedException { Thread.sleep(3000); d.quit(); } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Putting data elements in the SVG container via JSON data</title> <script type="text/javascript" src="d3_source/4.11.0/d3.min.js"></script> </head> <body> </body> <script> var jsonCirclesData = [ { "x_axis": 30, "y_axis": 30, "r": 20, "color": "green" }, { "x_axis": 70, "y_axis": 70, "r": 20, "color": "purple" }, { "x_axis": 110, "y_axis": 100, "r": 20, "color": "red" } ]; var svgContainer = d3.select("body") .append("svg") .attr("width", 200) .attr("height", 200); var circles = svgContainer.selectAll("circle") .data(jsonCirclesData) .enter() .append("circle"); var circleAttributes = circles .attr("cx", function (d) {return d.x_axis; }) .attr("cy", function (d) {return d.y_axis; }) .attr("r", function (d) {return d.r; }) .attr("fill", function (d) {return d.color; }) </script>
use blockscape_core::primitives::Coord; use definitions::*; const MAX_HP: u32 = 100; /// Transfers data between buildings. pub struct DataBus { location: Coord, hp: u32 } impl Describable for DataBus { fn id(&self) -> u8 { 4 } fn str_id(&self) -> &'static str { "data_bus" } fn object_name(&self) -> &'static str { "Data Bus" } fn instance_name(&self) -> Option<&str> { None } fn status(&self) -> Option<&str> { None } fn description(&self) -> &'static str { "Allows for the transfer of data between structures." } } impl Worldly for DataBus { fn location(&self) -> Coord { self.location } fn hp(&self) -> u32 { self.hp } fn max_hp(&self) -> u32 { MAX_HP } fn decay_rate(&self) -> f32 { 0.006 } fn sp(&self) -> u32 { 0 } fn max_sp(&self) -> u32 { 0 } fn sp_regen_rate(&self) -> u32 { 0 } fn sp_regen_cost(&self) -> f32 { 0.0 } fn charge(&self) -> u64 { 0 } fn max_charge(&self) -> u64 { 0 } fn charge_rate(&self) -> u64 { 0 } fn passive_cost(&self) -> f32 { 0.0 } // TODO: Add energy cost fn data(&self) -> u64 { 0 } fn max_data(&self) -> u64 { 0 } fn transfer_rate(&self) -> u64 { 0 } fn passive_data(&self) -> f32 { 0.0 } fn energy_cost(&self) -> u64 { 120_000 } fn data_cost(&self) -> u64 { 40_000 } } impl Structure for DataBus { fn category(&self) -> &'static str { "infrastructure" } fn blocking(&self) -> bool { false } fn xy_len(&self) -> (u32, u32) { (1, 1) } } impl DataBus { pub fn new(location: Coord) -> DataBus { DataBus { location, hp: 0 } } pub fn prebuilt(location: Coord) -> DataBus { DataBus { location, hp: MAX_HP } } }
<h1>Reactive Form Works!</h1> <div class="Form-Class w-50 m-auto"> <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div class="form-group mb-3"> <label class="form-label">Full Name</label> <input type="text" class="form-control" placeholder="Full Name" name="FullName" formControlName="FullName"> <div class="alert alert-danger" *ngIf="FullName.touched && FullName.invalid"> <div *ngIf="FullName.errors && FullName.errors?.required"> Full Name is required..</div> <div *ngIf="FullName.errors && FullName.errors?.minlength"> Full Name is must be 5 charectors long..</div> </div> </div> <div class="form-group mb-3"> <label class="form-label">Email</label> <input type="email" class="form-control" placeholder="Email" name="Email" formControlName="Email"> <div class="alert alert-danger" *ngIf="Email.touched && Email.invalid"> <div *ngIf="Email.errors && Email.errors?.required"> Email is required..</div> <div *ngIf="Email.errors && Email.errors?.pattern"> invalid Email Address....</div> </div> </div> <!-- Contact details nested From Group --> <div formGroupName="contactDetails"> <div class="form-group mb-3"> <label class="form-label">Address</label> <textarea type="text" cols="30" rows="3" class="form-control" placeholder="Address" name="Address" formControlName="Address"></textarea> <div class="alert alert-danger" *ngIf="Address.touched && Address.invalid"> <div *ngIf="Address.errors && Address.errors?.required"> Address is required..</div> </div> </div> <div class="form-group mb-3"> <label class="form-label">Shiping Address</label> <textarea type="text" cols="30" rows="3" class="form-control" placeholder="Shiping Address" name="ShipingAddress" formControlName="ShipingAddress"></textarea> <div class="alert alert-danger" *ngIf="ShipingAddress.touched && ShipingAddress.invalid"> <div *ngIf="ShipingAddress.errors && ShipingAddress.errors?.required"> Shiping Address is required..</div> </div> </div> <div class="form-group mb-3"> <label class="form-label">Contac No</label> <input type="number" class="form-control" placeholder="Contact No" name="contactNo" formControlName="contactNo"> <div class="alert alert-danger" *ngIf="contactNo.touched && contactNo.invalid"> <div *ngIf="contactNo.errors && contactNo.errors?.required"> Contact No is required..</div> <div *ngIf="contactNo.errors && contactNo.errors?.pattern"> invalid contact No....</div> </div> </div> <!-- Contact details Array From Group --> <div class="form-group mb-3"> <label class="form-label">Skills</label> <input type="text" class="form-control" (keyup.enter)="addSkills(skill)" #skill> <ul class="list-group"> <li class="list-group-item" *ngFor="let skill of Skills.controls; let i = index "> {{skill.value}} <a class="btn btn-sm btn-danger" (click)="removeSkills(i)">X</a> </li> </ul> </div> <!-- Contact details Array From Group --> </div> <!-- Contact details nested From Group --> <div class="form-group mb-3"> <button class="btn btn-primary" [disabled]="form.invalid">Submit</button> </div> </form> </div>
<?php ob_start(); session_start(); require_once("Includes/db.php"); $cardTypeIsEmpty = false; if (isset($_SESSION['userID'])) { $idUser = $_SESSION['userID']; $userType = $_SESSION['userType']; $fullname = $_SESSION['fullname']; } else { header('Location: index.php'); exit; } if ($userType != 'Admin') { header('Location: index.php'); exit; } if ($_SERVER['REQUEST_METHOD'] == "GET") { if (isset($_GET['idCard'])) { $cardSelectedId = $_GET['idCard']; $cardItem = DBUtil::getInstance()->getCardDetail($cardSelectedId); } } if ($_SERVER['REQUEST_METHOD'] == "POST") { $cardItem = array("idCard" => $_POST['idCard'], "cardCode" => $_POST['cardCode'], "longTerm" => $_POST['longTerm'], "remainTimes" => $_POST['remainTimes'], "idCardType" => $_POST['idCardType']); } ?> <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Templates and open the template in the editor. --> <html> <head> <meta charset="UTF-8"> <title>Thông tin loại thẻ</title> </head> <body> <?php include 'header.php' ?> <h2 style="color: #188420;"><center>THÔNG TIN CHI TIẾT THẺ</center></h2> <div style="width: 90%"> <form class="form-horizontal" role="form" action="editCard.php" method="POST" > <input type="hidden" name="idCard" value="<?php echo $cardItem["idCard"]; ?>" /> <div class="form-group"> <label class="control-label col-sm-2" for="cardCode">Mã thẻ<label style="color: red">(*)</label>:</label> <div class="col-sm-10"> <input type="text" readonly="true" class="form-control" name="cardCode" value="<?php echo $cardItem["cardCode"]; ?>" /> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="idCardType">Tên Loại Thẻ<label style="color: red">(*)</label>: </label> <div class="col-sm-10"> <select class="selectpicker" name='idCardType' id='idCardType' value='<?php echo $cardItem["idCardType"]; ?>'> <option value=''>Chọn</option> <?php $listCardType = DBUtil::getInstance()->getListCardType(); while ($row = mysqli_fetch_array($listCardType)) { if ($cardItem["idCardType"] == $row["idCardType"]) { $selected = ' selected="selected"'; } else { $selected = ''; } echo "<option value=" . htmlentities($row["idCardType"]) . $selected . ">" . htmlentities($row["typeName"], ENT_QUOTES, 'utf-8') . "</option>\n"; } mysqli_free_result($listCardType); ?> </select> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="longTerm">Thẻ Dài Hạn:</label> <div class="col-sm-10"> <input type="checkbox" name="longTerm" value="<?php echo $cardItem['longTerm']; ?>" <?php if ($cardItem['longTerm'] == 1) echo "checked='checked'"; ?>/> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="remainTimes">Số lần quẹt còn lại:</label> <div class="col-sm-10"> <input type="text" class="form-control numberOnly" name="remainTimes" value="<?php echo $cardItem["remainTimes"]; ?>" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input class="btn btn-success" type="<?php if ($userType == 'Admin' || 1==1) echo 'submit'; else echo 'hidden'; ?>" value="Lưu chỉnh sửa" /> <input type="button" class="btn btn-success" value="Trở lại" onClick="history.back();" /> </div> </div> </form> </div> <?php /** Check that the page was requested from itself via the POST method. */ if ($_SERVER['REQUEST_METHOD'] == "POST") { $mess = ''; if ($_POST['idCardType'] == "") { $cardTypeIsEmpty = true; $mess = $mess . "<br/>Loại thẻ bắt buộc nhập "; } if (!$cardTypeIsEmpty) { if(isset($_POST['longTerm'])) $longTerm = 1; else $longTerm = 0; DBUtil::getInstance()->updateCard($_POST["idCard"], $_POST["idCardType"], $longTerm, $_POST["remainTimes"]); header('Location: listCard.php'); exit; } else { echo("<div class='alert alert-danger'><strong>Lỗi!</strong> " . $mess . "</div>"); } } ?> </body> <script> $(".numberOnly").keypress(function (e) { //if the letter is not digit then display error and don't type anything if (e.which != 8 && e.which != 46 && e.which != 0 && (e.which < 48 || e.which > 57)) { return false; } }); </script> </html>
package by.arvisit.cabapp.driverservice.mapper; import static by.arvisit.cabapp.driverservice.util.DriverTestData.NEW_DRIVER_NAME; import static by.arvisit.cabapp.driverservice.util.DriverTestData.getCar; import static by.arvisit.cabapp.driverservice.util.DriverTestData.getCarResponseDto; import static by.arvisit.cabapp.driverservice.util.DriverTestData.getDriver; import static by.arvisit.cabapp.driverservice.util.DriverTestData.getDriverRequestDto; import static by.arvisit.cabapp.driverservice.util.DriverTestData.getDriverResponseDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mapstruct.factory.Mappers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import by.arvisit.cabapp.driverservice.dto.CarRequestDto; import by.arvisit.cabapp.driverservice.dto.DriverRequestDto; import by.arvisit.cabapp.driverservice.dto.DriverResponseDto; import by.arvisit.cabapp.driverservice.persistence.model.Car; import by.arvisit.cabapp.driverservice.persistence.model.Driver; @ExtendWith(MockitoExtension.class) class DriverMapperTest { private static final String IS_AVAILABLE_FIELD = "isAvailable"; private static final String ID_FIELD = "id"; @InjectMocks private DriverMapper driverMapper = Mappers.getMapper(DriverMapper.class); @Mock private CarMapper carMapper; @Test void shouldMapFromEntityToResponseDto() { Driver entity = getDriver().build(); when(carMapper.fromEntityToResponseDto(any(Car.class))) .thenReturn(getCarResponseDto().build()); DriverResponseDto actualResponseDto = driverMapper.fromEntityToResponseDto(entity); DriverResponseDto expectedResponseDto = getDriverResponseDto().build(); assertThat(actualResponseDto) .usingRecursiveComparison() .isEqualTo(expectedResponseDto); } @Test void shouldMapFromRequestDtoToEntity() { DriverRequestDto requestDto = getDriverRequestDto().build(); when(carMapper.fromRequestDtoToEntity(any(CarRequestDto.class))) .thenReturn(getCar().build()); Driver actualEntity = driverMapper.fromRequestDtoToEntity(requestDto); Driver expectedEntity = getDriver().build(); assertThat(actualEntity) .usingRecursiveComparison() .ignoringFields(ID_FIELD, IS_AVAILABLE_FIELD) .isEqualTo(expectedEntity); } @Test void shouldUpdateEntityWithRequestDto() { DriverRequestDto requestDto = getDriverRequestDto() .withName(NEW_DRIVER_NAME) .build(); Driver entityToUpdate = getDriver().build(); driverMapper.updateEntityWithRequestDto(requestDto, entityToUpdate); assertThat(entityToUpdate.getName()) .isEqualTo(requestDto.name()); } }
// import { twMerge } from 'tailwind-merge'; import { FormControl, FormErrorMessage } from '@chakra-ui/react'; import { forwardRef } from 'react'; import { capitalize } from '@utils/constants'; import { Controller } from 'react-hook-form'; const ControlledCheckbox = forwardRef((props: any, _ref) => { const { label, checkboxValue, checked, control, name, className, showError = true, } = props; return ( <Controller name={name} control={control} render={({ field: { onChange }, fieldState: { error } }) => ( <FormControl isInvalid={Boolean(error)}> {error?.message && showError && ( <FormErrorMessage className="font-bold" fontSize={10} mt="0.5"> {error?.message ? capitalize(error?.message) : ''} </FormErrorMessage> )} <div className="text-[13px] flex gap-[5px] items-center cursor-pointer"> <input type="checkbox" name={name} checked={checked} id={checkboxValue} value={checkboxValue} className={`${className} border-[#0e2038] accent-[#0e2038] cursor-pointer`} onChange={e => onChange(e.target.checked ? e.target.value : '')} /> <label htmlFor={checkboxValue} className="text-[13px] font-[400] text-start cursor-pointer opacity-100" > {label} </label> </div> </FormControl> )} /> ); }); export default ControlledCheckbox;
package com.roleplayer.master.ui.universe.settings import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.asLiveData import com.roleplayer.common.domain.model.Universe import com.roleplayer.common.domain.model.UserResumed import com.roleplayer.common.presentation.utils.text.flow.asLiveDataResult import com.roleplayer.master.repositories.universe.UniverseRepository import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.flow.flowOn import java.io.InputStream class UniverseSettingsViewModel( private val masterId: String, private val universeId: String, private val repository: UniverseRepository ) : ViewModel() { val players = repository.getUniversePlayers(universeId) .flowOn(IO) .asLiveDataResult() val bannedPlayers = repository.getBannedPlayers(universeId) .flowOn(IO) .asLiveDataResult() val universe = repository.getUniverse(universeId, masterId) .asLiveDataResult() val playersCount = repository.getUniversePlayersCount(universeId) .flowOn(IO) .asLiveData() private val _imageInputStream = MutableLiveData<InputStream?>() fun setImageInputStream(inputStream: InputStream?) { _imageInputStream.value = inputStream } fun saveUniverse(universe: Universe) = repository.saveUniverse(universe, _imageInputStream.value) .flowOn(IO) .asLiveDataResult() fun banPlayer(playerToBan: UserResumed) = repository.banPlayerFromUniverse(universeId, playerToBan) .flowOn(IO) .asLiveDataResult() fun unBanPlayer(playerToUnBan: UserResumed) = repository.unBanPlayerFromUniverse(universeId, playerToUnBan) .flowOn(IO) .asLiveDataResult() fun deleteUniverse(universe: Universe) = repository.deleteUniverse(universe) .flowOn(IO) .asLiveDataResult() class Factory( private val masterId: String, private val universeId: String, private val repository: UniverseRepository ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") if (modelClass.isAssignableFrom(UniverseSettingsViewModel::class.java)) { return UniverseSettingsViewModel(masterId, universeId, repository) as T } throw IllegalArgumentException("Unknown") } } }
/* Copyright (c) 2006-2023 SpaceSUR and CONAE This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. This file is part of the SuriLib project and its derived programs. You must retain this copyright notice and license text in all copies or substantial portions of the software. If you develop a program based on this software, you must provide a visible notice to its users that it contains code from the SuriLib project and provide a copy of this license. The notice should be displayed in a way that is easily accessible to users, such as in the program's "About" box or documentation. For more information about SpaceSUR, visit <https://www.spacesur.com>. For more information about CONAE, visit <http://www.conae.gov.ar/>. */ // Includes Estandar #include <vector> #include <math.h> // Includes Suri #include "SpectralAngleMapperAlgorithm.h" #include "suri/xmlnames.h" #include "suri/DataTypes.h" #include "suri/AuxiliaryFunctions.h" #include "ClassInformation.h" // Includes Wx // Defines // forwards namespace suri { /** Macro para registrar el tipo de algoritmo de clasificacion de forma automatica */ AUTO_REGISTER_CLASS(ClassificationAlgorithmInterface, SpectralAngleMapperAlgorithm, 0) /** * El algoritmo de clasificacion spectral angle mapper debe verificar las firmas espectrales * definidas en cada clase para cada banda. Cada registro de la firma espectral * En caso de que el pixel en todas las bandas este dentro del intervalo definido, * se considera que pasa a formar parte de la clase definida. * En caso contrario, pasa a ser parte de la clase NOCLASE (AND entre condiciones de banda). * @param[out] pDest imagen con ints donde se guardan los ids * @param[in] pSource imagen que se quiere clasificar * @param[in] Size cantidad de pixeles en la imagen a clasificar * @param[in] Classes vector con la informacion de las clases a clasificar */ template<typename T> bool samClassification( int* pDest, std::vector<void*> &pSource, size_t Size, int NDVPixelValue, double Ndv, bool NdvAvailable, const std::vector<SpectralAngleMapperAlgorithm::ClassSpectralInfo> &Classes) { int bandcount = pSource.size(); std::vector<T*> psrc; if (Classes.empty()) return false; // realizo una conversion de los tipos de datos for (int i = 0; i < bandcount; i++) psrc.push_back(static_cast<T*>(pSource[i])); // Para cada pixel en la imagen for (size_t pixelposition = 0; pixelposition < Size; pixelposition++) { int classindex = ClassInformation::NoClassIndex; bool invalidpixel = true; // Salida para pixel no valido. // (valor no valido en todas las bandas involucradas) // Ver TCK #7325 if (NdvAvailable) { for (int i = 0; i < bandcount && invalidpixel; ++i) { if (static_cast<double>(psrc[i][pixelposition]) != CLASSIFICATION_NDV) invalidpixel = false; } } else { invalidpixel = false; } // Si el pixel es valido hago el proc normal. if (invalidpixel == false) { std::vector<SpectralAngleMapperAlgorithm::ClassSpectralInfo>::const_iterator cit = Classes.begin(); for (int c = 0; classindex == ClassInformation::NoClassIndex && cit != Classes.end(); ++cit, ++c) { double spectralangle = cit->maxangle_ + 1; double upper = 0; double lowerpixel = 0, lowerreflectance = 0; std::vector<SpectralAngleMapperAlgorithm::BandSpectralInfo>::const_iterator bit = cit->bands_.begin(); for (; bit != (cit->bands_.end()); ++bit) { // obtengo el valor del pixel en la banda double pixeldata = static_cast<double>(psrc.at(bit->band_)[pixelposition]); upper += (pixeldata * bit->reflectance_); lowerpixel += (pixeldata * pixeldata); lowerreflectance += (bit->reflectance_ * bit->reflectance_); } if (lowerpixel == 0 || lowerreflectance == 0) continue; double lower = sqrt(lowerpixel * lowerreflectance); spectralangle = acos(upper / lower); classindex = spectralangle <= cit->maxangle_ ? cit->classIndex_ : ClassInformation::NoClassIndex; } } else { // Sino le pongo un valor para la parte de la imagen que no // es valida. classindex = NDVPixelValue; } pDest[pixelposition] = classindex; } return true; } /** * El algoritmo de clasificacion spectral angle mapper debe verificar las firmas espectrales * definidas en cada clase para cada banda. Cada registro de la firma espectral * En caso de que el pixel en todas las bandas este dentro del intervalo definido, * se considera que pasa a formar parte de la clase definida. * En caso contrario, pasa a ser parte de la clase NOCLASE (AND entre condiciones de banda). * @param[out] pDest imagen con ints donde se guardan los ids * @param[in] pSource imagen que se quiere clasificar * @param[in] Size cantidad de pixeles en la imagen a clasificar * @param[in] Classes vector con la informacion de las clases a clasificar */ template<typename T> bool samCalculator( float* pDest, std::vector<void*> &pSource, size_t Size, int NDVPixelValue, double Ndv, bool NdvAvailable, const std::vector<SpectralAngleMapperAlgorithm::ClassSpectralInfo> &Classes) { int bandcount = pSource.size(); std::vector<T*> psrc; if (Classes.empty()) return false; // realizo una conversion de los tipos de datos for (int i = 0; i < bandcount; i++) psrc.push_back(static_cast<T*>(pSource[i])); // Para cada pixel en la imagen for (size_t pixelposition = 0; pixelposition < Size; pixelposition++) { int classindex = ClassInformation::NoClassIndex; bool invalidpixel = true; // Salida para pixel no valido. // (valor no valido en todas las bandas involucradas) if (NdvAvailable) { for (int i = 0; i < bandcount && invalidpixel; ++i) { if (static_cast<double>(psrc[i][pixelposition]) != Ndv) invalidpixel = false; } } else { invalidpixel = false; } // Si el pixel es valido hago el proc normal. if (invalidpixel == false) { std::vector<SpectralAngleMapperAlgorithm::ClassSpectralInfo>::const_iterator cit = Classes.begin(); double pixelspectralangle = Classes.begin()->maxangle_ + 1; for (int c = 0; classindex == ClassInformation::NoClassIndex && cit != Classes.end(); ++cit, ++c) { double spectralangle = cit->maxangle_ + 1; double upper = 0; double lowerpixel = 0, lowerreflectance = 0; std::vector<SpectralAngleMapperAlgorithm::BandSpectralInfo>::const_iterator bit = cit->bands_.begin(); for (; bit != (cit->bands_.end()); ++bit) { // obtengo el valor del pixel en la banda double pixeldata = static_cast<double>(psrc.at(bit->band_)[pixelposition]); upper += (pixeldata * bit->reflectance_); lowerpixel += (pixeldata * pixeldata); lowerreflectance += (bit->reflectance_ * bit->reflectance_); } if (lowerpixel == 0 || lowerreflectance == 0) continue; double lower = sqrt(lowerpixel * lowerreflectance); spectralangle = acos(upper / lower); pixelspectralangle = spectralangle < pixelspectralangle ? spectralangle : pixelspectralangle; spectralangle <= cit->maxangle_ ? cit->classIndex_ : ClassInformation::NoClassIndex; classindex = pixelspectralangle; } } else { // Sino le pongo un valor para la parte de la imagen que no // es valida. classindex = NDVPixelValue; } pDest[pixelposition] = classindex; } return true; } /** Constructor */ SpectralAngleMapperAlgorithm::SpectralAngleMapperAlgorithm() : noClassIndex_(0) { } /** Inicializa mapa de tipos de datos. */ INITIALIZE_DATATYPE_MAP(SpectralAngleMapperAlgorithm::ClassifyFunctionType, samClassification); INITIALIZE_DATATYPE_MAP(SpectralAngleMapperAlgorithm::FloatClassifyFunctionType, samCalculator); /** Destructor */ SpectralAngleMapperAlgorithm::~SpectralAngleMapperAlgorithm() { } /** * Actualiza los datos internos del algoritmo con los del nodo. * @param[in] pAlgorithmNode nodo del algoritmo * @return informa si el nodo era del tipo correto. */ bool SpectralAngleMapperAlgorithm::Update(const wxXmlNode* pAlgorithmNode) { wxXmlNode* pchild = pAlgorithmNode ? pAlgorithmNode->GetChildren() : NULL; if (pchild == NULL) return false; bool ok = true; classes_.clear(); while (ok && pchild != NULL) { if (pchild->GetName().compare(CLASSIFICATION_NO_CLASS_NODE) == 0) { noClassIndex_ = StringToNumber<int>(pchild->GetNodeContent().c_str()); } else if (pchild->GetName().compare(CLASSIFICATION_CLASS_NODE) == 0) { ClassSpectralInfo classinfo; ok = LoadClassInfoFromXml(pchild, classinfo); if (ok) classes_.push_back(classinfo); } pchild = pchild->GetNext(); } return ok; } /** * Metodo auxiliar que actualiza la informacion de clases en funcion del xml * @param[in] pClassNode nodo xml con la informacion de clases * @param[out] ClassInfo estructura en donde se almacena la configuracion de * clase que se encontraba en el xml * @return true en caso de parsear con exito el nodo * @return false en caso contrario */ bool SpectralAngleMapperAlgorithm::LoadClassInfoFromXml(const wxXmlNode* pClassNode, ClassSpectralInfo& ClassInfo) { wxXmlNode* pchild = pClassNode ? pClassNode->GetChildren() : NULL; if (!pchild) return false; bool ok = true; while (ok && pchild != NULL) { if (pchild->GetName().compare(CLUSTER_INDEX_NODE) == 0) { ClassInfo.classIndex_ = StringToNumber<int>(pchild->GetNodeContent().c_str()); } else if (pchild->GetName().compare(SAM_NODE) == 0) { ClassInfo.maxangle_ = StringToNumber<double>(pchild->GetNodeContent().c_str()); } else if (pchild->GetName().compare(CLASSIFICATION_BAND_NODE) == 0) { wxXmlNode* pband = pchild->GetChildren(); BandSpectralInfo bandinfo; while (ok && pband != NULL) { if (pband->GetName().compare(CLUSTER_INDEX_NODE) == 0) { bandinfo.band_ = StringToNumber<int>(pband->GetNodeContent().c_str()); } else if (pband->GetName().compare(CLASSIFICATION_REFLECTANCE_NODE) == 0) { bandinfo.reflectance_ = StringToNumber<double>(pband->GetNodeContent().c_str()); } pband = pband->GetNext(); } ClassInfo.bands_.push_back(bandinfo); } pchild = pchild->GetNext(); } return ok; } /** Genera nodo con los datos internos del algoritmo. Se utilizara una estructura * como la siguiente para la definicion * * \verbatim * <classificacion> * <nombre_aglritmo>SpectralAngleMapperAlgorithm</nombre_aglritmo> * <noclase> * <indice>0</indice> !-- nocluster no puede tener indice anterior. * </noclase> * <sam> double </sam> * <clase> * <indice>1</indice> <!-- Indice que posee el cluster --> * <banda> * <!-- Indice de la banda --> * <indice> 0 </indice> * <!-- Reflectancia definida para cada banda --> * <reflectance> double </reflectance> * </banda> * </clase> * </algoritmo> * </classificacion> * \endverbatim*/ wxXmlNode* SpectralAngleMapperAlgorithm::GetNode() { wxXmlNode *palgorithmnode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT(CLASSIFICATION_ALGORITHM_NODE)); // se agrega nombre del algoritmo new wxXmlNode(new wxXmlNode(palgorithmnode, wxXML_ELEMENT_NODE, ALGORITHM_NAME_NODE), wxXML_TEXT_NODE, wxEmptyString, ALGORITHM_VALUE_SAM); // generacion de nodo no clase con indice 0 wxXmlNode* pclassnode = new wxXmlNode(palgorithmnode, wxXML_ELEMENT_NODE, CLASSIFICATION_NO_CLASS_NODE); // se agrega como hijo el indice de no clase wxString noclassindex; noclassindex << ClassInformation::NoClassIndex; new wxXmlNode(new wxXmlNode(pclassnode, wxXML_ELEMENT_NODE, CLUSTER_INDEX_NODE), wxXML_TEXT_NODE, wxEmptyString, noclassindex); std::vector<ClassSpectralInfo>::const_iterator it = classes_.begin(); // se recorren las definiciones de las clases y se arma el xml de las mismas for (; it != classes_.end(); ++it) { pclassnode = CreateClassNode(*it); // completar el nodo palgorithmnode->AddChild(pclassnode); } return palgorithmnode; } /** * Metodo auxiliar que crea un nodo xml que representa la informacion * que contiene la clase que se pasa por parametro * @param[in] ClassInfo estructura que contiene la informacion de la clase * @return nodo xml con la informacion */ wxXmlNode* SpectralAngleMapperAlgorithm::CreateClassNode( const ClassSpectralInfo& ClassInfo) const { wxXmlNode* pclassnode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, CLASSIFICATION_CLASS_NODE); // nodo con indice de la clase new wxXmlNode(new wxXmlNode(pclassnode, wxXML_ELEMENT_NODE, CLUSTER_INDEX_NODE), wxXML_TEXT_NODE, wxEmptyString, NumberToString<int>(ClassInfo.classIndex_).c_str()); // nodo con angulo espectral de la clase new wxXmlNode(new wxXmlNode(pclassnode, wxXML_ELEMENT_NODE, SAM_NODE), wxXML_TEXT_NODE, wxEmptyString, DoubleToString(ClassInfo.maxangle_)); std::vector<BandSpectralInfo>::const_iterator bit = ClassInfo.bands_.begin(); for (; bit != ClassInfo.bands_.end(); ++bit) { // se genera el nodo para cada banda wxXmlNode* pbandsnode = CreateBandNode(*bit); pclassnode->AddChild(pbandsnode); } return pclassnode; } /** * Metodo auxiliar que genera un nodo xml con la informacion de la firma espectral * de la banda que se pasa por parametro * @param[in] BandInfo estructura que contiene la informacion de las bandas * @return nodo xml con el contenido de la banda pasada por parametro */ wxXmlNode* SpectralAngleMapperAlgorithm::CreateBandNode( const BandSpectralInfo& BandInfo) const { // se genera el nodo para cada banda wxXmlNode* pbandsnode = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, CLASSIFICATION_BAND_NODE); // indice new wxXmlNode(new wxXmlNode(pbandsnode, wxXML_ELEMENT_NODE, CLUSTER_INDEX_NODE), wxXML_TEXT_NODE, wxEmptyString, NumberToString<int>(BandInfo.band_).c_str()); // reflectancia new wxXmlNode(new wxXmlNode(pbandsnode, wxXML_ELEMENT_NODE, CLASSIFICATION_REFLECTANCE_NODE), wxXML_TEXT_NODE, wxEmptyString, DoubleToString(BandInfo.reflectance_).c_str()); return pbandsnode; } /** * Utiliza la funcion de sam para asignar una clase a cada pixel. * @param[in] pDest destino de la clasificacion * @param[in] pSource fuente de datos para clasificar * @param[in] Size cantidad de pixeles * @return true si puede aplicar la funcion de clasificacion, false en otro caso */ bool SpectralAngleMapperAlgorithm::Classify(int* pDest, std::vector<void*> pSource, size_t Size, const std::string &DataType) { function_ = samClassificationTypeMap[DataType]; return function_(pDest, pSource, Size, GetNDVPixelValue(), GetNoDataValue(), IsNoDataValueAvailable(), classes_); } /** * Utiliza la funcion de sam para asignar una clase a cada pixel. * @param[in] pDest destino de la clasificacion * @param[in] pSource fuente de datos para clasificar * @param[in] Size cantidad de pixeles * @return true si puede aplicar la funcion de clasificacion, false en otro caso */ bool SpectralAngleMapperAlgorithm::Classify(float* pDest, std::vector<void*> pSource, size_t Size, const std::string &DataType) { return samCalculatorTypeMap[DataType](pDest, pSource, Size, GetNDVPixelValue(), GetNoDataValue(), IsNoDataValueAvailable(), classes_); } bool SpectralAngleMapperAlgorithm::Check() const { bool validdef = true; std::vector<ClassSpectralInfo>::const_iterator it = classes_.begin(); for (; validdef && it != classes_.end(); ++it) { std::string minstr, maxstr; std::vector<BandSpectralInfo>::const_iterator bit = it->bands_.begin(); for (; validdef && bit != it->bands_.end(); ++bit) { // if (bit->min_ > bit->max_) // validdef = false; } } return validdef; } } /** namespace suri */
#include "person.h" #include "database.h" #include "../config/config.h" #include <Poco/Data/MySQL/Connector.h> #include <Poco/Data/MySQL/MySQLException.h> #include <Poco/Data/SessionFactory.h> #include <Poco/Data/RecordSet.h> #include <Poco/JSON/Parser.h> #include <Poco/Dynamic/Var.h> #include <sstream> #include <exception> using namespace Poco::Data::Keywords; using Poco::Data::Session; using Poco::Data::Statement; namespace database { void Person::init() { try { Poco::Data::Session session = database::Database::get().create_session(); for (auto &hint : database::Database::get_all_hints()) { Statement drop_stmt(session); drop_stmt << "DROP TABLE IF EXISTS Users" << hint, now; std::cout << hint << std::endl; Statement create_stmt(session); create_stmt << "CREATE TABLE IF NOT EXISTS `Person` (`login` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL," << "`first_name` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL," << "`last_name` VARCHAR(256) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL," << "`age` SMALLINT NOT NULL," << "PRIMARY KEY (`login`),KEY `fn` (`first_name`),KEY `ln` (`last_name`));" << hint, now; } } catch (Poco::Data::MySQL::ConnectionException &e) { std::cout << "connection:" << e.what() << std::endl; throw; } catch (Poco::Data::MySQL::StatementException &e) { std::cout << "statement:" << e.what() << std::endl; throw; } } Poco::JSON::Object::Ptr Person::toJSON() const { Poco::JSON::Object::Ptr root = new Poco::JSON::Object(); root->set("login", _login); root->set("first_name", _first_name); root->set("last_name", _last_name); root->set("age", _age); return root; } Person Person::fromJSON(const std::string &str) { Person person; Poco::JSON::Parser parser; Poco::Dynamic::Var result = parser.parse(str); Poco::JSON::Object::Ptr object = result.extract<Poco::JSON::Object::Ptr>(); person.login() = object->getValue<std::string>("login"); person.first_name() = object->getValue<std::string>("first_name"); person.last_name() = object->getValue<std::string>("last_name"); person.age() = object->getValue<long>("age"); return person; } Person Person::read_by_login(std::string login) { try { std::string hint = database::Database::sharding_hint(login); Poco::Data::Session session = database::Database::get().create_session(); Poco::Data::Statement select(session); Person a; select << "SELECT login, first_name, last_name, age FROM Person where login=?", into(a._login), into(a._first_name), into(a._last_name), into(a._age), use(login), range(0, 1); select << hint; select.execute(); std::cout << "searching in: " << hint << std::endl; Poco::Data::RecordSet rs(select); if (!rs.moveFirst()) throw std::logic_error("not found"); return a; } catch (Poco::Data::MySQL::ConnectionException &e) { std::cout << "connection:" << e.what() << std::endl; throw; } catch (Poco::Data::MySQL::StatementException &e) { std::cout << "statement:" << e.what() << std::endl; throw; } } std::vector<Person> Person::read_all() { try { Poco::Data::Session session = database::Database::get().create_session(); Statement select(session); std::vector<Person> result; for (auto &hint : database::Database::get_all_hints()) { Statement select(session); Person a; select << "SELECT login, first_name, last_name, age FROM Person" << hint, into(a._login), into(a._first_name), into(a._last_name), into(a._age), range(0, 1); while (!select.done()) { if(select.execute()) result.push_back(a); } } return result; } catch (Poco::Data::MySQL::ConnectionException &e) { std::cout << "connection:" << e.what() << std::endl; throw; } catch (Poco::Data::MySQL::StatementException &e) { std::cout << "statement:" << e.what() << std::endl; throw; } } std::vector<Person> Person::search(std::string first_name, std::string last_name) { try { Poco::Data::Session session = database::Database::get().create_session(); std::vector<Person> result; for (auto &hint : database::Database::get_all_hints()) { Statement select(session); Person a; first_name+="%"; last_name+="%"; select << "SELECT login, first_name, last_name, age FROM Person where first_name LIKE ? and last_name LIKE ?", into(a._login), into(a._first_name), into(a._last_name), into(a._age), use(first_name), use(last_name), range(0, 1); select << hint; while (!select.done()) { if(select.execute()) result.push_back(a); } } return result; } catch (Poco::Data::MySQL::ConnectionException &e) { std::cout << "connection:" << e.what() << std::endl; throw; } catch (Poco::Data::MySQL::StatementException &e) { std::cout << "statement:" << e.what() << std::endl; throw; } } void Person::save_to_mysql() { try { Poco::Data::Session session = database::Database::get().create_session(); Poco::Data::Statement insert(session); std::string hint = database::Database::sharding_hint(_login); std::cout << hint << std::endl; insert << "INSERT INTO Person (login,first_name,last_name,age) VALUES(?, ?, ?, ?)", use(_login), use(_first_name), use(_last_name), use(_age); insert << hint; insert.execute(); Poco::Data::Statement select(session); std::cout << "inserted:" << _login << std::endl; } catch (Poco::Data::MySQL::ConnectionException &e) { std::cout << "connection:" << e.what() << std::endl; throw; } catch (Poco::Data::MySQL::StatementException &e) { std::cout << "statement:" << e.what() << std::endl; throw; } } const std::string &Person::get_login() const { return _login; } const std::string &Person::get_first_name() const { return _first_name; } const std::string &Person::get_last_name() const { return _last_name; } long Person::get_age() const { return _age; } std::string &Person::login() { return _login; } std::string &Person::first_name() { return _first_name; } std::string &Person::last_name() { return _last_name; } long &Person::age() { return _age; } }
import React from "react"; import { Add } from "@mui/icons-material"; import { Button, Container, Grid, Typography } from "@mui/material"; import { posts } from "../../mock/blogData"; import BlogFilter from "./searchAndFilter/BlogFilter"; import OverlayBlog from "./blogRenderer/OverlayBlog"; import EachBlog from "./blogRenderer/EachBlog"; import BlogSearch from "./searchAndFilter/BlogSearch"; import { StyledStackRowBetween } from "../../components/Styles"; const Blog: React.FC = () => { return ( <Container maxWidth="lg"> <StyledStackRowBetween marginBottom={4}> <Typography variant="h4">Blog</Typography> <Button startIcon={<Add />} variant="contained"> New Post </Button> </StyledStackRowBetween> <StyledStackRowBetween marginBottom={5}> <BlogSearch /> <BlogFilter /> </StyledStackRowBetween> <Grid container spacing={3}> {posts.slice(0, 3).map((post, idx) => { return ( <Grid key={post.id} item xs={12} sm={idx === 0 ? 12 : 6} md={idx === 0 ? 6 : 3}> <OverlayBlog post={post} isLatestPost={idx === 0} /> </Grid> ); })} {posts.slice(3).map((post) => { return ( <Grid item xs={12} sm={6} md={3} key={post.id}> <EachBlog post={post} /> </Grid> ); })} </Grid> </Container> ); }; export default Blog;
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule, FormBuilder, FormControl } from '@angular/forms'; import { CreateUserComponent } from './create-user.component'; import { SharedService } from '../../../shared/services/shared/shared.service'; import { CreatePlayerService } from '../../../services/create-player/create-player.service'; import { Player } from '../../../config/interfaces/player.interface'; import { InputComponent } from '../../atom/input/input.component'; import { InputRadioComponent } from '../../atom/input-radio/input-radio.component'; import { ButtonComponent } from '../../atom/button/button.component'; import { Observable } from 'rxjs'; describe('CreateUserComponent', () => { let component: CreateUserComponent; let fixture: ComponentFixture<CreateUserComponent>; let sharedService: SharedService; let formBuilder: FormBuilder; let createPlayerService: CreatePlayerService; let mockCreatePlayerService = { addPlayer: (newPlayer: Player) => {}, joinGame: (newPlayer: Player) => {}, createPlayerSession: (newPlayer: Player) => {}, }; let mockSharedService = { isFormSubmitted: false, gameName: '', newPlayerSubject: {}, newPlayer$: {} as Observable<Player>, gameId: '', baseUrl: 'localhost:4200/room-game/', sendNewPlayer: (player: Player) => {}, setFormSubmitted: (value: boolean) => {}, generateUniqueId: () => {}, setGameId: (id: string | null) => {}, setGameName: (name: string) => {}, getGameName: () => {}, getIdRoom: () => {}, getUrl: () => {} }; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ CreateUserComponent, InputComponent, InputRadioComponent, ButtonComponent ], providers: [ { provide: CreatePlayerService, useValue: mockCreatePlayerService }, { provide: SharedService, useValue: mockSharedService } ], imports: [ReactiveFormsModule] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(CreateUserComponent); component = fixture.componentInstance; sharedService = fixture.debugElement.injector.get(SharedService); formBuilder = fixture.debugElement.injector.get(FormBuilder); createPlayerService = fixture.debugElement.injector.get(CreatePlayerService); component.playerForm = formBuilder.group({ playerName: new FormControl(''), gameMode: new FormControl('') }); fixture.detectChanges(); }); afterEach(() => { jest.clearAllMocks(); }) it('should create', () => { expect(component).toBeTruthy(); }); // Output() formSubmitted it('formSubmitted: should emit formSubmitted event', () => { const spy = jest.spyOn(component.formSubmitted, 'emit'); component.formSubmitted.emit(); expect(spy).toHaveBeenCalled(); }); // onInputValueChange() it('onInputValueChange: should call onInputValueChange', () => { const mockEvent = { target: { value: 'Sprint 32' } }; component.playerForm = formBuilder.group({ playerName: '', }); component.onInputValueChange(mockEvent.target.value); expect(component.playerForm.controls['playerName'].value).toBe(mockEvent.target.value); }); // onInputRadioChange() it('onInputRadioChange: should call onInputRadioChange with value "player"', () => { const mockEvent = { target: { value: 'player' } }; component.playerForm = formBuilder.group({ gameMode: '', }); component.onInputRadioChange(mockEvent.target.value as 'player' | 'viewer'); expect(component.playerForm.controls['gameMode'].value).toBe(mockEvent.target.value); }); it('onInputRadioChange: should call onInputRadioChange with value "viewer"', () => { const mockEvent = { target: { value: 'viewer' } }; component.playerForm = formBuilder.group({ gameMode: '', }); component.onInputRadioChange(mockEvent.target.value as 'player' | 'viewer'); expect(component.playerForm.controls['gameMode'].value).toBe(mockEvent.target.value); }); // generateId() it('generateId: should return a number between 1 and 100', () => { const spy1 = jest.spyOn(Math, 'random').mockReturnValue(0.5); const spy2 = jest.spyOn(Math, 'floor').mockReturnValue(51); component.generateId(); expect(spy1).toHaveBeenCalledTimes(1); expect(spy1).toHaveReturnedWith(0.5); expect(spy2).toHaveBeenCalledTimes(1); expect(spy2).toHaveReturnedWith(51); }); // onSubmit() it('onSubmit: should create a new player and trigger appropriate services', () => { const id = jest.spyOn(component as any, 'generateId').mockReturnValue(1); const idGame = jest.spyOn(mockSharedService, 'getIdRoom').mockImplementation(); const initialLetter = jest.spyOn(component as any, 'extractInitialLettersToPlayer').mockReturnValue('Pl'); const spy1 = jest.spyOn(createPlayerService, 'addPlayer').mockImplementation(); const spy2 = jest.spyOn(createPlayerService, 'joinGame').mockImplementation(); const spy3 = jest.spyOn(createPlayerService, 'createPlayerSession').mockImplementation(); const spy4 = jest.spyOn(component.formSubmitted, 'emit').mockImplementation(); component.playerForm = formBuilder.group({ playerName: new FormControl('Player'), gameMode: new FormControl('player') }); const mockPlayer = { id: 1, idGame, initialLetter: 'Pl', name: 'Player', gameMode: 'player', selectedCard: false, isHost: true, point: 0 }; component.onSubmit(); expect(spy1).toHaveBeenCalledWith(mockPlayer); expect(spy1).toHaveBeenCalledTimes(1); expect(spy2).toHaveBeenCalledWith(mockPlayer); expect(spy2).toHaveBeenCalledTimes(1); expect(spy3).toHaveBeenCalledWith(mockPlayer); expect(spy3).toHaveBeenCalledTimes(1); expect(spy4).toHaveBeenCalledTimes(1); expect(id).toHaveBeenCalledTimes(1); expect(id).toHaveReturnedWith(1); expect(initialLetter).toHaveBeenCalledTimes(1); expect(initialLetter).toHaveReturnedWith('Pl'); }); // cambiar descripcion it('onSubmit: should not call any service if the form is invalid', done => { const spy1 = jest.spyOn(component, 'generateId').mockImplementation(); const spy2 = jest.spyOn(mockSharedService, 'getIdRoom').mockImplementation(); const spy3 = jest.spyOn(component as any, 'extractInitialLettersToPlayer') const spy4 = jest.spyOn(createPlayerService, 'addPlayer').mockImplementation(); const spy5 = jest.spyOn(createPlayerService, 'joinGame').mockImplementation(); const spy6 = jest.spyOn(createPlayerService, 'createPlayerSession').mockImplementation(); const spy7 = jest.spyOn(component.formSubmitted, 'emit').mockImplementation(); // Usar done para terminar la ejecucion del form // component.playerForm.controls['playerName'].reset(''); const mockPlayer = { id: 1, idGame: 1, initialLetter: 'Pl', name: 'Player', gameMode: 'player', selectedCard: false, isHost: true, point: 0 }; component.onSubmit(); expect(spy1).not.toHaveBeenCalled(); expect(spy2).not.toHaveBeenCalled(); expect(spy3).not.toHaveBeenCalled(); expect(spy4).not.toHaveBeenCalled(); expect(spy4).not.toHaveBeenCalledWith(mockPlayer); expect(spy5).not.toHaveBeenCalled(); expect(spy6).not.toHaveBeenCalled(); expect(spy7).not.toHaveBeenCalled(); }); // extractInitialLettersToPlayer it('extractInitialLettersToPlayer: should call extractInitialLettersToPlayer when onSubmit is called', () => { const spy1 = jest.spyOn(component as any, 'extractInitialLettersToPlayer').mockReturnValue('Pl'); component.extractInitialLettersToPlayer('Player'); expect(spy1).toHaveBeenCalledTimes(1); expect(spy1).toHaveReturnedWith('Pl'); }); });
import { useLoaderData } from "@remix-run/react"; import type { LoaderArgs } from "@remix-run/server-runtime"; import { json } from "@remix-run/server-runtime"; export const loader = async ({ context: { payload } }: LoaderArgs) => { const users = await payload.find({ collection: "users", }); return json({ userCount: users.totalDocs }, { status: 200 }); }; export default function Index() { const { userCount } = useLoaderData<typeof loader>(); return ( <div style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.4" }}> <h1>Welcome to Remix</h1> <ul> <li> <a target="_blank" href="https://remix.run/tutorials/blog" rel="noreferrer" > 15m Quickstart Blog Tutorial </a> </li> <li> <a target="_blank" href="https://remix.run/tutorials/jokes" rel="noreferrer" > Deep Dive Jokes App Tutorial </a> </li> <li> <a target="_blank" href="https://remix.run/docs" rel="noreferrer"> Remix Docs </a> </li> <li> <a target="_blank" href="https://remix.run/docs" rel="noreferrer"> Amount of users: {userCount} </a> </li> </ul> </div> ); }
import Nav from './nav'; export default function Home() { return ( <section> <Nav props={1} /> <div className="flex flex-col items-center w-full h-full" > <div className="card w-full h-full bg-base-100 border border-primary"> <div className="card-body items-center text-center"> <h1 className="card-title">Writing</h1> <p>Es la capacidad de producir un texto coherente y relevante. La ortografía y las estructuras gramaticales son los mayores obstáculos a superar, aunque supone un reto menor que la escritura porque da más tiempo a pensar y, en ocasiones, permite usar un diccionario. Practicamos esta habilidad cuando escribimos mensajes, notas o textos. </p> <br /> <p><strong>Cómo practicar:</strong> Comunicarse por escrito en inglés con frecuencia (con amistades, profesores…) y hacer apuntes personales (listas de la compra o de tareas) en inglés. Llevar un diario o hacer redacciones que pueda corregir una persona especializada. Copiar expresiones útiles de libros o revistas para estudiar y aprenderlas.</p> <br /> <iframe width="80%" height="350px" src="https://www.youtube.com/embed/1HkeuMw7PyM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> <br /> </div> </div> <div className="card w-full h-1000px bg-base-100 border border-primary"> <div className="card-body"> <br /> <h1 className="card-title">Verbo To be</h1> <p>A diferencia del español, donde existe el verbo “ser” y el verbo “estar”, en inglés existe un solo verbo para expresar ambos significados: el verbo to be. Es el contexto el que determina su significado. Por ejemplo: <li>I am a doctor. / Soy médico.</li> <li>I’m at home. / Estoy en casa.</li> <li>Harper is from the U.S. / Harper es de EEUU.</li> <li>Noah is on vacation at the beach. / Noah está de vacaciones en la playa.</li> </p> <h1 className="card-title">Verbo to be en presente</h1> <br /> <p>Sujeto Verbo to be en presente <li>I - am (‘m)</li> <li>He / she / it - is (‘s)</li> <li>You / we / they - are (‘re)</li> Por ejemplo: <br /> <li>My suitcase is very heavy. / Mi maleta es muy pesada.</li> <li>Rome is the capital of Italy. / Roma es la capital de Italia.</li> </p> <br /> <h1 className="card-title">Estructura negativa del verbo to be en presente</h1> <p>Sujeto Verbo to be en presente <li>I - am not (‘m not)</li> <li>He / she / it is not (isn’t / ‘s not)</li> <li>You / we / they are not (aren’t / ‘re not)</li> Por ejemplo: <li>I’m not interested in soccer. / Yo no estoy interesado en el fútbol.</li> <li>He isn’t married. / Él no está casado.</li> </p> <br /> <h1 className="card-title">Estructura interrogativa del verbo to be en presente</h1> <p>Verbo to be en presente Sujeto <li>Am - I ?</li> <li>Is - he / she / it ?</li> <li>Are - you / we / they ?</li> Por ejemplo: <li>Is the weather nice today? / ¿El tiempo está agradable hoy?</li> <li>Are you ready? / ¿Estás listo?</li> </p> <br /> <iframe width="100%" height="450px" src="https://www.youtube.com/embed/O-pELo5MMkQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> </div> </div> <div className="card w-full h-full bg-base-100 border border-primary"> <div className="card-body "> <h1 className="card-title">Pronombres personales en función del sujeto en inglés</h1> <strong>Los pronombres personales en función del sujeto reemplazan al sujeto de la oración.</strong> <p>TIP: Te darás cuenta que en el español se omite, pero en el inglés siempre se muestra como parte importante de la oración. </p> <br /> <div className="flex flex-col flex-wrap"> <p>Pronombres - Traducción - Ejemplo - Traducción</p> <br/> <li>I (Yo) - I am a teacher - Soy profesor</li> <li>You (Tú) - You are a good student - Tú eres un buen estudiante</li> <li>He (Él) - He is my father - Él es mi padre</li> <li>She (Ella) - She is late everyday - Ella llega tarde todos los días</li> <li>It (Ello / Eso) - It is my house - Es mi casa</li> <li>We (Nosotros) -We have two cats - Tenemos dos gatos</li> <li>They (Ellos) - They are twins - Ellos son gemelos</li> </div> <br /> <iframe width="100%" height="450px" src="https://www.youtube.com/embed/mDdBvF0j-Zk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> <br /> <h1 className="card-title"> Pronombres personal en función del objeto</h1> <strong>Los pronombres personales en función del objeto son todos aquellos que recaen en el objeto y complementan la oración. </strong> <p>TIP: los puedes ver acompañados de preposiciones como a, con, de, en, para, y otras.</p> <br /> <div className="flex flex-col flex-wrap"> <p>Pronombres - Traducción - Ejemplo - Traducción</p> <br/> <li>Me (me / mí) Give me that book - Dame ese libro</li> <li>You ( ti / … te) She loves you - Ella te ama</li> <li>Him (lo / … se / … él) Just help him - Solo ayúdalo</li> <li>Her (la / … se / … ella) The email is for her - El correo electrónico es para ella</li> <li>It (lo / ... se) I'll think about it - Lo pensaré</li> <li>Us (nos / … nosotros) Can you see us? - ¿Nos puedes ver?</li> <li>Them (los / … ellos) Did you talk to them? - ¿Hablaste con ellos?</li> </div> <br /> <iframe width="100%" height="450px" src="https://www.youtube.com/embed/ftLQRXDcr40" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> <br /> <h1 className="card-title"> Pronombres posesivos</h1> <strong>Los pronombres posesivos son aquellos que indican pertenencia. Son muy comunes y por lo general se emplean al final de la oración.</strong> <p>TIP: no confundas con los adjetivos posesivos, estos no reemplazan al sustantivo sino que lo describen y siempre van antes de un sustantivo.</p> <br /> <div className="flex flex-col flex-wrap"> <p>Pronombres - Traducción - Ejemplo - Traducción</p> <br/> <li>Mine (… mío) This coat is mine - Este abrigo es mío</li> <li>Yours (... tuyo) These keys are yours - Estas llaves son tuyas</li> <li>His (… de él / … suyo /de él) This phone is his - Este teléfono es suyo</li> <li>Hers (… de ella / … suyo / de ella) My notebook is old, hers is new - Mi cuaderno es viejo, el de ella es nuevo</li> <li>Ours (… nuestro) That red truck is going to be ours - Ese camión rojo va a ser nuestro</li> <li>Theirs (suyo /de ellos) My apartment is here, theirs is there - Mi apartamento está aquí, el de ellos allá</li> </div> <br /> <iframe width="100%" height="450" src="https://www.youtube.com/embed/BjO37cbHv2s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> <br /> </div> </div> <div className="card w-full h-full bg-base-100 border border-primary"> <div className="card-body items-center text-center"> <iframe src="https://h5p.org/h5p/embed/1341398" width="90%" height="751px" frameborder="0" allowfullscreen="allowfullscreen" allow="geolocation *; microphone *; camera *; midi *; encrypted-media *" title="Professions in english and spanish"></iframe> <script src="https://h5p.org/sites/all/modules/h5p/library/js/h5p-resizer.js" charset="UTF-8"></script> </div> </div> </div> </section> ) }
import { Component } from '@angular/core'; import { Platform } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { TranslateService } from '@ngx-translate/core'; import { AuthService } from './services/auth.service'; import { TripService } from './services/trip.service'; import { TRIP_STATUS_WAITING, TRIP_STATUS_GOING } from 'src/environments/environment.prod'; import { AngularFireAuth } from '@angular/fire/auth'; import { DriverService } from './services/driver.service'; import { Router } from '@angular/router'; import { take } from 'rxjs/operators'; import { BackgroundMode } from '@ionic-native/background-mode/ngx'; import { Storage } from '@ionic/storage'; import { CommonService } from './services/common.service'; @Component({ selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.scss'] }) export class AppComponent { public appPages = [ { title: 'Home', url: '/home', icon: 'home' }, { title: 'Ride History', url: '/history', icon: 'time' }, { title: 'Wallet', url: '/wallet', icon: 'wallet' }, { title: 'Settings', url: '/settings', icon: 'settings' } ]; positionTracking: any; driver: any; user: any = {}; constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private translate: TranslateService, private afAuth: AngularFireAuth, private tripService: TripService, private driverService: DriverService, private authService: AuthService, private router: Router, private bgmode: BackgroundMode, private storage: Storage, private common: CommonService ) { this.translate.setDefaultLang('en'); this.translate.use('en'); this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { this.statusBar.styleDefault(); this.splashScreen.hide(); // check for login stage, then redirect this.afAuth.authState.subscribe(authData => { if (authData) { let root: any = 'home'; // check for uncompleted trip this.tripService.getTrips().valueChanges().pipe(take(1)).subscribe((trips: any) => { console.log(trips); trips.forEach(trip => { if (trip.status == TRIP_STATUS_WAITING || trip.status == TRIP_STATUS_GOING) { this.tripService.setCurrentTrip(trip.key); root = 'pickup'; } }); this.user = this.authService.getUserData(); this.driverService.setUser(this.user); this.driverService.getDriver().valueChanges().subscribe(snapshot => { this.driver = snapshot; }); this.router.navigateByUrl(root) }); } else { this.router.navigateByUrl('login'); this.driver = null; } }); this.storage.get('iondriver_settings').then(data => { if (data != null && data != undefined) { let res = JSON.parse(data); if (res.bgmode) this.common.enableBgMode(); else this.common.disableBgMode(); } }); }); } }
program ECompiler; (* Expression Compiler * Parser pentru expresii aritmentice intregi. * Adunari, scaderi, inmultiri, impartiri si paranteze. * Accepta variabile de tipul $1, $2. * Spatiile sunt ignorate. * 1 + ($1 + 5) * $2 * Genereaza cod AROMA care citeste variabilele, evalueaza expresia si tipareste rezultatul. *) (********* Lexer *********) (* Tokenii sunt caractere, spatiile sunt ignorate *) type Tokenizer = object currentToken : char; firstTime : boolean; procedure init begin firstTime := true; end; function lookAhead : char begin if firstTime then lookAhead := nextToken; firstTime := false; lookAhead := currentToken; end; function nextToken : char begin repeat currentToken := readChar; until currentToken <> ' '; # Ignora spatiile nextToken := currentToken; end; function readChar : char # Functia trebuie reimplementata begin readChar := (char)0; end; end; (* un Tokenizer care citeste date de la intrare *) type StdinTokenizer = object(Tokenizer) function readChar : char begin readChar := readCharacter; end; end; (********* Syntax tree *********) type Expression = object procedure destroy begin dispose(this); end; procedure allocateVars begin end; (* Functia intoarce registrul virtual in care este evaluata expresia *) function compile : integer begin compile := 0; end; end; type Constant = object(Expression) value : integer; function compile : integer var r : integer; begin writeString(" ldr r0,="); writeInteger(value); writeln; r := newReg; writeString(" fsitod vd"); writeInteger(r); writeString(",r0"); writeln; compile := r; end; end; type Variable = object(Expression) index : integer; procedure allocateVars begin (* $index se aloca in registrul vd<index> *) if index>=lastReg then lastReg:=index + 1; end; function compile : integer begin compile := index; end; end; type Operation = object(Expression) oper1, oper2 : ref Expression; procedure destroy begin oper1.destroy; oper2.destroy; Expression.destroy; end; procedure init(o1,o2: ref Expression) begin oper1 := ref o1; oper2 := ref o2; end; procedure allocateVars begin oper1.allocateVars; oper2.allocateVars; end; function compileOp(op:array[1..6] of char) : integer var l, r, res:integer; begin l := oper1.compile; r := oper2.compile; res := newReg; writeString(" "); writeString(op); writeString(" vd"); writeInteger(res); writeString(",vd"); writeInteger(l); writeString(",vd"); writeInteger(r); writeln; compileOp := res; end; end; type Addition = object(Operation) function compile : integer begin compile := compileOp("FADDD"); end; end; type Subtraction = object(Operation) function compile : integer begin compile := compileOp("FSUBD"); end; end; type Multiplication = object(Operation) function compile : integer begin compile := compileOp("FMULD"); end; end; type Division = object(Operation) function compile : integer begin compile := compileOp("FDIVD"); end; end; var e : ref Expression; input : StdinTokenizer; lastReg : integer; i:integer; function newReg:integer begin newReg := lastReg; lastReg := lastReg + 1; end; (********* Parser *********) function newOperation(op:char) : ref Operation var ea: ref Addition; es: ref Subtraction; em: ref Multiplication; ed: ref Division; begin if op='+' then begin new(ea); newOperation := ref ea; end else if op='-' then begin new(es); newOperation := ref es; end else if op='*' then begin new(em); newOperation := ref em; end else begin new(ed); newOperation := ref ed; end; end; function parseAddExpression(stream: ref Tokenizer) : ref Expression var e, r : ref Expression; x: ref Operation; op: char; begin e := ref parseMulExpression(stream); # e poate fi null in caz de eroare la parsare while not isNull(e) and (stream.LookAhead='+' or stream.LookAhead='-') do begin op := stream.nextToken; r := ref parseMulExpression(stream); if isNull(r) then begin e.destroy; e := ref null; end else begin x := ref newOperation(op); x.init(e, r); e:= ref x; end; end; parseAddExpression := ref e; end; function parseMulExpression(stream: ref Tokenizer) : ref Expression var e, r : ref Expression; x: ref Operation; op: char; begin e := ref parseOperand(stream); # e poate fi null in caz de eroare la parsare while not isNull(e) and (stream.LookAhead='*' or stream.LookAhead='/') do begin op := stream.nextToken; r := ref parseOperand(stream); if isNull(r) then begin e.destroy; e := ref null; end else begin x := ref newOperation(op); x.init(e, r); e:= ref x; end; end; parseMulExpression := ref e; end; function parseOperand(stream: ref Tokenizer) : ref Expression var e : ref Expression; ev : ref Variable; ec : ref Constant; c : char; begin (* Operand := ( expresie ) *) if stream.lookAhead = '(' then begin c := stream.nextToken; e := ref parseAddExpression(stream); if not isNull(e) then begin if stream.nextToken <> ')' then begin writeString ("Eroare: lipseste ')' ! "); e.destroy; e:= ref null; end; end end else (* Operand := $ variabila *) if stream.lookAhead = '$' then begin c := stream.nextToken; if not isDigit(stream.lookAhead) then begin writeString ("Eroare: lipseste numarul variabilei ! "); e:= ref null; end else begin new(ev); ev.index := evalInteger(stream); e := ref ev; end; end else (* Operand := constanta *) if isDigit(stream.lookAhead) then begin new(ec); ec.value := evalInteger(stream); e := ref ec; end else begin writeString("Eroare: lipseste un operand! "); e:= ref null; end; parseOperand := ref e; end; function isDigit(c:char) : boolean begin isDigit := (c >= '0') and (c <= '9'); end; function toInt(c:char) : integer begin toInt := (integer)c - (integer)'0'; end; function evalInteger(stream:ref Tokenizer) : integer var n : integer; begin n := 0; while isDigit(stream.lookAhead) do n := n * 10 + toInt(stream.nextToken); evalInteger := n; end; procedure writeln begin writeCharacter((char)10); end; begin input.init; e := ref parseAddExpression(input); if not isNull(e) then begin (* Prologue *) writeString(".code"); writeln; writeString(" ldr sp,=$FFFFFFF0"); writeln; (* Read variables *) lastReg := 0; e.allocateVars; i:=0; while i<lastReg do begin writeString(" bl readReal"); writeln; writeString(" fcpyd vd"); writeInteger(i); writeString(",d0"); writeln; i:=i+1; end; (* Evaluate expression *) i := e.compile; (* Write result *) writeString(" fcpyd d0,vd"); writeInteger(i); writeln; writeString(" bl writeReal"); writeln; (* Epilogue *) writeString(" mov lr,0"); writeln; writeString(" b lr"); writeln; e.destroy; end end.
""" Unittests for the class Vector4 """ from python import unittest from python import numpy as np from python import cmath from python import math from __init__ import Vector4 """ Test the implementation of Vector4. """ def test_repr(): """ Check that the representation returns a string that recreates the object. """ vec = Vector4(1.0, 2.0, 3.0, 4.0) vec2 = Vector4(1, 2, 3, 4) unittest.TestCase().assertEqual(repr(vec), "Vector4(1.0, 2.0, 3.0, 4.0)") unittest.TestCase().assertEqual(repr(vec2), "Vector4(1, 2, 3, 4)") test_repr() def test_repr_vectorized(): """ Check that the representation returns a string that recreates the object. """ x1 = np.array([1.0, 2.0, 3.0, 5.]) x2 = np.array([1., 2., 3., 6.]) x3 = np.array([1., 2., 3., 7.]) x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) print(vec) unittest.TestCase().assertEqual(repr(vec), "Vector4(" "array([1, 2, 3, 5]), " "array([1, 2, 3, 6]), " "array([1, 2, 3, 7]), " "array([1, 2, 3, 8]))") #test_repr_vectorized() #still to do def test_add(): """ Check that two 4-vectors can be added. """ vec = Vector4(1, 2, 3, 4) vec2 = Vector4(3, 4, 5, 10) vec5 = vec + vec2 #print(vec3) #print(vec5) unittest.TestCase().assertEqual(str(vec+ vec2), "Vector4(4, 6, 8, 14)") test_add() def test_add_vectorized(): """ Check that numpy arrays can be used in additions. """ x1 = np.array([1., 2., 3., 5.]) x2 = np.array([1., 2., 3., 6.]) x3 = np.array([1., 2., 3., 7.]) x4 = np.array([1., 2., 3., 8.]) vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(6, 7, 8, 9) sum = vec + vec2 unittest.TestCase().assertEqual(list(sum.coords[0]), [7, 9, 11, 14]) unittest.TestCase().assertEqual(list(sum.coords[1]), [7, 9, 11, 15]) unittest.TestCase().assertEqual(list(sum.coords[2]), [7, 9, 11, 16]) unittest.TestCase().assertEqual(list(sum.coords[3]), [7, 9, 11, 17]) y1 = np.array([2., 2., 3., 5.]) y2 = np.array([2., 2., 3., 6.]) y3 = np.array([2., 2., 3., 7.]) y4 = np.array([2., 2., 3., 8.]) vec2 = Vector4(y1, y2, y3, y4) sum = vec + vec2 unittest.TestCase().assertEqual(list(sum.coords[0]), [3, 4, 6, 10]) unittest.TestCase().assertEqual(list(sum.coords[1]), [3, 4, 6, 12]) unittest.TestCase().assertEqual(list(sum.coords[2]), [3, 4, 6, 14]) unittest.TestCase().assertEqual(list(sum.coords[3]), [3, 4, 6, 16]) test_add_vectorized() #works? original implementation seems off def test_add_types(): """ Check that a 4-vectors and numbers cannot be added. """ vec = Vector4(1., 2., 3., 4.) unittest.TestCase().assertRaises(TypeError,lambda: vec + 4) #test_add_types() #works(?) but doesnt raise type error def test_iadd(): """ Check that two 4-vectors can be added in-place. """ vec = Vector4(1, 2, 3, 4) vec2 = Vector4(3, 4, 5, 10) vec2 += vec unittest.TestCase().assertEqual(str(vec2), "Vector4(4, 6, 8, 14)") test_iadd() def test_iadd_types(): """ Check that a 4-vectors and numbers cannot be added in-place. """ def func1(): vec = Vector4(1., 2., 3., 4.) vec += 4 unittest.TestCase().assertRaises(TypeError, func1) #test_iadd_types() #works but not proper error raised def test_iadd_vectorized_right(): """ Check that numpy arrays can be in-place added from the right. """ x1 = [1., 2., 3., 5.] x2 = [1., 2., 3., 6.] x3 = [1., 2., 3., 7.] x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(6., 7., 8., 9.) vec2 += vec #print(vec2) unittest.TestCase().assertEqual(list(vec2.coords[0]), [7, 9, 11, 14]) unittest.TestCase().assertEqual(list(vec2.coords[1]), [7, 9, 11, 15]) unittest.TestCase().assertEqual(list(vec2.coords[2]), [7, 9, 11, 16]) unittest.TestCase().assertEqual(list(vec2.coords[3]), [7, 9, 11, 17]) test_iadd_vectorized_right() def test_iadd_vectorized_left(): """ Check that numpy arrays can be in-place added from the left. """ x1 = [1., 2., 3., 5.] x2 = [1., 2., 3., 6.] x3 = [1., 2., 3., 7.] x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(6., 7., 8., 9.) vec += vec2 unittest.TestCase().assertEqual(list(vec.coords[0]), [7, 9, 11, 14]) unittest.TestCase().assertEqual(list(vec.coords[1]), [7, 9, 11, 15]) unittest.TestCase().assertEqual(list(vec.coords[2]), [7, 9, 11, 16]) unittest.TestCase().assertEqual(list(vec.coords[3]), [7, 9, 11, 17]) test_iadd_vectorized_left() def test_iadd_vectorized_both(): """ Check that two numpy arrays can be in-place. """ x1 = [1., 2., 3., 5.] x2 = [1., 2., 3., 5.] x3 = [1., 2., 3., 7.] x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(x4, x3, x2, x1) vec += vec2 unittest.TestCase().assertEqual(list(vec.coords[0]), [2, 4, 6, 13]) unittest.TestCase().assertEqual(list(vec.coords[1]), [2, 4, 6, 12]) unittest.TestCase().assertEqual(list(vec.coords[2]), [2, 4, 6, 12]) unittest.TestCase().assertEqual(list(vec.coords[3]), [2, 4, 6, 13]) test_iadd_vectorized_both() def test_sub(): """ Check that two 4-vectors can be subtracted. """ vec = Vector4(1, 2, 3, 4) vec2 = Vector4(3, 4, 5, 10) unittest.TestCase().assertEqual(str(vec - vec2), "Vector4(-2, -2, -2, -6)") test_sub() def test_sub_vectorized(): """ Check that numpy arrays can be used in differences. """ x1 = [1., 2., 3., 5.] x2 = [1., 2., 3., 6.] x3 = [1., 2., 3., 7.] x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(6, 2, 1, 0) sum = vec - vec2 unittest.TestCase().assertEqual(list(sum.coords[0]), [-5, 0, 2, 5]) unittest.TestCase().assertEqual(list(sum.coords[1]), [-5, 0, 2, 6]) unittest.TestCase().assertEqual(list(sum.coords[2]), [-5, 0, 2, 7]) unittest.TestCase().assertEqual(list(sum.coords[3]), [-5, 0, 2, 8]) y1 = [2., 2., 3., 5.] y2 = [2., 2., 3., 1.] y3 = [2., 2., 3., 2.] y4 = [2., 2., 3., 0.] vec2 = Vector4(y1, y2, y3, y4) sum = vec - vec2 unittest.TestCase().assertEqual(list(sum.coords[0]), [-1, 0, 0, 0]) unittest.TestCase().assertEqual(list(sum.coords[1]), [-1, 0, 0, 5]) unittest.TestCase().assertEqual(list(sum.coords[2]), [-1, 0, 0, 5]) unittest.TestCase().assertEqual(list(sum.coords[3]), [-1, 0, 0, 8]) test_sub_vectorized() def test_sub_types(): """ Check that a 4-vectors and numbers cannot be subtracted. """ vec = Vector4(1, 2, 3, 4) unittest.TestCase().assertRaises(TypeError, lambda: vec - 4) #test_sub_types() def test_isub(): """ Check that two 4-vectors can be subtracted in-place. """ vec = Vector4(1, 2, 3, 4) vec2 = Vector4(3, 4, 5, 10) vec -= vec2 unittest.TestCase().assertEqual(str(vec), "Vector4(-2, -2, -2, -6)") test_isub() def test_isub_types(): """ Check that a 4-vectors and numbers cannot be subtracted in-place. """ def func2(): vec = Vector4(1, 2, 3, 4) vec -= 4 unittest.TestCase().assertRaises(TypeError, func2) #test_isub_types() def test_isub_vectorized_right(): """ Check that numpy arrays can be used in in-place differences from the right. """ x1 = [1., 2., 3., 5.] x2 = [1., 2., 3., 6.] x3 = [1., 2., 3., 7.] x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(3, 2, 0, 9) vec2 -= vec unittest.TestCase().assertEqual(list(vec2.coords[0]), [2, 0, -3, 4]) unittest.TestCase().assertEqual(list(vec2.coords[1]), [2, 0, -3, 3]) unittest.TestCase().assertEqual(list(vec2.coords[2]), [2, 0, -3, 2]) unittest.TestCase().assertEqual(list(vec2.coords[3]), [2, 0, -3, 1]) test_isub_vectorized_right() def test_isub_vectorized_left(): """ Check that numpy arrays can be used in in-place differences from the left. """ x1 = [1., 2., 3., 5.] x2 = [1., 2., 3., 6.] x3 = [1., 2., 3., 7.] x4 = [1., 2., 3., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(3, 2, 0, 9) vec -= vec2 unittest.TestCase().assertEqual(list(vec.coords[0]), [-2, 0, 3, -4]) unittest.TestCase().assertEqual(list(vec.coords[1]), [-2, 0, 3, -3]) unittest.TestCase().assertEqual(list(vec.coords[2]), [-2, 0, 3, -2]) unittest.TestCase().assertEqual(list(vec.coords[3]), [-2, 0, 3, -1]) test_isub_vectorized_left() def test_isub_vectorized_both(): """ Check that two numpy arrays can be used in in-place differences. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(x4, x3, x2, x1) vec -= vec2 unittest.TestCase().assertEqual(list(vec.coords[0]), [0, 0, -3]) unittest.TestCase().assertEqual(list(vec.coords[1]), [0, 0, -2]) unittest.TestCase().assertEqual(list(vec.coords[2]), [0, 0, 2]) unittest.TestCase().assertEqual(list(vec.coords[3]), [0, 0, 3]) test_isub_vectorized_both() def test_mul_scalar(): """ Check that multiplying the vector by a scalar, scales the vector. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec = vec * 2 unittest.TestCase().assertEqual(list(vec.coords[0]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[1]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[2]), [2, 4, 14]) unittest.TestCase().assertEqual(list(vec.coords[3]), [2, 4, 16]) test_mul_scalar() def test_mul_scalar_vectorized(): """ Check that multiplying a numpy-vector by a scalar works. """ vec = Vector4(1, 0, 4, 5) unittest.TestCase().assertEqual(str(vec * 2), 'Vector4(2, 0, 8, 10)') test_mul_scalar_vectorized() def test_mul_dot_product(): """ Check that multiplying two vectors, returns the dot product. """ vec = Vector4(2, 0, 4, 5) vec2 = Vector4(7, 0, -1, 3) unittest.TestCase().assertEqual(vec * vec2, 14 - 0 + 4 - 15) test_mul_dot_product() def test_mul_dot_product_vectorized_left(): """ Check that multiplying two vectors (the left a numpy array), returns an array of dot products. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(7, 0, -1, 3) products = vec * vec2 unittest.TestCase().assertEqual(list(products), [5, 10, 5*7 + 7 - 3*8]) test_mul_dot_product_vectorized_left() def test_mul_dot_product_vectorized_right(): """ Check that multiplying two vectors (the right a numpy array), returns an array of dot products. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(7, 0, -1, 3) products = vec2 * vec unittest.TestCase().assertEqual(list(products), [5, 10, 5*7 + 7 - 3*8]) test_mul_dot_product_vectorized_right() def test_mul_dot_product_vectorized_both(): """ Check that multiplying two numpy vectors returns an array of dot products. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec2 = Vector4(x3, x4, x1, x2) products = vec * vec2 unittest.TestCase().assertEqual(list(products), [-2, -8, -80]) test_mul_dot_product_vectorized_both() def test_rmul_scalar(): """ Check that multiplying the vector by a scalar from left, scales the vector. """ vec = Vector4(1, 0, 4, 5) unittest.TestCase().assertEqual(str(2 * vec), 'Vector4(2, 0, 8, 10)') test_rmul_scalar() def test_rmul_scalar_vectorized(): """ Check that multiplying the numpy vector by a scalar from left, scales the vector. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec = 2 * vec unittest.TestCase().assertEqual(list(vec.coords[0]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[1]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[2]), [2, 4, 14]) unittest.TestCase().assertEqual(list(vec.coords[3]), [2, 4, 16]) test_rmul_scalar_vectorized() def test_imul_scalar(): """ Check that multiplying a vector by a scaler in-place, scales the vector. """ vec = Vector4(1, 0, 4, 5) vec *= 2 unittest.TestCase().assertEqual(str(vec), 'Vector4(2, 0, 8, 10)') test_imul_scalar() def test_imul_scalar_vectorized(): """ Check that multiplying a numpy vector by a scaler in-place, scales the vector. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec *= 2 unittest.TestCase().assertEqual(list(vec.coords[0]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[1]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[2]), [2, 4, 14]) unittest.TestCase().assertEqual(list(vec.coords[3]), [2, 4, 16]) test_imul_scalar_vectorized() def test_imul_dot_product(): """ Check that multiplying a vector by a vector in-place, raises an error. """ def func3(): vec = Vector4(2, 0, 4, 5) vec2 = Vector4(7, 0, -1, 3) vec *= vec2 unittest.TestCase().assertRaises(TypeError, func3) #test_imul_dot_product() #works but doesnt raise error def test_neg(): """ Check that negating the vector is equivalent to multiplication with -1. """ vec = Vector4(-2, 0, -8, -10) unittest.TestCase().assertEqual(str(-vec), 'Vector4(2, 0, 8, 10)') test_neg() def test_neg_vectorized(): """ Check that negating the vector is equivalent to multiplication with -1. """ x1 = [-2., -4., -10.] x2 = [-2., -4., -10.] x3 = [-2., -4., -14.] x4 = [-2., -4., -16.] vec = -Vector4(x1, x2, x3, x4) unittest.TestCase().assertEqual(list(vec.coords[0]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[1]), [2, 4, 10]) unittest.TestCase().assertEqual(list(vec.coords[2]), [2, 4, 14]) unittest.TestCase().assertEqual(list(vec.coords[3]), [2, 4, 16]) test_neg_vectorized() def test_div_scalar(): """ Check that dividing a vector by a scalar, scales the vector. """ vec = Vector4(1, 0, 4, 5) unittest.TestCase().assertEqual(str(vec / 2.0), 'Vector4(0.5, 0.0, 2.0, 2.5)') test_div_scalar() def test_div_scalar_vectorized(): """ Check that dividing a numpy vector by a scalar, scales the vector. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec = vec / 2.0 unittest.TestCase().assertEqual(list(vec.coords[0]), [0.5, 1, 2.5]) unittest.TestCase().assertEqual(list(vec.coords[1]), [0.5, 1, 2.5]) unittest.TestCase().assertEqual(list(vec.coords[2]), [0.5, 1, 3.5]) unittest.TestCase().assertEqual(list(vec.coords[3]), [0.5, 1, 4]) test_div_scalar_vectorized() def test_floordiv_scalar(): """ Check that dividing a vector by a scalar, scales the vector. """ vec = Vector4(1, 0, 4, 5) unittest.TestCase().assertEqual(str(vec // 3), 'Vector4(0, 0, 1, 1)') test_floordiv_scalar() def test_ifloordiv_scalar(): """ Check that dividing a vector by a scalar in-place, scales the vector. """ vec = Vector4(1, 0, 4, 5) vec //= 3 unittest.TestCase().assertEqual(str(vec), 'Vector4(0, 0, 1, 1)') test_ifloordiv_scalar() def test_div_types(): """ Check that dividing two vectors, raises an exception. """ vec = Vector4(2, 0, 4, 5) vec2 = Vector4(7, 0, -1, 3) unittest.TestCase().assertRaises(TypeError, lambda: vec / vec2) #test_div_types() #come back to this def test_floordiv_types(): """ Check that dividing two vectors, raises an exception. """ vec = Vector4(2, 0, 4, 5) vec2 = Vector4(7, 0, -1, 3) unittest.TestCase().assertRaises(TypeError, lambda: vec // vec2) #test_floordiv_types() #come back to this def test_rdiv_scalar(): """ Check that dividing a scalar by vector raises an exception. """ vec = Vector4(1, 0, 4, 5) unittest.TestCase().assertRaises(TypeError, lambda: 1 / vec) #test_rdiv_scalar() #come back for this def test_rdiv_types(): """ Check that dividing two vectors raises an exception. """ vec = Vector4(1, 0, 4, 5) vec2 = Vector4(1, 0, 4, 5) unittest.TestCase().assertRaises(TypeError, lambda: vec2 / vec) #test_rdiv_types() come back for this def test_idiv_types(): """ Check that dividing a vector by a vector in-place, raises an error. """ def func4(): vec = Vector4(2, 0, 4, 5) vec2 = Vector4(7, 0, -1, 3) vec /= vec2 unittest.TestCase().assertRaises(TypeError, func4) #test_idiv_types() #come back for this def test_idiv_scalar(): """ Check that dividing a vector by a scalar in-place, scales the vector. """ vec = Vector4(1, 0, 4, 5) vec /= 2.0 unittest.TestCase().assertEqual(str(vec), 'Vector4(0.5, 0.0, 2.0, 2.5)') test_idiv_scalar() def test_idiv_scalar_vectorized(): """ Check that dividing a numpy vector by a scalar in-place, scales the vector. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) vec /= 2.0 unittest.TestCase().assertEqual(list(vec.coords[0]), [0.5, 1, 2.5]) unittest.TestCase().assertEqual(list(vec.coords[1]), [0.5, 1, 2.5]) unittest.TestCase().assertEqual(list(vec.coords[2]), [0.5, 1, 3.5]) unittest.TestCase().assertEqual(list(vec.coords[3]), [0.5, 1, 4]) test_idiv_scalar_vectorized() def test_mag(): """ Check that mag returns the magnitude of the vectors respecting the metric. """ vec = Vector4(4, 0, 3, 4) unittest.TestCase().assertEqual(vec.mag, 3j) vec = Vector4(7, 2, 3, 4) unittest.TestCase().assertEqual(vec.mag, cmath.sqrt(49 - 4 - 9 - 16)) test_mag() def test_mag_vectorized(): """ Check that mag returns the magnitude of the numpy vectors respecting the metric. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) unittest.TestCase().assertEqual(list(vec.mag), [cmath.sqrt(-2), cmath.sqrt(-8), cmath.sqrt(-113)]) test_mag_vectorized() def test_mag2(): """ Check that mag returns the square magnitude of the vectors respecting the metric. """ vec = Vector4(4, 0, 3, 4) unittest.TestCase().assertEqual(vec.mag2, -9) vec = Vector4(7, 2, 3, 4) unittest.TestCase().assertEqual(vec.mag2, 49 - 4 - 9 - 16) test_mag2() def test_mag2_vectorized(): """ Check that mag returns the square magnitude of the numpy vectors respecting the metric. """ x1 = [1., 2., 5.] x2 = [1., 2., 5.] x3 = [1., 2., 7.] x4 = [1., 2., 8.] vec = Vector4(x1, x2, x3, x4) unittest.TestCase().assertEqual(list(vec.mag2), [-2, -8, -113]) test_mag2_vectorized() def test_eta(): """ Check that eta returns the pseudo-rapidity of a vector. """ # Forward vector = Vector4(1, 0, 0, 1) unittest.TestCase().assertEqual(vector.eta, float('inf')) vector = Vector4(0, 0, 0, 1) unittest.TestCase().assertEqual(vector.eta, float('inf')) # Backward vector = Vector4(1, 0, 0, -1) unittest.TestCase().assertEqual(vector.eta, float('-inf')) # Center vector = Vector4(1, 0, 1, 0) unittest.TestCase().assertAlmostEqual(vector.eta, 0) vector = Vector4(1, 1, 0, 0) unittest.TestCase().assertAlmostEqual(vector.eta, 0) # 45 deg vector = Vector4(1, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.eta, 0.8813735870195428) vector = Vector4(1, 1, 0, 1) unittest.TestCase().assertAlmostEqual(vector.eta, 0.8813735870195428) vector = Vector4(10, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.eta, 0.8813735870195428) vector = Vector4(0, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.eta, 0.8813735870195428) test_eta() def test_eta_vectorized(): """ Check that eta returns the pseudo-rapidity of a numpy vector. """ x1 = [1., 1., 1.] x2 = [0., 0., 0.] x3 = [0., 1., 1.] x4 = [1., 0., 1.] vec = Vector4(x1, x2, x3, x4) etas = list(vec.eta) unittest.TestCase().assertAlmostEqual(etas[0], float('inf')) unittest.TestCase().assertAlmostEqual(etas[1], 0) unittest.TestCase().assertAlmostEqual(etas[2], 0.8813735870195428) test_eta_vectorized() def test_theta(): """ Check that theta returns the azimuthal angle of the vector. """ # Forward vector = Vector4(1, 0, 0, 1) unittest.TestCase().assertEqual(vector.theta, 0) vector = Vector4(0, 0, 0, 1) unittest.TestCase().assertEqual(vector.theta, 0) # Backward vector = Vector4(1, 0, 0, -1) unittest.TestCase().assertEqual(vector.theta, cmath.pi) # Center vector = Vector4(1, 0, 1, 0) unittest.TestCase().assertEqual(vector.theta, cmath.pi / 2) vector = Vector4(1, 1, 0, 0) unittest.TestCase().assertEqual(vector.theta, cmath.pi / 2) # 45 deg vector = Vector4(1, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.theta, cmath.pi / 4) vector = Vector4(1, 1, 0, 1) unittest.TestCase().assertAlmostEqual(vector.theta, cmath.pi / 4) vector = Vector4(10, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.theta, cmath.pi / 4) vector = Vector4(0, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.theta, cmath.pi / 4) test_theta() def test_theta_vectorized(): """ Check that theta returns the azimuthal angle of the numpy vector. """ x1 = [1., 1., 1.] x2 = [0., 0., 0.] x3 = [0., 1., 1.] x4 = [1., 0., 1.] vec = Vector4(x1, x2, x3, x4) unittest.TestCase().assertEqual(list(vec.theta), [0, cmath.pi / 2, cmath.pi / 4]) test_theta_vectorized() def test_phi(): """ Check that phi returns the polar angle of the vector. """ vector = Vector4(1, 1, 0, 1) unittest.TestCase().assertEqual(vector.phi, 0) vector = Vector4(1, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.phi, cmath.pi / 2) vector = Vector4(0, -1, 0, 1) unittest.TestCase().assertAlmostEqual(vector.phi, cmath.pi) vector = Vector4(1, -1, 0, 1) unittest.TestCase().assertAlmostEqual(vector.phi, cmath.pi) vector = Vector4(1, -1, 0, 10) unittest.TestCase().assertAlmostEqual(vector.phi, cmath.pi) vector = Vector4(1, 0, -1, 1) unittest.TestCase().assertAlmostEqual(vector.phi, -cmath.pi / 2) test_phi() def test_phi_vectorized(): """ Check that phi returns the polar angle of the numpy vector. """ x1 = [1., 1., 1.] x2 = [1., -1., 0.] x3 = [0., 0., -1.] x4 = [1., 10., 1.] vec = Vector4(x1, x2, x3, x4) phis = list(vec.phi) unittest.TestCase().assertEqual(phis[0], 0) unittest.TestCase().assertEqual(phis[1], cmath.pi) unittest.TestCase().assertEqual(phis[2], -cmath.pi / 2) test_phi_vectorized() def test_trans(): """ Check that trans returns the length of the transverse vector. """ vector = Vector4(1, 1, 0, 1) unittest.TestCase().assertEqual(vector.trans, 1) vector = Vector4(1, 0, 1, 1) unittest.TestCase().assertAlmostEqual(vector.trans, 1) vector = Vector4(0, -1, 0, 1) unittest.TestCase().assertAlmostEqual(vector.trans, 1) vector = Vector4(1, -1, 0, 1) unittest.TestCase().assertAlmostEqual(vector.trans, 1) vector = Vector4(1, -1, 0, 10) unittest.TestCase().assertAlmostEqual(vector.trans, 1) vector = Vector4(1, 3, 4, 1) unittest.TestCase().assertAlmostEqual(vector.trans, 5) test_trans() def test_trans_vectorized(): """ Check that trans returns the length of the transverse vector. """ x1 = [1., 1., 1.] x2 = [1., -1., 3.] x3 = [0., 0., 4.] x4 = [1., 10., 1.] vec = Vector4(x1, x2, x3, x4) unittest.TestCase().assertEqual(list(vec.trans), [1, 1, 5]) test_trans_vectorized() def assertListAlmostEqual(list_a, list_b, *args, **kwds): list_a = list(list_a) list_b = list(list_b) if len(list_a) != len(list_b): unittest.TestCase().assertEqual(list_a, list_b) for a, b in zip(list_a, list_b): unittest.TestCase().assertAlmostEqual(a, b, *args, **kwds) def test_eta_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([1], [0], [1], [1]) assertListAlmostEqual(vector.eta, [0.8813735870195428]) test_eta_single_item() def test_phi_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([0], [-1], [0], [1]) assertListAlmostEqual(vector.phi, [cmath.pi]) test_phi_single_item() def test_mag_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([0], [0], [1], [0]) assertListAlmostEqual(vector.mag, [1j]) vector = Vector4([1], [0], [0], [0]) assertListAlmostEqual(vector.mag, [1]) test_mag_single_item() def test_mag2_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([2], [0], [1], [0]) assertListAlmostEqual(vector.mag2, [3]) test_mag2_single_item() def test_theta_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([1], [0], [1], [1]) assertListAlmostEqual(vector.theta, [cmath.pi / 4]) test_theta_single_item() def test_trans_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([0], [-1], [0], [1]) assertListAlmostEqual(vector.trans, [1]) test_trans_single_item() class BoostTestCase(): """ Test the implementation of Lorentz boosts. """ def assertListAlmostEqual(list_a, list_b, *args, **kwds): list_a = list(list_a) list_b = list(list_b) if len(list_a) != len(list_b): unittest.TestCase().assertEqual(list_a, list_b) for a, b in zip(list_a, list_b): unittest.TestCase().assertAlmostEqual(a, b, *args, **kwds) def test_beta_simple_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([20], [40], [0], [0]) boosted = vector.boost([1], [0], [0], [3./5], mode = 'beta') assertListAlmostEqual(boosted[0], [-5]) assertListAlmostEqual(boosted[1], [35]) assertListAlmostEqual(boosted[2], [0]) assertListAlmostEqual(boosted[3], [0]) test_beta_simple_single_item() def test_beta_simple(): """ Check that a simple, regular boost with beta parameter returns the boosted vector. """ vector = Vector4(20, 40, 0, 0) boosted = vector.boost(1, 0, 0, 3./5, mode = 'beta') unittest.TestCase().assertAlmostEqual(boosted[0], -5) unittest.TestCase().assertAlmostEqual(boosted[1], 35) unittest.TestCase().assertAlmostEqual(boosted[2], 0) unittest.TestCase().assertAlmostEqual(boosted[3], 0) test_beta_simple() def test_beta_simple_vectorized(): """ Check that a simple, regular boost with beta parameter returns the boosted numpy vector. """ x1 = [20., 40.] x2 = [40., 80.] x3 = [0., 0.] x4 = [0., 0.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(1, 0, 0, 3./5, mode ='beta') assertListAlmostEqual(boosted[0], [-5., -10.]) assertListAlmostEqual(boosted[1], [35., 70.]) assertListAlmostEqual(boosted[2], [0., 0.]) assertListAlmostEqual(boosted[3], [0., 0.]) test_beta_simple_vectorized() def test_beta(): """ Check that a regular boost with beta parameter returns the boosted vector. """ vector = Vector4(1, 2, 3, 4) boosted = vector.boost(5, 3, 4, 0.5, mode = 'beta') unittest.TestCase().assertAlmostEqual(boosted[0], -1.7030374948677893) unittest.TestCase().assertAlmostEqual(boosted[1], 2.1332035938635183) unittest.TestCase().assertAlmostEqual(boosted[2], 3.0799221563181116) unittest.TestCase().assertAlmostEqual(boosted[3], 4.106562875090814) test_beta() def test_beta_vecrorized(): """ Check that a regular boost with beta parameter returns the boosted numpy vector. """ x1 = [1., -2.] x2 = [2., -4.] x3 = [3., -6.] x4 = [4., -8.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(5, 3, 4, 0.5, mode = 'beta') r = [-1.7030374948677893, 2.1332035938635183, 3.0799221563181116, 4.106562875090814] result = np.array([r, [-x * 2 for x in r]]) assertListAlmostEqual(boosted[0], result.T[0]) assertListAlmostEqual(boosted[1], result.T[1]) assertListAlmostEqual(boosted[2], result.T[2]) assertListAlmostEqual(boosted[3], result.T[3]) test_beta_vecrorized() def test_beta_rest(): """ Check that a regular boost with beta=0 returns the same vector. """ vector = Vector4(1, 2, 3, 4) boosted = vector.boost(5, 3, 4, 0, mode = 'beta') unittest.TestCase().assertAlmostEqual(boosted[0], 1) unittest.TestCase().assertAlmostEqual(boosted[1], 2) unittest.TestCase().assertAlmostEqual(boosted[2], 3) unittest.TestCase().assertAlmostEqual(boosted[3], 4) test_beta_rest() def test_beta_rest_vectorized(): """ Check that a regular boost with beta=0 returns the same numpy vector. """ x1 = [1., -2.] x2 = [2., -4.] x3 = [3., -6.] x4 = [4., -8.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(5, 3, 4, 0, mode = 'beta') assertListAlmostEqual(boosted[0], [1., -2.]) assertListAlmostEqual(boosted[1], [2., -4.]) assertListAlmostEqual(boosted[2], [3., -6.]) assertListAlmostEqual(boosted[3], [4., -8.]) test_beta_rest_vectorized() def test_gamma_simple(): """ Check that a simple, regular boost with gamma parameter returns the boosted vector. """ vector = Vector4(20, 40, 0, 0) boosted = vector.boost(1., 0., 0., 5./4, mode = 'gamma') unittest.TestCase().assertAlmostEqual(boosted[0], -5) unittest.TestCase().assertAlmostEqual(boosted[1], 35) unittest.TestCase().assertAlmostEqual(boosted[2], 0) unittest.TestCase().assertAlmostEqual(boosted[3], 0) test_gamma_simple() def test_gamma_simple_vectorized(): """ Check that a simple, regular boost with gamma parameter returns the boosted numpy vector. """ x1 = [20., 40.] x2 = [40., 80.] x3 = [0., 0.] x4 = [0., 0.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(1., 0., 0., 5./4, mode = 'gamma') assertListAlmostEqual(boosted[0], [-5., -10.]) assertListAlmostEqual(boosted[1], [35., 70.]) assertListAlmostEqual(boosted[2], [0., 0.]) assertListAlmostEqual(boosted[3], [0., 0.]) test_gamma_simple_vectorized() def test_gamma(): """ Check that a regular boost with gamma parameter returns the boosted vector. """ vector = Vector4(1, 2, 3, 4) boosted = vector.boost(5., 3., 4., (1/math.sqrt(0.75)), mode = 'gamma') unittest.TestCase().assertAlmostEqual(boosted[0], -1.7030374948677893) unittest.TestCase().assertAlmostEqual(boosted[1], 2.1332035938635183) unittest.TestCase().assertAlmostEqual(boosted[2], 3.0799221563181116) unittest.TestCase().assertAlmostEqual(boosted[3], 4.106562875090814) test_gamma() def test_gamma_vectorized(): """ Check that a regular boost with gamma parameter returns the boosted numpy vector. """ x1 = [1., -2.] x2 = [2., -4.] x3 = [3., -6.] x4 = [4., -8.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(5., 3., 4., (1/math.sqrt(0.75)), mode = 'gamma') r = [-1.7030374948677893, 2.1332035938635183, 3.0799221563181116, 4.106562875090814] result = np.array([r, [-x * 2 for x in r]]) assertListAlmostEqual(boosted[0], result.T[0]) assertListAlmostEqual(boosted[1], result.T[1]) assertListAlmostEqual(boosted[2], result.T[2]) assertListAlmostEqual(boosted[3], result.T[3]) test_gamma_vectorized() def test_gamma_rest(): """ Check that a regular boost with gamma=0 returns the same vector. """ vector = Vector4(1, 2, 3, 4) boosted = vector.boost(5., 3., 4., 1, mode ='gamma') unittest.TestCase().assertAlmostEqual(boosted[0], 1) unittest.TestCase().assertAlmostEqual(boosted[1], 2) unittest.TestCase().assertAlmostEqual(boosted[2], 3) unittest.TestCase().assertAlmostEqual(boosted[3], 4) test_gamma_rest() def test_gamma_rest_vectorized(): """ Check that a regular boost with gamma=0 returns the same numpy vector. """ x1 = [1., -2.] x2 = [2., -4.] x3 = [3., -6.] x4 = [4., -8.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(5., 3., 4., 1, mode ='gamma') assertListAlmostEqual(boosted[0], [1., -2.]) assertListAlmostEqual(boosted[1], [2., -4.]) assertListAlmostEqual(boosted[2], [3., -6.]) assertListAlmostEqual(boosted[3], [4., -8.]) test_gamma_rest_vectorized() def assertBetween(min, actual, max): unittest.TestCase().assertLess(min, actual) unittest.TestCase().assertLess(actual, max) def test_particle(): """ Check that a boost from a moving particle returns the correct vector. """ m = 125.0 # Pair of taus in the y-z-plane tau_1 = Vector4.e_m_eta_phi(m / 2, 1.777, 2, math.pi / 2) tau_2 = Vector4.e_m_eta_phi(m / 2, 1.777, -2, -math.pi / 2) # Higgs boosted in ~x direction higgs = Vector4.m_eta_phi_pt(m, 0.1, 0.1, 345.6) tau_1 = tau_1.boost_particle(higgs) tau_2 = tau_2.boost_particle(higgs) assertBetween(0, tau_1.eta, 2) assertBetween(0, tau_1.phi, math.pi/2) assertBetween(-2, tau_2.eta, 0) assertBetween(-math.pi/2, tau_2.phi, 0) delta_R = math.sqrt((tau_1.eta - tau_2.eta)**2 + (tau_1.phi - tau_2.phi)**2) # approximation: dR = 2 * m / pT unittest.TestCase().assertAlmostEqual(delta_R, 2 * higgs.m / higgs.p_t, 1) test_particle() def test_particle_vectorized(): """ Check that a boost from a moving particle returns the correct vector. """ m = 125.0 # Pair of taus in the y-z-plane x1 = [m / 2, m / 2] x2 = [1.777, 1.777] x3 = [2., -2.] x4 = [math.pi / 2, -math.pi / 2] taus = Vector4.e_m_eta_phi(x1, x2, x3, x4) # Higgs boosted in ~x direction higgs = Vector4.m_eta_phi_pt(m, 0.1, 0.1, 345.6) taus = taus.boost_particle(higgs) assertBetween(0, taus.eta[0], 2) assertBetween(0, taus.phi[0], math.pi/2) assertBetween(-2, taus.eta[1], 0) assertBetween(-math.pi/2, taus.phi[1], 0) delta_R = math.sqrt((taus.eta[1] - taus.eta[0])**2 + (taus.phi[1] - taus.phi[0])**2) # approximation: dR = 2 * m / pT unittest.TestCase().assertAlmostEqual(delta_R, 2 * higgs.m / higgs.p_t, 1) test_particle_vectorized() def test_vectorized_beta(): """ Check that a vectorized beta parameter can be used. """ vector = Vector4(1, 2, 3, 4) boosted = vector.boost(5, 3, 4, [0, 0.5], mode='beta') assertListAlmostEqual(boosted[0], [1., -1.7030374948677893]) assertListAlmostEqual(boosted[1], [2., 2.1332035938635183]) assertListAlmostEqual(boosted[2], [3., 3.0799221563181116]) assertListAlmostEqual(boosted[3], [4., 4.106562875090814]) test_vectorized_beta() def test_vectorized_gamma(): """ Check that a vectorized gamma parameter can be used. """ vector = Vector4(1, 2, 3, 4) boosted = vector.boost(5., 3., 4.,[1., 1/math.sqrt(0.75)], mode='gamma') assertListAlmostEqual(boosted[0], [1., -1.7030374948677893]) assertListAlmostEqual(boosted[1], [2., 2.1332035938635183]) assertListAlmostEqual(boosted[2], [3., 3.0799221563181116]) assertListAlmostEqual(boosted[3], [4., 4.106562875090814]) test_vectorized_gamma() def test_beta_vecrorized_axis(): """Check that operand and beta can be vectorized.""" vector = Vector4([1., -1.], [2., -2.], [3., -3.], [4., -4.]) boosted = vector.boost([5., 5.], [3., 3.], [4., 4.], 0.5, mode = 'beta') result = np.array([[-1.7030374948677893, 2.1332035938635183, 3.0799221563181116, 4.106562875090814], [1.7030374948677893, -2.1332035938635183, -3.0799221563181116, -4.106562875090814]]) assertListAlmostEqual(boosted[0], result.T[0]) assertListAlmostEqual(boosted[1], result.T[1]) assertListAlmostEqual(boosted[2], result.T[2]) assertListAlmostEqual(boosted[3], result.T[3]) test_beta_vecrorized_axis() def test_beta_vecrorized_both(): """Check that operand and beta can be vectorized.""" x1 = [1., -2.] x2 = [2., -4.] x3 = [3., -6.] x4 = [4., -8.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(5., 3., 4., [0.5, 0.], mode ='beta') result = np.array([[-1.7030374948677893, 2.1332035938635183, 3.0799221563181116, 4.106562875090814], [-2., -4., -6., -8.]]) assertListAlmostEqual(boosted[0], result.T[0]) assertListAlmostEqual(boosted[1], result.T[1]) assertListAlmostEqual(boosted[2], result.T[2]) assertListAlmostEqual(boosted[3], result.T[3]) test_beta_vecrorized_both() def test_gamma_vecrorized_both(): """Check that operand and gamma can be vectorized.""" x1 = [1., -2.] x2 = [2., -4.] x3 = [3., -6.] x4 = [4., -8.] vector = Vector4(x1, x2, x3, x4) boosted = vector.boost(5., 3., 4., [1/math.sqrt(0.75), 1], mode = 'gamma') result = np.array([[-1.7030374948677893, 2.1332035938635183, 3.0799221563181116, 4.106562875090814], [-2., -4., -6., -8.]]) assertListAlmostEqual(boosted[0], result.T[0]) assertListAlmostEqual(boosted[1], result.T[1]) assertListAlmostEqual(boosted[2], result.T[2]) assertListAlmostEqual(boosted[3], result.T[3]) test_gamma_vecrorized_both() def test_beta_vecrorized_all(): """Check that operand and beta can be vectorized.""" vector = Vector4([1., -1.], [2., -2.], [3., -3.], [4., -4.]) boosted = vector.boost([5., 1.], [3., 3.], [4., 2.], [0.5, 0.], mode='beta') result = np.array([[-1.7030374948677893, 2.1332035938635183, 3.0799221563181116, 4.106562875090814], [-1., -2., -3., -4.]]) assertListAlmostEqual(boosted[0], result.T[0]) assertListAlmostEqual(boosted[1], result.T[1]) assertListAlmostEqual(boosted[2], result.T[2]) assertListAlmostEqual(boosted[3], result.T[3]) test_beta_vecrorized_all() def test_X_rotation(): """ Check that the 4-vector is rotated properly in the x-direction. """ vector = Vector4(1, 2, 3, 4) rotated = vector.rotate_X(np.pi/2) unittest.TestCase().assertAlmostEqual(rotated[0],1) unittest.TestCase().assertAlmostEqual(rotated[1],-3) unittest.TestCase().assertAlmostEqual(rotated[2],2) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_X_rotation() def test_Y_rotation(): """ Check that the 4-vector is rotated properly in the x-direction. """ vector = Vector4(1, 2, 3, 4) rotated = vector.rotate_Y(np.pi/2) unittest.TestCase().assertAlmostEqual(rotated[0],3) unittest.TestCase().assertAlmostEqual(rotated[1],2) unittest.TestCase().assertAlmostEqual(rotated[2],-1) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_Y_rotation() def test_Z_rotation(): """ Check that the 4-vector is rotated properly in the x-direction. """ vector = Vector4(1, 2, 3, 4) rotated = vector.rotate_Z(np.pi/2) unittest.TestCase().assertAlmostEqual(rotated[0],-2) unittest.TestCase().assertAlmostEqual(rotated[1],1) unittest.TestCase().assertAlmostEqual(rotated[2],3) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_Z_rotation() def test_rotate_X_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([1], [2], [3], [4]) rotated = vector.rotate_X(np.pi/2) assertListAlmostEqual(rotated[0], [1]) assertListAlmostEqual(rotated[1], [-3]) assertListAlmostEqual(rotated[2], [2]) assertListAlmostEqual(rotated[3], [4]) test_rotate_X_single_item() def test_rotate_Y_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([1], [2], [3], [4]) rotated = vector.rotate_Y(np.pi/2) assertListAlmostEqual(rotated[0], [3]) assertListAlmostEqual(rotated[1], [2]) assertListAlmostEqual(rotated[2], [-1]) assertListAlmostEqual(rotated[3], [4]) test_rotate_Y_single_item() def test_rotate_Z_single_item(): """Check single-item arrays don't turn into scalars.""" vector = Vector4([1], [2], [3], [4]) rotated = vector.rotate_Z(np.pi/2) assertListAlmostEqual(rotated[0], [-2]) assertListAlmostEqual(rotated[1], [1]) assertListAlmostEqual(rotated[2], [3]) assertListAlmostEqual(rotated[3], [4]) test_rotate_Z_single_item() def test_rotate_X_simple_vectorized(): """ Check that a simple, regular rotation about the X axis returns the transformed numpy vector. """ x1 = np.array([1, 2]) x2 = np.array([2, 4]) x3 = np.array([3, 6]) x4 = np.array([4, 8]) vector = Vector4(x1, x2, x3, x4) rotated = vector.rotate_X(np.pi/2) assertListAlmostEqual(rotated[0], [1, 2]) assertListAlmostEqual(rotated[1], [-3, -6]) assertListAlmostEqual(rotated[2], [2, 4]) assertListAlmostEqual(rotated[3], [4, 8]) test_rotate_X_simple_vectorized() def test_rotate_Y_simple_vectorized(): """ Check that a simple, regular rotation about the Y axis returns the transformed numpy vector. """ x1 = np.array([1, 2]) x2 = np.array([2, 4]) x3 = np.array([3, 6]) x4 = np.array([4, 8]) vector = Vector4(x1, x2, x3, x4) rotated = vector.rotate_Y(np.pi/2) assertListAlmostEqual(rotated[0], [3, 6]) assertListAlmostEqual(rotated[1], [2, 4]) assertListAlmostEqual(rotated[2], [-1, -2]) assertListAlmostEqual(rotated[3], [4, 8]) test_rotate_Y_simple_vectorized() def test_rotate_Z_simple_vectorized(): """ Check that a simple, regular rotation about the Z axis returns the transformed numpy vector. """ x1 = np.array([1, 2]) x2 = np.array([2, 4]) x3 = np.array([3, 6]) x4 = np.array([4, 8]) vector = Vector4(x1, x2, x3, x4) rotated = vector.rotate_Z(np.pi/2) assertListAlmostEqual(rotated[0], [-2, -4]) assertListAlmostEqual(rotated[1], [1, 2]) assertListAlmostEqual(rotated[2], [3, 6]) assertListAlmostEqual(rotated[3], [4, 8]) test_rotate_Z_simple_vectorized() def test_X_rotation_degree(): """ Check that the 4-vector is rotated properly in the x-direction using degrees. """ vector = Vector4(1, 2, 3, 4) rotated = vector.rotate_X(90, rad=0) #print(rotated) unittest.TestCase().assertAlmostEqual(rotated[0],1) unittest.TestCase().assertAlmostEqual(rotated[1],-3) unittest.TestCase().assertAlmostEqual(rotated[2],2) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_X_rotation_degree() def test_Y_rotation_degree(): """ Check that the 4-vector is rotated properly in the y-direction using degrees. """ vector = Vector4(1, 2, 3, 4) rotated = vector.rotate_Y(90, rad=0) #print(rotated) unittest.TestCase().assertAlmostEqual(rotated[0],3) unittest.TestCase().assertAlmostEqual(rotated[1],2) unittest.TestCase().assertAlmostEqual(rotated[2],-1) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_Y_rotation_degree() def test_Z_rotation_degree(): """ Check that the 4-vector is rotated properly in the z-direction using degrees. """ vector = Vector4(1, 2, 3, 4) rotated = vector.rotate_Z(90, rad=0) #print(rotated) unittest.TestCase().assertAlmostEqual(rotated[0],-2) unittest.TestCase().assertAlmostEqual(rotated[1],1) unittest.TestCase().assertAlmostEqual(rotated[2],3) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_Z_rotation_degree() def test_Inverse(): """ Check that the inverse function properly inverses a rotation matrix and delivers the correct result. """ vector = Vector4(-2, 1, 3, 4) matrix = np.array([ [0.0,-1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) rotated = vector.inverse(matrix) unittest.TestCase().assertAlmostEqual(rotated[0],1) unittest.TestCase().assertAlmostEqual(rotated[1],2) unittest.TestCase().assertAlmostEqual(rotated[2],3) unittest.TestCase().assertAlmostEqual(rotated[3],4) test_Inverse()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - WebApplication5</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" /> <link rel="shortcut icon" href="~/img/phone.png"/> </head> <body style="background-color: #E6E6FA; "> <header style="background-color: #E6E6FA"> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">WebApplication5</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="About">About</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Phone">Phone</a> </li> <li> <a class="nav-link text-dark" asp-controller="Home" asp-action="Information">Information for Pushkin</a> </li> <li> <a class="nav-link text-dark" asp-controller="Home" asp-action="Email">Email</a> </li> @if (User.IsInRole("admin")) { <li> <a class="nav-link text-dark" asp-action="Buy" asp-controller="Home">Sale</a> </li> } @if (User.IsInRole("admin")) { <li> <a class="nav-link text-dark" asp-action="Users" asp-controller="Home">Users</a> </li> } </ul> <div class="dropdown"> <a class="btn btn-info dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Registration </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> @if (User.Identity.IsAuthenticated) { <a class="dropdown-item" asp-controller="Account" asp-action="Logout">Logout (@User.Identity.Name)</a> } else { <a class="dropdown-item" asp-controller="Account" asp-action="Login">Login</a> } <a class="dropdown-item" asp-controller="Account" asp-action="Personal_Area">Your account</a> </div> </div> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2021 - WebApplication5 - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
package main import ( "crypto/md5" "encoding/hex" "fmt" "io/ioutil" "log" "net/http" "net/url" "strconv" "strings" "time" "github.com/PuerkitoBio/goquery" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "gopkg.in/yaml.v2" ) type Config struct { Address string `yaml:"address"` Username string `yaml:"username"` Password string `yaml:"password"` } type Port struct { Name string `json:"port"` State string `json:"state"` LinkStatus string `json:"link_status"` TxGoodPkt int `json:"tx_good_pkt"` TxBadPkt int `json:"tx_bad_pkt"` RxGoodPkt int `json:"rx_good_pkt"` RxBadPkt int `json:"rx_bad_pkt"` } type PortStatistics struct { Ports []Port `json:"port_statistics"` } func main() { // Read config.json config, err := readConfig("config.yaml") if err != nil { log.Fatal("Error reading configuration:", err) } // Check if required fields are provided in the configuration file if config.Address == "" || config.Username == "" || config.Password == "" { log.Fatal("Missing required fields in the configuration file.") } // Set the base URL baseURL := "http://" + config.Address + "/port.cgi?page=stats" // Set the URL parameters params := url.Values{} params.Set("page", "stats") // Set the form parameters formParams := url.Values{} username := config.Username password := config.Password formParams.Set("username", username) formParams.Set("password", password) formParams.Set("language", "EN") formParams.Set("Response", getMD5Hash(username+password)) // Create a new HTTP client client := &http.Client{} // Create Prometheus metrics portState := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "port_state", Help: "State of the port", }, []string{"port"}) portLinkStatus := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "port_link_status", Help: "Link status of the port", }, []string{"port"}) portTxGoodPkt := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "port_tx_good_pkt", Help: "Number of good packets transmitted on the port", }, []string{"port"}) portTxBadPkt := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "port_tx_bad_pkt", Help: "Number of bad packets transmitted on the port", }, []string{"port"}) portRxGoodPkt := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "port_rx_good_pkt", Help: "Number of good packets received on the port", }, []string{"port"}) portRxBadPkt := prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "port_rx_bad_pkt", Help: "Number of bad packets received on the port", }, []string{"port"}) // Expose our metrics with a custom registry r := prometheus.NewRegistry() handler := promhttp.HandlerFor(r, promhttp.HandlerOpts{}) // Register Prometheus metrics r.MustRegister(portState) r.MustRegister(portLinkStatus) r.MustRegister(portTxGoodPkt) r.MustRegister(portTxBadPkt) r.MustRegister(portRxGoodPkt) r.MustRegister(portRxBadPkt) // Start the Prometheus exporter endpoint http.Handle("/metrics", handler) fmt.Println("Starting Prometheus exporter on :8080/metrics") go func() { log.Fatal(http.ListenAndServe(":8080", nil)) }() // Start updating the values every second ticker := time.NewTicker(1 * time.Second) for range ticker.C { // Create a new GET request with the parameters req, err := http.NewRequest("GET", baseURL, strings.NewReader(formParams.Encode())) if err != nil { log.Println("Error creating request:", err) continue } // Set the cookie header cookieValue := getMD5Hash(username + password) cookie := &http.Cookie{Name: "admin", Value: cookieValue} req.AddCookie(cookie) // Set the Content-Type header req.Header.Set("Content-Type", "application/x-www-form-urlencoded") // Set the request parameters req.URL.RawQuery = params.Encode() // Send the request resp, err := client.Do(req) if err != nil { log.Println("Error sending request:", err) continue } // Load the HTML document doc, err := goquery.NewDocumentFromReader(resp.Body) resp.Body.Close() if err != nil { log.Println("Error loading HTML document:", err) continue } var stats PortStatistics doc.Find("table tr").Each(func(i int, s *goquery.Selection) { if i != 0 { port := Port{} s.Find("td").Each(func(j int, td *goquery.Selection) { switch j { case 0: port.Name = td.Text() case 1: port.State = td.Text() case 2: port.LinkStatus = td.Text() case 3: port.TxGoodPkt, _ = strconv.Atoi(strings.TrimSpace(td.Text())) case 4: port.TxBadPkt, _ = strconv.Atoi(strings.TrimSpace(td.Text())) case 5: port.RxGoodPkt, _ = strconv.Atoi(strings.TrimSpace(td.Text())) case 6: port.RxBadPkt, _ = strconv.Atoi(strings.TrimSpace(td.Text())) } }) stats.Ports = append(stats.Ports, port) } }) // Update Prometheus metrics for _, port := range stats.Ports { portState.WithLabelValues(port.Name).Set(stateToFloat(port.State)) portLinkStatus.WithLabelValues(port.Name).Set(linkStatusToFloat(port.LinkStatus)) portTxGoodPkt.WithLabelValues(port.Name).Set(float64(port.TxGoodPkt)) portTxBadPkt.WithLabelValues(port.Name).Set(float64(port.TxBadPkt)) portRxGoodPkt.WithLabelValues(port.Name).Set(float64(port.RxGoodPkt)) portRxBadPkt.WithLabelValues(port.Name).Set(float64(port.RxBadPkt)) } } } // Helper function to convert port state to float func stateToFloat(state string) float64 { if state == "UP" { return 1 } return 0 } // Helper function to convert link status to float func linkStatusToFloat(status string) float64 { if status == "Link Up" { return 1 } return 0 } // Helper function to calculate MD5 hash func getMD5Hash(text string) string { hash := md5.Sum([]byte(text)) return hex.EncodeToString(hash[:]) } // Helper function to read config file func readConfig(filename string) (Config, error) { var config Config // Read the configuration file data, err := ioutil.ReadFile(filename) if err != nil { return config, err } // Unmarshal the YAML data into the Config struct err = yaml.Unmarshal(data, &config) if err != nil { return config, err } return config, nil }
// For more information about this file see https://dove.feathersjs.com/guides/cli/service.test.html import assert from 'assert'; import { app } from '../../../src/app'; import { User, UserType } from '../../../src/services/users/users.schema'; const createUser = (_id: string, typ: UserType): User => ({ _id: 'lease.test.' + _id, typ, email: _id + '@test.com', password: 'password', }); describe('building service', () => { const testAdminUser = createUser('test-admin', UserType.Admin); const testTenantUser = createUser('test-tenant', UserType.Tenant); const testLandlordUser = createUser('test-landlord', UserType.Landlord); const buildingData = [ { _id: 'building-1', name: 'Test Building 1', address: '123 Main Street', requestTypes: [] }, { _id: 'building-2', name: 'Test Building 2', address: '456 Elm Street', requestTypes: [] }, ]; let buildingIDs: string[] = []; before(async function () { try { const createdBuildings = await Promise.all( buildingData.map((data) => app.service('building').create(data, { user: testAdminUser })) ); buildingIDs = createdBuildings.map((building) => building._id); } catch (error) { console.error('Error in before hook:', error); } }); after(async () => { const buildingService = app.service('building'); const deletePromises = buildingIDs.map((id) => buildingService.remove(id, { user: testAdminUser }) ); await Promise.all(deletePromises); // Clear the IDs after deletion buildingIDs = []; }); it('registered the service', () => { const service = app.service('building'); assert.ok(service, 'Registered the service'); }); it('creates a new building', async () => { const data = buildingData[0]; // use the first building data data._id = 'building-3'; const createdBuilding = await app.service('building').create(data, { user: testAdminUser }); assert.ok(createdBuilding._id, 'Building created successfully'); assert.strictEqual(createdBuilding.name, data.name, 'Building name is correct'); assert.strictEqual(createdBuilding.address, data.address, 'Building address is correct'); await app.service('building')._remove(data._id); }); it('tenant cannot create a new building', async () => { const data = buildingData[0]; // use the first building data data._id = 'building-4'; try { const createdBuilding = await app.service('building').create(data, { user: testTenantUser }); // If it doesn't throw an error, that means building was created which is not expected assert.fail('Building creation should not have succeeded for a tenant user'); } catch (error) { if (error instanceof Error) { assert.strictEqual(error.name, 'Forbidden', 'Should throw forbidden error for tenant user'); } } }); it('landlord cannot create a new building', async () => { const data = buildingData[0]; // use the first building data data._id = 'building-4'; try { const createdBuilding = await app .service('building') .create(data, { user: testLandlordUser }); // If it doesn't throw an error, that means building was created which is not expected assert.fail('Building creation should not have succeeded for a landlord user'); } catch (error) { if (error instanceof Error) { assert.strictEqual( error.name, 'Forbidden', 'Should throw forbidden error for landlord user' ); } } }); it('gets a building', async () => { const buildingName = buildingData[0].name; // Use the name of the first created building const retrievedBuilding = await app.service('building').get(buildingIDs[0]); assert.strictEqual( retrievedBuilding.name, buildingName, 'Retrieved building name matches requested name' ); // You can add more assertions here to check other properties of the retrieved building }); it('updates a building', async () => { const updatedBuildingData = { name: 'Updated Building', }; const updatedBuilding = await app .service('building') .patch(buildingIDs[0], updatedBuildingData, { user: testAdminUser }); assert.strictEqual(updatedBuilding.name, 'Updated Building', 'Building name is updated'); }); it('removes a building', async () => { const buildingData = { _id: 'building-id', name: 'Sample Building for Deletion', address: '123 Deletion Street', requestTypes: [], }; // Create a building just for this test const createdBuilding = await app .service('building') .create(buildingData, { user: testAdminUser }); // Remove the created building await app.service('building').remove(createdBuilding._id, { user: testAdminUser }); try { // Try to retrieve the removed building await app.service('building').get(createdBuilding._id); assert.fail('Building was not removed'); } catch (error) { assert.strictEqual((error as Error).name, 'NotFound', 'Building not found after removal'); } }); //test case below assumes name parameter is required it('fails to create a building with invalid data', async () => { const invalidBuildingData = { _id: 'building-id', name: '', // Invalid data: missing required name property address: '123 Main Street', requestTypes: [], }; try { await app.service('building').create(invalidBuildingData); assert.fail('Building creation should have failed'); } catch (error) { assert.ok(error, 'An error was thrown as expected'); } }); it('tenant cannot update a building', async () => { const updateData = { _id: 'id', name: 'Updated Name', address: '123 Updated Street', requestTypes: [], }; try { await app.service('building').update(buildingIDs[0], updateData, { user: testTenantUser }); assert.fail('Building update should not have succeeded for a tenant user'); } catch (error) { if (error instanceof Error) { assert.strictEqual(error.name, 'Forbidden', 'Should throw forbidden error for tenant user'); } } }); it('tenant cannot patch a building', async () => { const patchData = { name: 'Updated Name', address: '123 Updated Street' }; try { await app.service('building').patch(buildingIDs[0], patchData, { user: testTenantUser }); assert.fail('Building patch should not have succeeded for a tenant user'); } catch (error) { if (error instanceof Error) { assert.strictEqual(error.name, 'Forbidden', 'Should throw forbidden error for tenant user'); } } }); it('landlord cannot patch a building other than req types', async () => { const patchData = { name: 'Updated Name', address: '123 Updated Street' }; try { await app.service('building').patch(buildingIDs[0], patchData, { user: testLandlordUser }); // console.log('here'); assert.fail('Building patch should not have succeeded for a landlord user'); } catch (error) { if (error instanceof Error) { assert.strictEqual( error.name, 'Forbidden', 'Should throw forbidden error for landlord user' ); } } }); it('landlord can patch req types', async () => { const patchData = { requestTypes: ['testtype1', 'testtype2'] }; try { await app .service('building') .patch(buildingIDs[0], patchData, { user: testLandlordUser }) .then(async () => { await app .service('building') .get(buildingIDs[0]) .then((res) => { assert.deepStrictEqual(res.requestTypes, patchData.requestTypes); }); }); } catch (error) { if (error instanceof Error) { assert.strictEqual( error.name, 'Forbidden', 'Should throw forbidden error for landlord user' ); } } }); it('tenant cannot remove a building', async () => { try { await app.service('building').remove(buildingIDs[0], { user: testTenantUser }); assert.fail('Building removal should not have succeeded for a tenant user'); } catch (error) { if (error instanceof Error) { assert.strictEqual(error.name, 'Forbidden', 'Should throw forbidden error for tenant user'); } } }); it('landlord cannot remove a building', async () => { try { await app.service('building').remove(buildingIDs[0], { user: testLandlordUser }); assert.fail('Building removal should not have succeeded for a landlord user'); } catch (error) { if (error instanceof Error) { assert.strictEqual( error.name, 'Forbidden', 'Should throw forbidden error for landlord user' ); } } }); });
<!DOCTYPE html> <html> <head> <title>TP</title> </head> <body> <script type="text/javascript"> var misPeliculas = []; function Pelicula(tituloP){ this.id = null; this.titulo = tituloP; this.descripcion = ""; this.anio = 0; this.duracion = ""; this.actores = []; this.director = []; } var pelicula1 = new Pelicula(); pelicula1.id = 1; pelicula1.titulo = "Snatch"; pelicula1.descripcion = "Cerdos y diamantes"; pelicula1.anio = 2005; pelicula1.duracion = "2hs"; pelicula1.actores = ["Brad Pitt"]; pelicula1.director = ["Tarantino"]; var pelicula2 = new Pelicula(); pelicula2.id = 2; pelicula2.titulo = "Ice Age"; pelicula2.descripcion = "El deshielo"; pelicula2.anio = 2010; pelicula2.duracion = "1:30hs"; pelicula2.actores = ["Mani", "Cid", "Diego"]; pelicula2.director = ["Neandertal"]; misPeliculas.push(pelicula1); misPeliculas.push(pelicula2); /*function agregarPelicula(){ var id = 1; while(confirm("¿Quiere agregar pelicula?")){ var titulo = prompt("Ingrese titulo de la pelicula"); var descripcion = prompt("Ingrese la descripcion de la pelicula"); var anio = parseInt(prompt("Ingrese el año de la pelicula")); var duracion = prompt("Ingrese la duracion de la misma"); var actoresEnLaPelicula = []; var directoresDeLaPelicula = []; while(confirm("¿Desea agregar un actor?")){ var actorAAgregar = prompt("Ingrese nombre del actor/a"); actoresEnLaPelicula.push(actorAAgregar); } while(confirm("¿Desea agregar un director?")){ var director = prompt("Ingrese nombre del actor/a"); directoresDeLaPelicula.push(director); } function Pelicula(tituloP){ this.id = null; this.descripcion = ""; this.anio = 0; this.duracion = ""; this.titulo = tituloP; this.actores = []; } var peli = new Pelicula(titulo); peli.id = id; id++; peli.actores = actoresEnLaPelicula; misPeliculas.push(peli); } console.log(misPeliculas); }*/ function modificarPelicula(){ var atributosAModificar = []; var atributosPelicula = ["titulo", "descripcion", "anio", "duracion", "actores", "director"]; var atributo = prompt("¿Que atributo desea modificar? (titulo, descripcion, anio, duracion, actores, director)").toLowerCase(); while(!atributosPelicula.includes(atributo)){ var atributo = prompt("Ingrese una opcion valida \n¿Que atributo desea modificar? (titulo, descripcion, anio, duracion, actores, director)").toLowerCase(); } atributosAModificar.push(atributo); while (confirm("¿Desea agregar otro atributo a modificar?")){ var atributo = prompt("¿Que atributo desea modificar? (titulo, descripcion, anio, duracion, actores, director)").toLowerCase(); while(!atributosPelicula.includes(atributo)){ var atributo = prompt("Ingrese una opcion valida \n¿Que atributo desea modificar? (titulo, descripcion, anio, duracion, actores, director)").toLowerCase(); } atributosAModificar.push(atributo); } var idPelicula = parseInt(prompt("Ingrese el id de la pelicula que desea modificar")); if (! isNaN(idPelicula)) { for (var a = 0; a < atributosAModificar.length; a++) { switch(atributosAModificar[a]){ case "titulo": for(i in misPeliculas){ var peli = misPeliculas[i]; console.log("peli;", peli); console.log("peli.id", peli.id); if (peli.id == idPelicula) { peli.titulo = prompt("Ingrese el nuevo titulo de la pelicula"); } } break; case "descripcion": for(i in misPeliculas){ var peli = misPeliculas[i]; if (peli.id == idPelicula) { peli.descripcion = prompt("Ingrese la nueva descripcion de la pelicula"); } } break; case "anio": for(i in misPeliculas){ var peli = misPeliculas[i]; if (peli.id == idPelicula) { peli.anio = prompt("Ingrese el nuevo anio de la pelicula"); } } break; case "duracion": for(i in misPeliculas){ var peli = misPeliculas[i]; if (peli.id == idPelicula) { peli.duracion = prompt("Ingrese la nueva duracion de la pelicula"); } } break; case "actores": for(i in misPeliculas){ var peli = misPeliculas[i]; if (peli.id == idPelicula) { var actoresParaAgregar = []; var actoresNuevos = prompt("Ingrese nombre del actor/a"); actoresParaAgregar.push(actoresNuevos); while(confirm("¿Desea agregar un actor?")){ var actoresNuevos = prompt("Ingrese nombre del actor/a"); actoresParaAgregar.push(actoresNuevos); } peli.actores = actoresParaAgregar; } } break; case "director": for(i in misPeliculas){ var peli = misPeliculas[i]; if (peli.id == idPelicula) { var directoresNuevos = []; while(confirm("¿Desea agregar un director?")){ var director = prompt("Ingrese nombre del actor/a"); directoresNuevos.push(director); } peli.director = directoresNuevos; } } break; default: alert("Opcion incorrecta"); break; } } } else { alert("No ingreso un numero de id valido"); } } modificarPelicula("titulo", "duracion"); console.log(misPeliculas[0]); console.log(misPeliculas[1]); </script> </body> </html>
import { Line } from 'rc-progress'; import React, { memo } from 'react' import { Link } from 'react-router-dom'; import ChartTabs from '../../Components/ChartTabs'; function SocialMedia(props) { return ( <> <section className="info"> <div className="container"> {Object.keys(props.userData.socialMedia).map((platform, index) => { const platformData = props.userData.socialMedia[platform]; return ( <section className="social_data-container" key={index}> <div className="row"> <div className="col-md-4"> <div className="barnd_colmn"> <div className="logo"> <img src={platformData.logo} alt={platformData.name} /> </div> <div className="barnd_text"> <h2 className="title">{platformData.name}</h2> <label className="sub_title"> Data verified and last updated: {platformData.lastUpdated} </label> </div> </div> <ul className="social_small-data"> {platformData.rankings?.map((data, idx) => ( <li key={idx}> <label className="value">{data.value}</label> <span className="name">{data.name}</span> </li> ))} </ul> <Link to={`/leaderboard/${platform}`} state={{ page_name: platform }} className="socialBtn"> See Deals </Link> </div> <div className="col-md-3"> <ul className={"socailStat_gridView"}> {Object.keys(platformData.statistics).map((stat, idx) => ( <li key={idx}> <label className="title"> {stat.charAt(0).toUpperCase() + stat.slice(1)}{" "} <i className="icon"> <img src={`/assets/images/${stat}.svg`} alt={stat} /> </i> </label> <span className="count"> {platformData.statistics[stat]} </span> </li> ))} </ul> </div> <div className="col-md-5"> <ChartTabs chartData={platformData} /> </div> </div> </section> ); })} </div> </section> </> ) } export default memo(SocialMedia);
<template> <div id="app"> <!-- <img src="./assets/logo.png"> --> <router-link to="/home" tag="button" replace>home</router-link> <router-link to="/about">about</router-link> <!-- <div @click="btnhome">home</div> <div @click="btnabout">about</div> 通过代码改变路由 --> <!-- <router-link :to="'/user/'+userId">user</router-link> <router-link :to="{path: '/query', query:{name: 'ljy', age: 24, height: 180}}"> 路由传参</router-link> --> <button @click="btnUser">user</button> <button @click="btnQuery">路由传参</button> <keep-alive exclude="query"> <router-view/> </keep-alive> </div> </template> <script> export default { name: 'App', data() { return { userId: 'ljy' } }, methods: { btnhome() { // this.$router.push('/home') this.$router.replace('/home') }, btnabout() { // this.$router.push('/about') this.$router.replace('/about') }, btnUser() { this.$router.push('/user/' + this.userId) }, btnQuery() { this.$router.push({ path: '/query', query: {name: 'ljy', age: 18, height: 180} }) } }, } </script> <style> #app { /* font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; */ } .active { color: red; } </style>
package Checkout; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; public class CheckoutCustomer { WebDriver driver; WebDriverWait expliciWait; String emailAddress = getEmailAddress(); String Phone = getPhoneNumber(); Actions action; String Address = getAddress(); @BeforeClass public void beforeClass() { driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().window().maximize(); } @Test public void TC_01_Url() { // Open Site driver.get("https://dev-shop-poc.drberg.com/"); sleepInSeconds(5); action = new Actions(driver); // Login driver.findElement(By.xpath("//button[@aria-label='profile']")).click(); sleepInSeconds(2); driver.findElement(By.xpath("//input[@name='popup-email']")).sendKeys("hung.ngo@mgisolutions.com"); sleepInSeconds(2); driver.findElement(By.xpath("//button[text()=' CONTINUE WITH EMAIL ']")).click(); sleepInSeconds(2); action.click(driver.findElement(By.xpath("//input[@class='input-password']"))).perform(); sleepInSeconds(2); driver.findElement(By.xpath("//input[@class='input-password']")).sendKeys("Admin@123"); sleepInSeconds(2); driver.findElement(By.xpath("//button[text()='SIGN IN']")).click(); sleepInSeconds(10); // Add product to Cart By addToCart = By.xpath("//a[text()='Chewable Vitamin C Complex']/parent::div/parent::div/following-sibling::div//button"); JavascriptExecutor jsExcutor = (JavascriptExecutor) driver; jsExcutor.executeScript("arguments[0].click();",driver.findElement(addToCart)); sleepInSeconds(5); driver.findElement(By.xpath("//div[@class='alert-content notification-animation']/button")).click(); sleepInSeconds(2); // Open Cart page driver.findElement(By.xpath("//button[@aria-label='cart']")).click(); sleepInSeconds(8); driver.findElement(By.xpath("//a[text() = 'View cart']")).click(); // Open Checkout page driver.findElement(By.xpath("//span[contains(text(),'Checkout with credit card')]")).click(); sleepInSeconds(15); // Choose shipping method driver.findElement(By.xpath("//span[text()='USPS Ground Advantage (2-5 days) TN']")).click(); // Input Card information WebElement CheckoutButton = driver.findElement(By.xpath("//div[@class='payment_container flex flex-col']//following-sibling::button")); WebElement iframeCCN = driver.findElement(By.xpath("//div[@data-bluesnap='ccn']/iframe")); driver.switchTo().frame(iframeCCN); driver.findElement(By.xpath("//input[@id='ccn']")).sendKeys("4111111111111111"); driver.switchTo().defaultContent(); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", CheckoutButton); By cardholderName = By.xpath("//input[@id='cardholder-name']"); driver.findElement(cardholderName).sendKeys("MGI"); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", CheckoutButton); WebElement iframeEXP = driver.findElement(By.xpath("//div[@data-bluesnap='exp']/iframe")); driver.switchTo().frame(iframeEXP); driver.findElement(By.xpath("//input[@id='exp']")).sendKeys("06/26"); driver.switchTo().defaultContent(); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", CheckoutButton); WebElement iframeCVV = driver.findElement(By.xpath("//div[@data-bluesnap='cvv']/iframe")); driver.switchTo().frame(iframeCVV); driver.findElement(By.xpath("//input[@id='cvv']")).sendKeys("315"); driver.switchTo().defaultContent(); ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", CheckoutButton); sleepInSeconds(3); // Selected checkbox driver.findElement(By.xpath("//label[text()='Save card to my wallet for future purchases']//preceding-sibling::div//input")).click(); sleepInSeconds(3); // Place Order /*By checkoutButton = By.xpath("//div[@class='payment_container flex flex-col']//following-sibling::button"); driver.findElement(checkoutButton).click();*/ jsExcutor.executeScript("arguments[0].click();", CheckoutButton); sleepInSeconds(30); } @Test public void TC_02_Url() { } public void sleepInSeconds(long timeInSecond) { try { Thread.sleep(timeInSecond * 1000); } catch (InterruptedException e) { throw new RuntimeException(e); } } public String getEmailAddress(){ Random rand = new Random(); return "automation" + rand.nextInt(99999) + "@gmail.net"; } public String getPhoneNumber(){ Random rand = new Random(); return "" + rand.nextInt(999) + rand.nextInt(999) + rand.nextInt(9999) + ""; } public String getAddress(){ Random rand = new Random(); return rand.nextInt(99) + " Denali Highway"; } public void selectItemdropdown(String parentXpath, String childItemXpath, String itemTextExpected){ driver.findElement(By.xpath(parentXpath)).click(); sleepInSeconds(5); List<WebElement> allItems = driver.findElements(By.xpath(childItemXpath)); for (WebElement items: allItems){ if (items.getText().equals(itemTextExpected)){ items.click(); break; } } } @AfterClass public void afterClass() { driver.quit(); } }
import { useNavigate } from 'react-router-dom' import { Container, Box, TextField, Button, FormLabel, CircularProgress, Typography, IconButton } from '@mui/material' import LoadingErrorWraper from '../Components/LoadingErrorWraper' import { useEffect, useState } from 'react' import useFetch from '../hooks/useFetch' import { useAuthContext } from '../Auth/AuthProvider' import pig from '../../public/pig.svg' import { CopyAll } from '@mui/icons-material' const updateErrorInitialData = { name: '', lastName: '', alias: '', birthdate: '', } const Profile = () => { const { setAuthUser, authUser } = useAuthContext() const navigate = useNavigate() const [error, setError] = useState(null) const [success, setSuccess] = useState(null) const [loading, setLoading] = useState(false) const [pageLoading, setPageLoading] = useState(true) const [updateError, setUpdateError] = useState(updateErrorInitialData) const [updateData, setUpdateData] = useState({ name: '', lastName: '', alias: '', cvu: '', email: '', birthdate: '', }); useEffect(()=> { if(authUser) { setUpdateData({ name: authUser.name, lastName: authUser.lastName, alias: authUser.alias, birthdate: authUser.birthdate, email: authUser.email, cvu: authUser.cvu, }); setPageLoading(false) } },[authUser]) const handleUpdateError = (errorResponse) => { if (errorResponse?.status?.name){ setUpdateError({...updateError, name:'El campo es obligatorio'}) } if (errorResponse?.status?.lastName){ setUpdateError({...updateError, lastName:'El campo es obligatorio'}) } if (errorResponse?.status?.alias){ setUpdateError({...updateError, alias:'El campo es obligatorio'}) } if (errorResponse?.status?.birthdate){ setUpdateError({...updateError, birthdate:'El campo es obligatorio'}) } } const handleSubmit = async e => { e.preventDefault(); setLoading(true) const [data, error] = await useFetch('/update', 'PUT', updateData, true); if (data) { localStorage.removeItem('user') localStorage.setItem('user', JSON.stringify(data.data)) setAuthUser(data.data) setSuccess('Perfil acutalizado correctamente') setLoading(false) } else { setError(error.response.data.message) handleUpdateError(error.response.data) setLoading(false) } } const handleChange = (event) => { setError(null) setUpdateError(updateErrorInitialData) const field = event.target.name; const value = event.target.value; setUpdateData({ ...updateData, [field]: value }) }; return ( <Box display='flex' justifyContent='center' alignItems='center' flexDirection='column' gap={2} minWidth='90%' padding={4} marginTop={4}> <Box display='flex' bgcolor='whitesmoke' flexDirection='column' justifyContent='center' width='40%' padding={4} gap={2} borderRadius={4} > <Box display='flex' justifyContent='center' gap={2} alignItems='center' flexDirection='column'> <Typography variant='h5'>Perfil de usuario</Typography> </Box> <LoadingErrorWraper error={error} loading={pageLoading} succesSpecific={success}> <InnerForm handleChange={handleChange} handleSubmit={handleSubmit} updateData={updateData} updateError={updateError} loading={loading} authUser={authUser} /> </LoadingErrorWraper> </Box> </Box> ) } export default Profile const InnerForm = ({handleSubmit,handleChange,updateData,updateError,loading, authUser}) => { const handleCopy = (text) => { navigator.clipboard.writeText('') navigator.clipboard.writeText(text) } return ( <form onSubmit={handleSubmit}> <Box display='flex' flexDirection='column' gap={1}> <FormLabel title='Mail' htmlFor='mail'>Mail</FormLabel> <TextField required id='mail' name='mail' type='text' size='small' disabled value={updateData.email} /> <FormLabel title='Nombre' htmlFor='name'>Nombre</FormLabel> <TextField required id='name' name='name' error={Boolean(updateError.name)} helperText={updateError.name} type='text' size='small' value={updateData.name} onChange={handleChange} /> <FormLabel title='Apellido' htmlFor='lastName'>Apellido</FormLabel> <TextField required id='lastName' name='lastName' error={Boolean(updateError.lastName)} helperText={updateError.lastName} type='text' size='small' value={updateData.lastName} onChange={handleChange} /> <FormLabel title='Alias' htmlFor='alias'>Alias</FormLabel> <TextField required size='small' id='alias' error={Boolean(updateError.alias)} helperText={updateError.alias} name='alias' type='text' value={updateData.alias} onChange={handleChange} /> <FormLabel title='Fecha de nacimiento' htmlFor='birthdate'>Fecha de nacimiento</FormLabel> <input required style={{ height: '40px', borderRadius: '5px', color: 'grey', border: '1px solid', borderColor: 'lightgray' }} type='date' name='birthdate' id='birthday' value={updateData.birthdate} onChange={handleChange} /> <Box display='flex' width='100%' justifyContent='center' alignItems='center' margin='1em 0 0.1em 0'> <Typography fontWeight='bold' textAlign='center'>{`CVU: ${updateData.cvu}`}</Typography><IconButton onClick={() => handleCopy(updateData.cvu)}><CopyAll /></IconButton> </Box> <Box display='flex' width='100%' justifyContent='center' alignItems='center' margin='0 0 1em 0'> <Typography fontWeight='bold' textAlign='center'>{`Alias: ${authUser.alias}`}</Typography><IconButton onClick={() => handleCopy(updateData.alias)}><CopyAll /></IconButton> </Box> <Button variant='contained' disabled={loading} type='submit'>{loading ? <CircularProgress /> : 'Actualizar'}</Button> </Box> </form> ) }
if !exists('g:loaded_cmp') | finish | endif set completeopt=menuone,noinsert,noselect lua <<EOF local cmp = require'cmp' -- local lspkind = require'lspkind' --   פּ ﯟ   some other good icons local kind_icons = { Text = "", Method = "", Function = "", Constructor = "", Field = "ﰠ", Variable = "", Class = "ﴯ", Interface = "", Module = "", Property = "ﰠ", Unit = "塞", Value = "", Enum = "", Keyword = "", Snippet = "", Color = "", File = "", Reference = "", Folder = "", EnumMember = "", Constant = "", Struct = "פּ", Event = "", Operator = "", TypeParameter = "" } cmp.setup({ snippet = { expand = function(args) require('luasnip').lsp_expand(args.body) end, }, mapping = { ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ behavior = cmp.ConfirmBehavior.Replace, select = true }), -- ['<Tab>'] = cmp.mapping(function(fallback) -- if cmp.visible() then -- cmp.select_next_item() -- elseif require("luasnip").expand_or_jumpable() then -- require("luasnip").expand_or_jump() -- elseif has_words_before() then -- cmp.complete() -- else -- fallback() -- end -- end, { "i", "s" }), -- ["<S-Tab>"] = cmp.mapping(function(fallback) -- if cmp.visible() then -- cmp.select_prev_item() -- elseif require("luasnip").jumpable(-1) then -- require("luasnip").jump(-1) -- else -- fallback() -- end -- end, { "i", "s" }), }, sources = { -- Youtube: Could enable this only for lua, but nvim_lua handles that already. { name = "nvim_lsp" }, { name = "luasnip" }, { name = "buffer", keyword_length = 3 }, { name = "treesitter" }, { name = "path" }, --{ -- name = 'look' -- keyword_length = 2, -- option = { -- convert_case = true, -- loud = true -- --dict = '/usr/share/dict/words' -- } --}, }, -- sources = cmp.config.sources({ -- { name = 'nvim_lsp' }, -- { name = 'luasnip' }, -- }, { -- { name = 'buffer' }, -- { name = 'look', keyword_length = 2 }, -- }), -- formatting = { -- fields = {"kind", "abbr", "menu"}, -- format = lspkind.cmp_format({with_text = false, maxwidth = 50}) -- }, formatting = { fields = {"kind", "abbr", "menu"}, format = function(entry, vim_item) -- Kind icons vim_item.kind = string.format("%s", kind_icons[vim_item.kind]) -- vim_item.kind = string.format('%s %s', kind_icons[vim_item.kind], vim_item.kind) -- This concatonates the icons with the name of the item kind vim_item.menu = ({ nvim_lsp = "[LSP]", luasnip = "[Snippet]", buffer = "[Buffer]", path = "[Path]", })[entry.source.name] return vim_item end, }, }) -- vim.cmd [[highlight! default link CmpItemKind CmpItemMenuDefault]] EOF
package MyPackage; public class Chap8_PracticeSet { //Question-1 /*static void table(int n) { for (int i=1; i<=10; i++) { System.out.format("%d X %d = %d\n",n,i,n*i); } }*/ //Question-2 /*static void pattern(int n) { for (int i=0; i<n; i++) { for (int j=i; j<i; j++) { System.out.print("*"); } System.out.println(); } }*/ //Question-3 /*static int sumRec(int n) { if (n==1) { return 1; } else { return n + sumRec(n-1); ------> sum(5)= 5+sum(4)....so on } }*/ //Question-4 /*static void pattern1(int n) { for (int i=0; i<n; i++) { for (int j=4; j>i; j--) { System.out.print("*"); } System.out.println(); } }*/ //Question-5 /*static int fib(int n) { if (n==1 || n==2) { return n-1; } else { return fib(n-1) + fib(n-2); } }*/ //Question-6 /*static int average_Sum(float ...arr) { float result = 0; for (float a: arr) { result = result + a; } float avg = result/arr.length; return (int) avg; }*/ //Question-7 /*static void pattern_Recr(int n) { if (n > 0) { for (int i=n; i>0; i--) { System.out.print("*"); } System.out.println(); pattern_Recr(n-1); } }*/ //Question-8 /*static void pattern1_Recr(int n) { if (n > 0) { pattern1_Recr(n-1); for (int i=0; i<n; i++) { System.out.print("*"); } System.out.println(); } }*/ // pattern1_Recr(3) // pattern1_Recr(2) + 3 times star and new line // pattern1_Recr(1) + 2 times star and new line + 3 times star and new line // pattern1_Recr(0) + 1 times star and new line + 2 times star and new line + 3 times star and new line //Question-9 /*static float celToFar(int c) { return (c * 1.8f) + 32.0f; }*/ //Question-10 static int sumOfNatural(int n) { int sum = 0; for (int i=0; i<n; i++) { sum = sum + i; } return sum; } public static void main(String[] args) { // table(5); // pattern(4); // int c = sumRec(5); // System.out.println(c); // pattern1(4); // int result = fib(7); // System.out.println(result); // float x = average_Sum(1,2,3,4,5,6); // System.out.print("Average of argument you passed is:" +x); // int r = pattern_Recr(4);; // System.out.println(r); // pattern1_Recr(4); // pattern_Recr(4); // float result = celToFar(70); // System.out.println("Given value in celsius is: " +result); int num = 10; System.out.println("Tha sum of first " +num+ " th natural number is: " +sumOfNatural(num)); } }
#ifndef _FE_CORE_ALLOCATOR_HXX_ #define _FE_CORE_ALLOCATOR_HXX_ // Copyright © from 2023 to current, UNKNOWN STRYKER. All Rights Reserved. #include <FE/core/prerequisites.h> #include <FE/core/private/allocator_base.hpp> BEGIN_NAMESPACE(FE) template <class Implementation> class new_delete_allocator : public allocator_base { public: using base_type = allocator_base; using value_type = typename Implementation::value_type; using pointer = typename Implementation::pointer; using const_pointer = typename Implementation::const_pointer; using reference = typename Implementation::reference; using const_reference = typename Implementation::const_reference; using size_type = typename Implementation::size_type; using difference_type = typename Implementation::difference_type; using allocator = Implementation; _MAYBE_UNUSED_ static constexpr inline auto is_trivial = FE::is_trivial<value_type>::value; _MAYBE_UNUSED_ static constexpr inline ADDRESS is_address_aligned = Implementation::is_address_aligned; private: static allocator s_allocator; public: constexpr new_delete_allocator() noexcept {} template <typename AnotherImplementation = Implementation> constexpr new_delete_allocator(_MAYBE_UNUSED_ const new_delete_allocator<AnotherImplementation>& other_p) noexcept {} _NODISCARD_ _FORCE_INLINE_ pointer allocate(size_type count_p) noexcept { FE_ASSERT(count_p == 0, "${%s@0}: queried allocation size is ${%lu@1}.", TO_STRING(MEMORY_ERROR_1XX::_FATAL_ERROR_INVALID_SIZE), &count_p); pointer const l_result = s_allocator.allocate(count_p); if constexpr (is_trivial == FE::TYPE_TRIVIALITY::_NOT_TRIVIAL) { pointer const l_end = l_result + count_p; for (pointer begin = l_result; begin != l_end; ++begin) { new(begin) value_type(); } } return l_result; } _NODISCARD_ _FORCE_INLINE_ pointer reallocate(pointer pointer_p, size_type prev_count_p, size_type new_count_p) noexcept { pointer const l_result = s_allocator.reallocate(pointer_p, prev_count_p, new_count_p); if constexpr (is_trivial == FE::TYPE_TRIVIALITY::_NOT_TRIVIAL) { if (new_count_p > prev_count_p) { pointer const l_end = l_result + new_count_p; for (pointer begin = l_result + prev_count_p; begin != l_end; ++begin) { new(begin) value_type(); } } else { pointer const l_end = pointer_p + prev_count_p; for (pointer begin = pointer_p + new_count_p; begin != l_end; ++begin) { begin->~value_type(); } } } return l_result; } _FORCE_INLINE_ void deallocate(pointer pointer_p, size_type count_p) noexcept { FE_ASSERT(count_p == 0, "${%s@0}: queried allocation size is ${%lu@1}.", TO_STRING(MEMORY_ERROR_1XX::_FATAL_ERROR_INVALID_SIZE), &count_p); FE_ASSERT(pointer_p == nullptr, "${%s@0}: attempted to delete ${%p@1}.", TO_STRING(MEMORY_ERROR_1XX::_FATAL_ERROR_NULLPTR), pointer_p); if constexpr (is_trivial == FE::TYPE_TRIVIALITY::_NOT_TRIVIAL) { pointer const l_end = pointer_p + count_p; for (pointer begin = pointer_p; begin != l_end; ++begin) { begin->~value_type(); } } s_allocator.deallocate(pointer_p, count_p); } }; template <class Implementation> typename new_delete_allocator<Implementation>::allocator new_delete_allocator<Implementation>::s_allocator; template<typename T, class Alignment = typename FE::SIMD_auto_alignment> class aligned_allocator : public allocator_base { public: using base_type = allocator_base; using value_type = T; using pointer = value_type*; using const_pointer = const pointer; using reference = value_type&; using const_reference = const reference; using size_type = var::size_t; using difference_type = var::ptrdiff_t; _MAYBE_UNUSED_ static constexpr inline auto is_trivial = FE::is_trivial<value_type>::value; _MAYBE_UNUSED_ static constexpr inline ADDRESS is_address_aligned = (std::is_same<FE::SIMD_auto_alignment, Alignment>::value == true) ? ADDRESS::_ALIGNED : ADDRESS::_NOT_ALIGNED; constexpr aligned_allocator() noexcept {} template <typename U = T> constexpr aligned_allocator(_MAYBE_UNUSED_ const aligned_allocator<U, Alignment>& other_p) noexcept {} _NODISCARD_ _FORCE_INLINE_ pointer allocate(size_type count_p) noexcept { FE_ASSERT(count_p == 0, "${%s@0}: queried allocation size is ${%lu@1}.", TO_STRING(MEMORY_ERROR_1XX::_FATAL_ERROR_INVALID_SIZE), &count_p); return base_type::trackable_alloc<value_type, Alignment>(count_p * sizeof(value_type)); } _NODISCARD_ _FORCE_INLINE_ pointer reallocate(pointer pointer_p, size_type prev_count_p, size_type new_count_p) noexcept { if (new_count_p == 0) { base_type::trackable_free<value_type, Alignment>(pointer_p, prev_count_p * sizeof(value_type)); return nullptr; } return base_type::trackable_realloc<value_type, Alignment>(pointer_p, prev_count_p * sizeof(value_type), new_count_p * sizeof(value_type)); } _FORCE_INLINE_ void deallocate(pointer pointer_p, size_type count_p) noexcept { FE_ASSERT(count_p == 0, "${%s@0}: queried allocation size is ${%lu@1}.", TO_STRING(MEMORY_ERROR_1XX::_FATAL_ERROR_INVALID_SIZE), &count_p); FE_ASSERT(pointer_p == nullptr, "${%s@0}: attempted to delete ${%p@1}.", TO_STRING(MEMORY_ERROR_1XX::_FATAL_ERROR_NULLPTR), pointer_p); base_type::trackable_free<value_type, Alignment>(pointer_p, count_p * sizeof(value_type)); } }; END_NAMESPACE #endif
// import { Injectable } from '@angular/core'; // import { HttpClient } from '@angular/common/http'; // import {map, Observable, tap} from 'rxjs'; // import { Media } from './media'; // // // @Injectable({ // providedIn: 'root' // }) // export class MediaService { // private apiBaseUrl = 'http://localhost:8080'; // // constructor(private http: HttpClient) { // } // // public getMedias(): Observable<Media[]> { // return this.http.get<Media[]>(this.apiBaseUrl + "/medias"); // } // // // public deleteMedia(mediaId: number): Observable<any> { // console.log('Deleting media with ID:', mediaId); // return this.http.delete<any>(`${this.apiBaseUrl}/medias/${mediaId}`); // } // // updateMedia(mediaId: number, updatedMedia: any): Observable<Media> { // const url = `${this.apiBaseUrl}/medias/${mediaId}`; // console.log(updatedMedia); // return this.http.put<Media>(url, updatedMedia); // } // addMedia(addedMedia: any): Observable<Media> { // console.log(addedMedia); // return this.http.post<Media>(`${this.apiBaseUrl}/medias`, addedMedia); // } // } import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {map, Observable, tap} from 'rxjs'; import { Media } from './media'; @Injectable({ providedIn: 'root' }) export class MediaService { private apiBaseUrl = 'http://localhost:8080'; constructor(private http: HttpClient) { } public getMedias(): Observable<Media[]> { return this.http.get<Media[]>(this.apiBaseUrl + "/medias"); } public deleteMedia(mediaId: number): Observable<any> { console.log('Deleting media with ID:', mediaId); return this.http.delete<any>(`${this.apiBaseUrl}/medias/${mediaId}`); } updateMedia(mediaId: number, updatedMedia: any): Observable<Media> { const url = `${this.apiBaseUrl}/medias/${mediaId}`; console.log(updatedMedia); return this.http.put<Media>(url, updatedMedia); } addMedia(addedMedia: any): Observable<Media> { console.log(addedMedia); return this.http.post<Media>(`${this.apiBaseUrl}/medias`, addedMedia); } }
import React from "react"; import { cloneDeep } from "lodash"; import TimeEntries from "./components/TimeEntries/TimeEntries"; import TimeEntry from "./components/TimeEntry/TimeEntry"; import TimeRemaining from "./components/TimeRemaining/TimeRemaining"; import Toast from "./components/Toast/Toast"; import WumpaHunt from "./components/WumpaHunt/WumpaHunt"; import StoreContext, { IStore, defaultStore } from "./contexts/StoreContext"; import { waitForFonts, TWindow } from "./helpers"; import * as serviceWorker from "./serviceWorker"; import "./App.css"; class App extends React.Component<{}, IStore> { private appRef = React.createRef<HTMLDivElement>(); private timeInputRef = React.createRef<HTMLInputElement>(); private scrollLockInterval: number | undefined; public state = cloneDeep(defaultStore); public componentDidMount() { serviceWorker.register({ onSuccess: () => this.notify("This app works offline"), onUpdate: () => this.notify("Update installed"), }); if (navigator.userAgent.indexOf("Safari") > -1) { const visualViewport = (window as TWindow).visualViewport; if (visualViewport) { this.scrollLockInterval = setInterval( this.lockScrolling ) as unknown as number; visualViewport.addEventListener("resize", this.onResizeSafari); } } const localStore = localStorage.getItem("wumpa-store"); if (localStore !== null) { const importedStore = JSON.parse(localStore) as IStore; importedStore.times = importedStore.times.map((time) => time === null ? undefined : time ); this.setState(importedStore); } } public componentWillUnmount() { if (navigator.userAgent.indexOf("Safari") > -1) { const visualViewport = (window as TWindow).visualViewport; if (visualViewport) { clearInterval(this.scrollLockInterval); visualViewport.removeEventListener("resize", this.onResizeSafari); } } } public render() { return ( <StoreContext.Provider value={{ store: this.state, setStore: this.setStore, }} > <div className="App" onFocus={(event) => { // Click anywhere to focus on the input event.target === this.appRef.current && this.timeInputRef.current && this.timeInputRef.current.focus(); }} ref={this.appRef} tabIndex={0} > <div className="Grid"> <TimeRemaining className="Grid-timeRemaining" /> <WumpaHunt className="Grid-wumpaHunt" /> <TimeEntries className="Grid-timeEntries" /> <div className="Grid-toasts"> {this.state.notifications.map((notification, i) => ( <Toast key={`${notification.time}-${i}`} {...notification} /> ))} </div> <TimeEntry inputRef={this.timeInputRef} /> </div> </div> </StoreContext.Provider> ); } private notify = async (message: string) => { await waitForFonts(); setTimeout(() => { this.setState({ notifications: [ ...this.state.notifications, { message, time: Date.now(), }, ], }); }, 100); }; /** * Safari adds extra space to the bottom of the document when the keyboard is open. * * This method prevents scrolling downwards. */ private lockScrolling = () => { const scrollingElement = document.scrollingElement || document.documentElement; if (scrollingElement.scrollTop > 0) { scrollingElement.scrollTop = 0; } }; /** * Safari does not resize the window when toggling the keyboard, however Safari 13 does support window.viewport */ private onResizeSafari = (event: Event) => { const viewport = event.target as (EventTarget & { height: number }) | null; if (viewport) { const scrollingElement = (document.scrollingElement || document.documentElement) as HTMLElement; scrollingElement.style.height = `${viewport.height}px`; } }; private setStore = (newStore: Partial<IStore>) => { this.setState({ ...this.state, ...newStore }, () => localStorage.setItem( "wumpa-store", JSON.stringify({ ...this.state, notifications: undefined }) ) ); }; } export default App;
// // GridBootcamp.swift // TextBootcamp // // Created by Dipon Sutradhar on 15/12/21. // import SwiftUI struct GridBootcamp: View { let columns : [GridItem] = [ GridItem(.flexible(), spacing: nil, alignment: nil), GridItem(.flexible(), spacing: nil, alignment: nil), GridItem(.flexible(), spacing: nil, alignment: nil), ] var body: some View { ScrollView{ Rectangle() .fill(.orange) .frame(height : 400) LazyVGrid(columns: columns, alignment: .center, spacing: 10, pinnedViews: []) { Section { ForEach(0..<20) { index in Rectangle() .fill(.blue) .frame(height : 150) } } header: { Text("Section 1") .font(.title) .frame(maxWidth : .infinity,alignment: .leading) .background(Color.blue) .padding() } Section { ForEach(0..<20) { index in Rectangle() .fill(.green) .frame(height : 150) } } header: { Text("Section 2") .font(.title) .frame(maxWidth : .infinity,alignment: .leading) .background(Color.green) .padding() } } }.padding(5) } } struct GridBootcamp_Previews: PreviewProvider { static var previews: some View { GridBootcamp() } }
<template> <div> <div> <!--按钮列表--> <el-button-group class="toolBox"> <el-button size="small" v-for="(item,index) in buttonGroups" :key="index" @click="dynamicMethod(item.method,item.params)" :icon="item.icon">{{item.label}}</el-button> </el-button-group> </div> <!--数据表格--> <el-row> <el-col :span="24"> <el-table :data="tableData" border stripe highlight-current-row ref="multipleTable" :height="tableHeight" @row-click="handleRowClick" style="width: 100%"> <el-table-column type="selection" width="55"> </el-table-column> <el-table-column type="index" width="65" label="序号" align="center" fixed :show-overflow-tooltip="true"></el-table-column> <template v-for="(el,i) in tableColumns"> <el-table-column :label="el.label" header-align="center" v-if="el.show " :width="el.width || ''" :key="el.prop" :fixed="el.fixed" :prop="el.prop" :sortable="el.sortable" show-overflow-tooltip> </el-table-column> </template> <el-table-column fixed="right" label="操作" width="300"> <template slot-scope="scope"> <!-- <el-button @click="handleAuthVClick(scope.row)" type="text" size="small">权限查看</el-button> --> <el-button type="text" @click="handleDelClick(scope.row)" size="small">删除</el-button> <el-button type="text" @click="handleEditClick(scope.row)" size="small">编辑</el-button> </template> </el-table-column> </el-table> </el-col> </el-row> <!--分页插件--> <el-row> <el-col :span="24"> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current" :page-sizes="pageSizeOptions" :page-size="size" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> </el-col> </el-row> <!--列自定义--> <CustomTableCols :defaultCols="defaultColumns" customName="employe" @changeColumns="changeColumns" /> <!--查询条件--> <Search :show.sync="showSearch" :condition="searchCondition" :form="searchForm" @ok="setCondition" @hidden="showSearch=false" /> <!--新增编辑页面--> <CustomForm :show.sync="showForm" title="员工编辑" :control="employeControl" :model="employeForm" :rules="employeRules" @ok="saveForm" @hidden="showForm=false" /> <!--分配角色--> <el-dialog title="角色分配" :visible.sync="visible" width="400px" @close="visible=false"> <el-tree node-key="id" style="height:400px!important;overflow-y: auto;" :data="treeData" :props="treeProps" ref="tree" show-checkbox :highlight-current="true" :default-checked-keys="checkedKeys" :default-expand-all="true"></el-tree> <div slot="footer" class="dialog-footer"> <el-button @click="visible=false">取消</el-button> <el-button @click="selectAll()" type="primary">全选</el-button> <el-button @click="submitRole()" type="primary">确定</el-button> </div> </el-dialog> <!--赋权页面--> <treelist :show.sync="showTree" title="权限查看" ptype="employe" :pid="employeId" @ok="showTree=false" @hidden="showTree=false" /> </div> </template> <script> import CustomTableCols from '../../components/CustomTableCols' import Search from '../../components/Search' import CustomForm from '../../components/CustomForm' import treelist from '../../components/TreeList' export default { components: { CustomTableCols, Search, CustomForm, treelist }, data () { var validateComfirmPwd = (rule, value, callback) => { if (this.employeForm.cmfPassWord !== value) { callback(new Error('确认密码与新密码不一致!')) } else { callback() } } return { initData: {}, tableData: [], educationArray: [], deptArray: [], jobsArray: [], tableHeight: '400px', current: 1, size: 10, total: 0, pageSizeOptions: [10, 20, 50, 100], searchForm: { workNo: '', name: '', foreignName: '', mobilePhone: '', email: '', status: '' }, searchCondition: [ { index: 0, label: '工号', field: 'workNo', type: 'input', show: true }, { index: 1, label: '姓名', field: 'name', type: 'input', show: true }, { index: 2, label: '英文名', field: 'foreignName', type: 'input', show: true }, { index: 3, label: '手机号', field: 'mobilePhone', type: 'input', show: true }, { index: 4, label: '邮箱', field: 'email', type: 'input', show: true }, { index: 6, label: '状态', field: 'status', type: 'input', show: true } ], showSearch: false, buttonGroups: [ { index: 0, label: '查询', method: 'showCondition', icon: 'el-icon-search' }, { index: 1, label: '新建', method: 'addAndEdit', icon: 'el-icon-plus' }, { index: 2, label: '离职', method: 'enableemploye', params: false, icon: 'el-icon-delete' }, { index: 5, label: '删除', method: 'delete', icon: 'el-icon-delete' }, { index: 6, label: '刷新', method: 'searchData', icon: 'el-icon-refresh' } ], tableColumns: [], defaultColumns: [ { label: '工号', prop: 'workNo', show: true, fixed: false, sortable: false, width: 100 }, { label: '姓名', prop: 'name', show: true, fixed: false, sortable: false, width: 100 }, { label: '英文名', prop: 'foreignName', show: true, fixed: false, sortable: false, width: 100 }, { label: '手机', prop: 'mobilePhone', show: true, fixed: false, sortable: false, width: 100 }, { label: '座机号', prop: 'telePhone', show: true, fixed: false, sortable: false, width: 100 }, { label: '邮箱', prop: 'email', show: true, fixed: false, sortable: false, width: 150 }, { label: '生日', prop: 'birthday', show: true, fixed: false, sortable: false, width: 120 }, { label: '学历', prop: 'education', show: true, fixed: false, sortable: false, width: 100 }, { label: '部门', prop: 'department', show: true, fixed: false, sortable: false, width: 100 }, { label: '职位', prop: 'position', show: true, fixed: false, sortable: false, width: 100 }, { label: '状态', prop: 'status', show: true, fixed: false, sortable: false, width: 80 }, { label: '入职日期', prop: 'entryDate', show: true, fixed: false, sortable: false, width: 120 }, { label: '离职日期', prop: 'departureDate', show: true, fixed: false, sortable: false, width: 120 } ], showForm: false, employeForm: { id: '', workNo: '', name: '', foreignName: '', mobilePhone: '', telePhone: '', email: '', birthday: '', education: '', department: '', position: '' , status: '', entryDate: '', departureDate: '' }, employeControl: [ { label: 'ID', field: 'id', type: 'hidden', show: false, readonly: true }, { label: '工号', field: 'workNo', type: 'input', show: true, readonly: true }, { label: '姓名', field: 'name', type: 'input', show: true, readonly: false }, { label: '英文名', field: 'foreignName', type: 'input', show: true, readonly: false }, { label: '手机', field: 'mobilePhone', type: 'input', show: true, readonly: false }, { label: '座机号', field: 'telePhone', type: 'input', show: true, readonly: false }, { label: '邮箱', field: 'email', type: 'input', show: true }, { label: '生日', field: 'birthday', type: 'date', show: true }, { label: '学历', field: 'education', type: 'select', show: true, options: null }, { label: '部门', field: 'department', type: 'tree-select', show: true, options: null, isClearable: true, // 可清空(可选) isAccordion: true, // 可收起(可选 props: { // 配置项(必选) value: 'deptCode', label: 'deptName', children: 'children', }, }, { label: '职位', field: 'position', type: 'select', show: true, options: null }, { label: '入职日期', field: 'entryDate', type: 'date', show: true }, { label: '离职日期', field: 'departureDate', type: 'date', show: true } ], employeRules: { workNo: [ { required: true, message: '请输入工号', trigger: 'blur' }, { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' } ], name: [ { required: true, message: '请输入姓名', trigger: 'blur' }, { min: 1, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' } ], mobilePhone: [ { required: true, message: '请输入手机', trigger: 'blur' }, { min: 11, max: 11, message: '长度11 个字符', trigger: 'blur' } ], email: [ { required: true, message: '请输入邮箱', trigger: 'blur' }, ], birthday: [ { required: true, message: '请输入生日', trigger: 'blur' }, ], education: [ { required: true, message: '请输入学历', trigger: 'blur' }, ], department: [ { required: true, message: '请输入部门', trigger: 'blur' }, ], position: [ { required: true, message: '请输入职位', trigger: 'blur' }, ], }, multipleSelection: [], visible: false, treeData: [], treeProps: { label: 'roleName' }, checkedKeys: [], employeId: null, showTree: false } }, methods: { /** * */ getDicItem () { this.$http .get('/api/sysDicItem/item-list-bydiccode', { params: { dicCode: 'EDUCATION' } }) .then(res => { if (res.code == 0) { if (res.data) { let that = this; res.data.forEach(item => { that.educationArray.push({ label: item.dicItemName, value: item.dicItemValue }); }); } } else { this.$message.error(res.msg) } }) .catch(err => { console.log(err.message) }) }, /** * 加载职位列表 * */ getJobs () { this.$http .get('/api/sysJobs/all-list', { params: { dicCode: 'EDUCATION' } }) .then(res => { if (res.code == 0) { if (res.data) { let that = this; res.data.forEach(item => { that.jobsArray.push({ label: item.name, value: item.code }); }); } } else { this.$message.error(res.msg) } }) .catch(err => { console.log(err.message) }) }, /** * */ getDept () { this.$http .get('/api/sysDept/tree-all-list', { params: { dicCode: 'EDUCATION' } }) .then(res => { if (res.code == 0) { if (res.data) { let that = this; that.deptArray = res.data; } } else { this.$message.error(res.msg) } }) .catch(err => { console.log(err.message) }) }, /** * */ searchData () { this.$http .get('/api/sysEmploye/list', { params: this._handerParams() }) .then(res => { if (res.code == 0) { this.tableData = res.data.records this.total = res.data.total this.current = res.data.current this.size = res.data.size } else { this.$message.error(res.msg) } }) .catch(err => { console.log(err.message) }) }, /** * 查询条件处理 */ _handerParams () { const params = { current: this.current, size: this.size, workNo: this.searchForm.workNo, name: this.searchForm.name, foreignName: this.searchForm.foreignName, mobilePhone: this.searchForm.mobilePhone, } return params }, /** * 新增修改数据 */ addAndEdit () { // 设置账号栏位可编辑 for (const item in this.employeForm) { this.employeForm[item] = '' } this.employeControl[1].readonly = false this.employeControl[8].options = this.educationArray this.employeControl[9].options = this.deptArray this.employeControl[10].options = this.jobsArray this.showForm = true }, /** * 是否启用/禁用员工 */ enableemploye (isEnable) { console.log(this.multipleSelection) if (this.$refs.multipleTable.selection.length <= 0) { this.$message.warning('请选择要操作的员工') return } const idArray = [] this.$refs.multipleTable.selection.forEach(element => { idArray.push(element.id) }) this.$http.post('/api/sysEmploye/enable?enable=' + isEnable, idArray).then(res => { if (res.code == '0') { this.$message.success(res.msg) this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }, /** * 选择事件 */ handleSelectionChange (val) { this.multipleSelection = val }, // 点击行触发,选中或不选中复选框 handleRowClick (row, column, event) { this.$refs.multipleTable.toggleRowSelection(row) }, /** * 动态调用方法 */ dynamicMethod (methodname, params) { this[methodname](params) }, /** * 展示查询条件 */ showCondition () { this.showSearch = true console.log(this.showSearch) }, /** * 设置查询条件 */ setCondition (from) { const newData = JSON.parse(JSON.stringify(from)) this.searchForm = newData this.searchData() }, /** * 保存表单 */ saveForm (from) { const newData = JSON.parse(JSON.stringify(from)) this.employeForm = newData this.$http.post('/api/sysEmploye/save', this.employeForm).then(res => { if (res.code == '0') { this.$message.success(res.msg) this.showForm = false this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }, /** * 删除员工 */ handleDelClick (row) { // 设置账号栏位不可编辑 this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { const idArray = [] this.$refs.multipleTable.selection.forEach(element => { idArray.push(element.id) }) this.$http.post('/api/sysEmploye/delete', idArray).then(res => { if (res.code == '0') { this.$message.success(res.msg) this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }).catch(() => { this.$message.info('已取消删除') }) }, /** * 密码重置 */ handleResetClick (row) { this.$http.post('/api/sysEmploye/rest-password', [row.id]).then(res => { if (res.code == '0') { this.$message.success(res.msg) this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }, /** * 角色分配 */ handleRoleClick (row) { this.visible = true this.employeId = row.id this.$http.get('/api/sysRoleemploye/role-list-set', { params: { employeId: row.id } }).then(res => { console.log(res) this.treeData = res.data.tree this.checkedKeys = res.data.checkIds }).catch(err => { console.log(err.message) }) }, /** * 修改数据 */ handleEditClick (row) { // 设置账号栏位不可编辑 for (const item in this.employeForm) { this.employeForm[item] = '' } this.employeControl[1].readonly = true this.employeControl[8].options = this.educationArray this.employeControl[9].options = this.deptArray this.employeControl[10].options = this.jobsArray this.showForm = true this.employeForm.workNo = row.workNo this.employeForm.name = row.name this.employeForm.foreignName = row.foreignName this.employeForm.email = row.email this.employeForm.mobilePhone = row.mobilePhone this.employeForm.telePhone = row.telePhone this.employeForm.birthday = row.birthday this.employeForm.education = row.education this.employeForm.department = row.department this.employeForm.position = row.position this.employeForm.entryDate = row.entryDate this.employeForm.departureDate = row.departureDate this.employeForm.id = row.id }, /** * 授权 */ handleAuthClick () { }, /** *权限查看 */ handleAuthVClick (row) { this.employeId = row.id this.showTree = true }, /** * 分配角色 */ setRole () { if (this.$refs.multipleTable.selection.length <= 0) { this.$message.warning('请选择要操作的员工') } if (this.$refs.multipleTable.selection.length > 1) { this.$message.warning('只能选择一个员工') } const id = this.$refs.multipleTable.selection[0].id this.employeId = id this.visible = true this.$http.get('/api/sysRoleemploye/role-list-set', { params: { employeId: id } }).then(res => { console.log(res) this.treeData = res.data.tree this.checkedKeys = res.data.checkIds }).catch(err => { console.log(err.message) }) }, // 树形全选操作 selectAll () { var keys = [] if (this.treeData.length > this.$refs.tree.getCheckedNodes().length) { this.treeData.map(function (item) { keys.push(item.id) }) this.$refs.tree.setCheckedKeys(keys) } else { this.$refs.tree.setCheckedKeys([]) } }, /** * 角色分配提交 */ submitRole () { const nodes = this.$refs.tree.getCheckedNodes() this.$http.post('/api/sysRoleemploye/save?employeId=' + this.employeId, nodes).then(res => { this.visible = false if (res.code == '0') { this.$message.success(res.msg) this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }, /** * 重置密码 */ restPwd () { if (this.$refs.multipleTable.selection.length <= 0) { this.$message.warning('请选择要操作的员工') return } const idArray = [] this.$refs.multipleTable.selection.forEach(element => { idArray.push(element.id) }) this.$http.post('/api/sysEmploye/rest-password', idArray).then(res => { if (res.code == '0') { this.$message.success(res.msg) this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }, /** * 删除员工 */ delete () { if (this.$refs.multipleTable.selection.length <= 0) { this.$message.warning('请选择要操作的员工') return } this.$confirm('此操作将永久删除选择的员工, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { const idArray = [] this.$refs.multipleTable.selection.forEach(element => { idArray.push(element.id) }) this.$http.post('/api/sysEmploye/delete', idArray).then(res => { if (res.code == '0') { this.$message.success(res.msg) this.searchData() } else { this.$message.error(res.msg) } }).catch(err => { console.log(err.message) }) }).catch(() => { this.$message.info('已取消删除') }) }, /** * 自定义列修改 */ changeColumns (val) { console.log('changeColumns--' + val) this.tableColumns = [] this.$nextTick(() => { this.tableColumns = val }) }, /** * table每页数字变化 */ handleSizeChange (val) { console.log(`每页 ${val} 条`) this.size = val this.searchData() }, /** * table页数变化 */ handleCurrentChange (val) { console.log(`当前页: ${val}`) this.current = val this.searchData() } }, created () { this.tableHeight = document.documentElement.clientHeight - 240 // this.tableColumns = this.defaultColumns this.getDicItem(); this.getDept(); this.getJobs(); this.searchData() } } </script>