text
stringlengths 184
4.48M
|
---|
/***
* Copyright (c) 2010 readyState Software Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.readystatesoftware.mapviewballoons;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import java.util.List;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.inferiorhumanorgans.WayToGo.Agency.BaseAgency;
import com.inferiorhumanorgans.WayToGo.MainActivity;
import com.inferiorhumanorgans.WayToGo.MapView.StopOverlayItem;
import com.inferiorhumanorgans.WayToGo.R;
import com.inferiorhumanorgans.WayToGo.Util.Stop;
import java.util.ArrayList;
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.ItemizedOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
/**
* An abstract extension of ItemizedOverlay for displaying an information balloon
* upon screen-tap of each marker overlay.
*
* @author Jeff Gilfelt
*/
public class BalloonItemizedOverlay<Item extends OverlayItem> extends ItemizedOverlay<Item> {
private static final String LOG_NAME = BalloonItemizedOverlay.class.getCanonicalName();
private BalloonOverlayView<Item> balloonView;
private View clickRegion;
private int viewOffset;
private Item currentFocussedItem;
private int currentFocussedIndex;
private MapView mapView;
private MapController mc;
protected final List<Item> mItemList;
private static final int mDrawnItemsLimit = Integer.MAX_VALUE;
final private Context theContext;
/**
* Create a new BalloonItemizedOverlay
*
* @param defaultMarker - A bounded Drawable to be drawn on the map for each item in the overlay.
* @param mapView - The view upon which the overlay items are to be drawn.
*/
public BalloonItemizedOverlay(List<Item> pList, Drawable defaultMarker, Context aContext, MapView aMapView) {
super(defaultMarker, new DefaultResourceProxyImpl(aContext));
theContext = aContext;
mItemList = pList;
viewOffset = 0;
mapView = aMapView;
mc = mapView.getController();
populate();
}
public BalloonItemizedOverlay(Drawable defaultMarker, Context aContext, MapView aMapView) {
this(new ArrayList<Item>(), defaultMarker, aContext, aMapView);
}
@Override
protected Item createItem(int index) {
return mItemList.get(index);
}
@Override
public int size() {
return Math.min(mItemList.size(), mDrawnItemsLimit);
}
public boolean addItem(Item item) {
boolean result = mItemList.add(item);
populate();
return result;
}
public void addItem(int location, Item item) {
mItemList.add(location, item);
}
public boolean addItems(List<Item> items) {
boolean result = mItemList.addAll(items);
populate();
return result;
}
public void removeAllItems() {
removeAllItems(true);
}
public void removeAllItems(boolean withPopulate) {
mItemList.clear();
if (withPopulate) {
populate();
}
}
public boolean removeItem(Item item) {
boolean result = mItemList.remove(item);
populate();
return result;
}
public Item removeItem(int position) {
Item result = mItemList.remove(position);
populate();
return result;
}
/**
* Set the horizontal distance between the marker and the bottom of the information
* balloon. The default is 0 which works well for center bounded markers. If your
* marker is center-bottom bounded, call this before adding overlay items to ensure
* the balloon hovers exactly above the marker.
*
* @param pixels - The padding between the center point and the bottom of the
* information balloon.
*/
public void setBalloonBottomOffset(int pixels) {
viewOffset = pixels;
}
public int getBalloonBottomOffset() {
return viewOffset;
}
/**
* Override this method to handle a "tap" on a balloon. By default, does nothing
* and returns false.
*
* @param index - The index of the item whose balloon is tapped.
* @param item - The item whose balloon is tapped.
* @return true if you handled the tap, otherwise false.
*/
protected boolean onBalloonTap(int index, Item item) {
if (!(item instanceof StopOverlayItem)) {
return true;
}
final StopOverlayItem stopItem = (StopOverlayItem) item;
final Stop ourStop = stopItem.getTheStop();
final BaseAgency ourAgency = ourStop.agency();
final Intent ourIntent = ourAgency.getPredictionIntentForStop(ourStop);
if (theContext instanceof Activity) {
final Activity ourActivity = (Activity) theContext;
final MainActivity ourMain = (MainActivity) ourActivity.getParent();
com.inferiorhumanorgans.WayToGo.BaseActivityGroup ag = (com.inferiorhumanorgans.WayToGo.BaseActivityGroup) ourMain.getActivityForTabTag(ourAgency.getClass().getCanonicalName());
if (ag != null) {
Log.d(LOG_NAME, "Creating on activity group: " + ag);
ag.startChildActivity(ourIntent.toUri(0), ourIntent);
} else {
Log.d(LOG_NAME, "No activity group found??");
theContext.startActivity(ourIntent);
}
}
return true;
}
@Override
public boolean onSingleTapUp(final MotionEvent event, final MapView mapView) {
final Projection pj = mapView.getProjection();
final int eventX = (int) event.getX();
final int eventY = (int) event.getY();
final Point mItemPoint = new Point();
final Point mTouchScreenPoint = new Point();
/* These objects are created to avoid construct new ones every cycle. */
pj.fromMapPixels(eventX, eventY, mTouchScreenPoint);
int markerIndex = -1;
for (int i = 0; i < this.mItemList.size(); ++i) {
final Item item = getItem(i);
final Drawable marker = (item.getMarker(0) == null) ? this.mDefaultMarker : item.getMarker(0);
pj.toPixels(item.getPoint(), mItemPoint);
if (hitTest(item, marker, mTouchScreenPoint.x - mItemPoint.x, mTouchScreenPoint.y
- mItemPoint.y)) {
markerIndex = i;
break;
}
}
if (markerIndex == -1) {
return false;
}
currentFocussedIndex = markerIndex;
currentFocussedItem = createItem(markerIndex);
boolean isRecycled;
if (balloonView == null) {
balloonView = createBalloonOverlayView();
clickRegion = (View) balloonView.findViewById(R.id.balloon_inner_layout);
clickRegion.setOnTouchListener(createBalloonTouchListener());
isRecycled = false;
} else {
isRecycled = true;
}
balloonView.setVisibility(View.GONE);
List<Overlay> mapOverlays = mapView.getOverlays();
if (mapOverlays.size() > 1) {
hideOtherBalloons(mapOverlays);
}
balloonView.setData(currentFocussedItem);
GeoPoint point = currentFocussedItem.getPoint();
MapView.LayoutParams params = new MapView.LayoutParams(
MapView.LayoutParams.WRAP_CONTENT, MapView.LayoutParams.WRAP_CONTENT, point,
MapView.LayoutParams.BOTTOM_CENTER, 0, 0);
// params.mode = MapView.LayoutParams.MODE_MAP;
balloonView.setVisibility(View.VISIBLE);
if (isRecycled) {
balloonView.setLayoutParams(params);
} else {
mapView.addView(balloonView, params);
}
mc.animateTo(point);
return true;
}
/**
* Creates the balloon view. Override to create a sub-classed view that
* can populate additional sub-views.
*/
protected BalloonOverlayView<Item> createBalloonOverlayView() {
return new BalloonOverlayView<Item>(getMapView().getContext(), getBalloonBottomOffset());
}
/**
* Expose map view to subclasses.
* Helps with creation of balloon views.
*/
protected MapView getMapView() {
return mapView;
}
/**
* Sets the visibility of this overlay's balloon view to GONE.
*/
protected void hideBalloon() {
if (balloonView != null) {
balloonView.setVisibility(View.GONE);
}
}
/**
* Hides the balloon view for any other BalloonItemizedOverlay instances
* that might be present on the MapView.
*
* @param overlays - list of overlays (including this) on the MapView.
*/
private void hideOtherBalloons(List<Overlay> overlays) {
for (Overlay overlay : overlays) {
if (overlay instanceof BalloonItemizedOverlay<?> && overlay != this) {
((BalloonItemizedOverlay<?>) overlay).hideBalloon();
}
}
}
/**
* Sets the onTouchListener for the balloon being displayed, calling the
* overridden {@link #onBalloonTap} method.
*/
private OnTouchListener createBalloonTouchListener() {
return new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
View l = ((View) v.getParent()).findViewById(R.id.balloon_main_layout);
Drawable d = l.getBackground();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int[] states = {android.R.attr.state_pressed};
if (d.setState(states)) {
d.invalidateSelf();
}
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
int newStates[] = {};
if (d.setState(newStates)) {
d.invalidateSelf();
}
// call overridden method
onBalloonTap(currentFocussedIndex, currentFocussedItem);
return true;
} else {
return false;
}
}
};
}
public boolean onSnapToItem(int x, int y, Point snapPoint, MapView mapView) {
return false;
}
} |
import { NextResponse, type NextRequest } from "next/server";
import { createMiddlewareClient } from "@supabase/auth-helpers-nextjs";
export async function middleware(req: NextRequest) {
try {
const res = NextResponse.next();
const supabase = createMiddlewareClient({ req, res });
const {
data: { session },
} = await supabase.auth.getSession();
const user = session?.user;
const { data, error } = await supabase.rpc("check_user_step");
if (
user &&
!error &&
data !== 2 &&
req.nextUrl.pathname !== "/onboarding" &&
!req.nextUrl.pathname.includes("/api") &&
!req.nextUrl.pathname.startsWith("/auth")
) {
req.nextUrl.pathname = "/onboarding";
return NextResponse.redirect(req.nextUrl);
}
if (user && req.nextUrl.pathname === "/login") {
req.nextUrl.pathname = "";
return NextResponse.redirect(req.nextUrl);
}
/* NOTE : ADMIN ROUTES */
if (req.nextUrl.pathname.startsWith("/admin")) {
if (!user) return NextResponse.error();
const { data, error } = await supabase
.from("User")
.select("role")
.eq("id", user.id)
.single<{ role: string }>();
if (error || !data || data.role.toLowerCase() != "admin")
return NextResponse.error();
}
return res;
} catch (e) {
return NextResponse.next({ request: { headers: req.headers } });
}
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|favicon.ico|auth/callback|auth/pw-callback).*)",
],
}; |
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { Student } from './entities/student.entity';
import { Event } from '../events/entities/event.entity';
import { EventsService } from '../events/events.service';
import { MailerService } from '@nestjs-modules/mailer';
import { RecoverPasswordDto } from './dto/recover-password.dto';
import { UpdatePasswordDto } from './dto/update-password.dto';
@Injectable()
export class StudentService {
constructor(
@InjectRepository(Student)
private studentRepo: Repository<Student>,
@InjectRepository(Event)
private eventRepo: Repository<Event>,
private eventService: EventsService,
private mailerService: MailerService,
){}
async create(createStudentDto: CreateStudentDto) {
const alreadyRegistered = await this.studentRepo.findOne({where: {email: createStudentDto.email }, relations: ["events"]});
if (alreadyRegistered) throw new HttpException("Esse email já foi registrado, utilize outro", HttpStatus.BAD_REQUEST)
const student = await this.studentRepo.create(createStudentDto);
return await this.studentRepo.save(student);
}
async findAll() {
return await this.studentRepo.find({relations: ["events"]});
}
async findOne(id: number) {
return await this.studentRepo.findOne({where: {id: id}, relations: ["events"]})
}
async findEvents(id: number) {
const student = await this.studentRepo.findOne({where: {id: id}, relations: ["events"]});
return student.events;
}
async addEvent(id: number, updateStudentDto: UpdateStudentDto) {
const event = await this.eventRepo.findOneBy(updateStudentDto.event)
let student = await this.findOne(id)
if(!student){
throw new HttpException("Usuário não encontrado", HttpStatus.BAD_REQUEST)
}
// Se o evento já estiver cheio
if(event.capacity === event.filled){
throw new HttpException(`O evento ${event.title} está lotado`, HttpStatus.BAD_REQUEST)
}
//Se o estudante já está cadastrado no evento
const foundEvent = student.events.find(stdevent => stdevent.id === event.id)
if(foundEvent){
throw new HttpException(`Você já está registrado(a) no evento ${foundEvent.title}`, HttpStatus.BAD_REQUEST)
}
await this.eventService.updateFilled(event.id,1)
student.events.push(event)
return await this.studentRepo.save(student)
}
async removeEvent(id: number, updateStudentDto: UpdateStudentDto){
const event = await this.eventRepo.findOneBy(updateStudentDto.event)
let student = await this.findOne(id)
const foundEvent = student.events.find(stdevent => stdevent.id === event.id)
if(!foundEvent){
throw new HttpException("Você não está registrado(a) nesse evento", HttpStatus.BAD_REQUEST)
}
const eventIndex = student.events.findIndex(e => e.id === event.id);
student.events.splice(eventIndex,1);
await this.eventService.updateFilled(event.id,-1)
return await this.studentRepo.save(student)
}
async remove(id: number) {
const student = await this.findOne(id);
if(!student){
throw new HttpException("Usuário não encontrado", HttpStatus.BAD_REQUEST)
}
const studentEvents = student.events;
for (let i = 0; i < Object.keys(studentEvents).length; i++) {
await this.eventService.updateFilled(studentEvents[i].id,-1)
}
return await this.studentRepo.delete(id);
}
async findOneLogin(email: string): Promise<Student | undefined> {
return await this.studentRepo.findOne({where: {email: email}});
}
async recoverPassword(recoverDto: RecoverPasswordDto){
if(!recoverDto.email){
throw new HttpException("É preciso passar o email na requisição!", HttpStatus.BAD_REQUEST);
}
const student = await this.studentRepo.findOne({where:{email: recoverDto.email}});
if(!student){
throw new HttpException("Este email não está cadastrado", HttpStatus.BAD_REQUEST);
}
const mail = {
to: student.email,
from: 'noreply@application.com',
subject: 'Recuperação de senha - CT de portas abertas',
template: 'recover-password',
context: {
password: student.password,
}
}
this.mailerService.sendMail(mail);
}
async updatePassword(id: number, updatePasswordDto: UpdatePasswordDto){
try {
return await this.studentRepo.update(id, updatePasswordDto);
} catch (err) {
throw new HttpException("Falha na atualização da senha. Tente novamente!", HttpStatus.INTERNAL_SERVER_ERROR)
}
}
} |
import {
TestBed,
getTestBed
} from '@angular/core/testing';
import {
TranslateModule,
TranslateLoader
} from '@ngx-translate/core';
import {
HttpClient,
HttpClientModule,
} from '@angular/common/http';
import {
AppTasks,
StateStore,
AppEngine,
NetworkError,
ResponseError,
TimeoutError
} from 'app-engine';
// import mixpanel from 'mixpanel-browser';
import {
NgReduxTestingModule,
MockNgRedux
} from '@angular-redux/store/testing';
import cloneDeep from 'lodash/cloneDeep';
import { Platform } from 'ionic-angular';
import { PlatformMock } from 'ionic-mocks';
import { File } from '@ionic-native/file';
import { FileMock } from '@ionic-native-mocks/file';
import {
InformationModelModule,
InformationModelService,
ModelManagerService,
} from '../modules/information-model';
import { DeviceControlService } from './device-control-service';
import { PopupService } from './popup-service';
import {
PopupServiceMock,
createTranslateLoader,
} from '../mocks/providers.mocks';
import {
AppTasksMock,
AppEngineMock
} from '../mocks/app-engine.mocks';
import {
baseDevice,
testControllers,
} from '../mocks/testing-items.mocks';
describe('Check device control service', () => {
let instance: DeviceControlService;
let appTasks: AppTasks;
let ims: InformationModelService;
let mms: ModelManagerService;
beforeAll(() => {
TestBed.configureTestingModule({
imports: [
NgReduxTestingModule,
InformationModelModule.forRoot(),
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [HttpClient]
},
}),
],
providers: [
{ provide: Platform, useFactory: () => PlatformMock.instance() },
{ provide: AppEngine, useClass: AppEngineMock },
AppTasks,
{ provide: File, useClass: FileMock },
{ provide: PopupService, useClass: PopupServiceMock },
StateStore,
DeviceControlService,
],
});
const injector = getTestBed();
instance = injector.get(DeviceControlService);
appTasks = injector.get(AppTasks);
ims = injector.get(InformationModelService);
mms = injector.get(ModelManagerService);
// prevent mixpanel uninitialized issue
// mixpanel.init('appConfig.mixpanel.token');
return mms.load('http://');
});
it('test isAvailable() function', () => {
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
expect(instance.isAvailable('a device id')).toBeTruthy();
expect(instance.isAvailable('a device id', 'H00')).toBeTruthy();
expect(instance.isAvailable('a device id', 'H01')).toBeTruthy();
instance.setDevice('a device id', { H00: 1 });
expect(instance.isAvailable('a device id')).toBeFalsy();
expect(instance.isAvailable('a device id', 'H00')).toBeFalsy();
expect(instance.isAvailable('a device id', 'H01')).toBeTruthy();
return new Promise(resolve => setTimeout(() => resolve(), 1000));
});
it('test setDevice() - normal commands', done => {
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1 });
return new Promise(resolve => setTimeout(() => resolve(), 1000))
.then(() => done());
});
it('test setDevice() - multiple commands', done => {
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
const testDevice = cloneDeep(baseDevice);
testDevice.profile.esh.model = 'RAS-AC';
devicesStub.next({
'a device id': testDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 1000))
.then(() => done());
});
it('test setDevice() - multiple commands, no model', done => {
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 500))
.then(() => done());
});
it('test setDevice() - multiple commands, empty model', done => {
spyOn(ims, 'getUIModel').and.returnValue({});
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 500))
.then(() => done());
});
it('test setDevice() - throwing network error', done => {
spyOn(appTasks, 'wsRequestSetTask').and.callFake(() => Promise.reject(new NetworkError('network error')));
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 500))
.then(() => done());
});
it('test setDevice() - throwing response error', done => {
spyOn(appTasks, 'wsRequestSetTask').and.callFake(() => Promise.reject(new ResponseError(400, 'response error')));
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 500))
.then(() => done());
});
it('test setDevice() - throwing timeout error', done => {
spyOn(appTasks, 'wsRequestSetTask').and.callFake(() => Promise.reject(new TimeoutError('timeout error')));
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 500))
.then(() => done());
});
it('test setDevice() - throwing other error', done => {
spyOn(appTasks, 'wsRequestSetTask').and.callFake(() => Promise.reject(new Error('other error')));
const devicesStub = MockNgRedux.getSelectorStub(['core', 'devices']);
devicesStub.next({
'a device id': baseDevice,
});
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
return new Promise(resolve => setTimeout(() => resolve(), 500))
.then(() => done());
});
it('test filter multiple commands', () => {
expect(instance.filter({ H01: 0 }, testControllers)).toEqual({ H01: 0, });
expect(instance.filter({ H01: 1, H03: 17 }, testControllers)).toEqual({ H01: 1, H03: 17 });
expect(instance.filter({ H01: 2, H03: 17 }, testControllers)).toEqual({ H01: 2 });
expect(instance.filter({ H01: 2, H03: 17, H02: 4 }, testControllers)).toEqual({ H01: 2, H02: 4 });
expect(instance.filter({ H00: 0, H01: 0, H03: 17, H02: 4 }, testControllers, { H00: 0 })).toEqual({ H00: 0 });
});
it('test clear()', () => {
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5, H02: 4 });
instance.setDevice('a device id', { H00: 1, H01: 1, H02: 4 });
instance.setDevice('a device id', { H00: 1, H03: 5, H02: 4 });
instance.setDevice('a device id', { H00: 1, H01: 1, H03: 5 });
instance.clear();
});
}); |
####################################
## Author : Mohamed Ahmed Amer | Hamo
## Github : https://github.com/H7AM0
## Telegram : https://t.me/hamo_back
## Instagram : https://instagram.com/4.4cq/
####################################
##### pip install GmailBox==0.0.9
####################################
import asyncio
from GmailBox.asyncio import GmailBox
async def check_inbox(Gmail, email):
"""Asynchronously check and display emails in the inbox recursively."""
print(f' [*] Your email: {email}')
input(" [?] Press Enter to check inbox: ")
# Fetch inbox messages asynchronously for the given email
inbox = await Gmail.inbox(email)
if inbox:
for message in inbox:
print("=" * 21)
print(message)
print("=" * 21)
# Recursively check the inbox again
await check_inbox(Gmail, email)
else:
print(f' [!] No messages were received.')
print("=" * 21)
# Recursively check the inbox again
await check_inbox(Gmail, email)
async def main():
"""Main function to initialize GmailBox and start checking the inbox asynchronously."""
async with GmailBox() as Gmail:
# Create a new email asynchronously
New_Gmail = await Gmail.new_email()
email = New_Gmail.email
# Start checking the inbox
await check_inbox(Gmail, email)
# Entry point of the script
if __name__ == "__main__":
asyncio.run(main()) |
# Working directory (change)
setwd("/home/giovanni/Scrivania/teresa/ms-gwr-revised")
rm(list=ls())
graphics.off()
cat("\014")
## DATA PREPARATION
## This script is used to projects event and site coordinates on a UTM system, and prepares the dataset
## that is used for the calibration of the Geographically weighted model.
## It loads data from files:
## - "data_dir/italian_data_pga.RData"
## - "data_dir/confini_ut33.shp"
## and saves the pre-processed data in
## two files:
## - "data_dir/utm_coordinates.RData"
## - "data_dir/regressors.RData"
# Load data
dataset = readRDS("data_dir/italian_data_pga.RData")
# write.csv(dataset, "data_dir/italian_data_pga.csv")
# shapefiles
shape_utm = st_read('data_dir/confini_ut33.shp')
## Shapefiles -------------------------------------------
# Removal of unused regions
shape_utm_no_lamp = shape_utm
shape_utm_no_lamp$geometry[[1]][[12]] = NULL
shape_utm_no_sardinia = shape_utm
shape_utm_no_sardinia$geometry[[1]][[3]] = NULL
for (i in 4:10){
shape_utm_no_sardinia$geometry[[1]][[4]] = NULL
}
for (i in 12:57){
shape_utm_no_sardinia$geometry[[1]][[5]] = NULL
}
# Remove Sortino
SRT.lat = 37.16657
SRT.long = 15.05421
SRT.idx = 4632
dataset = dataset[-SRT.idx,]
# Projection of event and site coordinates to work with UTM33
latitude_ev = dataset$ev_latitude
longitude_ev = dataset$ev_longitude
long_lat_ev = cbind(longitude_ev, latitude_ev)
utm_ev = project(long_lat_ev, "+proj=utm +zone=33 ellps=WGS84")
utm_ev = as.data.frame(utm_ev)
long_lat_ev = as.data.frame(long_lat_ev)
latitude_st = dataset$st_latitude
longitude_st = dataset$st_longitude
long_lat_st = cbind(longitude_st, latitude_st)
utm_st = project(long_lat_st, "+proj=utm +zone=33 ellps=WGS84")
utm_st = as.data.frame(utm_st)
long_lat_st = as.data.frame(long_lat_st)
# Midpoint
utm_md = (utm_ev + utm_st)/2
# Build spatial points data frame for UTM33 coordinates
utm_ev_sp = SpatialPointsDataFrame(utm_ev, dataset[,1:6])
utm_st_sp = SpatialPointsDataFrame(utm_st, dataset[,1:6])
utm_md_sp = SpatialPointsDataFrame(utm_md, dataset[,1:6])
# Transform shapefile into spatial dataframe
shape_utm_spatial = as_Spatial(shape_utm_no_sardinia)
grid_utm = makegrid(shape_utm_spatial, cellsize = 10000) # cellsize in map units!
grid_utm = SpatialPoints(grid_utm, proj4string = CRS(proj4string(shape_utm_spatial)))
grid_inside_utm = grid_utm[shape_utm_spatial,]
coords_utm = grid_inside_utm@coords
coords_df_utm = as.data.frame(coords_utm)
save(utm_md_sp, utm_ev_sp, utm_st_sp, coords_utm, file="data_dir/utm_coordinates.RData")
save(utm_md, utm_ev, utm_st, shape_utm_no_lamp, file="data_dir/spacial_info_plots.RData")
## Build the data -------------------------------------
mh = 5.5
mref = 5.324
h = 6.924
attach(dataset)
b1 = (mag-mh)*(mag<=mh)
b2 = (mag-mh)*(mag>mh)
c1 = (mag-mref)*log10(sqrt(JB_complete^2+h^2))
c2 = log10(sqrt(JB_complete^2+h^2))
c3 = sqrt(JB_complete^2+h^2)
f1 = as.numeric(fm_type_code == "SS")
f2 = as.numeric(fm_type_code == "TF")
k = log10(vs30/800)*(vs30<=1500)+log10(1500/800)*(vs30>1500)
y = log10(rotD50_pga)
detach(dataset)
save(b1,b2,c1,c2,c3,f1,f2,k,mh,mref,h,y, file="data_dir/regressors.RData") |
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
final class Solution {
func maxDepth(_ root: TreeNode?) -> Int {
guard let root = root else { return 0 }
return max(maxDepth(root.left), maxDepth(root.right)) + 1
}
}
let r = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
Solution().maxDepth(r) |
package gr.hua.dit.ds.BloodRegistry.controllers;
import gr.hua.dit.ds.BloodRegistry.config.JwtUtils;
import gr.hua.dit.ds.BloodRegistry.entities.model.Role;
import gr.hua.dit.ds.BloodRegistry.entities.model.User;
import gr.hua.dit.ds.BloodRegistry.payload.request.LoginRequest;
import gr.hua.dit.ds.BloodRegistry.payload.response.JwtResponse;
import gr.hua.dit.ds.BloodRegistry.repositories.RoleRepository;
import gr.hua.dit.ds.BloodRegistry.repositories.UserRepository;
import gr.hua.dit.ds.BloodRegistry.services.UserDetailsImpl;
import jakarta.annotation.PostConstruct;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;//Interface from Spring Security for authenticate users.
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
@Autowired
PasswordEncoder encoder;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
System.out.println("authentication");
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
System.out.println("authentication: " + authentication);
SecurityContextHolder.getContext().setAuthentication(authentication);
System.out.println("post authentication");
String jwt = jwtUtils.generateJwtToken(authentication);
System.out.println("jw: " + jwt);
UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream()
.map(item -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity.ok(new JwtResponse(jwt,
userDetails.getId(),
userDetails.getUsername(),
userDetails.getEmail(),
roles));
}
} |
import { UriMatchStrategySetting } from "../../../models/domain/domain-service";
import { Utils } from "../../../platform/misc/utils";
import { DeepJsonify } from "../../../types/deep-jsonify";
import { LoginLinkedId as LinkedId } from "../../enums";
import { linkedFieldOption } from "../../linked-field-option.decorator";
import { Login } from "../domain/login";
import { Fido2CredentialView } from "./fido2-credential.view";
import { ItemView } from "./item.view";
import { LoginUriView } from "./login-uri.view";
export class LoginView extends ItemView {
@linkedFieldOption(LinkedId.Username)
username: string = null;
@linkedFieldOption(LinkedId.Password)
password: string = null;
passwordRevisionDate?: Date = null;
totp: string = null;
uris: LoginUriView[] = [];
autofillOnPageLoad: boolean = null;
fido2Credentials: Fido2CredentialView[] = null;
constructor(l?: Login) {
super();
if (!l) {
return;
}
this.passwordRevisionDate = l.passwordRevisionDate;
this.autofillOnPageLoad = l.autofillOnPageLoad;
}
get uri(): string {
return this.hasUris ? this.uris[0].uri : null;
}
get maskedPassword(): string {
return this.password != null ? "••••••••" : null;
}
get subTitle(): string {
// if there's a passkey available, use that as a fallback
if (Utils.isNullOrEmpty(this.username) && this.fido2Credentials?.length > 0) {
return this.fido2Credentials[0].userName;
}
return this.username;
}
get canLaunch(): boolean {
return this.hasUris && this.uris.some((u) => u.canLaunch);
}
get hasTotp(): boolean {
return !Utils.isNullOrWhitespace(this.totp);
}
get launchUri(): string {
if (this.hasUris) {
const uri = this.uris.find((u) => u.canLaunch);
if (uri != null) {
return uri.launchUri;
}
}
return null;
}
get hasUris(): boolean {
return this.uris != null && this.uris.length > 0;
}
get hasFido2Credentials(): boolean {
return this.fido2Credentials != null && this.fido2Credentials.length > 0;
}
matchesUri(
targetUri: string,
equivalentDomains: Set<string>,
defaultUriMatch: UriMatchStrategySetting = null,
): boolean {
if (this.uris == null) {
return false;
}
return this.uris.some((uri) => uri.matchesUri(targetUri, equivalentDomains, defaultUriMatch));
}
static fromJSON(obj: Partial<DeepJsonify<LoginView>>): LoginView {
const passwordRevisionDate =
obj.passwordRevisionDate == null ? null : new Date(obj.passwordRevisionDate);
const uris = obj.uris.map((uri) => LoginUriView.fromJSON(uri));
const fido2Credentials = obj.fido2Credentials?.map((key) => Fido2CredentialView.fromJSON(key));
return Object.assign(new LoginView(), obj, {
passwordRevisionDate,
uris,
fido2Credentials,
});
}
} |
import { Component, ViewChild } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { NavController } from '@ionic/angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
sliderValue: number = 20;
tempoVariation: number = 50;
volume: number = 50;
metric: string = '4/4';
metronomeOn: boolean = false;
isMuted: boolean = false;
username: string = '';
@ViewChild('clickSound') clickSound: any;
private interval: any;
private isPlaying: boolean = false;
// Declaración de las opciones de sonido y el sonido seleccionado
soundOptions: any[] = [
{ name: 'Clasic', path: 'assets/CLASIC_BEAT.mp3' },
{ name: 'Cubase_High', path: 'assets/CUBASE_HIGH2.mp3' },
{ name: 'Cubase_Low', path: 'assets/CUBASE_LOW2.mp3' },
// Agrega más opciones de sonido según sea necesario
];
selectedSound: any = this.soundOptions[0];
constructor(private platform: Platform, private router: Router, private route: ActivatedRoute, private navCtrl: NavController ){
this.route.params.subscribe(params => {
this.username = params['username'];
});
this.sliderValue = 40;
}
toggleMute() {
this.isMuted = !this.isMuted;
if (this.isMuted) {
this.muteSound();
} else {
this.unmuteSound();
}
}
private muteSound() {
// Pausar o silenciar el sonido según tu lógica específica
// Ejemplo para un elemento de audio HTML:
this.clickSound.nativeElement.muted = true;
}
private unmuteSound() {
// Reanudar o restablecer el sonido según tu lógica específica
// Ejemplo para un elemento de audio HTML:
this.clickSound.nativeElement.muted = false;
}
increaseBPM() {
// Implementa la lógica para aumentar el valor del ritmo (bpm)
if (this.sliderValue < 300) { // Por ejemplo, puedes definir un valor máximo (300 en este caso)
this.sliderValue += 10; // Aumenta el valor del ritmo en 10 unidades
}
}
decreaseBPM() {
// Implementa la lógica para disminuir el valor del ritmo (bpm)
if (this.sliderValue > 10) { // Por ejemplo, puedes definir un valor mínimo (10 en este caso)
this.sliderValue -= 10; // Disminuye el valor del ritmo en 10 unidades
}
}
// onSliderChange(event: any) {
// const newValue = event.detail.value;
// this.sliderValue = newValue;
// // Puedes agregar lógica adicional aquí según sea necesario
// }
onSliderChange(event: any) {
const newValue = event.detail.value;
if (newValue < 40) {
this.sliderValue = 40;
} else if (newValue > 300) {
this.sliderValue = 300;
} else {
this.sliderValue = newValue;
}
// Luego, aquí puedes agregar cualquier lógica adicional que necesites en función del valor actual del slider.
}
toggleMetronome() {
this.metronomeOn = !this.metronomeOn;
if (this.metronomeOn) {
this.startMetronome();
} else {
this.stopMetronome();
}
}
startMetronome() {
if (this.isPlaying) return;
this.stopMetronome();
const bpm = this.sliderValue;
const intervalMs = (60 / bpm) * 1000;
this.interval = setInterval(() => {
if (this.metronomeOn) {
this.playClickSound();
}
}, intervalMs);
this.isPlaying = true;
}
stopMetronome() {
if (this.interval) {
clearInterval(this.interval);
this.isPlaying = false;
}
}
// playClickSound() {
// console.log('Reproduciendo sonido...'); // Agrega un mensaje de depuración
// if (this.platform.is('cordova')) {
// const clickSound = new Audio('assets/BEAT.mp3'); // Asegúrate de que la ruta sea correcta
// clickSound.volume = this.volume / 100;
// clickSound.play();
// } else {
// this.clickSound.nativeElement.volume = this.volume / 100;
// this.clickSound.nativeElement.play();
// }
// }
playClickSound() {
console.log('Reproduciendo sonido...');
if (this.platform.is('cordova')) {
const clickSound = new Audio(this.selectedSound.path); // Utiliza el sonido seleccionado
clickSound.volume = this.volume / 100;
clickSound.play();
} else {
this.clickSound.nativeElement.src = this.selectedSound.path; // Utiliza el sonido seleccionado
this.clickSound.nativeElement.volume = this.volume / 100;
this.clickSound.nativeElement.play();
}
}
volver() {
this.router.navigate(['/login']);
}
} |
class GameConfig {
final int level;
final Difficulty difficulty;
final int maxFailureAllowed;
final int randomnessSeed;
final Hand hand;
final int passMark;
final int maximumScore;
int get secondStarScore => passMark + (maximumScore - passMark) ~/ 2;
GameConfig({
required this.level,
required this.hand,
required this.difficulty,
}) : passMark = 15 + (level - 1) * 2,
maximumScore = 25 + (level - 1) * 3,
maxFailureAllowed = 5,
randomnessSeed = difficulty.randomnessSeed,
assert(level >= 1 && level <= 15);
int computeScoreStars(int score) {
final currentRawScore = score ~/ 2;
if (currentRawScore == maximumScore) return 3;
if (currentRawScore >= secondStarScore) return 2;
if (currentRawScore >= passMark) return 1;
return 0;
}
}
enum Hand {
left('Left Hand'),
right('Right Hand');
final String description;
const Hand(this.description);
}
enum Difficulty {
easy(10, Duration(minutes: 6), Duration(minutes: 1, seconds: 30)),
normal(100, Duration(minutes: 4), Duration(minutes: 1)),
hard(200, Duration(minutes: 2), Duration(seconds: 15));
final int randomnessSeed;
final Duration gameTime;
final Duration gameWarningTime;
const Difficulty(this.randomnessSeed, this.gameTime, this.gameWarningTime);
}
enum Finger {
thumb,
pointing,
middle,
ring,
pinky;
} |
---
title: waitForAllSettled(dependencies)
sidebar_label: waitForAllSettled()
---
Un assistant de concurrence qui renvoie un ensemble de [`Loadable`s](/docs/api-reference/core/Loadable) pour l'état actuel des dépendances demandées. Il attend que toutes les dépendances soient soit une valeur ou une erreur.
Les dépendances peuvent être fournies sous forme de tableau de tuples ou de dépendances nommées dans un objet.
---
```jsx
function waitForAllSettled(dependencies: Array<RecoilValue<>>):
RecoilValueReadOnly<UnwrappedArrayOfLoadables>
```
```jsx
function waitForAllSettled(dependencies: {[string]: RecoilValue<>}):
RecoilValueReadOnly<UnwrappedObjectOfLoadables>
```
---
`waitForAllSettled()` est similaire à [`waitForNone()`](/docs/api-reference/utils/waitForNone), sauf qu'il attend qu'au moins une dépendance ait une valeur (ou une erreur) disponible au lieu de retourner immédiatement. |
from typing import Collection
import requests
from bs4 import BeautifulSoup
from bs4.element import ResultSet, Tag
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.ui import WebDriverWait
def get_driver() -> WebDriver:
"""
Возвращает экземпляр веб-драйвера chrome
"""
options = Options()
options.add_argument("--no-sandbox") # Отключает режим песочницы
options.add_argument("--disable-gpu") # Отключает использование видеокарты
options.add_argument("--disable-dev-shm-usage") # Отключает временное хранилище
options.add_argument("--start-maximized") # Максимальное окно браузера
options.add_argument("--headless") # Отключает графические интерфейс
return webdriver.Chrome(options=options)
def get_session() -> requests.Session:
"""
Возвращает сессию для более быстрых запросов к сайтам
"""
return requests.Session()
def get_soup(html_str: str) -> BeautifulSoup:
"""
Возвращает soup спарсенной страницы
"""
return BeautifulSoup(html_str, "html.parser")
def clear(soup: BeautifulSoup | Tag) -> str:
"""
Убирает код и лишние отступы
"""
return soup.get_text().strip()
def get_hrefs(result_set: ResultSet | Collection[Tag]):
"""
Возвращает список из href элементов
"""
return [element["href"] for element in result_set]
def wait(driver: webdriver, locator: str, value: str, timeout: int = 10):
"""
Ожидает появление элемента на web-странице
"""
WebDriverWait(driver, timeout).until(
expected_conditions.presence_of_element_located((locator, value))
) |
<div class="popup box">
<form [formGroup]="postForm" class="log-in" autocomplete="off">
<p>Update Password</p>
<div class="floating-label">
<input placeholder="Enter Old Password " type="password" name="oldpassword " id="oldpassword" formControlName="oldpassword" name="oldpassword" [ngClass]="{
'is-invalid':
(postForm.get('oldpassword')?.touched ||
postForm.get('oldpassword')?.dirty) &&
!postForm.get('oldpassword')?.valid
}" required />
</div>
<span class="invalid" *ngIf="
postForm.controls['oldpassword'].invalid &&
(postForm.controls['oldpassword'].dirty ||
postForm.controls['oldpassword'].touched)
">
<span *ngIf="postForm.get('oldpassword')?.errors?.required">
Please enter oldpassword id
</span>
<span *ngIf="postForm.get('oldpassword')?.errors?.oldpassword">
Please enter a valid oldpassword id
</span>
</span>
<div formGroupName="passwordGroup">
<div class="floating-label">
<input type="password" class="form-control" placeholder="New Password" formControlName="password" [ngClass]="{
'is-invalid':
postForm.get('passwordGroup')?.errors ||
((postForm.get('passwordGroup.password')?.touched ||
postForm.get('passwordGroup.password')?.dirty) &&
!postForm.get('passwordGroup.password')?.valid)
}" required />
</div>
<span class="invalid" *ngIf="
postForm.get('passwordGroup')?.errors ||
((postForm.get('passwordGroup.password')?.touched ||
postForm.get('passwordGroup.password')?.dirty) &&
!postForm.get('passwordGroup.password')?.valid)
">
<span *ngIf="postForm.get('passwordGroup.password')?.errors?.required">
Please enter your password
</span>
<span *ngIf="
postForm.get('passwordGroup.password')?.errors?.password ||
postForm.get('passwordGroup.password')?.errors?.pattern
">
Please enter a valid password
</span>
</span>
<div class="floating-label">
<input type="password" placeholder="Confirm New Password " formControlName="confirmpassword" [ngClass]="{
'is-invalid':
postForm.get('passwordGroup')?.errors ||
((postForm.get('passwordGroup.confirmpassword')?.touched ||
postForm.get('passwordGroup.confirmpassword')?.dirty) &&
!postForm.get('passwordGroup.confirmpassword')?.valid)
}" required />
</div>
<span class="invalid" *ngIf="
postForm.get('passwordGroup')?.errors ||
((postForm.get('passwordGroup.confirmpassword')?.touched ||
postForm.get('passwordGroup.confirmpassword')?.dirty) &&
!postForm.get('passwordGroup.confirmpassword')?.valid)
">
<span
*ngIf="
postForm.get('passwordGroup.confirmpassword')?.errors?.required
"
>
Confirm your password
</span>
<span *ngIf="postForm.get('passwordGroup')?.errors?.match">
The confirmation does not match.
</span>
</span>
</div>
<br />
</form>
<div class="loader" *ngIf="disable"></div>
<div class="error" *ngIf="error">
<p>{{ mssg }}</p>
</div>
<div class="success" *ngIf="success">
<p>{{ mssg }}</p>
</div>
<div class="option">
<button type="submit " (click)="updateUserPassword()" [disabled]="disable">
Save Changes
</button>
<button (click)="close()">No</button>
</div>
</div> |
package com.example.demo.dto;
import com.example.demo.domain.AttachFile;
import com.example.demo.domain.Category;
import com.example.demo.domain.Member;
import com.querydsl.core.annotations.QueryProjection;
import lombok.*;
import java.util.List;
@Builder
@Getter
@Setter
public class BoardDTO {
private Long boardId;
private char isNotice;
private String title;
private String content;
private String contentHTML;
private char isSecret;
private String writer;
private String modifyer;
private Category category;
private Member member;
@QueryProjection
public BoardDTO(Long boardId, char isNotice, String title, String content, String contentHTML,
char isSecret, String writer, String modifyer, Category category, Member member){
this.boardId = boardId;
this.isNotice = isNotice;
this.title = title;
this.content = content;
this.contentHTML = contentHTML;
this.isSecret = isSecret;
this.writer = writer;
this.modifyer = modifyer;
this.category = category;
this.member = member;
}
} |
package com.mcssoft.racemeeting.utility;
import android.content.Context;
import android.preference.PreferenceManager;
import mcssoft.com.racemeeting.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* utility class for general manipulation of time values (primarily for display).
*/
public class MeetingTime {
private MeetingTime(Context context) {
this.context = context;
setTimeFormatFromPreferences();
}
/**
* Get (initialise) an instance of MeetingTime.
* @param context The current context.
* @return An instance of MeetingTime.
*/
public static synchronized MeetingTime getInstance(Context context) {
if(!instanceExists()) {
instance = new MeetingTime(context);
}
return instance;
}
/**
* Get the current MeetingTime instance.
* @return The current MeetingTime instance.
*/
public static synchronized MeetingTime getInstance() {
return instance;
}
public static boolean instanceExists() {
return instance != null ? true : false;
}
/**
* Get the time as a string formatted HH:MM.
* @param timeInMillis The time value in mSec.
* @return The time based on the parameter timeInMillis value.
*/
public String getFormattedTimeFromMillis(long timeInMillis) {
String time;
SimpleDateFormat sdFormat;
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.setTime(new Date(timeInMillis));
setTimeFormatFromPreferences();
if(timeFormat.equals(MeetingResources.getInstance()
.getString(R.string.time_format_pref_12hr))) {
sdFormat = new SimpleDateFormat(MeetingResources.getInstance()
.getString(R.string.time_format_12hr), Locale.getDefault());
time = sdFormat.format(calendar.getTime());
time = time.replace("am","AM").replace("pm","PM");
} else {
sdFormat = new SimpleDateFormat(MeetingResources.getInstance()
.getString(R.string.time_format_24hr), Locale.getDefault());
time = sdFormat.format(calendar.getTime());
}
return time;
}
public String getFormattedDateFromMillis(long timeInMillis) {
String ddMMyyyy;
SimpleDateFormat sdFormat;
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.setTime(new Date(timeInMillis));
sdFormat = new SimpleDateFormat(MeetingResources.getInstance()
.getString(R.string.date_format), Locale.getDefault());
ddMMyyyy = sdFormat.format(calendar.getTime());
return ddMMyyyy;
}
/**
* Get the time in milli seconds based on the given hour and minute values.
* @param time int[2] where; [0] == hour, [1] == minute (can be null).
* @return The time in milli seconds, or null.
*/
public long getMillisFromTimeComponent(int [] time) {
if (time == null || time.length != 2) {
return R.integer.init_default;
}
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.set(Calendar.HOUR_OF_DAY, time[0]);
calendar.set(Calendar.MINUTE, time[1]);
return calendar.getTimeInMillis();
}
/**
* Get the current time in milli seconds.
* @return The time in milli seconds.
*/
public long getTimeInMillis() {
return Calendar.getInstance(Locale.getDefault()).getTimeInMillis();
}
/**
* Get the HH (hour) and MM (minute) time components of the given time.
* @param timeInMillis The time value in mSec.
* @param component An identifier for the time component.
* @return The time components; int[0] == hour or minute, and int[1] == minute or -1, or null
* if the parameter is unrecognised.
*/
public int [] getTimeComponent(long timeInMillis, int component) {
int [] time = new int[2];
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.setTime(new Date(timeInMillis));
switch(component) {
case R.integer.time_component_hour_minute:
time[0] = calendar.get(Calendar.HOUR_OF_DAY);
time[1] = calendar.get(Calendar.MINUTE);
break;
case R.integer.time_component_hour:
time[0] = calendar.get(Calendar.HOUR_OF_DAY);
time[1] = R.integer.init_default;
break;
case R.integer.time_component_minute:
time[0] = calendar.get(Calendar.MINUTE);
time[1] = R.integer.init_default;
break;
default:
time = null;
}
return time;
}
public String getTimeFormatPrefKey() {
String timeFormatPrefKey = null;
if (timeFormat.equals(MeetingResources.getInstance()
.getString(R.string.time_format_pref_12hr))) {
timeFormatPrefKey = MeetingResources.getInstance()
.getString(R.string.time_format_pref_12hr_key);
} else if (timeFormat.equals(MeetingResources.getInstance()
.getString(R.string.time_format_pref_24hr))) {
timeFormatPrefKey = MeetingResources.getInstance()
.getString(R.string.time_format_pref_24hr_key);
}
return timeFormatPrefKey;
}
/**
* Get a time value in millis that is the current time minus (parameter).
* @param reminderTime A time value in minutes.
* @param raceTime A time value in milli seconds.
* @return A time value that is the race time minus the reminder time.
*/
public long getTimeMinus(int reminderTime, long raceTime) {
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.setTime(new Date(raceTime));
calendar.add(Calendar.MINUTE, -reminderTime);
return calendar.getTimeInMillis();
}
/**
* Ensure instance values are made NULL.
*/
public void destroy() {
context = null;
instance = null;
}
/**
* Check if the current time is after the time given.
* @param timeInMillis The given time.
* @return True if current time is after the given time, else false.
*/
public boolean isTimeAfter(long timeInMillis) {
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.setTime(new Date(timeInMillis));
return Calendar.getInstance().after(calendar);
}
/**
* Get a value that represents midnight (00:00 hours of the current day).
* @return Time in mSec representing mignight.
*/
public long getMidnight() {
Calendar calendar = Calendar.getInstance(Locale.getDefault());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
return calendar.getTimeInMillis();
}
/**
* Check if the given time is a time from today.
* @param timeInMillis The given time.
* @return True if the given time is a time from today, else false.
* Note: A return value of false means a time on a previous day.
*/
public boolean isTimeToday(long timeInMillis) {
Calendar today = Calendar.getInstance(Locale.getDefault());
Calendar toCheck = Calendar.getInstance(Locale.getDefault());
toCheck.setTime(new Date(timeInMillis));
if(toCheck.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
return true;
}
return false;
}
/**
* Set the time format 12HR/24HR from the app's shared preferences.
*/
private void setTimeFormatFromPreferences() {
if(PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(MeetingResources.getInstance()
.getString(R.string.time_format_pref_key), false)) {
timeFormat = MeetingResources.getInstance().getString(R.string.time_format_pref_24hr);
} else {
timeFormat = MeetingResources.getInstance().getString(R.string.time_format_pref_12hr);
}
}
private String timeFormat; // the current time format (12HR/24HR).
private Context context; // app context for shared preferences.
private static volatile MeetingTime instance = null;
} |
a=[1,5,34,53,2,13,43]
def merge(a,left_half,right_half):
i=0 #for left half
j=0 #for right half
k=0 #for full array
while i< len(left_half) and j < len(right_half):
if left_half[i] <= right_half [j]:
a[k]=left_half[i]
i+=1
else:
a[k]=right_half[j]
j+=1
k+=1
#if after this some element may remain in one of the half due to diff lengths
#if elements remain in left half
while(i<len(left_half)):
a[k]=left_half[i]
i+=1
k+=1
#if element remain in right half
while(j<len(right_half)):
a[k]=right_half[j]
j+=1
k+=1
def dividelist(a):
# if only 1 element present inside list #base condition
#then return that element
if len(a)<2:
return a
#more than one element
else:
mid=len(a)//2
left_half=a[ :mid]
right_half=a[mid: ]
dividelist(left_half)
dividelist(right_half)
merge(a,left_half,right_half)
return a
dividelist(a)
print(a)
note:
Time complexity of Merge Sort is Theta(nLogn) in all 3 cases (worst, average and best) as merge sort always
divides the array into two halves and take linear time to merge two halves.
Auxiliary Space: O(n) |
import moment from 'moment-timezone';
import { InteractionManager } from 'react-native';
import * as RNFS from 'react-native-fs';
import {
type configLoggerType,
consoleTransport,
fileAsyncTransport,
logger,
type transportFunctionType,
} from 'react-native-logs';
export type LogLevels = 'debug' | 'info' | 'warn' | 'error';
// TODO: Add Sentry transport
// @ts-ignore
const transport: transportFunctionType[] = [
// Only enable CONSOLE logging in development
__DEV__ ? consoleTransport : null,
// Always enable FILE logging
fileAsyncTransport,
// Always enable SENTRY logging (for now)
].filter((t) => t !== null);
const transportOptions = {
FS: RNFS,
fileName: `chainit-log_${moment().format('MM-dd-yyyy')}.txt`,
colors: {
info: 'blueBright',
warn: 'yellowBright',
error: 'redBright',
},
};
const config: configLoggerType = {
levels: {
debug: 0,
info: 1,
warn: 2,
error: 3,
},
severity: 'debug',
transport,
transportOptions,
dateFormat: (date) => {
return (
'[' +
moment.utc(date.toUTCString()).format('MM-DD-YYYY h:mm:ss A z') +
'] '
);
},
printLevel: true,
printDate: true,
enabled: true,
// These two options improve performance impacts
async: false,
asyncFunc: InteractionManager.runAfterInteractions,
};
// ReturnType annotation here fixes TypeScript warnings about private / protected members
// @ts-ignore
export const globalLogger: any = logger.createLogger<LogLevels>(config);
export function getLoggerByNamespace(namespace?: string) {
// @ts-ignore
const logger = globalLogger.extend(namespace);
globalLogger.enable(namespace);
return logger;
} |
import Account from "../../../domain/entity/Account";
import RepositoryFactory from "../../../domain/factory/IRepositoryFactory";
import IAccountRepository from "../../../domain/repository/IAccountRepository";
import { PubSubService } from "../../../infra/service/PubSub";
export default class DeleteAccount {
accountRepository: IAccountRepository;
mailService: any;
constructor (readonly repositoryFactory: RepositoryFactory) {
this.accountRepository = repositoryFactory.createAccountRepository();
this.mailService = new PubSubService();
}
async execute (id: string): Promise<boolean> {
const account = await this.accountRepository.getById(id);
if (!account) {
throw "Account not found!";
}
await this.accountRepository.delete(id);
const payload = {
email: account.email,
subject: 'Conta removida com sucesso!',
body: `${account.name}, sua conta de cpf ${account.cpf} foi removida!` }
this.mailService.publish(payload);
return true;
}
} |
# SVG fespelarlighting . surface scale 属性
> 原文:[https://www . geeksforgeeks . org/SVG-fespelarlighting-surface scale-property/](https://www.geeksforgeeks.org/svg-fespecularlighting-surfacescale-property/)
**SVG FeSpecularllighting . surfaceScale 属性**返回对应于 FeSpecularllighting . surface scale 元素的 surface scale 组件的 SVGAnimatedNumber 对象。
**语法:**
```html
var a = FESpecularLighting.surfaceScale
```
**返回值:**该属性返回对应于 fesspecularllighting . surfaceScale 元素的 surface scale 组件的 SVGAnimatedNumber 对象。
**例 1:**
## 超文本标记语言
```html
<!DOCTYPE html>
<html>
<body>
<svg height="200" width="200"
viewBox="0 0 220 220">
<filter id="filter">
<feSpecularLighting in="BackgroundImage"
specularConstant="0.8" surfaceScale="1"
specularExponent="20" kernelUnitLength="1"
lighting-color="red" id="gfg">
<fePointLight x="100" y="100" z="220" />
</feSpecularLighting>
<feComposite in="SourceGraphic" in2="specOut"
operator="arithmetic" k1="0" k2="1"
k3="1" k4="0" />
</filter>
<rect x="60" y="60" width="150" height="150"
style="stroke: #000000; fill: lightgreen;
filter: url(#filter);" />
<script type="text/javascript">
var g = document.getElementById("gfg");
console.log(g.surfaceScale);
console.log("surfaceScale value is : ",
g.surfaceScale.baseVal)
</script>
</svg>
</body>
</html>
```
**输出:**

**例 2:**
## 超文本标记语言
```html
<!DOCTYPE html>
<html>
<body>
<svg height="200" width="200">
<filter id="filter">
<feSpecularLighting specularExponent="5"
lighting-color="gold" result="light"
surfaceScale="5" in="SourceGraphic"
id="gfg">
<fePointLight x="100" y="100" z="100" />
</feSpecularLighting>
<feComposite in="SourceGraphic"
in2="specOut" operator="arithmetic"
k1="1" k2="0" k3="1" k4="0" />
</filter>
<rect x="1" y="1" width="200" height="200"
style="stroke: #000000; fill: green;
filter: url(#filter);" />
<rect x="50" y="50" width="100" height="100"
style="stroke: #000000; fill: green;
filter: url(#filter);" />
<g fill="#FFFFFF" stroke="black"
font-size="10" font-family="Verdana" />
<text x="60" y="100">GeeksForGeeks</text>
<script type="text/javascript">
var g = document.getElementById("gfg");
console.log(g.surfaceScale);
console.log("surfaceScale value is : ",
g.surfaceScale.baseVal)
</script>
</svg>
</body>
</html>
```
**输出:**

**例 3:**
## 超文本标记语言
```html
<!DOCTYPE html>
<html>
<body>
<svg height="200" width="200"
viewBox="0 0 220 220">
<filter id="filter">
<feSpecularLighting specularExponent="2"
lighting-color="shadow" result="light"
surfaceScale="6" in="BackgroundImage"
id="gfg">
<fePointLight x="200" y="200" z="100" />
</feSpecularLighting>
<feComposite in="SourceGraphic"
in2="specOut" operator="arithmetic"
k1="0" k2="1" k3="1" k4="0" />
</filter>
<rect x="40" y="40" width="200" height="200"
style="stroke: black; fill: green;
filter: url(#filter);" />
<circle cx="130" cy="130" r="50"
style="fill: black; filter:url(#filter)" />
<script type="text/javascript">
var g = document.getElementById("gfg");
console.log(g.surfaceScale);
console.log("surfaceScale value is : ",
g.surfaceScale.baseVal)
</script>
</svg>
</body>
</html>
```
**输出:**

**支持的浏览器:**
* 谷歌 Chrome
* 边缘
* 火狐浏览器
* 旅行队
* 歌剧
* 微软公司出品的 web 浏览器 |
import { useSwapAssets } from '@/composables/swap/useSwapAssets';
import { parseFixed } from '@ethersproject/bignumber';
import LS_KEYS from '@/constants/local-storage.keys';
import { NATIVE_ASSET_ADDRESS } from '@/constants/tokens';
import { bnum, lsGet, lsSet } from '@/lib/utils';
import { getWrapAction, WrapType } from '@/lib/utils/balancer/wrapper';
import { COW_SUPPORTED_NETWORKS } from '@/services/cowswap/constants';
import {
canUseJoinExit,
someJoinExit,
SubgraphPoolBase,
SwapTypes,
} from '@balancer-labs/sdk';
import useWeb3 from '@/services/web3/useWeb3';
import { networkId } from '../useNetwork';
import useNumbers, { FNumFormats } from '../useNumbers';
import { useTokens } from '@/providers/tokens.provider';
import { useUserSettings } from '@/providers/user-settings.provider';
import useCowswap from './useCowswap';
import useSor from './useSor';
import useJoinExit from './useJoinExit';
export type SwapRoute = 'wrapUnwrap' | 'balancer' | 'cowswap' | 'joinExit';
export type UseSwapping = ReturnType<typeof useSwapping>;
export const swapGasless = ref<boolean>(
lsGet<boolean>(LS_KEYS.Swap.Gasless, true)
);
export default function useSwapping(
exactIn: Ref<boolean>,
tokenInAddressInput: Ref<string>,
tokenInAmountInput: Ref<string>,
tokenOutAddressInput: Ref<string>,
tokenOutAmountInput: Ref<string>
) {
// COMPOSABLES
const { fNum } = useNumbers();
const { getToken, tokens } = useTokens();
const { blockNumber } = useWeb3();
const { slippage } = useUserSettings();
const { setInputAsset, setOutputAsset } = useSwapAssets();
// COMPUTED
const slippageBufferRate = computed(() => parseFloat(slippage.value));
const wrapType = computed(() =>
getWrapAction(tokenInAddressInput.value, tokenOutAddressInput.value)
);
const isWrap = computed(() => wrapType.value === WrapType.Wrap);
const isUnwrap = computed(() => wrapType.value === WrapType.Unwrap);
const tokenIn = computed(() => getToken(tokenInAddressInput.value));
const tokenOut = computed(() => getToken(tokenOutAddressInput.value));
const isNativeAssetSwap = computed(
() => tokenInAddressInput.value === NATIVE_ASSET_ADDRESS
);
const tokenInAmountScaled = computed(() =>
parseFixed(tokenInAmountInput.value || '0', tokenIn.value.decimals)
);
const tokenOutAmountScaled = computed(() =>
parseFixed(tokenOutAmountInput.value || '0', tokenOut.value.decimals)
);
const requiresTokenApproval = computed(() => {
if (wrapType.value === WrapType.Unwrap || isNativeAssetSwap.value) {
return false;
}
return true;
});
const effectivePriceMessage = computed(() => {
const tokenInAmount = parseFloat(tokenInAmountInput.value);
const tokenOutAmount = parseFloat(tokenOutAmountInput.value);
if (tokenInAmount > 0 && tokenOutAmount > 0) {
return {
tokenIn: `1 ${tokenIn.value?.symbol} = ${fNum(
bnum(tokenOutAmount).div(tokenInAmount).toString(),
FNumFormats.token
)} ${tokenOut.value?.symbol}`,
tokenOut: `1 ${tokenOut.value?.symbol} = ${fNum(
bnum(tokenInAmount).div(tokenOutAmount).toString(),
FNumFormats.token
)} ${tokenIn.value?.symbol}`,
};
}
return {
tokenIn: '',
tokenOut: '',
};
});
const isCowswapSupportedOnNetwork = computed(() =>
COW_SUPPORTED_NETWORKS.includes(networkId.value)
);
const swapRoute = computed<SwapRoute>(() => {
if (wrapType.value !== WrapType.NonWrap) {
return 'wrapUnwrap';
} else if (isNativeAssetSwap.value) {
return 'balancer';
}
if (swapGasless.value && isCowswapSupportedOnNetwork.value) {
return 'cowswap';
} else {
const swapInfoAvailable =
joinExit.swapInfo.value?.returnAmount &&
!joinExit.swapInfo.value?.returnAmount.isZero();
const joinExitSwapAvailable = swapInfoAvailable
? canUseJoinExit(
exactIn.value ? SwapTypes.SwapExactIn : SwapTypes.SwapExactOut,
tokenInAddressInput.value,
tokenOutAddressInput.value
)
: false;
const joinExitSwapPresent = joinExitSwapAvailable
? someJoinExit(
sor.pools.value as SubgraphPoolBase[],
joinExit.swapInfo.value?.swaps ?? [],
joinExit.swapInfo.value?.tokenAddresses ?? []
)
: false;
// Currently joinExit swap is only suitable for ExactIn and non-eth swaps
return joinExitSwapPresent ? 'joinExit' : 'balancer';
}
});
const isCowswapSwap = computed(() => swapRoute.value === 'cowswap');
const isBalancerSwap = computed(() => swapRoute.value === 'balancer');
const isJoinExitSwap = computed(() => swapRoute.value === 'joinExit');
const isWrapUnwrapSwap = computed(() => swapRoute.value === 'wrapUnwrap');
const isGaslessSwappingDisabled = computed(
() => isNativeAssetSwap.value || isWrapUnwrapSwap.value
);
const hasSwapQuote = computed(
() =>
parseFloat(tokenInAmountInput.value) > 0 &&
parseFloat(tokenOutAmountInput.value) > 0
);
const sor = useSor({
exactIn,
tokenInAddressInput,
tokenInAmountInput,
tokenOutAddressInput,
tokenOutAmountInput,
wrapType,
tokenInAmountScaled,
tokenOutAmountScaled,
sorConfig: {
handleAmountsOnFetchPools: true,
},
tokenIn,
tokenOut,
slippageBufferRate,
isCowswapSwap,
});
const cowswap = useCowswap({
exactIn,
tokenInAddressInput,
tokenInAmountInput,
tokenOutAddressInput,
tokenOutAmountInput,
tokenInAmountScaled,
tokenOutAmountScaled,
tokenIn,
tokenOut,
slippageBufferRate,
});
const joinExit = useJoinExit({
exactIn,
tokenInAddressInput,
tokenInAmountInput,
tokenOutAddressInput,
tokenOutAmountInput,
tokenInAmountScaled,
tokenOutAmountScaled,
tokenIn,
tokenOut,
slippageBufferRate,
pools: sor.pools as Ref<SubgraphPoolBase[]>,
});
const isLoading = computed(() => {
if (hasSwapQuote.value || isWrapUnwrapSwap.value) {
return false;
}
if (isCowswapSwap.value) {
return cowswap.updatingQuotes.value;
}
return joinExit.swapInfoLoading.value || sor.poolsLoading.value;
});
const isConfirming = computed(
() =>
sor.confirming.value ||
cowswap.confirming.value ||
joinExit.confirming.value
);
const submissionError = computed(
() =>
sor.submissionError.value ||
cowswap.submissionError.value ||
joinExit.submissionError.value
);
// METHODS
async function swap(successCallback?: () => void) {
if (isCowswapSwap.value) {
return cowswap.swap(() => {
if (successCallback) {
successCallback();
}
cowswap.resetState();
});
} else if (isJoinExitSwap.value) {
return joinExit.swap(() => {
if (successCallback) {
successCallback();
}
joinExit.resetState();
});
} else {
// handles both Balancer and Wrap/Unwrap swaps
return sor.swap(() => {
if (successCallback) {
successCallback();
}
sor.resetState();
});
}
}
function resetSubmissionError() {
sor.submissionError.value = null;
cowswap.submissionError.value = null;
joinExit.submissionError.value = null;
}
function setSwapGasless(flag: boolean) {
swapGasless.value = flag;
lsSet(LS_KEYS.Swap.Gasless, swapGasless.value);
}
function toggleSwapGasless() {
setSwapGasless(!swapGasless.value);
handleAmountChange();
}
function getQuote() {
if (isCowswapSwap.value) {
return cowswap.getQuote();
}
if (isJoinExitSwap.value) {
return joinExit.getQuote();
}
return sor.getQuote();
}
function resetAmounts() {
sor.resetInputAmounts('');
}
async function handleAmountChange() {
if (exactIn.value) {
tokenOutAmountInput.value = '';
} else {
tokenInAmountInput.value = '';
}
cowswap.resetState(false);
sor.resetState();
joinExit.resetState();
if (isCowswapSwap.value) {
cowswap.handleAmountChange();
} else {
await sor.handleAmountChange();
await joinExit.handleAmountChange();
}
}
// WATCHERS
watch(tokenInAddressInput, async () => {
setInputAsset(tokenInAddressInput.value);
handleAmountChange();
});
watch(tokenOutAddressInput, () => {
setOutputAsset(tokenOutAddressInput.value);
handleAmountChange();
});
onMounted(() => {
const gaslessDisabled = window.location.href.includes('gasless=false');
if (gaslessDisabled) {
setSwapGasless(false);
}
});
watch(blockNumber, () => {
if (isCowswapSwap.value) {
if (!cowswap.hasValidationError.value) {
cowswap.handleAmountChange();
}
} else if (isJoinExitSwap.value) {
if (!joinExit.hasValidationError.value) {
joinExit.handleAmountChange();
}
} else if (isBalancerSwap.value) {
sor.updateSwapAmounts();
}
});
watch(slippageBufferRate, () => {
handleAmountChange();
});
return {
// computed
isWrap,
isUnwrap,
isNativeAssetSwap,
tokenIn,
tokenOut,
tokenInAmountScaled,
tokenOutAmountScaled,
tokens,
requiresTokenApproval,
effectivePriceMessage,
swapRoute,
exactIn,
isLoading,
cowswap,
sor,
joinExit,
isCowswapSwap,
isBalancerSwap,
isJoinExitSwap,
wrapType,
isWrapUnwrapSwap,
tokenInAddressInput,
tokenInAmountInput,
tokenOutAddressInput,
tokenOutAmountInput,
slippageBufferRate,
isConfirming,
submissionError,
resetSubmissionError,
swapGasless,
toggleSwapGasless,
isGaslessSwappingDisabled,
isCowswapSupportedOnNetwork,
resetAmounts,
// methods
getQuote,
swap,
handleAmountChange,
};
} |
package com.clb.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clb.constant.Cache;
import com.clb.domain.PageResult;
import com.clb.domain.Result;
import com.clb.domain.dto.Condition;
import com.clb.domain.entity.Book;
import com.clb.service.BookService;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/book")
@RequiredArgsConstructor
@Validated
public class BookController {
private final BookService bookService;
/**
* 书籍信息的分页查询
*
* @param condition 查询条件,包含书名、作者和isbn及分页条件
*/
@PostMapping
@Cacheable(cacheNames = Cache.BOOK_PAGE)
public PageResult<List<Book>> getBookPage(@RequestBody Condition condition) {
log.debug("查询条件:{}", condition);
Page<Book> bookPage = bookService.getBookPage(condition);
List<Book> data = bookPage.getRecords();
Long total = bookPage.getTotal();
return PageResult.success(data, total);
}
/**
* 根据isbn删除书籍信息
*
* @param isbn 书号
*/
@CacheEvict(value = Cache.BOOK_PAGE, allEntries = true)
@DeleteMapping("/{isbn}")
public Result<String> deleteBookByIsbn(@PathVariable @Pattern(regexp = "^\\S{1,20}$") String isbn) {
log.debug("isbn:{}", isbn);
bookService.deleteBookByIsbn(isbn);
return Result.success();
}
/**
* 添加图书
*
* @param book 图书信息
*/
@PostMapping("/add")
@CacheEvict(value = Cache.BOOK_PAGE, allEntries = true)
public Result<String> addBook(@RequestBody Book book) {
log.debug("book:{}", book);
return bookService.add(book);
}
/**
* 根据isbn更新图书信息
*
* @param book 更新后图书信息
*/
@PutMapping
@CacheEvict(value = Cache.BOOK_PAGE, allEntries = true)
public Result<String> updateBook(@RequestBody Book book) {
log.debug("book:{}", book);
return bookService.updateBook(book);
}
} |
// Product Except Self
//
// Given an integer array nums, return an array answer such that answer[i]
// is equal to the product of all the elements of nums except nums[i].
// Must be in O(n) time
//
// Solution:
// Walk through array, grabbing the product at the index
// and setting the current index in result to the product (before updating product).
// Then repeat the process backwards (reset the product).
function productExceptSelf(nums: number[]): number[] {
const result = nums.map(n=>1);
let curProduct = 1;
for(let i=0; i<nums.length; i++) {
result[i] = curProduct;
curProduct *= nums[i];
}
curProduct = 1;
for(let j=nums.length-1; j>=0; j--) {
result[j] *= curProduct;
curProduct *= nums[j];
}
return result;
};
console.log(productExceptSelf([1,2,3,4]));
// solution: [24,12,8,6]
console.log(productExceptSelf([-1,1,0,-3,3]));
// solution: [0,0,9,0,0]
// Derivation:
// [1,2,3,4]
// 0 1 2 3 <--indices
//i
//0, 1 - - -
//1, 2 1 - -
//2, 6 3 2 -
//3, 24 12 8 6
// notice the current/latest index product is the product of the previous entries
//
// The same works for each index, e.g. [1,2,3]
// 1*2=2 (for index 2)
//
// It can then be repeated backwards to get the products ahead of the index
// (the missing numbers above, denoted by -) |
"use client";
import Link from "next/link";
import React, { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import axios from "axios";
export default function SignPage() {
const router = useRouter();
const [formData, setFormData] = useState({
email: "",
password: "",
redirect: false,
});
const handleInputChange = (event) => {
setFormData((inputs) => ({
...inputs,
[event.target.name]: event.target.value,
}));
};
const [loading, setLoading] = useState(false);
const searchParams = useSearchParams();
const redirectUrl = searchParams.get("redirect") || "/";
console.log(redirectUrl);
const handleSubmit = async (e) => {
e.preventDefault();
try {
setLoading(true);
const response = await axios.post("/api/users/login", formData);
if (("Login success", response.data.success)) {
if (redirectUrl !== "/") window.location.href = redirectUrl;
else router.push(redirectUrl);
}
} catch (error) {
console.error(error.message);
} finally {
setLoading(false);
}
};
return (
<div className="flex items-center h-screen">
<div className="p-12 bg-white mx-auto rounded-2xl w-full sm:w-3/4 md:w-[60%] lg:w-[40%] shadow-xl ">
<div className="mb-4 text-center">
<h3 className="font-semibold text-2xl text-gray-800">Sign In </h3>
<p className="text-gray-400 mt-2">Please sign in to your account.</p>
</div>
<div className="space-y-5 text-gray-700">
<div className="space-y-2">
<label className="text-sm font-medium text-gray-700 tracking-wide">
Email
</label>
<input
className=" w-full text-base px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-400"
type="email"
onChange={handleInputChange}
value={formData?.email}
name="email"
placeholder="mail@gmail.com"
/>
</div>
<div className="space-y-2">
<label className="mb-5 text-sm font-medium text-gray-700 tracking-wide">
Password
</label>
<input
className="w-full content-center text-base px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-400"
type="password"
onChange={handleInputChange}
value={formData?.password}
name="password"
placeholder="Enter your password"
/>
</div>
<div className="flex items-center justify-between">
<div className="flex items-center">
<input
id="remember_me"
name="remember_me"
type="checkbox"
className="h-4 w-4 bg-blue-500 focus:ring-blue-400 border-gray-300 rounded"
/>
<label
htmlFor="remember_me"
className="ml-2 block text-sm text-gray-800"
>
Remember me
</label>
</div>
<div className="text-sm">
<a href="#" className="text-blue-400 hover:text-blue-500">
Forgot your password?
</a>
</div>
</div>
<div>
<button
onClick={handleSubmit}
type="submit"
className="w-full flex justify-center bg-blue-400 hover:bg-blue-500 text-gray-100 p-3 rounded-full tracking-wide font-semibold shadow-lg cursor-pointer transition ease-in duration-500"
>
Sign in
</button>
</div>
<div className="text-center">
<Link
className="inline-block text-sm text-blue-500 align-baseline hover:text-blue-800"
href="/signup"
>
Don't have an account?{" "}
<span className="underline">Sign Up</span>
</Link>
</div>
</div>
</div>
</div>
);
} |
use glob::glob;
use std::{
collections::HashMap,
fs::Metadata,
path::{Path, PathBuf},
time::SystemTime,
};
use std::{thread, time};
#[derive(Clone)]
struct FileMeta {
sha_hash: String,
modified: SystemTime,
}
pub struct FileWatcher {
file_meta: HashMap<String, FileMeta>,
path: String,
}
impl FileWatcher {
pub fn create(path: &str) -> FileWatcher {
return FileWatcher {
path: String::from(path),
file_meta: HashMap::new(),
};
}
pub fn scan(&mut self) {
let target_path: String = self.path.clone() + "**/*";
for entry in glob(target_path.as_str()).unwrap() {
if let Ok(path_buf) = entry {
self.track(path_buf)
}
}
}
pub fn watch(&mut self) {
loop {
self.scan();
//TODO thread sleep should probably be configurable
let delay = time::Duration::from_millis(500);
std::thread::sleep(delay);
}
}
fn track(&mut self, path: PathBuf) {
let mut path_string: &str;
let mut meta: Metadata;
let mut modified: SystemTime;
if path.to_str().is_none() || path.symlink_metadata().is_err() {
//TODO should probably error?
return;
}
path_string = path.to_str().unwrap();
meta = path.symlink_metadata().unwrap();
if meta.modified().is_err() {
//TODO should probably error?
return;
}
modified = meta.modified().unwrap();
self.try_push_meta(path_string.to_string(), modified);
}
fn try_push_meta(&mut self, path: String, modified: SystemTime) {
if !self.file_meta.contains_key(&path) {
self.insert_meta(path.clone(), modified);
return;
}
let file_meta = self.file_meta.get(&path.clone()).unwrap();
if (file_meta.modified != modified) {
if let Ok(sha_hash) = sha256::try_digest(Path::new(&path)) {
if (file_meta.sha_hash != sha_hash) {
println!("File modified: {} ({})", path, sha_hash);
self.file_meta.remove(&path.clone());
self.file_meta.insert(path, FileMeta { sha_hash, modified });
}
}
}
}
fn insert_meta(&mut self, path: String, modified: SystemTime) {
if let Ok(sha_hash) = sha256::try_digest(Path::new(&path)) {
println!("Indexing new file: {} ({})", path, sha_hash);
self.file_meta.insert(path, FileMeta { sha_hash, modified });
return;
}
}
} |
import React, { useContext, useEffect } from "react";
import { View, StyleSheet } from "react-native";
import { Context as AuthContext } from "../context/authContext";
import AuthForm from "../components/AuthForm";
import Navilink from "../components/NavLink";
const SignupScreen = ({ navigation }) => {
const { signup, state, clearErrorMessage, tryLocalSignin } =
useContext(AuthContext);
useEffect(() => {
navigation.addListener("blur", () => {
clearErrorMessage();
});
}, []);
return (
<View style={styles.container}>
<AuthForm
headerText="Sign Up for Tracker"
errorMessage={state.errorMessage}
submitButtonText="Sign Up"
onSubmit={({ email, password }) => {
signup({ email, password });
}}
/>
<Navilink
text="Already have an account? Sign In instead."
routeName="Signin"
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
marginBottom: 250,
},
});
export default SignupScreen; |
import express from "express";
import homeController from "../controllers/homeController";
import userController from "../controllers/userController";
import doctorController from "../controllers/doctorController";
import patientController from "../controllers/patientController";
import specialtyController from "../controllers/specialtyController";
import clinicController from "../controllers/clinicController";
let router = express.Router();
let initWebRoutes = (app) => {
router.get('/', homeController.getHomePage);
router.get('/crud', homeController.getCRUD);
router.post('/post-crud', homeController.postCRUD);
router.get('/get-crud',homeController.displayGetCRUD);
router.get('/edit-crud',homeController.getEditCRUD);
router.post('/put-crud',homeController.putCRUD);
router.get('/delete-crud',homeController.deleteCRUD);
router.post('/api/login',userController.handleLogin);
router.get('/api/get-api-all-users',userController.handleGetAllUsers);
router.post('/api/create-new-user',userController.handleCreateNewUser);
router.put('/api/edit-user',userController.handleEditUser);
router.delete('/api/delete-user',userController.handleDeleteUser);
router.get('/api/allcodes', userController.getAllCode);
router.get('/api/top-doctor-home', doctorController.getTopDoctorHome);
router.get('/api/get-all-doctors', doctorController.getAllDoctors);
router.post('/api/save-info-doctors', doctorController.postInfoDoctor);
router.get('/api/get-all-detail-doctor-by-id', doctorController.getDetailDoctorById);
router.post('/api/bulk-create-schedule', doctorController.bulkCreateSchedule);
router.get('/api/get-schedule-doctor-by-date', doctorController.getScheduleByDate);
router.get('/api/get-extra-info-doctor-by-id', doctorController.getExtraInfoDoctorById);
router.get('/api/get-profile-doctor-by-id', doctorController.getProfileDoctorById);
router.get('/api/get-list-patient-for-doctor', doctorController.getListPatientForDoctor);
router.post('/api/send-remedy', doctorController.sendRemedy);
router.post('/api/patient-book-appointment', patientController.postBookAppointment);
router.post('/api/verify-book-appointment',patientController.postVerifyBookAppointment);
router.post('/api/create-new-specialty',specialtyController.createSpecialty);
router.get('/api/get-specialty',specialtyController.getAllSpecialty);
router.get('/api/get-detail-specialty-by-id',specialtyController.getDetailSpecialtyById);
router.post('/api/create-new-clinic',clinicController.createClinic);
router.get('/api/get-clinic',clinicController.getAllClinic);
router.get('/api/get-detail-clinic-by-id',clinicController.getDetailClinicById);
return app.use("/", router)
}
module.exports = initWebRoutes; |
/*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.blobstore.compact.internal;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.sonatype.nexus.formfields.ComboboxFormField;
import org.sonatype.nexus.scheduling.TaskConfiguration;
import org.sonatype.nexus.scheduling.TaskDescriptorSupport;
import static org.sonatype.nexus.formfields.FormField.MANDATORY;
/**
* Task descriptor for {@link CompactBlobStoreTask}.
*
* @since 3.0
*/
@Named
@Singleton
public class CompactBlobStoreTaskDescriptor
extends TaskDescriptorSupport
{
public static final String TYPE_ID = "blobstore.compact";
public static final String BLOB_STORE_NAME_FIELD_ID = "blobstoreName";
@Inject
public CompactBlobStoreTaskDescriptor() {
super(TYPE_ID,
CompactBlobStoreTask.class,
"Admin - Compact blob store",
VISIBLE,
EXPOSED,
new ComboboxFormField<String>(
BLOB_STORE_NAME_FIELD_ID,
"Blob store",
"Select the blob store to compact",
MANDATORY
).withStoreApi("coreui_Blobstore.read").withIdMapping("name")
);
}
@Override
public void initializeConfiguration(final TaskConfiguration configuration) {
configuration.setBoolean(MULTINODE_KEY, true);
}
} |
<?php
namespace WebAppSeller\Models;
class Equipe extends \Phalcon\Mvc\Model
{
/**
*
* @var integer
* @Primary
* @Identity
* @Column(column="id", type="integer", nullable=false)
*/
protected $id;
/**
*
* @var integer
* @Column(column="id_chef_de_projet", type="integer", nullable=false)
*/
protected $id_chef_de_projet;
/**
*
* @var string
* @Column(column="nom", type="string", length=50, nullable=false)
*/
protected $nom;
/**
* Method to set the value of field id
*
* @param integer $id
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Method to set the value of field id_chef_de_projet
*
* @param integer $id_chef_de_projet
* @return $this
*/
public function setIdChefDeProjet($id_chef_de_projet)
{
$this->id_chef_de_projet = $id_chef_de_projet;
return $this;
}
/**
* Method to set the value of field nom
*
* @param string $nom
* @return $this
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Returns the value of field id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Returns the value of field id_chef_de_projet
*
* @return integer
*/
public function getIdChefDeProjet()
{
return $this->id_chef_de_projet;
}
/**
* Returns the value of field nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Initialize method for model.
*/
public function initialize()
{
$this->setSchema("ecf_7");
$this->setSource("equipe");
$this->hasMany('id', 'WebAppSeller\Models\CompositionEquipe', 'id_equipe', ['alias' => 'CompositionEquipe']);
$this->belongsTo('id_chef_de_projet', 'WebAppSeller\Models\ChefDeProjet', 'id', ['alias' => 'ChefDeProjet']);
}
/**
* Allows to query a set of records that match the specified conditions
*
* @param mixed $parameters
* @return Equipe[]|Equipe|\Phalcon\Mvc\Model\ResultSetInterface
*/
public static function find($parameters = null): \Phalcon\Mvc\Model\ResultsetInterface
{
return parent::find($parameters);
}
/**
* Allows to query the first record that match the specified conditions
*
* @param mixed $parameters
* @return Equipe|\Phalcon\Mvc\Model\ResultInterface|\Phalcon\Mvc\ModelInterface|null
*/
public static function findFirst($parameters = null): ?\Phalcon\Mvc\ModelInterface
{
return parent::findFirst($parameters);
}
/**
* @param $listIdDev
* @return bool
*/
public function checkEquipe($listIdDev): bool
{
$idChefProjet = $this->id_chef_de_projet;
$conditions = 'id_chef_de_projet = :idChefProjet:';
$bind = ['idChefProjet' => $idChefProjet];
if ($this->id !== null) {
$conditions .= ' AND id <> :idEquipeToExclude:';
$bind['idEquipeToExclude'] = $this->id;
}
$equipes = Equipe::find([
'conditions' => $conditions,
'bind' => $bind,
]);
// récupère les équipes du chef de projet
foreach ($equipes as $curEquipe) {
foreach ($curEquipe->CompositionEquipe as $curCompoEquipe) {
if (in_array($curCompoEquipe->getIdDeveloppeur(), $listIdDev)) {
return false;
}
}
}
return true;
}
} |
import { STATUSES } from '../../globals/const';
import type { SettlementStatusType } from '../../globals/types';
type StatusPillProps = {
className?: string;
size?: 'small' | 'medium';
animate?: boolean;
status: SettlementStatusType;
};
/**
* A pill element showing the settlement status
* @param {StatusPillProps} props
*/
const StatusPill = ({
size = 'medium',
className = '',
animate = true,
status,
}: StatusPillProps) => {
const animateClass = animate ? 'custom-animate-pulse' : '';
const sizeClass = {
small: 'px-2 py-0.5 text-xs',
medium: 'px-3 py-1 text-sm',
}[size];
const colorClass = {
[STATUSES.ACCEPTED]: 'bg-success',
[STATUSES.REJECTED]: 'bg-error',
[STATUSES.PENDING]: 'bg-info',
}[status];
return (
<span
className={`${sizeClass} ${className} ${animateClass} ${colorClass} absolute rounded-full font-bold uppercase text-white`}
>
{status}
</span>
);
};
export default StatusPill; |
# TlsSubscriptions
(*.tlsSubscriptions*)
## Overview
The TLS subscriptions API allows you to programmatically generate TLS certificates that are procured and renewed by Fastly. Once a subscription is created for a given hostname or wildcard domain, DNS records are checked to ensure that the domain on the subscription is owned by the subscription creator. Provided DNS records are maintained, TLS certificates will automatically renew. If Fastly is unable to issue a certificate, we will retry to issue the certificate for 7 days past subscription creation or the latest certificate's not_after date, whichever is later. If after 7 days Fastly is unable to issue a certificate, the subscription state will change to `failed` and Fastly will stop retrying.
<https://developer.fastly.com/reference/api/tls/subs>
### Available Operations
* [createGlobalsignEmailChallenge](#createglobalsignemailchallenge) - Creates a GlobalSign email challenge.
* [createTlsSub](#createtlssub) - Create a TLS subscription
* [deleteGlobalsignEmailChallenge](#deleteglobalsignemailchallenge) - Delete a GlobalSign email challenge
* [deleteTlsSub](#deletetlssub) - Delete a TLS subscription
* [getTlsSub](#gettlssub) - Get a TLS subscription
* [listTlsSubs](#listtlssubs) - List TLS subscriptions
* [patchTlsSub](#patchtlssub) - Update a TLS subscription
## createGlobalsignEmailChallenge
Creates an email challenge for a domain on a GlobalSign subscription. An email challenge will generate an email that can be used to validate domain ownership. If this challenge is created, then the domain can only be validated using email for the given subscription.
### Example Usage
```typescript
import { Fastly } from "Fastly";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.createGlobalsignEmailChallenge({
requestBody: {
"key": "string",
},
tlsAuthorizationId: "aU3guUGZzb2W9Euo4Mo0r",
tlsSubscriptionId: "sU3guUGZzb2W9Euo4Mo0r",
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `request` | [operations.CreateGlobalsignEmailChallengeRequest](../../models/operations/createglobalsignemailchallengerequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.CreateGlobalsignEmailChallengeResponse](../../models/operations/createglobalsignemailchallengeresponse.md)>**
## createTlsSub
Create a new TLS subscription. This response includes a list of possible challenges to verify domain ownership.
### Example Usage
```typescript
import { Fastly } from "Fastly";
import { CertificateAuthority, TypeTlsSubscription } from "Fastly/dist/sdk/models/components";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.createTlsSub({
force: true,
tlsSubscription: {
data: {
attributes: {},
relationships: "string",
},
},
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `request` | [operations.CreateTlsSubRequest](../../models/operations/createtlssubrequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.CreateTlsSubResponse](../../models/operations/createtlssubresponse.md)>**
## deleteGlobalsignEmailChallenge
Deletes a GlobalSign email challenge. After a GlobalSign email challenge is deleted, the domain can use HTTP and DNS validation methods again.
### Example Usage
```typescript
import { Fastly } from "Fastly";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.deleteGlobalsignEmailChallenge({
globalsignEmailChallengeId: "string",
tlsAuthorizationId: "string",
tlsSubscriptionId: "string",
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `request` | [operations.DeleteGlobalsignEmailChallengeRequest](../../models/operations/deleteglobalsignemailchallengerequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.DeleteGlobalsignEmailChallengeResponse](../../models/operations/deleteglobalsignemailchallengeresponse.md)>**
## deleteTlsSub
Destroy a TLS subscription. A subscription cannot be destroyed if there are domains in the TLS enabled state.
### Example Usage
```typescript
import { Fastly } from "Fastly";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.deleteTlsSub({
tlsSubscriptionId: "sU3guUGZzb2W9Euo4Mo0r",
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `request` | [operations.DeleteTlsSubRequest](../../models/operations/deletetlssubrequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.DeleteTlsSubResponse](../../models/operations/deletetlssubresponse.md)>**
## getTlsSub
Show a TLS subscription.
### Example Usage
```typescript
import { Fastly } from "Fastly";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.getTlsSub({
include: "tls_authorizations",
tlsSubscriptionId: "sU3guUGZzb2W9Euo4Mo0r",
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `request` | [operations.GetTlsSubRequest](../../models/operations/gettlssubrequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.GetTlsSubResponse](../../models/operations/gettlssubresponse.md)>**
## listTlsSubs
List all TLS subscriptions.
### Example Usage
```typescript
import { Fastly } from "Fastly";
import { Sort } from "Fastly/dist/sdk/models/components";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.listTlsSubs({
include: "tls_authorizations",
pageNumber: 1,
pageSize: 20,
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| `request` | [operations.ListTlsSubsRequest](../../models/operations/listtlssubsrequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.ListTlsSubsResponse](../../models/operations/listtlssubsresponse.md)>**
## patchTlsSub
Change the TLS domains or common name associated with this subscription, update the TLS configuration for this set of domains, or retry a subscription with state `failed` by setting the state to `retry`.
### Example Usage
```typescript
import { Fastly } from "Fastly";
import { CertificateAuthority, TypeTlsSubscription } from "Fastly/dist/sdk/models/components";
(async() => {
const sdk = new Fastly({
token: "",
});
const res = await sdk.tlsSubscriptions.patchTlsSub({
force: true,
tlsSubscription: {
data: {
attributes: {},
relationships: "string",
},
},
tlsSubscriptionId: "sU3guUGZzb2W9Euo4Mo0r",
});
if (res.statusCode == 200) {
// handle response
}
})();
```
### Parameters
| Parameter | Type | Required | Description |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| `request` | [operations.PatchTlsSubRequest](../../models/operations/patchtlssubrequest.md) | :heavy_check_mark: | The request object to use for the request. |
| `config` | [AxiosRequestConfig](https://axios-http.com/docs/req_config) | :heavy_minus_sign: | Available config options for making requests. |
### Response
**Promise<[operations.PatchTlsSubResponse](../../models/operations/patchtlssubresponse.md)>** |
import { useCallback, useRef, useState } from "react";
export const useHttpClient = () => {
const [isLoading, setIsLaoding] = useState(false);
const [error, setError] = useState();
const activeHttpRequests = useRef([]);
const sendRequest = useCallback(
async (url, method = "GET", body = null, headers = {}) => {
setIsLaoding(true);
const httpAbortCtrl = new AbortController();
activeHttpRequests.current.push(httpAbortCtrl);
try {
const response = await fetch(url, {
method,
body,
headers,
signal: httpAbortCtrl.signal,
});
const responseData = await response.json();
activeHttpRequests.current = activeHttpRequests.current.filter(
(reqCtrl) => reqCtrl !== httpAbortCtrl
);
if (!response.ok) {
throw Error(responseData.message);
}
setIsLaoding(false);
return responseData;
} catch (err) {
console.log(err.message);
setIsLaoding(false);
setError(err.message);
throw err;
}
},
[]
);
const clearError = () => {
setError(null);
};
// useEffect(() => {
// return () => {
// // eslint-disable-next-line react-hooks/exhaustive-deps
// activeHttpRequests.current.forEach((abortCtrl) =>
// abortCtrl.abort()
// );
// };
// }, []);
return { isLoading, error, sendRequest, clearError };
}; |
import { useNavigate } from 'react-router-dom';
import { Box, Grid, IconButton, Typography } from '@material-ui/core';
import { ReplayRounded } from '@material-ui/icons';
import { ExerciseInstance } from '../../types';
import { exerciseNameToPathConverter, ProgressIcon } from '../../utils';
import useStyles from './styles';
interface IExerciseCard {
firstExercise: ExerciseInstance;
secondExercise: ExerciseInstance;
sets: number;
}
export const SupersetCard = ({
firstExercise,
secondExercise,
sets,
}: IExerciseCard) => {
const classes = useStyles();
const navigateTo = useNavigate();
const firstExerciseSetsXReps = `${sets} × ${firstExercise.repRange}`;
const secondExerciseSetsXReps = `${sets} × ${secondExercise.repRange}`;
const handleNavigate = (index: number) => {
if (index === 1) {
navigateTo(
`/progress/${exerciseNameToPathConverter(firstExercise.exercise.name)}`
);
}
if (index === 2) {
navigateTo(
`/progress/${exerciseNameToPathConverter(secondExercise.exercise.name)}`
);
}
};
return (
<Box className={classes.container}>
<Grid item container className={classes.exerciseContainer}>
<Grid item container direction="column">
<Typography variant="subtitle1">
{firstExercise.exercise.name}
</Typography>
<Grid item container className={classes.setsXrepsContainer}>
<ReplayRounded className={classes.icon} fontSize="small" />
<Typography variant="body1" className={classes.setsXreps}>
{firstExerciseSetsXReps}
</Typography>
</Grid>
</Grid>
<IconButton
className={classes.progressButton}
onClick={() => handleNavigate(1)}
>
<ProgressIcon />
</IconButton>
</Grid>
<Grid item container className={classes.exerciseContainer}>
<Grid item container direction="column">
<Typography variant="subtitle1">
{secondExercise.exercise.name}
</Typography>
<Grid item container className={classes.setsXrepsContainer}>
<ReplayRounded className={classes.icon} fontSize="small" />
<Typography variant="body1" className={classes.setsXreps}>
{secondExerciseSetsXReps}
</Typography>
</Grid>
</Grid>
<IconButton
className={classes.progressButton}
onClick={() => handleNavigate(2)}
>
<ProgressIcon />
</IconButton>
</Grid>
</Box>
);
};
export default SupersetCard; |
<?php
if ( ! defined( 'ABSPATH' ) ) {
die( 'You are not allowed to call this page directly.' );
}
/**
* @since 3.0
*/
class FrmFieldNumber extends FrmFieldType {
/**
* @var string
* @since 3.0
*/
protected $type = 'number';
protected $display_type = 'text';
protected function field_settings_for_type() {
$settings = array(
'size' => true,
'clear_on_focus' => true,
'invalid' => true,
'range' => true,
);
$frm_settings = FrmAppHelper::get_settings();
if ( $frm_settings->use_html ) {
$settings['max'] = false;
}
return $settings;
}
protected function extra_field_opts() {
return array(
'minnum' => 0,
'maxnum' => 9999999,
'step' => 'any',
);
}
/**
* @since 3.01.03
*/
protected function add_extra_html_atts( $args, &$input_html ) {
$this->add_min_max( $args, $input_html );
}
public function validate( $args ) {
$errors = array();
$this->remove_commas_from_number( $args );
//validate the number format
if ( ! is_numeric( $args['value'] ) && '' !== $args['value'] ) {
$errors[ 'field' . $args['id'] ] = FrmFieldsHelper::get_error_msg( $this->field, 'invalid' );
}
// validate number settings
if ( $args['value'] != '' ) {
$frm_settings = FrmAppHelper::get_settings();
// only check if options are available in settings
$minnum = FrmField::get_option( $this->field, 'minnum' );
$maxnum = FrmField::get_option( $this->field, 'maxnum' );
if ( $frm_settings->use_html && $maxnum !== '' && $minnum !== '' ) {
$value = (float) $args['value'];
if ( $value < $minnum ) {
$errors[ 'field' . $args['id'] ] = __( 'Please select a higher number', 'formidable' );
} elseif ( $value > $maxnum ) {
$errors[ 'field' . $args['id'] ] = __( 'Please select a lower number', 'formidable' );
}
}
$this->validate_step( $errors, $args );
}
return $errors;
}
/**
* Validates the step setting.
*
* @since 5.2.06
*
* @param array $errors Errors array.
* @param array $args Validation args.
*/
private function validate_step( &$errors, $args ) {
if ( isset( $errors[ 'field' . $args['id'] ] ) ) {
return; // Don't need to check if value is invalid before.
}
$step = FrmField::get_option( $this->field, 'step' );
if ( ! $step || ! is_numeric( $step ) ) {
return;
}
$result = $this->check_value_is_valid_with_step( $args['value'], $step );
if ( ! $result ) {
return;
}
$errors[ 'field' . $args['id'] ] = sprintf(
// Translators: %1$s: the first nearest value; %2$s: the second nearest value.
__( 'Please enter a valid value. Two nearest valid values are %1$s and %2$s', 'formidable' ),
floatval( $result[0] ),
floatval( $result[1] )
);
}
/**
* Checks if value is valid with the given step.
*
* @since 5.2.07
*
* @param numeric $value The value.
* @param numeric $step The step.
* @return int|array Return `0` if valid. Otherwise, return an array contains two nearest values.
*/
private function check_value_is_valid_with_step( $value, $step ) {
// Count the number of decimals.
$decimals = max( FrmAppHelper::count_decimals( $value ), FrmAppHelper::count_decimals( $step ) );
// Convert value and step to int to prevent precision problem.
$pow = pow( 10, $decimals );
$value = intval( $pow * $value );
$step = intval( $pow * $step );
$div = $value / $step;
if ( is_int( $div ) ) {
return 0;
}
$div = floor( $div );
return array( $div * $step / $pow, ( $div + 1 ) * $step / $pow );
}
/**
* IE fallback for number fields
* Remove the comma when HTML5 isn't supported
*
* @since 3.0
*/
private function remove_commas_from_number( &$args ) {
if ( strpos( $args['value'], ',' ) ) {
$args['value'] = str_replace( ',', '', $args['value'] );
FrmEntriesHelper::set_posted_value( $this->field, $args['value'], $args );
}
}
/**
* Force the value to be numeric before it's saved in the DB
*/
public function set_value_before_save( $value ) {
if ( ! is_numeric( $value ) ) {
$value = (float) $value;
}
return $value;
}
/**
* @since 4.0.04
*/
public function sanitize_value( &$value ) {
FrmAppHelper::sanitize_value( 'sanitize_text_field', $value );
}
} |
import { Flex } from '@chakra-ui/react';
import MenuToggle from './MenuToggle';
import MenuLinks from './MenuLinks';
import { useBoolean } from '@chakra-ui/react';
export default function NavBar(props) {
const [isOpen, setIsOpen] = useBoolean();
return (
<Flex
as="nav"
align={{
base: isOpen ? 'flex-start' : 'center',
md: 'center',
}}
justify={['flex-end', 'flex-end', 'center', 'center']}
wrap="wrap"
w="100%"
h={{
base: isOpen ? '100vh' : 'auto',
md: 'auto',
}}
p={{ base: '44px', md: 8 }}
paddingBottom={{ base: null, md: props.pb }}
bg={{
base: isOpen ? 'gray.800' : 'transparent',
md: 'transparent',
}}
{...props}
>
<MenuToggle toggle={setIsOpen.toggle} isOpen={isOpen} />
<MenuLinks isOpen={isOpen} />
</Flex>
);
} |
/*
* 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.
*/
package sample.controllers;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sample.user.UserDAO;
import sample.user.UserDTO;
import sample.product.ProductDAO;
import sample.product.ProductDTO;
/**
*
* @author USER
*/
@WebServlet(name = "UpdateProductController", urlPatterns = {"/UpdateProductController"})
public class UpdateProductController extends HttpServlet {
private static final String ERROR = "WEB-INF\\error.jsp";
private static final String SUCCESS = "ProductController";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String url = ERROR;
try {
String productID = request.getParameter("productID");
String name = request.getParameter("name");
String categoryID = request.getParameter("categoryID");
String descr = request.getParameter("descr");
String img = request.getParameter("img");
int quantity = Integer.parseInt(request.getParameter("quantity"));
int price = Integer.parseInt(request.getParameter("price"));
String statusID = request.getParameter("statusID");
String expiration = request.getParameter("expiration");
ProductDAO dao = new ProductDAO();
boolean check = dao.updateProduct(new ProductDTO(productID, name, categoryID, descr, img, quantity, price, statusID, expiration));
if (check) {
url = SUCCESS;
}
} catch (Exception e) {
log("Error at LoginController: " + e.toString());
} finally {
request.getRequestDispatcher(url).forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
} |
import 'package:flutter/material.dart';
import 'customTexts.dart';
class CustomTabulation extends StatefulWidget {
final List<String> tabs;
final List<Widget> tabContent;
CustomTabulation({required this.tabs, required this.tabContent});
@override
State<CustomTabulation> createState() => _CustomTabulationState();
}
class _CustomTabulationState extends State<CustomTabulation> {
int _currentIndex = 0; // Index to track the active section
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
// width: 150,
// height: 100,
decoration: BoxDecoration(
color: Colors.transparent,
border: null,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), // Top left corner rounded
topRight: Radius.circular(20), // Top right corner rounded
),
),
padding: EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
child: ToggleButtons(
isSelected: widget.tabs
.asMap()
.map((index, _) => MapEntry(index, _currentIndex == index))
.values
.toList(),
onPressed: (index) {
setState(() {
_currentIndex = index; // Toggle between sections
});
},
// selectedColor: const Color.fromARGB(255, 255, 255, 255),
color: Color.fromARGB(255, 7, 2, 54), // Light grey when not clicked
fillColor: Colors.transparent, // Dark blue when clicked
children: widget.tabs.map((tab) {
return SizedBox(
width: 150.0,
child: Container(
decoration: BoxDecoration(
border: null,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), // Top left corner rounded
topRight:
Radius.circular(20), // Top right corner rounded
),
color: Color.fromARGB(255, 5, 36, 83) // Background color
// color: Color.fromARGB(0, 3, 2, 80),
), // Increase the size of the rectangles
child: Center(
child: Text(
tab,
textAlign: TextAlign.center,
style: _currentIndex == widget.tabs.indexOf(tab)
? CustomTextStyles
.tabTextSelected // Selected tab text style
: CustomTextStyles
.tabTextUnselected, // Unselected tab text style
),
),
),
);
}).toList(),
),
),
Padding(
padding: EdgeInsets.only(left: 0, right: 8.0),
child: Container(
height: 1.0, // Height of the horizontal bar
color: Color.fromARGB(255, 5, 36, 83), // Grey bar color
margin: EdgeInsets.symmetric(
horizontal: 8.0), // Margin to stretch the bar
),
),
Expanded(
child: widget.tabContent[_currentIndex],
),
],
);
}
} |
/*******************************************************************************
* Copyright (c) 2012, All Rights Reserved.
*
* Generation Challenge Programme (GCP)
*
*
* This software is licensed for use under the terms of the GNU General Public
* License (http://bit.ly/8Ztv8M) and the provisions of Part F of the Generation
* Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL)
*
*******************************************************************************/
package org.generationcp.middleware.domain.dms;
import java.util.List;
import org.generationcp.middleware.domain.oms.Term;
import org.generationcp.middleware.util.Debug;
/**
* The Standard Variable with term, property, scale, method, data type, etc.
*
*/
public class StandardVariable {
private Term term = new Term();
private Term property;
private Term scale;
private Term method;
private Term dataType;
private Term storedIn;
private FactorType factorType;
private VariableConstraints constraints; // may be null
private List<Enumeration> enumerations;
public StandardVariable() {
}
public StandardVariable(Term property, Term scale, Term method,
Term dataType, Term storedIn, FactorType factorType,
VariableConstraints constraints,
List<Enumeration> enumerations) {
this.property = property;
this.scale = scale;
this.method = method;
this.dataType = dataType;
this.storedIn = storedIn;
this.factorType = factorType;
this.constraints = constraints;
this.enumerations = enumerations;
}
/* Copy constructor. Used by the copy method */
private StandardVariable(StandardVariable stdVar) {
this(stdVar.getProperty(), stdVar.getScale(), stdVar.getMethod(),
stdVar.getDataType(), stdVar.getStoredIn(), stdVar.getFactorType(), stdVar.getConstraints(),
stdVar.getEnumerations());
this.setId(0);
this.setName(stdVar.getName());
this.setDescription(stdVar.getDescription());
}
public int getId() {
return term.getId();
}
public void setId(int id) {
term.setId(id);
}
public String getName() {
return term.getName();
}
public void setName(String name) {
term.setName(name);
}
public String getDescription() {
return term.getDefinition();
}
public void setDescription(String description) {
term.setDefinition(description);
}
public Term getProperty() {
return property;
}
public void setProperty(Term property) {
this.property = property;
}
public Term getScale() {
return scale;
}
public void setScale(Term scale) {
this.scale = scale;
}
public Term getMethod() {
return method;
}
public void setMethod(Term method) {
this.method = method;
}
public Term getDataType() {
return dataType;
}
public void setDataType(Term dataType) {
this.dataType = dataType;
}
public Term getStoredIn() {
return storedIn;
}
public void setStoredIn(Term storedIn) {
this.storedIn = storedIn;
}
public VariableConstraints getConstraints() {
return constraints;
}
public void setConstraints(VariableConstraints constraints) {
this.constraints = constraints;
}
public List<Enumeration> getEnumerations() {
return enumerations;
}
public void setEnumerations(List<Enumeration> enumerations) {
this.enumerations = enumerations;
}
public FactorType getFactorType() {
return factorType;
}
public void setFactorType(FactorType factorType) {
this.factorType = factorType;
}
public Enumeration findEnumerationByName(String name) {
if (enumerations != null) {
for (Enumeration enumeration : enumerations) {
if (enumeration.getName().equals(name)) {
return enumeration;
}
}
}
return null;
}
public Enumeration findEnumerationById(int id) {
if (enumerations != null) {
for (Enumeration enumeration : enumerations) {
if (enumeration.getId() == id) {
return enumeration;
}
}
}
return null;
}
public boolean hasEnumerations() {
return (enumerations != null && enumerations.size() > 0);
}
public StandardVariable copy() {
return new StandardVariable(this);
}
public List<NameSynonym> getNameSynonyms() {
return term.getNameSynonyms();
}
public void setNameSynonyms(List<NameSynonym> nameSynonyms) {
this.term.setNameSynonyms(nameSynonyms);
}
public void print(int indent) {
Debug.println(indent, "Standard Variable: ");
indent += 3;
Debug.println(indent, "term: " + term);
Debug.println(indent, "property: " + property);
Debug.println(indent, "method " + method);
Debug.println(indent, "scale: " + scale);
Debug.println(indent, "storedIn: " + storedIn);
Debug.println(indent, "factorType: " + factorType);
if (constraints != null) {
Debug.println(indent, "constraints: " + constraints);
}
if (this.constraints != null) {
this.constraints.print(indent);
}
if (enumerations != null) {
Debug.println(indent, "enumerations: " + enumerations);
}
}
public int hashCode() {
return term.getId();
}
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof StandardVariable)) return false;
StandardVariable other = (StandardVariable) obj;
return other.getId() == getId();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("StandardVariable [");
builder.append("term=");
builder.append(term);
builder.append(", property=");
builder.append(property);
builder.append(", scale=");
builder.append(scale);
builder.append(", method=");
builder.append(method);
builder.append(", dataType=");
builder.append(dataType);
builder.append(", storedIn=");
builder.append(storedIn);
builder.append(", constraints=");
builder.append(constraints);
if (enumerations != null) {
builder.append(", enumerations=");
builder.append(enumerations);
}
builder.append("]");
return builder.toString();
}
} |
import 'package:work_orders_app/features/work_orders/data/models/checklist_model.dart';
class WorkOrderModel {
final int? assetId;
final List<int>? assignedUserIds;
final List<ChecklistModel>? checklist;
final String? description;
final int? id;
final String? priority;
final String? status;
final String? title;
WorkOrderModel({
required this.assetId,
required this.assignedUserIds,
required this.checklist,
required this.description,
required this.id,
required this.priority,
required this.status,
required this.title,
});
factory WorkOrderModel.fromJson(Map<String, dynamic> map) {
return WorkOrderModel(
assetId: map['assetId'],
description: map['description'],
id: map['id'].toInt(),
priority: map['priority'],
status: map['status'],
title: map['title'],
assignedUserIds: List<int>.from((map['assignedUserIds'] ?? [])),
checklist: List<ChecklistModel>.from(
(map['checklist'] as List?)?.map(
(x) => ChecklistModel.fromJson(x),
) ??
[],
),
);
}
@override
String toString() {
return 'WorkOrderModel(assetId: $assetId, assignedUserIds: $assignedUserIds, checklist: $checklist, description: $description, id: $id, priority: $priority, status: $status, title: $title)';
}
} |
using namespace System.IO
using namespace System.Collections.Generic
$PowerPoint = Read-Host "`nPlease enter the software name."
try
{
# Replace occurrences of "PowerPoint" in all files
Write-Host "`nReplacing occurrences of 'PowerPoint' with "$PowerPoint" in all files.`n"
$replace_successful = $true
Get-ChildItem -File -Recurse | ForEach-Object {
try {
If ((Get-Content $_.Extension -eq ".ps1") -or (Get-Content $_.Extension -eq ".bat"))
{
continue
}
} catch {}
try
{
(Get-Content $_.FullName) -replace 'PowerPoint', $PowerPoint | Set-Content $_.FullName
}
catch
{
Write-Host "`nAn error occurred when replacing file contents of " $_.FullName ":"
Write-Host $_
$replace_successful = $false
}
}
If($replace_successful)
{
Write-Host "Successfully replaced files contents.`n"
}
else
{
Write-Host "`nERROR: Could not replace some file contents.`n"
}
Write-Host "`nRenaming files and directories using "$PowerPoint":`n"
# Rename files and folders
$stack = [Stack[string]]::new()
$allPaths = [List[string]]::new()
# Get all files and directories containing "PowerPoint" recursively
Get-ChildItem -Recurse -Directory | ForEach-Object {
$dirpath = $_.FullName
$dirname = Split-Path $dirpath -Leaf
if ($dirname.Contains("PowerPoint"))
{
$stack.Push($dirpath)
$allPaths.Add($dirpath)
}
# Write-Host $_.FullName
foreach ($file in [Directory]::EnumerateFiles($dirpath))
{
$filename = [Path]::GetFileName($file)
if ($filename.Contains('PowerPoint') -and -not $allPaths.Contains($file))
{
$stack.Push($file)
$allPaths.Add($file)
}
}
}
# Add root files
Get-ChildItem -File | ForEach-Object {
if ($_.FullName.Contains("PowerPoint")) {
$stack.Push($_.FullName)
}
}
# Rename files and folders
while ($stack.Count) {
$poppedFullName = $stack.Pop()
$pathExists = (-not ([string]::IsNullOrEmpty($poppedFullName))) -and (Test-Path -Path $poppedFullName)
$filename = [Path]::GetFileName($poppedFullName)
if($filename.Contains('PowerPoint') -and $pathExists)
{
$newName = $filename.Replace('PowerPoint', $PowerPoint)
Write-Host "Renaming: " $poppedFullName " to: " $newName
Rename-Item -LiteralPath $poppedFullName -NewName $newName #-WhatIf
}
}
Write-Host "`nAll files and folders renamed successfully."
}
catch
{
Write-Host "`nERROR:"
Write-Host $_
} |
package com.mithilesh.blog.payload;
import com.mithilesh.blog.entity.Role;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class UserDto {
private int userId;
@NotEmpty
@Size(min = 3,message = "Name must be minimum length of 4")
private String name;
@Email(message = "Email address is not valid")
private String email;
@NotEmpty
@Size(min = 5,message = "UserName must be of minimum length of 5")
private String userName;
@NotEmpty
@Size(min = 3,max = 10,message = "Password length should be min 3 and max 10 in length")
private String password;
@NotEmpty
private String about;
private Set<CommentDto> comments=new HashSet<>();
Set<Role> roles = new HashSet<>();
} |
#include "userprog/syscall.h"
#include <stdio.h>
#include <syscall-nr.h>
#include "threads/interrupt.h"
#include "threads/thread.h"
#include "threads/loader.h"
#include "userprog/gdt.h"
#include "threads/flags.h"
#include "intrinsic.h"
#include "threads/init.h"
void syscall_entry (void);
void syscall_handler (struct intr_frame *);
/* System call.
*
* Previously system call services was handled by the interrupt handler
* (e.g. int 0x80 in linux). However, in x86-64, the manufacturer supplies
* efficient path for requesting the system call, the `syscall` instruction.
*
* The syscall instruction works by reading the values from the the Model
* Specific Register (MSR). For the details, see the manual. */
#define MSR_STAR 0xc0000081 /* Segment selector msr */
#define MSR_LSTAR 0xc0000082 /* Long mode SYSCALL target */
#define MSR_SYSCALL_MASK 0xc0000084 /* Mask for the eflags */
void check_address(const uint64_t *uaddr)
{
struct thread *curr = thread_current ();
if (uaddr == NULL || !(is_user_vaddr(uaddr)) || pml4_get_page(curr->pml4, uaddr) == NULL) {
exit(-1);
}
}
void halt (void)
{
power_off(); //
}
void exit(int status)
{
struct thread *curr = thread_current ();
curr -> exit_status = status;
printf("%s: exit(%d)\n", thread_name (), status);
thread_exit ();
}
bool create(const char *file, unsigned initial_size)
{
check_address (file);
return filesys_create(file, initial_size);
}
bool remove(const char *file)
{
check_address (file);
return filesys_remove (file);
}
void
syscall_init (void) {
write_msr(MSR_STAR, ((uint64_t)SEL_UCSEG - 0x10) << 48 |
((uint64_t)SEL_KCSEG) << 32);
write_msr(MSR_LSTAR, (uint64_t) syscall_entry);
/* The interrupt service rountine should not serve any interrupts
* until the syscall_entry swaps the userland stack to the kernel
* mode stack. Therefore, we masked the FLAG_FL. */
write_msr(MSR_SYSCALL_MASK,
FLAG_IF | FLAG_TF | FLAG_DF | FLAG_IOPL | FLAG_AC | FLAG_NT);
}
/* The main system call interface */
void
syscall_handler (struct intr_frame *f UNUSED) {
switch (f->R.rax)
{
case SYS_HALT:
halt();
break;
case SYS_EXIT:
exit(f->R.rdi);
break;
case SYS_CREATE:
f->R.rax = create(f->R.rdi, f->R.rsi);
break;
case SYS_REMOVE:
f->R.rax = remove(f->R.rdi);
break;
default:
exit(-1);
break;
}
} |
import 'dart:async';
import 'dart:convert';
import 'package:FdisTesting/models/login_model.dart';
import 'package:FdisTesting/utils/api.dart';
import 'package:FdisTesting/utils/shared_prefs.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
enum LoginState {
initial,
loading,
success,
error,
}
class LoginProvider with ChangeNotifier {
LoginState _loginState = LoginState.initial;
String loginErrorMessage = "";
final api = Api();
LoginModel loginModel = LoginModel();
LoginState get loginState => _loginState;
String get errorMessage => loginErrorMessage;
bool _isLoading = false;
bool get isLoading => _isLoading;
void setLoading(bool value) {
_isLoading = value;
notifyListeners();
}
Future<void> saveToken(String token) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('token', token);
}
void setLoginState(LoginState state) {
_loginState = state;
notifyListeners();
}
Future<bool> login({
required String username,
required String password,
required void Function(LoginState state) onLoginStateChanged,
}) async {
setLoginState(LoginState.loading);
setLoading(true);
try {
final response = await api.post(
endpoint: 'api/v1/dashboard/Mob/login',
body: {'username': username.trim(), 'password': password.trim()},
);
final item = response.data;
if (response.statusCode == 200) {
loginModel = LoginModel.fromJson(item);
SharedPrefs.saveToken(loginModel.data?.token ?? "");
SharedPrefs.saveUserId(loginModel.data?.userId ?? "");
SharedPrefs.saveIsLoggedIn(true);
_loginState = LoginState.success;
setLoading(false);
notifyListeners();
if (onLoginStateChanged != null) {
onLoginStateChanged(LoginState.success);
}
return true;
} else {
loginErrorMessage = 'Login failed';
setLoading(false);
_loginState = LoginState.error;
notifyListeners();
if (onLoginStateChanged != null) {
onLoginStateChanged(LoginState.error);
}
return false;
}
} catch (error) {
loginErrorMessage = error.toString();
setLoading(false);
_loginState = LoginState.error;
debugPrint(error.toString());
notifyListeners();
if (onLoginStateChanged != null) {
onLoginStateChanged(LoginState.error);
}
return false;
}
}
} |
<?php
namespace App\Controllers;
use App\Models\AdminModel;
use CodeIgniter\API\ResponseTrait;
class Admin extends BaseController
{
use ResponseTrait;
protected $modelName = 'App\Models\AdminModel';
protected $format = 'json';
public function index()
{
$model = new AdminModel();
$data = $model->findAll();
return $this->respond($data);
}
public function show($id = null)
{
$model = new AdminModel();
$data = $model->find($id);
if ($data) {
return $this->respond($data);
} else {
return $this->failNotFound('Admin not found');
}
}
public function create()
{
$jsonData = $this->request->getJSON();
$data = [
'nama_admin' => $jsonData->nama_admin,
'email_admin' => $jsonData->email_admin,
'password_admin' => password_hash($jsonData->password_admin, PASSWORD_DEFAULT)
];
$model = new AdminModel();
$model->insert($data);
$response = [
'status' => 200,
'messages' => 'Data berhasil ditambahkan',
'data' => $data
];
return $this->respondCreated($response);
}
public function update($id = null)
{
$jsonData = $this->request->getJSON();
$data = [
'nama_admin' => $jsonData->nama_admin,
'email_admin' => $jsonData->email_admin,
'password_admin' => password_hash($jsonData->password_admin, PASSWORD_DEFAULT)
];
$model = new AdminModel();
$model->update($id, $data);
$response = [
'status' => 200,
'messages' => 'Data berhasil diubah',
'data' => $data
];
return $this->respond($response);
}
public function delete($id = null)
{
$model = new AdminModel();
$model->delete($id);
$response = [
'status' => 200,
'messages' => 'Data berhasil dihapus'
];
return $this->respondDeleted($response);
}
} |
import { GetStaticPaths, GetStaticProps } from "next"
import Head from "next/head"
import Image from "next/image"
import Stripe from "stripe"
import { useShoppingCart } from "use-shopping-cart"
import { stripe } from "../../lib/stripe"
import { Button } from "../../styles/pages/app"
import { ImageContainer, ProductContainer, ProductDetails } from "../../styles/pages/product"
interface ProductProps {
product: {
id: string
name: string
imageUrl: string
price: number
priceFormated: string
description: string
defaultPriceId: string
}
}
export default function Product({ product }: ProductProps) {
const { addItem } = useShoppingCart()
const handleAddToCart = () => {
addItem({
id: product.id,
name: product.name,
currency: 'BRL',
price: product.price,
image: product.imageUrl,
price_id: product.defaultPriceId
})
}
return (
<>
<Head>
<title>{product.name} | Ignite Shop</title>
</Head>
<ProductContainer>
<ImageContainer>
<Image src={product.imageUrl} width={520} height={480} alt={product.name} />
</ImageContainer>
<ProductDetails>
<h1>{product.name}</h1>
<span>{product.priceFormated}</span>
<p>{product.description}</p>
<Button
onClick={handleAddToCart}
>
Colocar na sacola
</Button>
</ProductDetails>
</ProductContainer>
</>
)
}
export const getStaticPaths: GetStaticPaths = async () => {
return {
paths: [
{ params: { id: 'prod_O2MaBkLHLtqDdw' } }
],
fallback: 'blocking'
}
}
export const getStaticProps: GetStaticProps<any, { id: string }> = async ({ params }) => {
const productId = params.id
const product = await stripe.products.retrieve(productId, {
expand: ['default_price']
})
const price = product.default_price as Stripe.Price
return {
props: {
product: {
id: product.id,
name: product.name,
imageUrl: product.images[0],
price: price.unit_amount,
priceFormated: new Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL',
}).format(price.unit_amount / 100),
description: product.description,
defaultPriceId: price.id
},
},
revalidate: 60 * 60 * 1
}
} |
import { Component, OnInit, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { Observable } from 'rxjs';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { WikiPassageDto } from 'src/app/models/wiki-passage-dto';
import { WikiPassageService } from 'src/app/services/wiki-passage.service';
import { WikiPassagePageStatusEnum } from 'src/app/models/enums/wiki-passage-page-status.enum';
import { UserInfoService } from '../../services/user-info.service';
import { MarkedOptions, MarkedRenderer } from 'ngx-markdown';
import { NzDrawerService, NzDrawerRef, NzTableComponent } from 'ng-zorro-antd';
import { UploaderComponent } from '../uploader/uploader.component';
import { UploaderUsageEnum } from '../../models/uploader-usage.enum';
import { AdminCreateWikipassageComponent } from '../admin-components/admin-wikipassages/admin-create-wikipassage/admin-create-wikipassage.component';
import { GlobalService } from '../../services/global.service';
import { BreadCrumbDto } from '../../models/bread-crumb';
import { UserInfoDto } from '../../models/user-info-dto';
import { EditorComponent } from '../editor/editor.component';
import { WikiPassageCommentDto } from 'src/app/models/wiki-passage-comment-dto';
import { error } from 'console';
@Component({
selector: 'wiki-passage',
templateUrl: './wiki-passage.component.html',
styleUrls: ['./wiki-passage.component.css']
})
export class WikiPassageComponent implements OnInit {
/***
* 从路由信息中抓取的文章路由编号
***/
public routePath: string
/***
* 从服务端获取的维基文章对象
***/
public wikiPassage: WikiPassageDto;
/***
* 存储旧的维基文档内容,用于比对用户是否确实修改了文章内容
***/
public oldWikiPassageDtoContent: string;
public isLoading: boolean = true;
public color: string = "lightblue";
/***
* 页面状态。(处于展示状态,或有权限的用户正在进行编辑时显示md编辑器)
***/
public pageStatus: WikiPassagePageStatusEnum = WikiPassagePageStatusEnum.Displaying;
public isAdmin: boolean = false;
public currentUser: UserInfoDto;
/***
* 用户输入的评论
*/
public commentContent: string;
public commentCountText: string;
public isEditLocked: boolean = false;
private imStillOnlineTimer: NodeJS.Timer;
public isLoadingEditButton: boolean = false;
public isLoadingSaveButton: boolean = false;
public isPostingComment: boolean = false;
public isCommentPosted: boolean = false;
constructor(private route: ActivatedRoute,
private router: Router,
private wikiPassageService: WikiPassageService,
private userInfoService: UserInfoService,
private globalService: GlobalService,
private componentFactoryResolver: ComponentFactoryResolver
) {
}
ngOnInit(): void {
//从路由中抓取文章路由地址
this.getParamsMapId();
//检查是否为管理员
this.userInfoService.getCurrentLoginedUserInfo().subscribe(response => {
if (response) {
this.currentUser = response;
this.isAdmin = response.isAdmin;
}
});
}
/***
*从路由中抓取文章路由地址编号。
* */
private getParamsMapId(): void {
let host: WikiPassageComponent = this;
this.routePath = this.route.snapshot.paramMap.get("id");
host.getWikiPassage(host.routePath);
this.router.events.subscribe((event) => {
if (event.toString().startsWith("NavigationEnd")) {
if (this.route.snapshot.paramMap.get("id") != host.routePath) {
host.routePath = this.route.snapshot.paramMap.get("id");
host.getWikiPassage(host.routePath);
}
}
});
}
getWikiPassage(routePath: string): void {
this.wikiPassageService.getWikiPassage(routePath).subscribe(response => {
this.wikiPassage = response;
this.oldWikiPassageDtoContent = this.wikiPassage.content;
this.commentCountText = response.comments ? response.comments.length + " 条评论" : "0 条评论";
this.isLoading = false;
this.setBreadCrumbs();
//锁定编辑
if (response.editingUser != null && response.editingUser.id != this.currentUser.id) {
this.isEditLocked = true;
}
});
}
/**
*更新面包屑导航
* */
setBreadCrumbs(): void {
let crumbs: Array<BreadCrumbDto> = new Array<BreadCrumbDto>();
if (this.wikiPassage.breadCrumbs != null) {
for (var i = 0; i < this.wikiPassage.breadCrumbs.length; i++) {
crumbs.push(this.wikiPassage.breadCrumbs[i]);
}
}
crumbs.push(new BreadCrumbDto(`/wiki-passage/${this.wikiPassage.routePath}`, this.wikiPassage.title));
this.globalService.setBreadCrumbs(crumbs);
}
public edit(): void {
this.isLoadingEditButton = true;
this.wikiPassageService.lockPassageEditingStatus(this.wikiPassage.id).subscribe(response => {
if (response === true) {
this.pageStatus = WikiPassagePageStatusEnum.Editing;
this.isEditLocked = true;
this.wikiPassage.editingUser = this.currentUser;
this.globalService.successTip(`【已为你锁定】其他用户暂无权编辑,直至你完成保存。`);
this.startImStillOnlineCall();
} else {
this.globalService.ErrorTip(`【失败】其他用户正在进行编辑,请刷新查看。`);
}
this.isLoadingEditButton = false;
});
}
private startImStillOnlineCall(): void {
this.wikiPassageService.imStillOnlineCall(this.wikiPassage.id).subscribe(response => { });
this.imStillOnlineTimer = setTimeout(() => {
this.startImStillOnlineCall();
}, 15000);
}
public update(): void {
this.isLoadingSaveButton = true;
if (this.wikiPassage.content != this.oldWikiPassageDtoContent) {
this.wikiPassage.lastModifyUser = UserInfoService.CurrentUser;
this.wikiPassageService.putWikiPassage(this.wikiPassage).subscribe(response => {
this.isLoadingSaveButton = false;
clearTimeout(this.imStillOnlineTimer);
this.isEditLocked = false;
this.pageStatus = WikiPassagePageStatusEnum.Displaying;
this.globalService.successTip(`【保存成功】锁定解除,已释放编辑权限。`);
}, response => {
localStorage.setItem(this.routePath, this.wikiPassage.content);
this.isLoadingSaveButton = false;
this.globalService.ErrorTip("发生错误:保存失败,请重试。(草稿已保存)");
});
} else {
this.isLoadingSaveButton = false;
this.isEditLocked = false;
this.pageStatus = WikiPassagePageStatusEnum.Displaying;
this.globalService.successTip(`【保存成功】锁定解除,已释放编辑权限。`);
}
}
public postComments() {
this.isPostingComment = true;
let comment: WikiPassageCommentDto = new WikiPassageCommentDto();
comment.user = new UserInfoDto();
comment.user.id = this.currentUser.id;
comment.wikiPassageId = this.wikiPassage.id;
comment.content = this.commentContent;
this.wikiPassageService.postComment(comment).subscribe(
{
next: (res) => {
this.globalService.successTip(`评论已成功提交:将在审核通过后显示,敬请谅解。`);
this.commentContent = "【将在审核通过后显示,敬请谅解】:" + this.commentContent;
this.isCommentPosted = true;
},
error: () => {
this.isPostingComment = false;
}
});
}
//createChildPage(): void {
// let drawerRef: NzDrawerRef = this.drawerService.create<AdminCreateWikipassageComponent, { prefix: string, parentPassageId: number }>({
// nzTitle: "添加子文档",
// nzPlacement: 'right',
// nzWidth: 320,
// nzContent: AdminCreateWikipassageComponent,
// nzContentParams: {
// prefix: this.routePath + '@',
// parentPassageId: this.wikiPassage.id
// }
// });
// drawerRef.afterOpen.subscribe(response => { });
// drawerRef.afterClose.subscribe(response => {
// this.router.navigate([`/wiki-passage/${response.routePath}`]);
// });
//}
//gotoChildPage(routePath: string) {
// this.router.navigate([`/wiki-passage/${routePath}`]);
//}
}
// function that returns `MarkedOptions` with renderer override
export function markedOptionsFactory(): MarkedOptions {
const renderer = new MarkedRenderer();
renderer.table = (header: string, body: string) => {
return '<div class="fix_head_table"><table class="table table-bordered" style="min-width:850px;">' + "<thead>" + header + "</thead>" + "<tbody>" + body + "</tbody>" + '</table></div>';
};
renderer.image = (href: string, title: string, text: string) => {
return '<img src="' + href + '" alt="' + text + '" style="max-width:100%">';
};
return {
renderer: renderer,
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
};
} |
//MlpNetwork.h
#ifndef MLPNETWORK_H
#define MLPNETWORK_H
#include "Matrix.h"
#include "Digit.h"
#include "Dense.h"
#define MLP_SIZE 4
const MatrixDims imgDims = {28, 28};
const MatrixDims weightsDims[] = {{128, 784}, {64, 128}, {20, 64}, {10, 20}};
const MatrixDims biasDims[] = {{128, 1}, {64, 1}, {20, 1}, {10, 1}};
/**
* A class representing the mlp network
*/
class MlpNetwork
{
public:
/**
* Constructor - Accepts 2 arrays, size 4 each. one for weights and one for biases. constructs the network described
* @param weights matrix array of size 4
* @param biases matrix array of size 4
*/
MlpNetwork(Matrix weights[MLP_SIZE], Matrix biases[MLP_SIZE]);
/**
* Parenthesis operator - Applies the entire network on input
* @param img - matrix
* @return digit struct
*/
Digit operator()(const Matrix& img) const;
private:
Matrix* _weights;
Matrix* _biases;
Dense _firstDense;
Dense _secondDense;
Dense _thirdDense;
Dense _fourthDense;
};
#endif // MLPNETWORK_H |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
//-------METODI DEGLI ARRAYS--------//
//pop()estrae l'ultimo elemento della lista,push()aggiunge alla fine.
//shift()estrae il primo elemento della lista,unshift()aggiunge all'inizio
//splice():crea una nuova lista aggiungendo elementi nella posizione indicata
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');// inserito alla posizione 1
console.log(months); // darà: Array ["Jan", "Feb", "March", "April", "June"]
//concat():concatena due o + arrays
//slice():crea una nuova array da un array esistente indicando l'indice di partenza e di fine(non obbligatoria)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));// darà:["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));// darà:["camel", "duck"] (2 è COMPRESO,4 è ESCLUSO)
console.log(animals.slice(-2));// darà:["duck", "elephant"]
//--------ITERAZIONI DEGLI ARRAY--------//
//metodo forEach():richiama una funzione per ogni elemento dell'array
const arrayDiNumeri = [1,2,3,4,5,6,7,8,9,10]
//per stampare ogni elemento dell'array di solito utilizziamo un for loop
for (let i=0;i<arrayDiNumeri.length;i++){
const element = arrayDiNumeri[index]
console.log(element);
}
//forEach utlizza come paramentro una funzione e darà la stessa cosa del for loop
arrayDiNumeri.forEach(element =>{
console.log(element);
})
//questi sono i cosidetti funzioni callback:cioè una funzione che passa da un altra funzione come parametro
const callback = function(element){
console.log(callback)
}
//forEach può avere da uno a tre parametri
arrayDiNumeri.forEach((element,index,array) =>{
console.log(`a[${index}] = ${element}`)
console.log("Array:",array)
})
//----------------metodo map():torna come array
const prodotti = [
{ nome: "iphone", prezzo: 200},
{ nome: "Laptop ASUS", prezzo: 400},
{ nome: "Laptop ASUS", prezzo: 400},
{ nome: "Laptop ASUS", prezzo: 45},
{ nome: "Laptop ASUS", prezzo: 34},
{ nome: "Laptop ASUS", prezzo: 78},
{ nome: "Laptop ASUS", prezzo: 98},
{ nome: "Laptop ASUS", prezzo: 102},
]
const prezzi = prodotti.map(prodotto =>{
console.log(prodotto)//qua esiste perchè è all'interno(è in locale)
return prodotti.prezzo * 0,99
})
//questo è un modo più abbreviativo dove la freccia fa da return automatico
const prezzi2 = prodotti.map(prodotto => prodotto.prezzo*0,99)
console.log(prezzi);
console.log(prezzi2);
//----------------filter():ritorna l'array di oggetti filtrati(n di oggetti o uguali o di meno)
//importante: il return del filter deve tornare un valore booleano
const prodottiFiltrati = prodotti.filter( elemento =>{
return elemento.prezzo > 100
})
//modo abbreviato
const prodottiFiltrati2 = prodotti.filter(elemento => elemento.prezzo > 300)
console.log(prodottiFiltrati);
console.log(prodottiFiltrati2);
persone.filter(persona => persona.età >= 18).forEach(personaMaggiorenne => invaEmail(personaMaggiorenne.email))
//---------------reduce():ritorna un unico valore applicando una funzione a tutti gli elementi dell'array
//non ritorna per forza un array,utlizzato di solito per i calcoli
// I iterazione accumulatore = 0, elemento = 1 ---->quindi nuovo accumulatore 0+1=1
// II iterazione accumulatore 1, elemento = 2 ----->quindi nuovo accumulatore 1+2=3
// X iterazione accumulatore 45, elemento = 10 ----->accumulatore finale 45+10=55
//reduce() può avere tre parametri= accumulatore:
arrayDiNumeri.reduce((accumulatore,elemento,index) => {
console.log("valore accumulatore:", accumulatore);
console.log("Valore elemento:",elemento);
return accumulatore + elemento
}, 0)//è il valore iniziale dell'accumulatore,con moltiplicazione si inizia da 1
console.log(somma)
//every() determina se un array risponde ad un certo requisito in tutti i suoi elementi(risutato booleano)
//some() determina se un array risponde ad un certo requisito in qualcuno dei suoi elementi(risutato booleano)
//indexOf() determina la posizione di un elemento in base ad una chiave di ricerca
//find():ritorna il primo elemento che rispetta la condizione
const trovato = prodotti.find(elemento => elemento.prezzo === 5)
console.log(trovato)//mi torna un oggetto perchè l'array di partenza è un array
//findIndex()
const indice = prodotti.findIndex(elemento => elemento.prezzo === 5)
console.log(indice) //mi torna un numero perchè mi cerca l'indice
//----------ECMA(EUROPEAN COMPUTER MANUFACTURER'S ASSOCIATION)-ES6
//PARAMETRI DI DEFAULT
//ESEMPIO PRE-ES6
// const saluta = ()=>{
// console.log("Ciao il mio nome è ${nome} ")
// }
//CON ES6
const saluta =(nome = "Riccardo")=>{
console.log(`Ciao il mio nome è ${nome}`)
}
saluta("Palma")
saluta(); //di default darà RIccardo
//-----------SHORTHAND SYNTAX
//vecchio modo
const func = (nome, età) =>{
return{
name: nome,
age: età,
}
}
//quando voglio avere il nome dell'oggetto uguale al nome della proprietà
const func2 = (nome, età) =>{
return{
nome,
età,
}
}
//con la proprietà TERNARY
const func3 = (nome, età) =>{
return{
nome,
età:typeof età === "number" ? età : 0,
}
}
console.log(func("Riccardo, 18"));
console.log(func2("Riccardo, 18"));
console.log(func3("Riccando, 18"));
//------------OBJECT DESTRUCTURING
const persona = { nome: "Riccardo", cognome:"Gulin", età:18, professione:"Dev"}
// const nome =persona.nome;
// const cognome = persona.cognome;
//al posto di fare il codice sopra si utilizza la destrutturazione sotto che crea x variabili tramite una riga di codice
const{ nome, cognome, età, professione} = persona
//-------------ARRAY DESTRUCTURING
const persone =[
{ nome: "Riccardo", cognome:"Gulin", età:18, professione:"Dev"},
{ nome: "Riccardo", cognome:"Gulin", età:18, professione:"Dev"},
{ nome: "Riccardo", cognome:"Gulin", età:18, professione:"Dev"}
]
const[persona1,persona2] = persone;//si può anche assegnare un valore ad un elemento che non esiste
console.log(persona1)
console.log(persona2)
//2 destrutturazioni
// const[{ nome, cognome}, persona2] = persone
//-------------SPREAD OPERATOR SU OGGETTI
const ob1 = { nome: "Riccardo", cognome:"Gulin", età:18, professione:"Dev"}
const ob2 ={ ...obj1}//i tre puntini copiano tutte le proprieta dell'obj1
console.log(obj2);
//se si assegna un nuovo valore all'obj2 ,obj1 non cambia
obj2.nome = "Giorgio"
console.log(obj2);
const obj3 = {...obj1, ...obj2}//la copia avviene secondo un ordine preciso da sx a dx--->(chi viene dopo viene sovrascritto)
console.log(obj3)
const obj4 ={numeroTel: 123123123, email: "solo@gmail.it"};
const obj5 = {...obj1,...obj4}
console.log(obj5)//metterà insieme tutte le proprietà di obj1 e obj4 in un unico obj5
//se ci fossero state delle proprietà con lo stesso nome le sovrascrive con quello dichiarato più a destra
//----------SPREAD OPERATOR SU ARRAY
const stringa = "Ciao a tutti"
const array =[...stringa]//darà la stringa sottoforma di lettere singole con "" dentro un unico array
console.log(array)
const arr1 =[1, 2, 3]
const arr2 = [4, 5, 6]
const arr3 =[...arr1,...arr2]
console.log(arr3)//darà un unico array con tutti i numeri da 1 a 6
</script>
</body>
</html> |
import "./App.scss";
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import { routes } from "./communication/routes";
import Dashboard from "./screens/Dashboard";
import Navbar from "./components/molecules/Navbar/Navbar";
import News from "./screens/News";
import Cosmetics from "./screens/Cosmetics";
import Footer from "./components/molecules/Footer/Footer";
import SingleNews from "./screens/SingleNews";
const AppRouter = () => {
return (
<Router>
<Navbar />
<Routes>
<Route path={routes.DASHBOARD} element={<Dashboard />} />
<Route path={routes.NEWS} element={<News />} />
<Route path={`${routes.NEWS}/:newsParam`} element={<SingleNews />} />
<Route path={routes.COSMETICS} element={<Cosmetics />} />
</Routes>
<Footer />
</Router>
);
};
export default AppRouter; |
import UIKit
class MainViewController: UIViewController {
private var mainViewModel: TableViewViewModelType?
private let tableView = TableView()
private var selectedCell: TableViewCell?
private var startingAnimationPoint: CGPoint {
guard let cellCenterPoint = self.selectedCell?.center,
let navigationBarheight = self.navigationController?.navigationBar.frame.height,
let navigationBarYOffset = self.navigationController?.navigationBar.frame.origin.y else {return .zero}
return CGPoint(
x: cellCenterPoint.x,
y: cellCenterPoint.y + navigationBarheight + navigationBarYOffset
)
}
lazy var faButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(named: "Remove"), for: .normal)
button.layer.cornerRadius = 25
button.addShadowOnView()
button.addTarget(self, action: #selector(addTask), for: .touchUpInside)
return button
}()
convenience init(viewModel: TableViewViewModelType? = nil) {
self.init()
self.mainViewModel = viewModel
}
override func viewDidLoad() {
super.viewDidLoad()
setUpViews()
setUpConstraints()
setUpDelegates()
tableView.setUpHeader()
tableView.setUpFooter()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(tableView)
}
private func setUpViews() {
title = "Мои дела"
navigationController?.navigationBar.layoutMargins = UIEdgeInsets(top: 0, left: 32, bottom: 0, right: 0)
view.backgroundColor = .specialBackground
view.addSubview(tableView)
view.addSubview(faButton)
}
private func setUpDelegates() {
tableView.mainViewControllerDelegate = self
}
@objc func addTask() {
guard let mainViewModel else {return}
let detailViewModel = DetailViewModel(dataBase: mainViewModel.returnModel(), index: nil)
let vc = DetailViewController(viewModel: detailViewModel)
present(vc, animated: true)
}
}
extension MainViewController: TableViewMainProtocol {
func getViewModel() -> TableViewViewModelType? {
return mainViewModel
}
func cellTapped(withViewModel viewModel: DetailViewModelType?, selectedCell: TableViewCell) {
self.selectedCell = selectedCell
let vc = DetailViewController(viewModel: viewModel)
vc.transitioningDelegate = self
vc.modalPresentationStyle = .custom
present(vc, animated: true)
}
}
extension MainViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CellAnimator(duration: 0.3,
transitionMode: .present,
startingPoint: self.startingAnimationPoint)
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return CellAnimator(duration: 0.3,
transitionMode: .dismiss,
startingPoint: CGPoint(x: 0, y: 0))
}
}
extension MainViewController {
private func setUpConstraints() {
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
faButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -60),
faButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
faButton.heightAnchor.constraint(equalToConstant: 50),
faButton.widthAnchor.constraint(equalToConstant: 50),
])
}
} |
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../functions/functions.dart';
import '../../styles/styles.dart';
import '../../translations/translation.dart';
import '../../widgets/widgets.dart';
import '../loadingPage/loading.dart';
import '../noInternet/noInternet.dart';
import 'historydetails.dart';
class History extends StatefulWidget {
const History({Key? key}) : super(key: key);
@override
State<History> createState() => _HistoryState();
}
dynamic selectedHistory;
class _HistoryState extends State<History> {
int _showHistory = 0;
bool _isLoading = true;
dynamic isCompleted;
bool _cancelRide = false;
var _cancelId = '';
@override
void initState() {
_isLoading = true;
_getHistory();
super.initState();
}
//get history datas
_getHistory() async {
setState(() {
myHistoryPage.clear();
myHistory.clear();
});
var val = await getHistory('is_later=1',context);
if (val == 'success') {
setState(() {
_isLoading = false;
});
}
}
@override
Widget build(BuildContext context) {
var media = MediaQuery.of(context).size;
return Material(
child: ValueListenableBuilder(
valueListenable: valueNotifierBook.value,
builder: (context, value, child) {
return Directionality(
textDirection: (languageDirection == 'rtl')
? TextDirection.rtl
: TextDirection.ltr,
child: Stack(
children: [
Container(
height: media.height * 1,
width: media.width * 1,
color: page,
padding: EdgeInsets.fromLTRB(media.width * 0.05,
media.width * 0.05, media.width * 0.05, 0),
child: Column(
children: [
SizedBox(height: MediaQuery.of(context).padding.top),
Stack(
children: [
Container(
padding:
EdgeInsets.only(bottom: media.width * 0.05),
width: media.width * 1,
alignment: Alignment.center,
child: MyText(
text: languages[choosenLanguage]
['text_enable_history'],
size: media.width * twenty,
fontweight: FontWeight.w600,
),
),
Positioned(
child: InkWell(
onTap: () {
Navigator.pop(context);
},
child: Icon(Icons.arrow_back_ios,
color: textColor)))
],
),
SizedBox(
height: media.width * 0.05,
),
Container(
padding: EdgeInsets.all(media.width * 0.01),
height: media.width * 0.12,
width: media.width * 0.85,
decoration: BoxDecoration(
color: page,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
blurRadius: 2,
spreadRadius: 2,
color: Colors.grey.withOpacity(0.2))
]),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
InkWell(
onTap: () async {
setState(() {
myHistory.clear();
myHistoryPage.clear();
_showHistory = 0;
_isLoading = true;
});
await getHistory('is_later=1',context);
setState(() {
_isLoading = false;
});
},
child: Container(
height: media.width * 0.1,
alignment: Alignment.center,
width: media.width * 0.28,
decoration: BoxDecoration(
borderRadius: (_showHistory == 0)
? BorderRadius.circular(12)
: null,
boxShadow: [
BoxShadow(
color: (_showHistory == 0)
? Colors.black
.withOpacity(0.2)
: page,
spreadRadius: 2,
blurRadius: 2)
],
color: (_showHistory == 0)
? textColor
: page),
child: MyText(
text: languages[choosenLanguage]
['text_upcoming'],
size: media.width * fifteen,
fontweight: FontWeight.w600,
color: (_showHistory == 0)
? page
: textColor)),
),
InkWell(
onTap: () async {
setState(() {
myHistory.clear();
myHistoryPage.clear();
_showHistory = 1;
_isLoading = true;
});
await getHistory('is_completed=1',context);
setState(() {
_isLoading = false;
});
},
child: Container(
height: media.width * 0.1,
alignment: Alignment.center,
width: media.width * 0.26,
decoration: BoxDecoration(
borderRadius: (_showHistory == 1)
? BorderRadius.circular(12)
: null,
boxShadow: [
BoxShadow(
color: (_showHistory == 1)
? Colors.black
.withOpacity(0.2)
: page,
spreadRadius: 2,
blurRadius: 2)
],
color: (_showHistory == 1)
? textColor
: page),
child: MyText(
text: languages[choosenLanguage]
['text_completed'],
size: media.width * fifteen,
fontweight: FontWeight.w600,
color: (_showHistory == 1)
? page
: textColor)),
),
InkWell(
onTap: () async {
setState(() {
myHistory.clear();
myHistoryPage.clear();
_showHistory = 2;
_isLoading = true;
});
await getHistory('is_cancelled=1',context);
setState(() {
_isLoading = false;
});
},
child: Container(
height: media.width * 0.1,
alignment: Alignment.center,
width: media.width * 0.27,
decoration: BoxDecoration(
borderRadius: (_showHistory == 2)
? BorderRadius.circular(12)
: null,
boxShadow: [
BoxShadow(
color: (_showHistory == 2)
? Colors.black
.withOpacity(0.2)
: page,
spreadRadius: 2,
blurRadius: 2)
],
color: (_showHistory == 2)
? textColor
: page),
child: MyText(
text: languages[choosenLanguage]
['text_cancelled'],
size: media.width * fifteen,
fontweight: FontWeight.w600,
color: (_showHistory == 2)
? page
: textColor)),
)
],
),
),
SizedBox(
height: media.width * 0.1,
),
Expanded(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
children: [
(myHistory.isNotEmpty)
? Column(
children: myHistory
.asMap()
.map((i, value) {
return MapEntry(
i,
(_showHistory == 1)
?
//completed ride history
Column(
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
InkWell(
onTap: () {
selectedHistory =
i;
Navigator.push(
context,
MaterialPageRoute(
builder:
(context) =>
const HistoryDetails()));
},
child: Container(
margin: EdgeInsets.only(
top: media
.width *
0.025,
bottom: media
.width *
0.05,
left: media
.width *
0.015,
right: media
.width *
0.015),
width: media
.width *
0.85,
padding: EdgeInsets.fromLTRB(
media.width *
0.025,
media.width *
0.05,
media.width *
0.025,
media.width *
0.05),
decoration:
BoxDecoration(
borderRadius:
BorderRadius
.circular(
12),
color: Colors
.grey
.withOpacity(
0.1),
),
child: Column(
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
Container(
padding:
EdgeInsets.all(media.width * 0.02),
decoration: BoxDecoration(
color: topBar,
border: Border.all(
color: textColor.withOpacity(0.1),
),
borderRadius: BorderRadius.circular(media.width * 0.01)),
child:
MyText(
text:
myHistory[i]['request_number'],
size:
media.width * fourteen,
fontweight:
FontWeight.w600,
color: (isDarkTheme == true)
? Colors.black
: textColor,
),
),
MyText(
text: myHistory[i]
[
'accepted_at'],
size: media.width *
twelve,
fontweight:
FontWeight.w600,
),
],
),
Row(
mainAxisAlignment:
MainAxisAlignment
.start,
children: [
Container(
height:
media.width * 0.13,
width:
media.width * 0.13,
decoration: BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(image: NetworkImage(myHistory[i]['driverDetail']['data']['profile_picture']), fit: BoxFit.cover)),
),
SizedBox(
width:
media.width * 0.02,
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
SizedBox(
width: media.width * 0.3,
child: MyText(
text: myHistory[i]['driverDetail']['data']['name'],
size: media.width * eighteen,
fontweight: FontWeight.w600,
),
),
],
),
Expanded(
child:
Row(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Image.asset(
(myHistory[i]['transport_type'] == 'taxi') ? 'assets/images/taxiride.png' : 'assets/images/deliveryride.png',
height: media.width * 0.05,
width: media.width * 0.1,
fit: BoxFit.contain,
)
],
),
),
],
),
SizedBox(
height: media
.width *
0.05,
),
Row(
mainAxisAlignment:
MainAxisAlignment
.start,
children: [
Container(
height:
media.width * 0.05,
width:
media.width * 0.05,
alignment:
Alignment.center,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.green),
child:
Container(
height:
media.width * 0.025,
width:
media.width * 0.025,
decoration:
BoxDecoration(shape: BoxShape.circle, color: Colors.white.withOpacity(0.8)),
),
),
SizedBox(
width:
media.width * 0.06,
),
Expanded(
child:
MyText(
text:
myHistory[i]['pick_address'],
// maxLines:
// 1,
size:
media.width * twelve,
),
),
],
),
SizedBox(
height: media
.width *
0.03,
),
Row(
mainAxisAlignment:
MainAxisAlignment
.start,
children: [
Container(
height:
media.width * 0.06,
width:
media.width * 0.06,
alignment:
Alignment.center,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.red.withOpacity(0.1)),
child:
Icon(
Icons.location_on_outlined,
color:
const Color(0xFFFF0000),
size:
media.width * eighteen,
),
),
SizedBox(
width:
media.width * 0.05,
),
Expanded(
child:
MyText(
text:
myHistory[i]['drop_address'],
size:
media.width * twelve,
// maxLines:
// 1,
),
),
],
),
SizedBox(
height: media
.width *
0.02,
),
Row(
children: [
Expanded(
flex:
75,
child:
Row(
children: [
Icon(Icons.credit_card, color: textColor),
SizedBox(
width: media.width * 0.01,
),
MyText(
text: languages[choosenLanguage]['text_paymentmethod'],
size: media.width * fourteen,
fontweight: FontWeight.w600,
)
],
),
),
Expanded(
flex:
25,
child:
Row(
children: [
MyText(
text: (myHistory[i]['payment_opt'] == '1')
? languages[choosenLanguage]['text_cash']
: (myHistory[i]['payment_opt'] == '2')
? languages[choosenLanguage]['text_wallet']
: (myHistory[i]['payment_opt'] == '0')
? languages[choosenLanguage]['text_card']
: '',
size: media.width * fourteen,
color: textColor.withOpacity(0.5),
),
],
))
],
),
SizedBox(
height: media
.width *
0.02,
),
Row(
children: [
Expanded(
flex:
75,
child:
Row(
children: [
Icon(Icons.timer_sharp, color: textColor),
SizedBox(
width: media.width * 0.01,
),
MyText(
text: languages[choosenLanguage]['text_duration'],
size: media.width * fourteen,
fontweight: FontWeight.w600,
)
],
),
),
Expanded(
flex:
25,
child:
Row(
children: [
MyText(
text: (myHistory[i]['total_time'] < 50) ? '${myHistory[i]['total_time']} mins' : '${(myHistory[i]['total_time'] / 60).round()} hr',
size: media.width * fourteen,
color: textColor.withOpacity(0.5),
),
],
))
],
),
SizedBox(
height: media
.width *
0.02,
),
Row(
children: [
Expanded(
flex:
75,
child:
Row(
children: [
Icon(Icons.route_sharp, color: textColor),
SizedBox(
width: media.width * 0.01,
),
MyText(
text: languages[choosenLanguage]['text_distance'],
size: media.width * fourteen,
fontweight: FontWeight.w600,
)
],
),
),
Expanded(
flex:
25,
child:
Row(
children: [
MyText(
text: (myHistory[i]['total_time'] < 50) ? myHistory[i]['total_distance'] + myHistory[i]['unit'] : myHistory[i]['total_distance'] + myHistory[i]['unit'],
size: media.width * fourteen,
color: textColor.withOpacity(0.5),
),
],
))
],
),
SizedBox(
height: media
.width *
0.02,
),
Row(
children: [
Expanded(
flex:
75,
child:
Row(
children: [
Icon(Icons.receipt, color: textColor),
SizedBox(
width: media.width * 0.01,
),
MyText(
text: languages[choosenLanguage]['text_total'],
size: media.width * fourteen,
fontweight: FontWeight.w600,
)
],
),
),
Expanded(
flex:
25,
child:
MyText(
text: '${myHistory[i]['requestBill']['data']['requested_currency_symbol']} ${myHistory[i]['requestBill']['data']['total_amount'].toString()}',
size: media.width * fourteen,
fontweight: FontWeight.w600,
maxLines: 1,
))
],
),
],
),
),
),
],
)
: (_showHistory == 2)
?
//rejected ride
Column(
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
Container(
margin: EdgeInsets.only(
top: media
.width *
0.025,
bottom: media
.width *
0.05,
left: media
.width *
0.015,
right: media
.width *
0.015),
width: media
.width *
0.85,
padding: EdgeInsets.fromLTRB(
media.width *
0.025,
media.width *
0.05,
media.width *
0.025,
media.width *
0.05),
decoration:
BoxDecoration(
borderRadius:
BorderRadius.circular(
12),
color: Colors
.grey
.withOpacity(
0.1),
),
child: Column(
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
padding:
EdgeInsets.all(media.width * 0.02),
decoration: BoxDecoration(
color: topBar,
border: Border.all(
color: textColor.withOpacity(0.1),
),
borderRadius: BorderRadius.circular(media.width * 0.01)),
child:
MyText(
text: myHistory[i]['request_number'],
size: media.width * fourteen,
fontweight: FontWeight.w600,
color: (isDarkTheme == true) ? Colors.black : textColor,
),
),
Image
.asset(
(myHistory[i]['transport_type'] == 'taxi')
? 'assets/images/taxiride.png'
: 'assets/images/deliveryride.png',
height:
media.width * 0.05,
width:
media.width * 0.1,
fit:
BoxFit.contain,
)
],
),
SizedBox(
height: media.width *
0.02,
),
(myHistory[i]['driverDetail'] !=
null)
? Container(
padding: EdgeInsets.only(bottom: media.width * 0.05),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: media.width * 0.13,
width: media.width * 0.13,
decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(image: NetworkImage(myHistory[i]['driverDetail']['data']['profile_picture']), fit: BoxFit.cover)),
),
SizedBox(
width: media.width * 0.02,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: media.width * 0.3,
child: Text(
myHistory[i]['driverDetail']['data']['name'],
style: GoogleFonts.poppins(fontSize: media.width * eighteen, fontWeight: FontWeight.w600),
),
),
],
),
],
),
)
: Container(),
SizedBox(
height: media.width *
0.05,
),
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Container(
height: media.width * 0.05,
width: media.width * 0.05,
alignment: Alignment.center,
decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.green),
child: Container(
height: media.width * 0.025,
width: media.width * 0.025,
decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white.withOpacity(0.8)),
),
),
SizedBox(
width: media.width * 0.06,
),
SizedBox(
width: media.width * 0.5,
child: MyText(
text: myHistory[i]['pick_address'],
size: media.width * twelve,
),
),
],
),
Container(
padding:
EdgeInsets.all(media.width * 0.01),
decoration:
BoxDecoration(color: Colors.red.withOpacity(0.1), borderRadius: BorderRadius.circular(media.width * 0.01)),
child:
MyText(
text: languages[choosenLanguage]['text_cancelled'],
size: media.width * twelve,
color: Colors.red,
),
)
],
),
(myHistory[i]['drop_address'] !=
null)
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: media.width * 0.03,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: media.width * 0.06,
width: media.width * 0.06,
alignment: Alignment.center,
decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.red.withOpacity(0.1)),
child: Icon(Icons.location_on_outlined, color: const Color(0xFFFF0000), size: media.width * eighteen),
),
SizedBox(
width: media.width * 0.05,
),
Expanded(
child: MyText(
text: myHistory[i]['drop_address'],
// overflow: TextOverflow.ellipsis,
size: media.width * twelve,
),
),
],
),
],
)
: Container(),
],
),
),
],
)
: (_showHistory == 0)
?
//upcoming ride
Column(
crossAxisAlignment:
CrossAxisAlignment
.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment
.spaceBetween,
children: [
MyText(
text: myHistory[i]
[
'trip_start_time'],
size: media.width *
sixteen,
fontweight:
FontWeight.w600,
),
InkWell(
onTap:
() {
setState(() {
_cancelRide = true;
_cancelId = myHistory[i]['id'];
});
},
child:
MyText(
text:
languages[choosenLanguage]['text_cancel_ride'],
size:
media.width * sixteen,
fontweight:
FontWeight.w600,
color:
buttonColor,
),
),
],
),
Container(
margin: EdgeInsets.only(
top: media.width *
0.025,
bottom: media.width *
0.05,
left: media.width *
0.015,
right:
media.width * 0.015),
width: media
.width *
0.85,
padding: EdgeInsets.fromLTRB(
media.width *
0.025,
media.width *
0.05,
media.width *
0.025,
media.width *
0.05),
decoration:
BoxDecoration(
borderRadius:
BorderRadius.circular(12),
color: Colors
.grey
.withOpacity(0.1),
),
child:
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
MyText(text: myHistory[i]['request_number'], size: media.width * sixteen, fontweight: FontWeight.w600, color: textColor),
Image.asset(
(myHistory[i]['transport_type'] == 'taxi') ? 'assets/images/taxiride.png' : 'assets/images/deliveryride.png',
height: media.width * 0.05,
width: media.width * 0.1,
fit: BoxFit.contain,
)
],
),
SizedBox(
height:
media.width * 0.02,
),
(myHistory[i]['driverDetail'] != null)
? Container(
padding: EdgeInsets.only(bottom: media.width * 0.05),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: media.width * 0.16,
width: media.width * 0.16,
decoration: BoxDecoration(shape: BoxShape.circle, image: DecorationImage(image: NetworkImage(myHistory[i]['driverDetail']['data']['profile_picture']), fit: BoxFit.cover)),
),
SizedBox(
width: media.width * 0.02,
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: media.width * 0.3,
child: MyText(
text: myHistory[i]['driverDetail']['data']['name'],
size: media.width * eighteen,
fontweight: FontWeight.w600,
),
),
],
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Column(
children: [
const Icon(
Icons.cancel,
color: Color(0xffFF0000),
),
SizedBox(
height: media.width * 0.01,
),
],
),
],
),
),
],
),
)
: Container(),
Row(
mainAxisAlignment:
MainAxisAlignment.start,
children: [
Container(
height: media.width * 0.05,
width: media.width * 0.05,
alignment: Alignment.center,
decoration: const BoxDecoration(shape: BoxShape.circle, color: Colors.green),
child: Container(
height: media.width * 0.025,
width: media.width * 0.025,
decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.white.withOpacity(0.8)),
),
),
SizedBox(
width: media.width * 0.06,
),
SizedBox(
width: media.width * 0.5,
child: MyText(
text: myHistory[i]['pick_address'],
// maxLines: 1,
size: media.width * twelve,
),
),
],
),
SizedBox(
height:
media.width * 0.06,
),
(myHistory[i]['drop_address'] != null)
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: media.width * 0.03,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: media.width * 0.06,
width: media.width * 0.06,
alignment: Alignment.center,
decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.red.withOpacity(0.1)),
child: Icon(Icons.location_on_outlined, color: const Color(0xFFFF0000), size: media.width * eighteen),
),
SizedBox(
width: media.width * 0.05,
),
Expanded(
child: MyText(
text: myHistory[i]['drop_address'],
size: media.width * twelve,
// maxLines: 1,
),
),
],
),
],
)
: Container(),
],
),
),
],
)
: Container());
})
.values
.toList(),
)
: (_isLoading == false)
? Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
SizedBox(
height: media.width * 0.05,
),
Container(
alignment: Alignment.center,
height: media.width * 0.7,
width: media.width * 0.7,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/images/noorder.png'),
fit: BoxFit.contain)),
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
SizedBox(
height:
media.width * 0.07,
),
SizedBox(
width: media.width * 0.2,
child: MyText(
text: languages[
choosenLanguage]
['text_noorder'],
textAlign:
TextAlign.center,
fontweight:
FontWeight.w800,
size: media.width *
sixteen),
),
],
),
),
],
)
: Container(),
(myHistoryPage['pagination'] != null)
? (myHistoryPage['pagination']
['current_page'] <
myHistoryPage['pagination']
['total_pages'])
? InkWell(
onTap: () async {
setState(() {
_isLoading = true;
});
if (_showHistory == 0) {
await getHistoryPages(
'is_later=1&page=${myHistoryPage['pagination']['current_page'] + 1}');
} else if (_showHistory == 1) {
await getHistoryPages(
'is_completed=1&page=${myHistoryPage['pagination']['current_page'] + 1}');
} else if (_showHistory == 2) {
await getHistoryPages(
'is_cancelled=1&page=${myHistoryPage['pagination']['current_page'] + 1}');
}
setState(() {
_isLoading = false;
});
},
child: Container(
padding: EdgeInsets.all(
media.width * 0.025),
margin: EdgeInsets.only(
bottom: media.width * 0.05),
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(10),
color: page,
border: Border.all(
color: borderLines,
width: 1.2)),
child: MyText(
text: languages[choosenLanguage]
['text_loadmore'],
size: media.width * sixteen,
),
),
)
: Container()
: Container()
],
),
))
],
),
),
(_cancelRide == true)
? Positioned(
child: Container(
height: media.height * 1,
width: media.width * 1,
color: Colors.transparent.withOpacity(0.6),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
width: media.width * 0.9,
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Container(
height: media.height * 0.1,
width: media.width * 0.1,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: page),
child: InkWell(
onTap: () {
setState(() {
_cancelRide = false;
_cancelId = '';
});
},
child: Icon(
Icons.cancel_outlined,
color: textColor,
))),
],
),
),
Container(
padding: EdgeInsets.all(media.width * 0.05),
width: media.width * 0.9,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
color: page),
child: Column(
children: [
MyText(
text: languages[choosenLanguage]
['text_ridecancel'],
size: media.width * eighteen,
),
SizedBox(
height: media.width * 0.05,
),
Button(
onTap: () async {
setState(() {
_isLoading = true;
});
await cancelLaterRequest(
_cancelId,context);
await _getHistory();
setState(() {
_cancelRide = false;
_cancelId = '';
});
},
text: languages[choosenLanguage]
['text_cancel_ride'])
],
),
)
],
),
),
)
: Container(),
//no internet
(internet == false)
? Positioned(
top: 0,
child: NoInternet(
onTap: () {
setState(() {
internetTrue();
});
},
))
: Container(),
//loader
(_isLoading == true)
? const Positioned(top: 0, child: Loading())
: Container()
],
),
);
}));
}
} |
import Markdoc from '@markdoc/markdoc';
import type { ShikiConfig } from 'astro';
import { unescapeHTML } from 'astro/runtime/server/index.js';
import { bundledLanguages, getHighlighter, type Highlighter } from 'shikiji';
import type { AstroMarkdocConfig } from '../config.js';
const ASTRO_COLOR_REPLACEMENTS: Record<string, string> = {
'#000001': 'var(--astro-code-color-text)',
'#000002': 'var(--astro-code-color-background)',
'#000004': 'var(--astro-code-token-constant)',
'#000005': 'var(--astro-code-token-string)',
'#000006': 'var(--astro-code-token-comment)',
'#000007': 'var(--astro-code-token-keyword)',
'#000008': 'var(--astro-code-token-parameter)',
'#000009': 'var(--astro-code-token-function)',
'#000010': 'var(--astro-code-token-string-expression)',
'#000011': 'var(--astro-code-token-punctuation)',
'#000012': 'var(--astro-code-token-link)',
};
const COLOR_REPLACEMENT_REGEX = new RegExp(
`(${Object.keys(ASTRO_COLOR_REPLACEMENTS).join('|')})`,
'g'
);
const PRE_SELECTOR = /<pre class="(.*?)shiki(.*?)"/;
const LINE_SELECTOR = /<span class="line"><span style="(.*?)">([\+|\-])/g;
const INLINE_STYLE_SELECTOR = /style="(.*?)"/;
const INLINE_STYLE_SELECTOR_GLOBAL = /style="(.*?)"/g;
/**
* Note: cache only needed for dev server reloads, internal test suites, and manual calls to `Markdoc.transform` by the user.
* Otherwise, `shiki()` is only called once per build, NOT once per page, so a cache isn't needed!
*/
const highlighterCache = new Map<string, Highlighter>();
export default async function shiki({
langs = [],
theme = 'github-dark',
wrap = false,
}: ShikiConfig = {}): Promise<AstroMarkdocConfig> {
const cacheId = typeof theme === 'string' ? theme : theme.name || '';
let highlighter = highlighterCache.get(cacheId)!;
if (!highlighter) {
highlighter = await getHighlighter({
langs: langs.length ? langs : Object.keys(bundledLanguages),
themes: [theme],
});
highlighterCache.set(cacheId, highlighter);
}
return {
nodes: {
fence: {
attributes: Markdoc.nodes.fence.attributes!,
transform({ attributes }) {
let lang: string;
if (typeof attributes.language === 'string') {
const langExists = highlighter
.getLoadedLanguages()
.includes(attributes.language as any);
if (langExists) {
lang = attributes.language;
} else {
console.warn(
`[Shiki highlighter] The language "${attributes.language}" doesn't exist, falling back to plaintext.`
);
lang = 'plaintext';
}
} else {
lang = 'plaintext';
}
let html = highlighter.codeToHtml(attributes.content, { lang, theme });
// Q: Could these regexes match on a user's inputted code blocks?
// A: Nope! All rendered HTML is properly escaped.
// Ex. If a user typed `<span class="line"` into a code block,
// It would become this before hitting our regexes:
// <span class="line"
html = html.replace(PRE_SELECTOR, `<pre class="$1astro-code$2"`);
// Add "user-select: none;" for "+"/"-" diff symbols
if (attributes.language === 'diff') {
html = html.replace(
LINE_SELECTOR,
'<span class="line"><span style="$1"><span style="user-select: none;">$2</span>'
);
}
if (wrap === false) {
html = html.replace(INLINE_STYLE_SELECTOR, 'style="$1; overflow-x: auto;"');
} else if (wrap === true) {
html = html.replace(
INLINE_STYLE_SELECTOR,
'style="$1; overflow-x: auto; white-space: pre-wrap; word-wrap: break-word;"'
);
}
// theme.id for shiki -> shikiji compat
const themeName = typeof theme === 'string' ? theme : theme.name;
if (themeName === 'css-variables') {
html = html.replace(INLINE_STYLE_SELECTOR_GLOBAL, (m) => replaceCssVariables(m));
}
// Use `unescapeHTML` to return `HTMLString` for Astro renderer to inline as HTML
return unescapeHTML(html) as any;
},
},
},
};
}
/**
* shiki -> shikiji compat as we need to manually replace it
*/
function replaceCssVariables(str: string) {
return str.replace(COLOR_REPLACEMENT_REGEX, (match) => ASTRO_COLOR_REPLACEMENTS[match] || match);
} |
<template>
<div>
<v-card>
<v-card-title>
<v-text-field v-model="search" append-icon="mdi-magnify" label="Search" single-line hide-details></v-text-field>
<v-spacer></v-spacer>
<v-spacer></v-spacer>
<v-spacer></v-spacer>
</v-card-title>
<v-data-table :headers="headers" :items="courses" :search="search">
<template v-slot:item="row">
<tr>
<td>
{{row.item.course_code}} - {{row.item.title}}
</td>
<td>
{{ row.item.enrolments }} / {{ row.item.capacity }}
</td>
<td>
{{ formatDate(row.item.start_date) }}
</td>
<td>
{{ formatDate(row.item.end_date) }}
</td>
<td>
{{ formatDate(row.item.start_register) }}
</td>
<td>
{{ formatDate(row.item.end_register) }}
</td>
<td width="10">
<router-link :to="{ name: 'CourseDetail', params: { conduct_id: row.item.conduct_id }}">
<v-btn depressed small color="#0062E4">
<span style="color: white">View Class</span>
</v-btn>
</router-link>
</td>
</tr>
</template>
</v-data-table>
</v-card>
</div>
</template>
<script>
import axios from 'axios';
import moment from "moment";
export default {
name: 'TrainerCourses',
data: () => ({
courses: [],
search: '',
headers: [
{ text: 'Course', value: 'course_code', align: 'start', sortable: true},
{ text: 'Capacity', value: 'current', filterable: false, sortable: true},
{ text: 'Start Date', value: 'start_date', filterable: false, sortable: true},
{ text: 'End Date', value: 'end_date', filterable: false, sortable: true},
{ text: 'Register Start Date', value: 'start_register', filterable: false, sortable: true},
{ text: 'Register End Date', value: 'end_register', filterable: false, sortable: true},
{ text: '', value: 'actions', filterable: false, sortable: false}
],
}),
computed: {
apiLink(){
return this.$store.state.apiLink;
},
getUserId() {
return this.$store.state.userId;
}
},
methods: {
// Get all Courses that are conducted by trainer_id
getCoursesDetail(trainer_id) {
let updatedApiWithEndpoint = this.apiLink + "/getallcoursesthatareconductedbyuser";
let dataObj = { "trainerId": trainer_id }
axios.post(updatedApiWithEndpoint, dataObj)
.then((response) => {
this.courses = response.data.data;
})
.catch((error) => {
console.log(error, "No courses found")
})
},
formatDate(date) {
return moment(date).format('yyyy-MM-DD HH:mm');
}
},
created() {
// Calls method to get course details
this.getCoursesDetail(this.getUserId);
}
}
</script>
<style>
</style> |
import useScrollPosition from '@react-hook/window-scroll'
import { useWarningFlag, WrongNetworkBanner } from 'components/WarningWrapper/WarningWrapper'
import { Paths } from 'constants/paths'
import { Flex, Text } from 'rebass'
import styled from 'styled-components'
import Logo from '../../assets/svg/logo.svg'
import { useActiveWeb3React } from '../../hooks/web3'
import Web3Status from '../Web3Status'
import NetworkSelector from './NetworkSelector'
const HeaderFrame = styled.div<{ showBackground: boolean }>`
display: ${({ showBackground }) => (showBackground ? 'none' : 'grid')};
background-color: ${({ theme }) => theme.bg0};
display: flex;
align-items: center;
justify-content: space-between;
align-items: center;
flex-direction: row;
width: 100%;
height: 70px;
position: fixed;
top: 0;
z-index: 21;
padding: 12px;
padding: 10px 25px;
${({ theme }) => theme.mediaWidth.upToPhone`
padding: 0;
position: relative;
height: initial;
margin-bottom: 12px;
`};
`
const HeaderControls = styled.div`
display: flex;
flex-direction: row;
align-items: center;
justify-self: flex-end;
flex-wrap: wrap;
${({ theme }) => theme.mediaWidth.upToExtraSmall`
justify-content: flex-end;
`};
`
const HeaderElement = styled.div`
display: flex;
align-items: center;
/* addresses safari's lack of support for "gap" */
& > *:not(:first-child) {
margin-left: 8px;
}
${({ theme }) => theme.mediaWidth.upToMedium`
align-items: center;
`};
`
const AccountElement = styled.div<{ active: boolean }>`
display: flex;
flex-direction: row;
align-items: center;
border-radius: 50px;
white-space: nowrap;
width: 100%;
cursor: pointer;
:focus {
border: 1px solid blue;
}
`
const BalanceText = styled(Text)`
display: flex;
align-items: center;
font-size: 18px;
font-weight: 400;
padding: 0px 25px;
min-width: auto !important;
`
const Title = styled.a`
display: flex;
align-items: center;
pointer-events: auto;
justify-self: flex-start;
margin-right: auto;
text-decoration: none !important;
:hover {
cursor: pointer;
}
`
const Icon = styled.div`
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s;
width: 52px;
height: 52px;
border-radius: 50%;
box-shadow: 0px 3.333px 16.667px 0px rgba(40, 46, 63, 0.08);
background-color: ${({ theme }) => theme.bg0};
`
const LogoImg = styled.img``
export default function Header() {
const { account } = useActiveWeb3React()
const scrollY = useScrollPosition()
const { notSupportedChain } = useWarningFlag()
if (notSupportedChain) {
return <WrongNetworkBanner />
}
if (!account) {
return null
}
return (
<>
<HeaderFrame showBackground={scrollY > 16}>
<Flex>
{/*<Title href="https://xapp.com" target="_blank">*/}
{/*TODO decide what to live */}
<Title href={Paths.DEFAULT}>
<Icon>
<LogoImg width="auto" src={Logo} alt="logo" />
</Icon>
</Title>
</Flex>
<HeaderControls>
{account && <NetworkSelector />}
<HeaderElement>
<AccountElement active={!!account} style={{ pointerEvents: 'auto' }}>
<Web3Status />
</AccountElement>
</HeaderElement>
</HeaderControls>
</HeaderFrame>
</>
)
} |
import React, { useState } from "react";
import { Col, Row, Container, Card } from "react-bootstrap";
import { Link } from "react-router-dom";
import "../components/style.css";
function Search(props) {
const [query, setQuery] = useState("");
const [results, setResults] = useState([]);
const onChange = (e) => {
e.preventDefault();
setQuery(e.target.value);
fetch(`https://api.themoviedb.org/3/search/movie?api_key=ed31b81064e7c617fa201d727de6c48c&language=en-US&page=1&include_adult=false&query=${e.target.value}`).then((res) => res.json()).then(data => {
if (!data.errors) {
setResults(data.results);
}
else {
setResults([]);
}
})
}
return (
<div>
<Container fluid >
<Row>
<input type="text"
placeholder="Type and Let the Magic Happen ;)"
onChange={onChange}
value={query}
className="search input-group-text"
/>
</Row>
<Row className="text-center" >
{results.length > 0 && (
results.map((movie, index) => (
<Col key={index} xs={12} sm={6} md={4} lg={3} xl={3} className="text-center pb-3" >
<Card className="card-panel mb-3 bg-dark">
<div className="ml-2 map">
<Card.Img variant="top" src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`} />
<Card.Body >
<Card.Title className="text-width text-white" >{movie.title}</Card.Title>
<Link
to={`/movies/${movie.id}`}
className="btn btn-danger d-block mx-auto"
id="readmore"
>
Read More
</Link>
</Card.Body>
</div>
</Card>
</Col>
))
)}
</Row>
</Container>
</div>
)
}
export default Search; |
@c page
@node srfi specialize-procedures
@appendixsec @ansrfi{26} Notation for specializing parameters without currying
@cindex @srfi{} specialize-procedures
@noindent
The following libraries:
@example
(srfi specialize-procedures)
@end example
@noindent
are written by Sebastian Egner as the reference implementation for
@ansrfi{26}; see:
@center @url{http://srfi.schemers.org/srfi-26/srfi-26.html}
@noindent
for more details. The following documentation is an unofficial Texinfo
reformatting and minor modification of the original document by Marco
Maggi @email{marcomaggi@@gna.org} (Sat Oct 25, 2008).
@menu
* srfi specialize-procedures license:: Original document license.
* srfi specialize-procedures abstract:: Abstract.
* srfi specialize-procedures rationale:: Rationale.
* srfi specialize-procedures spec:: Specification.
* srfi specialize-procedures design:: Rationale design.
* srfi specialize-procedures ack:: Acknowledgements.
@end menu
@c ------------------------------------------------------------
@c page
@node srfi specialize-procedures license
@appendixsubsec Original document license
@noindent
Copyright @copyright{} 2002 Sebastian Egner. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@c ------------------------------------------------------------
@c page
@node srfi specialize-procedures abstract
@appendixsubsec Abstract
@noindent
When programming in functional style, it is frequently necessary to
specialize some of the parameters of a multi--parameter procedure. For
example, from the binary operation @func{cons} one might want to obtain
the unary operation @code{(lambda (x) (cons 1 x))}. This specialization
of parameters is also known as ``partial application'', ``operator
section'' or ``projection''.
The mechanism proposed here allows to write this sort of specialization
in a simple and compact way. The mechanism is best explained by a few
examples:
@example
(cut cons (+ a 1) <>) = (lambda (x2) (cons (+ a 1) x2))
(cut list 1 <> 3 <> 5) = (lambda (x2 x4) (list 1 x2 3 x4 5))
(cut list) = (lambda () (list))
(cut list 1 <> 3 <...>) = (lambda (x2 . xs) (apply list 1 x2 3 xs))
(cut <> a b) = (lambda (f) (f a b))
@end example
As you see, the macro @func{cut} specializes some of the parameters of
its first argument. The parameters that are to show up as formal
variables of the result are indicated by the symbol @code{<>}, pronouced
as ``slot''. In addition, the symbol @code{<...>}, pronounced as
``rest--slot'', matches all residual arguments of a variable argument
procedure. As you can see from the last example above, the first
argument can also be a slot, as one should expect in Scheme.
In addition to @func{cut}, there is a variant called @func{cute} (a
mnemonic for ``@func{cut} with evaluated non--slots'') which evaluates
the non--slot expressions at the time the procedure is specialized, not
at the time the specialized procedure is called. For example:
@example
(cute cons (+ a 1) <>) = (let ([a1 (+ a 1)])
(lambda (x2)
(cons a1 x2)))
@end example
As you see from comparing this example with the first example above, the
@func{cute}--variant will evaluate @code{(+ a 1)} once, while the
@func{cut}--variant will evaluate it during every invocation of the
resulting procedure.
The mechanism proposed in this @srfi{} allows specializing any subset
of the variables of a procedure. The result can be of fixed arity or of
variable arity. The mechanism does not allow permutation, omission,
duplication or any other processing of the arguments; for this it is
necessary to write to use a different mechanism such as @func{lambda}.
@c ------------------------------------------------------------
@c page
@node srfi specialize-procedures rationale
@appendixsubsec Rationale
@noindent
A particularly elegant way to deal with specialization is known as
currying (Schoenfinkel 1924, Curry 1958). The idea of currying is to
reduce multi--argument functions to single--argument functions by
regarding an @var{n}--ary function as a unary function mapping its first
argument into an (@var{n-1})--ary function (which is curried in turn).
This point of view, apart from its theoretical elegance, allows an
extremely compact notation for specializing the first argument of a
function. In the first example, one could simply write @code{(cons 1)}.
Yet, Scheme is not a curried language---the number of arguments passed
to a procedure must match the number of its parameters at all times.
This allows zero--arity and variable--arity procedures but in order to
specialize parameters one usually has to write down a lambda--expression
and invent some irrelevant identifiers for its formal variables (@var{x}
in the examples in the Abstract). For this reason, the mechanism
proposed in this @srfi{} provides a simple and compact notation for
specializing any subset of the parameters of a procedure.
Note: @emph{The mechanism proposed here is not currying!}
The purpose of the mechanism proposed here is to make the benefits of
currying available within the programming language Scheme. There are
two primary benefits of currying in practice: Higher--order types are
substantially simplified and there is a simple notation for specializing
parameters. The type aspect is irrelevant as Scheme has latent typing.
The specialization aspect is largly covered with this @srfi{}.
Here are a few more examples for illustration:
@example
(map (cut * 2 <>) '(1 2 3 4))
(map (cut vector-set! x <> 0) indices)
(for-each (cut write <> port) exprs)
(map (cut <> x y z) (list min max))
(for-each (cut <>) thunks)
@end example
@c ------------------------------------------------------------
@c page
@node srfi specialize-procedures spec
@appendixsubsec Specification
@findex cut
@findex cute
@noindent
The formal syntax of a specialized expression, in the style of the
Revised^5 Report on the Algorithmic Language Scheme:
@example
<cut-expression> --> (cut <slot-or-expr> <slot-or-expr>*)
| (cut <slot-or-expr> <slot-or-expr>* <...>)
| (cute <slot-or-expr> <slot-or-expr>*)
| (cute <slot-or-expr> <slot-or-expr>* <...>)
<slot-or-expr> --> <> ; a "slot"
| <expression> ; a "non-slot expression"
@end example
The macro @func{cut} transforms a @code{<cut-expression>} into a
@code{<lambda expression>} with as many formal variables as there are
slots in the list @code{<slot-or-expr>*}. The body of the resulting
@code{<lambda expression>} calls the first @code{<slot-or-expr>} with
arguments from @code{<slot-or-expr>*} in the order they appear.
In case there is a rest--slot symbol, the resulting procedure is also of
variable arity, and the body calls the first @code{<slot-or-expr>} with
all arguments provided to the actual call of the specialized procedure.
The macro @func{cute} is similar to the macro @func{cut}, except that it
first binds new variables to the result of evaluating the non--slot
expressions (in an unspecific order) and then substituting the variables
for the non--slot expressions. In effect, @func{cut} evaluates
non--slot expressions at the time the resulting procedure is called,
whereas @func{cute} evaluates the non--slot expressions at the time the
procedure is constructed.
@c ------------------------------------------------------------
@c page
@node srfi specialize-procedures design
@appendixsubsec Rationale design
@subsubheading Why not real currying/uncurrying?
@noindent
It is possible in Scheme to implement a macro turning a multi--argument
procedure into a nesting of single--argument procedures and back. These
operations are usually called ``curry'' and ``uncurry'' in other
programming languages.
Yet, Scheme remains an inherently uncurried language and is not prepared
to deal with curried procedures in a convenient way. Hence, a ``by the
book'' implementation of currying would only be useful if you apply it
in the sequence ``curry, specialize some arguments, and uncurry again'',
which is exactly the purpose of the macro @func{cut} specified in this
document. The primary relevance of currying/uncurrying in Scheme is to
teach concepts of combinatory logic.
@c ------------------------------------------------------------
@subsubheading Why not a more general mechanism, also allowing permutation omission and duplication of arguments?
@noindent
The reason is that I, the author of this @srfi{}, consider more general
mechanisms too dangerous to mix them with the mechanism proposed here.
In particular, as soon as parameters are being rearranged it is usually
necessary to be aware of the meaning of the parameters; unnamed
variables can be quite harmful then. The mechanism proposed here is
designed to prevent this.
Please refer to the discussion threads ``OK, how about...,'' (Alan
Bawden), ``is that useful?'' (Walter C. Pelissero), and ``l, the
ultimate curry that is not curry'' (Al Petrofsky).
@c ------------------------------------------------------------
@subsubheading Why are the macro called @func{cut}/@func{cute} and not [enter your favourite here]?
@noindent
Well, the original name proposed for this @srfi{} was @func{curry}
which immediately stirred some emotions as it does not what is commonly
known as currying. Some alternatives have been discussed, such as:
@example
section specialise specialize,
partial-apply partial-call partial-lambda,
_j _i $
& srfi-26 foobar
xyz schoenfinkelize curry-which-isnt-curry
tandoori
@end example
@noindent
and it has also been suggested to pick a five letter symbol uniformly at
random and fix this as a name. To be fair, not all of these name have
been put forward as serious proposals, some of them were merely to
illustrate a point in the discussion. In addition, I have played with
the game of the name quite a bit and considered other candidates not
listed here.
Despite the fact that the discussion list only represents a highly
biased random sample of people's opinion (motivation to post a message
is higher if you disagree, for example) it told me that the @srfi{}
could potentially benefit from a different name; however impractical it
may be to go for unanimous popularity.
The name @func{cut} refers to ``operator section'', as the concept is
often called in other programming languages, but I tend to remember it
as the acronym for ``Curry Upon This''. ;-) The names for the evaluating
version of @func{cut} that have been proposed were @func{cut!},
@func{cutlet}, @func{cut*}, and @func{cute}.
@c ------------------------------------------------------------
@subsubheading Is it possible to implement the @srfi{} without macros?
@noindent
Not really. As Stephan Houben has pointed out during the discussion
(refer to ``Implementing it as a procedure'') it is possible to
implement the @func{cute}--mechanism as a procedure. Refer also to Al
Petrofsky's posting ``Problems with @emph{curry}'s formal
specification'' for details.
However, the procedural implementation comes with a slight performance
penalty and it is not possible the implement the @func{cut}--mechanism
as a procedure, too.
As both are needed, we rely on macros to implement the @srfi{}. Why is
there another symbol for the rest--slot when @func{lambda}--expressions
use the dotted notation for variable length argument lists? There are
two reasons. The first one is the existence of a procedural
implementation of a related mechanism (refer to the previous paragraph).
For a procedure, however, it is not possible to have dotted notation.
The second reason is the way the hygienic macro mechanism in @rnrs{5} is
defined to deal with dotted notation, as Felix Winkelmann has pointed
out. Refer to the discussion threads ``Improper lists in macros [WAS:
none]''.
@c ------------------------------------------------------------
@subsubheading Why is it impossible to specify when a non--slot is evaluate individually per non--slot?
@noindent
@func{cut} evaluates all non--slots at the time the specialized
procedure is called and @func{cute} evaluates all non--slots at the time
the procedure is being specialized. These are only the two extremes and
it is possible to define a syntax that allows to choose per non--slot.
However, I am convinced that the benefit of the greater flexibility is
not worth the risk of confusion. If a piece of code really depends on
the distinction, it might be better to make this explicit through
@func{let} and @func{lambda}.
@c ------------------------------------------------------------
@subsubheading Why is @code{(cut if <> 0 1)} etc. illegal?
@noindent
It is specified that a @code{<slot-or-expr>} must be either the slot
symbol or an @func{<expression>} in the sense of @rnrs{5}, Section
7.1.3. As if is no @func{<expression>}, the above case is illegal. The
reason why @func{cut} and @func{cute} are restricted in this sense is
the difficulty of defining the meaning of such generalized expressions.
Please refer to the discussion archive for details.
@c ------------------------------------------------------------
@c page
@node srfi specialize-procedures ack
@appendixsubsec Acknowledgements
@noindent
An important part of this @srfi{} is based on the contribution of other
people, mostly through the discussion archive. In particular, the
semantics and the design rationale have been greatly improved in the
course of the discussion. I would like to thank all who have
contributed.
@c ------------------------------------------------------------ |
import { NavLink } from "react-router-dom"
import styled from "styled-components"
import { colors } from "../../enums"
import InputComponent from "../InputComponent"
import UseStores from "../../hooks/useStores";
interface Props {
onClick?: () => void;
error?: string;
}
const UnderTitle = styled.p`
font-size: 15px;
font-weight: 400;
color: ${colors.gray};
`
const NavigationLink = styled(NavLink)`
color: ${colors.agonaBlue};
font-weight: 700;
text-decoration: none;
`
const Button = styled.button`
padding: 14px 40px;
border: 3px solid ${colors.agonaBlue};
margin: 110px 0 52px;
border-radius: 25px;
color: ${colors.agonaBlue};
font-weight: 700;
background-color: ${colors.white};
`
const ErrorMessage = styled.p`
margin-top: 17px;
color: ${colors.red};
font-size: 13px;
font-weight: 400;
`
const Register : React.FC<Props> = ({onClick, error}) => {
const { accountStore } = UseStores();
return (
<>
<InputComponent
placeholder="Адрес электронной почты"
validate="email"
width="375"
isRequired={true}
textAlign="center"
isError={error ? true : false}
onChangeValue={(value) => {
accountStore.setUserMail(value);
}}
/>
<InputComponent
placeholder="Пароль"
validate="password"
width="375"
isRequired={true}
textAlign="center"
isError={error ? true : false}
onChangeValue={(value) => {
accountStore.setUserPassword(value);
}}
/>
<InputComponent
placeholder="Повторите пароль"
validate="password"
width="375"
isRequired={true}
textAlign="center"
isError={error ? true : false}
onChangeValue={(value) => {
accountStore.setRegistrationSecondPassword(value);
}}
/>
{error && (
<ErrorMessage>{error}</ErrorMessage>
)}
<Button
onClick={onClick}
>
Регистрация
</Button>
<UnderTitle>
Есть логин для входа?
<NavigationLink to='/authorization/login'>
Войти
</NavigationLink>
</UnderTitle>
</>
)
}
export default Register |
"use client";
import { useEffect, useState } from "react";
import { PromptCardList } from "./PromptCardList";
const Feed = () => {
const [search, setSearch] = useState("");
const [prompts, setPrompts] = useState([]);
const [copied, setCopied] = useState("");
const handleCopiedPrompt = (prompt) => {
setCopied(prompt);
};
const getPrompts = async () => {
const response = await fetch("/api/prompt/getAllPrompts", {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
setPrompts(data);
};
useEffect(() => {
console.log("test");
getPrompts();
}, []);
const handleSearchChange = (e) => {
setSearch(e.target.value);
};
const getFilteredPrompts = async () => {
const response = await fetch(`/api/prompt/filterPrompt/${search}`);
const data = await response.json();
setPrompts(data);
};
useEffect(() => {
if (search?.length > 0) {
const timeOut = setTimeout(() => {
getFilteredPrompts();
}, 300);
return () => clearTimeout(timeOut);
} else {
getPrompts();
}
}, [search]);
const handleTagClick = (tag) => {
setSearch(tag);
};
return (
<section className="feed">
<form
className="relative w-full
flex-center"
>
<input
value={search}
onChange={handleSearchChange}
type="text"
placeholder="Search a tag or prompt..."
required
className="search_input peer"
/>
</form>
{prompts?.length > 0 ? (
<PromptCardList
copied={copied}
handleCopiedPrompt={handleCopiedPrompt}
prompts={prompts}
handleTagClick={handleTagClick}
/>
) : null}
</section>
);
};
export default Feed; |
import { useMutation, useQuery } from "react-query";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { toast } from "react-toastify";
import validator from "validator";
import { isValidPhoneNumber } from "react-phone-number-input";
import queryKeys from "../utils/queryKeys";
import { useAppContext } from "./useAppContext";
import { useForm } from "react-formid";
import { useFile } from "./useFile";
import { useState } from "react";
import ProfileImage from "../components/common/profile-image";
import Numeral from "react-numeral";
export const useStudent = () => {
const [searchParams] = useSearchParams();
const page = Number(searchParams.get("page") ?? "1");
const { apiServices, errorHandler, permission, user } =
useAppContext("students");
const [sortedStudents, setSortedStudents] = useState([]);
const [sorted, setSorted] = useState(false);
const [indexStatus, setIndexStatus] = useState(
permission?.read ? "all" : "myStudents"
);
const [session, setSession] = useState("");
const [admissionNumber, setAdmissionNumber] = useState("");
const [classes, setClasses] = useState({ present_class: "", sub_class: "" });
const [sortBy, setSortBy] = useState("");
const { id } = useParams();
const navigate = useNavigate();
const {
handleImageChange,
filePreview,
base64String,
reset: resetFile,
fileRef,
} = useFile();
const {
getFieldProps,
inputs,
setFieldValue,
handleSubmit,
errors,
setInputs,
handleChange,
reset: resetForm,
} = useForm({
defaultValues: {
surname: "",
firstname: "",
middlename: "",
admission_number: "",
genotype: "",
blood_group: "A+",
gender: "female",
dob: "",
nationality: "",
state: "",
session_admitted: "",
class: "",
present_class: "",
sub_class: "",
image: "",
home_address: "",
phone_number: "",
email_address: "",
file: null,
},
validation: {
surname: { required: true },
firstname: { required: true },
middlename: { required: true },
admission_number: { required: true },
genotype: { required: true },
blood_group: { required: true },
gender: { required: true },
dob: { required: true },
nationality: { required: true },
state: { required: true },
session_admitted: { required: true },
class: { required: true },
present_class: { required: true },
home_address: { required: true },
phone_number: {
required: (val) => !!val || "Phone number is required",
isValid: (val) =>
(typeof val === "string" && isValidPhoneNumber(val)) ||
"Phone number is invalid",
},
email_address: {
required: (val) => !!val || "Email address is required",
isValid: (val) => validator.isEmail(val) || "Email address is invalid",
},
},
});
const reset = () => {
resetFile();
resetForm();
};
const handleSortBy = ({ target: { value } }) => {
setSortBy(value);
};
const {
isLoading: studentListLoading,
data: students,
refetch: refetchStudents,
} = useQuery(
[queryKeys.GET_ALL_STUDENTS, page],
() => apiServices.getAllStudents(page),
{
enabled: permission?.read || false,
retry: 3,
onError(err) {
errorHandler(err);
},
select: (data) => {
const format = apiServices.formatData(data)?.map((student) => {
return {
...student,
image: (
<ProfileImage src={student?.image} wrapperClassName="mx-auto" />
),
};
});
return { ...data, data: format };
},
}
);
const { data: studentByClassAndSession, isLoading: studentByClassLoading } =
useQuery(
[
queryKeys.GET_STUDENTS_BY_ATTENDANCE,
user?.class_assigned,
user?.session,
],
() =>
apiServices.getStudentByClassAndSession(
user?.class_assigned,
user?.session
),
{
enabled: permission?.myStudents || false,
select: apiServices.formatData,
onError(err) {
errorHandler(err);
},
}
);
const { isLoading: studentDebtorsListLoading, data: studentDebtors } =
useQuery(
[queryKeys.GET_ALL_STUDENTS_DEBTORS],
apiServices.getAllStudentDebtors,
{
enabled: permission?.readDebtors || false,
retry: 3,
onError(err) {
errorHandler(err);
},
select: (data) => {
return apiServices.formatData(data)?.map((data) => ({
...data,
amount_due: (
<>
₦
<Numeral value={data.amount_due || "0"} format="0,0.00" />
</>
),
amount_paid: (
<>
₦
<Numeral value={data.amount_paid || "0"} format="0,0.00" />
</>
),
total_amount: (
<>
₦
<Numeral value={data.total_amount || "0"} format="0,0.00" />
</>
),
}));
},
}
);
const { isLoading: studentCreditorsListLoading, data: studentCreditors } =
useQuery(
[queryKeys.GET_ALL_STUDENTS_CREDITORS],
apiServices.getAllStudentCreditors,
{
enabled: permission?.readCreditors || false,
retry: 3,
onError(err) {
errorHandler(err);
},
select: (data) => {
return apiServices.formatData(data)?.map((data) => ({
...data,
amount_due: (
<>
₦
<Numeral value={data.amount_due || "0"} format="0,0.00" />
</>
),
amount_paid: (
<>
₦
<Numeral value={data.amount_paid || "0"} format="0,0.00" />
</>
),
total_amount: (
<>
₦
<Numeral value={data.total_amount || "0"} format="0,0.00" />
</>
),
}));
},
}
);
const { mutateAsync: addStudent, isLoading: addStudentLoading } = useMutation(
apiServices.addStudent,
{
onSuccess() {
toast.success("Student has been added successfully");
reset();
},
onError(err) {
errorHandler(err);
},
}
);
const { mutateAsync: updateStudent, isLoading: updateStudentLoading } =
useMutation(apiServices.updateStudent, {
onSuccess() {
toast.success("Student has been updated successfully");
},
onError(err) {
errorHandler(err);
},
});
const { mutateAsync: deleteStudent } = useMutation(
apiServices.deleteStudent,
{
onSuccess() {
toast.success("Student has been deleted successfully");
refetchStudents();
},
onError(err) {
errorHandler(err);
},
}
);
const { isLoading: getStudentBySessionLoading } = useQuery(
[queryKeys.GET_ALL_STUDENTS_BY_SESSION, session],
() => apiServices.getStudentBySession(session),
{
enabled: !!session && permission?.sortSession,
onError(err) {
errorHandler(err);
setSession("");
},
onSuccess(data) {
const format = apiServices.formatData(data)?.map((student) => {
return {
...student,
image: (
<ProfileImage src={student?.image} wrapperClassName="mx-auto" />
),
};
});
setSession("");
setSortedStudents(format);
setIndexStatus("all");
setSorted(true);
},
}
);
const { isLoading: getStudentByAdmissionNumberLoading } = useQuery(
[queryKeys.GET_ALL_STUDENTS_BY_ADMISSION_NUMBER, admissionNumber],
() => apiServices.getStudentByAdmissionNumber(admissionNumber),
{
enabled: !!admissionNumber && permission?.sortAdmissionNumber,
onError(err) {
errorHandler(err);
setAdmissionNumber("");
},
onSuccess(data) {
const format = apiServices.formatData(data)?.map((student) => {
return {
...student,
image: (
<ProfileImage src={student?.image} wrapperClassName="mx-auto" />
),
};
});
setAdmissionNumber("");
setSortedStudents(format);
setIndexStatus("all");
setSorted(true);
},
}
);
const { isLoading: getStudentByClassLoading } = useQuery(
[
queryKeys.GET_ALL_STUDENTS_BY_CLASS,
classes.present_class,
classes.sub_class,
],
() => apiServices.getStudentByClass(classes),
{
enabled: !!classes.present_class && permission?.sortStudentByClass,
onError(err) {
errorHandler(err);
setClasses({ present_class: "", sub_class: "" });
},
onSuccess(data) {
const format = apiServices.formatData(data)?.map((student) => {
return {
...student,
image: (
<ProfileImage src={student?.image} wrapperClassName="mx-auto" />
),
};
});
setClasses({ present_class: "", sub_class: "" });
setSortedStudents(format);
setIndexStatus("all");
setSorted(true);
},
}
);
const { mutateAsync: withdrawStudent, isLoading: withdrawStudentLoading } =
useMutation(apiServices.withdrawStudent, {
onSuccess() {
toast.success("Student has been withdrawn");
},
onError(err) {
errorHandler(err);
},
});
const { mutateAsync: acceptStudent, isLoading: acceptStudentLoading } =
useMutation(apiServices.acceptStudent, {
onSuccess() {
toast.success("Student has been accepted");
},
onError(err) {
errorHandler(err);
},
});
const { mutateAsync: transferStudent, isLoading: transferStudentLoading } =
useMutation(apiServices.transferStudent, {
onSuccess() {
toast.success("Student has been transferred");
},
onError(err) {
errorHandler(err);
},
});
const { mutateAsync: promoteStudent, isLoading: promoteStudentLoading } =
useMutation(apiServices.promoteStudent, {
onSuccess() {
toast.success("Student has been promoted");
},
onError(err) {
errorHandler(err);
},
});
const { mutateAsync: postHealthReport, isLoading: postHealthReportLoading } =
useMutation(apiServices.postHealthReport, {
onSuccess() {
toast.success("Health report has been created");
},
onError(err) {
errorHandler(err);
},
});
const {
mutateAsync: postCommunicationBook,
isLoading: postCommunicationBookLoading,
} = useMutation(apiServices.postCommunicationBook, {
onSuccess() {
toast.success("Record has been created");
},
onError(err) {
errorHandler(err);
},
});
const { isLoading: getStudentLoading, data: singleStudent } = useQuery(
[queryKeys.GET_STUDENT, id],
() => apiServices.getStudent(id),
{
retry: 3,
onError(err) {
errorHandler(err);
},
enabled: !!id,
select: apiServices.formatSingleData,
}
);
const { isLoading: alumniLoading, data: graduatedStudents } = useQuery(
[queryKeys.GET_GRADUATED_STUDENTS],
apiServices.getAlumniList,
{
retry: 3,
enabled: permission?.alumni,
select: (data) => {
return apiServices.formatData(data)?.map((student) => {
return {
...student,
image: (
<ProfileImage src={student?.image} wrapperClassName="mx-auto" />
),
};
});
},
onError(err) {
errorHandler(err);
},
}
);
const {
isLoading: studentLoginDetailsLoading,
data: studentLoginDetailsStudents,
} = useQuery(
[queryKeys.GET_STUDENT_LOGIN_DETAILS, page],
() => apiServices.getStudentLoginDetails(page),
{
retry: 3,
enabled: permission?.studentLoginDetails,
onError(err) {
errorHandler(err);
},
}
);
const { isLoading: communicationListLoading, data: communicationList } =
useQuery(
[queryKeys.GET_COMMUNICATION_BOOK],
apiServices.getCommunicationBook,
{
retry: 3,
enabled: permission?.communication ?? false,
select: apiServices.formatData,
onError(err) {
errorHandler(err);
},
}
);
const { mutate: graduateStudent, isLoading: graduateStudentLoading } =
useMutation(apiServices.graduateStudent, {
onSuccess() {
toast.success("Student is now an alumni");
navigate("/app/students");
},
onError(err) {
errorHandler(err);
},
});
const { mutate: postBusRouting, isLoading: postBusRoutingLoading } =
useMutation(apiServices.postBusRouting, {
onSuccess() {
toast.success("Student is now an alumni");
navigate("/app/students");
},
onError(err) {
errorHandler(err);
},
});
const handleUpdateStudent = async (data) => await updateStudent(data);
const handleDeleteStudent = async (data) => await deleteStudent(data);
const isLoading =
studentListLoading ||
addStudentLoading ||
updateStudentLoading ||
getStudentLoading ||
getStudentBySessionLoading ||
withdrawStudentLoading ||
studentDebtorsListLoading ||
studentCreditorsListLoading ||
getStudentByAdmissionNumberLoading ||
studentByClassLoading ||
graduateStudentLoading ||
alumniLoading ||
getStudentByClassLoading ||
studentLoginDetailsLoading ||
acceptStudentLoading ||
transferStudentLoading ||
promoteStudentLoading ||
postHealthReportLoading ||
postBusRoutingLoading ||
communicationListLoading ||
postCommunicationBookLoading;
return {
user,
isLoading,
students,
getFieldProps,
inputs,
setFieldValue,
handleSubmit,
errors,
setInputs,
handleChange,
isEdit: !!id,
handleImageChange,
filePreview,
base64String,
resetFile,
fileRef,
addStudent,
setSession,
sortedStudents,
withdrawStudent,
sorted,
setSorted,
indexStatus,
setIndexStatus,
studentDebtors,
studentCreditors,
permission,
handleSortBy,
sortBy,
setSortBy,
setAdmissionNumber,
setClasses,
studentByClassAndSession,
graduatedStudents,
graduateStudent,
studentLoginDetailsStudents,
acceptStudent,
transferStudent,
promoteStudent,
postHealthReport,
apiServices,
postBusRouting,
communicationList,
postCommunicationBook,
onDeleteStudent: handleDeleteStudent,
onUpdateStudent: handleUpdateStudent,
studentData: singleStudent,
};
}; |
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require("fs");
const cli = Object.freeze({
// commands
CERT_ANY: {
cmd: ["--certificates", "-c"],
desc: "Create all needed certificates",
},
CERT_SERVICE: {
cmd: ["--service", "-s"],
desc: "Only create server certificate",
},
CERT_USER: { cmd: ["--user", "-u"], desc: "Only create client certificates" },
LAN_HOST: { cmd: ["--host", "-h"], desc: "Display host ip information" },
});
function showUsage(name: string, version: string) {
console.log(`\n${name} ${version}`);
const tab = 10;
console.log(`\nUsage:`);
const node = "node ./node_modules";
console.log(`${" ".repeat(tab - 5)}${node}/${name} [command] [option]`);
console.log(`\nExample:`);
const serviceEx = `${name}`;
console.log(
`${" ".repeat(tab - 5)}${node}/${serviceEx}${" ".repeat(
30 - serviceEx.length
)} start service`
);
const clientEx = `${name} -u`;
console.log(
`${" ".repeat(tab - 5)}${node}/${clientEx}${" ".repeat(
30 - clientEx.length
)} create user certs`
);
const hostEx = `${name} -h`;
console.log(
`${" ".repeat(tab - 5)}${node}/${hostEx}${" ".repeat(
30 - hostEx.length
)} display hostname and ip`
);
console.log("\nCommands:");
void import("./utils/console.js")
.then(({ bold }) => {
Object.values(cli).forEach((commands) => {
const tab = 10;
if ("cmd" in commands) {
const cmd = commands.cmd.join("\n" + " ".repeat(tab - 5));
console.log(
`${" ".repeat(tab - 5)}${bold(cmd)}\n${" ".repeat(tab)}${
commands.desc
}`
);
}
});
})
.then(() => {
process.exit();
});
}
function getPkgRoot() {
let pkgRoot;
switch (true) {
case process.argv[1].endsWith("/dist/cjs/"):
pkgRoot = process.argv[1].replace("/dist/cjs/", "");
break;
case process.argv[1].endsWith("/dist/cjs"):
pkgRoot = process.argv[1].replace("/dist/cjs", "");
break;
case process.argv[1].endsWith("/dist/cjs/index.js"):
pkgRoot = process.argv[1].replace("/dist/cjs/index.js", "");
break;
case process.argv[1].endsWith("@nmemonica/utils"):
pkgRoot = process.argv[1];
break;
default:
throw new Error("Unexpected cwd");
}
return pkgRoot;
}
void import("./src/app.js").then(({ default: startService }) => {
if (
(require.main?.loaded === true &&
require.main.filename === `${process.argv[1]}/index.cjs`) ||
(require.main?.loaded === true &&
require.main.filename === `${process.argv[1]}index.cjs`) ||
(require.main?.loaded === true &&
require.main.filename === `${process.argv[1]}/dist/cjs/index.cjs`) ||
(require.main?.loaded === true &&
require.main.filename === `${process.argv[1]}`)
) {
// running from cli
switch (process.argv[2]) {
case cli.CERT_ANY.cmd[0]:
case cli.CERT_ANY.cmd[1]:
void import("./utils/signed-ca.js").then(({ ca }) => {
// running from cli
void ca
.get()
.then(() => {
console.log("CA already exists");
})
.catch(() => {
return ca.createNeeded();
})
.then(() => {
process.exit();
});
});
break;
case cli.CERT_SERVICE.cmd[0]:
case cli.CERT_SERVICE.cmd[1]:
void import("./utils/signed-ca.js").then(({ ca }) =>
ca.createServer().then(() => {
process.exit();
})
);
break;
case cli.CERT_USER.cmd[0]:
case cli.CERT_USER.cmd[1]:
void import("./utils/signed-ca.js").then(({ ca }) =>
ca.createClient().then(() => {
process.exit();
})
);
break;
case cli.LAN_HOST.cmd[0]:
case cli.LAN_HOST.cmd[1]:
void import("./utils/host.js").then(({ lan }) => {
console.log(JSON.stringify(lan));
});
break;
case undefined:
startService();
break;
default:
{
console.log(`\nUnknown flag '${process.argv[2]}'`);
const { name, version } = JSON.parse(
fs.readFileSync(getPkgRoot() + "/package.json", {
encoding: "utf-8",
}) as string
) as { name: string; version: string };
showUsage(name, version);
}
break;
}
}
}); |
import {Component, OnInit} from '@angular/core';
import {MatDialog} from '@angular/material';
import {Router} from '@angular/router';
import {map} from 'rxjs/operators';
import {AppSharedService} from '../../../../../shared/services/app-shared.service';
import {PageChangeEvent} from '../../../../../shared/models/page-change-event.model';
import {configs} from '../../../../../shared/configs';
import {UserService} from '../services/user.service';
import {User} from '../models/user.model';
import {ModalComponent} from '../../../../../shared/components/modal/modal.component';
import {ApiError} from '../../../../../shared/models/api-error.model';
@Component({
selector: 'app-list-user',
templateUrl: './list-user.component.html',
styleUrls: ['./list-user.component.css']
})
export class ListUserComponent implements OnInit {
users: User[];
constructor(private sharedService: AppSharedService,
private userService: UserService,
private router: Router,
private dialog: MatDialog) {
sharedService.emitPageChange(
new PageChangeEvent(configs.breadcrumb.sections.users, configs.breadcrumb.subSections.list));
}
ngOnInit(): void {
this.loadUsers();
}
goToAddUser(): void {
this.router.navigate(['users/add']);
}
goToEditUser(id: string): void {
this.router.navigate([`users/edit/${id}`]);
}
onDeleteUserClick(id: string): void {
const dialogRef = this.dialog.open(ModalComponent, {
height: configs.constants.modalHeight,
width: configs.constants.modalWidth,
data: {title: 'Delete', message: 'Are you sure you want to delete this user?'}
});
dialogRef.afterClosed().subscribe(result => {
if (result && result.isCallback) {
this.userService.delete(id)
.subscribe(() => {
const user = this.users.find(u => u.id === id);
this.users.splice(this.users.indexOf(user), 1);
},
(error: ApiError) => {
alert(error.errorMessage);
});
}
});
}
private loadUsers() {
this.userService.getAll()
.pipe(
map((users: User[]) => {
this.users = users;
})
)
.subscribe();
}
} |
import { AbstractControl, NG_VALIDATORS, ValidationErrors, Validator } from '@angular/forms';
export class CpfCnpjValidator implements Validator {
static cpfLength = 11;
static cnpjLength = 14;
/**
* Calcula o dígito verificador do CPF ou CNPJ.
*/
static buildDigit(arr: number[]): number {
const isCpf = arr.length < CpfCnpjValidator.cpfLength;
const digit = arr
.map((val, idx) => val * ((!isCpf ? idx % 8 : idx) + 2))
.reduce((total, current) => total + current) % CpfCnpjValidator.cpfLength;
if (digit < 2 && isCpf) {
return 0;
}
return CpfCnpjValidator.cpfLength - digit;
}
/**
* Valida um CPF ou CNPJ de acordo com seu dígito verificador.
*/
static validate(c: AbstractControl): ValidationErrors | null {
if (!(c || c.value)) {
return { value: true };
}
const cpfCnpj = c.value.replace(/\D/g, '');
// Verifica o tamanho da string. CpfCnpjValidator.cpfLength
if ([CpfCnpjValidator.cnpjLength].indexOf(cpfCnpj.length) < 0) {
return { length: true };
}
// Verifica se todos os dígitos são iguais.
if (/^([0-9])\1*$/.test(cpfCnpj)) {
return { equalDigits: true };
}
// A seguir é realizado o cálculo verificador.
// const cpfCnpjArr: number[] = cpfCnpj.split('').reverse().slice(2);
// cpfCnpjArr.unshift(CpfCnpjValidator.buildDigit(cpfCnpjArr));
// cpfCnpjArr.unshift(CpfCnpjValidator.buildDigit(cpfCnpjArr));
// if (cpfCnpj !== cpfCnpjArr.reverse().join('')) {
// // Dígito verificador não é válido, resultando em falha.
// return { digit: true };
// }
return null;
}
/**
* Implementa a interface de um validator.
*/
validate(c: AbstractControl): ValidationErrors | null {
return CpfCnpjValidator.validate(c);
}
} |
import Fastify, { FastifyInstance } from 'fastify';
import { PreparedRoute } from 'lib/Router/prepareRoutes';
import { validate as validateCommon } from 'schemas/main';
import { COOKIE_SECRET, SERVER_ADDRESS } from '../../config/application';
import { Context, HttpStatusCodes, RouteParams } from './types';
import { auth } from '../../plugins/auth';
interface AdapterProps {
routes: PreparedRoute[];
}
class Adapter {
private server: FastifyInstance;
private routes: PreparedRoute[];
constructor({ routes }: AdapterProps) {
this.routes = routes;
this.server = Fastify({
logger: true,
});
this.server.register(import('@fastify/formbody'));
this.server.register(import('@fastify/cookie'), {
secret: COOKIE_SECRET,
});
this.server.register(import('@fastify/csrf-protection'), {
cookieOpts: { signed: true },
});
this.server.register(import('@fastify/multipart'), {
addToBody: true,
});
// TODO: Add setup cors to config
this.server.register(import('@fastify/cors'));
this.server.register(import('@fastify/swagger'));
this.server.register(auth);
this.prepareRoutes();
}
prepareRoutes = (): void => {
this.routes.forEach(async ({ path, importPath }) => {
const currentRoute: { default: RouteParams[] } = await import(importPath);
if (currentRoute.default?.length) {
this.prepareRoute(currentRoute.default, path);
} else {
this.logError(importPath);
}
});
};
prepareRoute = (currentRoute: RouteParams[], path: string) => {
currentRoute.forEach(({ handler, schema, method, config }) => {
this.server.route({
method,
url: path,
config,
handler: async function (request, reply) {
const {
body,
headers,
params,
cookies,
query,
ip,
method,
url,
routerPath,
routerMethod,
} = request;
const validateRequest = validateCommon(schema);
if (
!validateRequest({
body,
params,
headers,
cookies,
query,
})
) {
const { errors } = validateRequest;
return reply.status(HttpStatusCodes.BadRequest).send({
errors,
});
}
const bindedHandler = handler.bind(this as Context);
const {
status,
body: replyBody,
headers: replyHeaders,
cookies: replyCookies,
} = await bindedHandler({
headers,
query,
body,
params,
cookies,
payload: {
ip,
routerPath,
routerMethod,
url,
method,
},
});
replyCookies?.forEach(({ name, path, value = '', action }) => {
reply[action](name, value, {
httpOnly: true,
path,
});
});
replyHeaders && reply.headers(replyHeaders);
reply.status(status).send(replyBody);
},
});
});
};
logError = (importPath: string) => {
console.error({
path: importPath,
message: `Please, check ${importPath}. It should be array of objects`,
});
};
start = async (port: number): Promise<void> => {
try {
await this.server.listen({
port,
host: SERVER_ADDRESS,
});
} catch (err) {
this.server.log.error(err);
process.exit(1);
}
};
}
export default Adapter; |
from django.contrib import admin
from .models import Post, Comments
from django_summernote.admin import SummernoteModelAdmin
@admin.register(Post)
class PostAdmin(SummernoteModelAdmin):
list_filter = ('status', 'created_on')
list_display = ('title', 'slug', 'status', 'created_on')
search_fields = ['title', 'content']
prepopulated_fields = {'slug': ('title',)}
summernote_fields = ('content',)
@admin.register(Comments)
class CommentsAdmin(admin.ModelAdmin):
list_filter = ('approved', 'created_on')
list_display = ('name', 'body', 'post', 'created_on', 'approved')
search_fields = ('name', 'email', 'body')
actions = ['approve_comments']
def approve_comments(self, request, queryset):
queryset.update(approved=True) |
When setting up and running a crypto exchange using the Codono source code, it's essential to consider specific security measures to ensure the safety of users' funds and data. Here are the top 10 things to avoid for a crypto exchange built on the Codono platform:
1. **Avoid Using Weak or Default Passwords**: Ensure that all user passwords, admin credentials, and API keys are strong and not set to default values.
2. **Avoid Storing Private Keys on the Server**: Private keys for users' crypto wallets should never be stored on the server. Use hardware wallets or other secure methods for key management.
3. **Avoid Using Insecure APIs**: Carefully vet and secure all APIs used for external integrations, such as price feeds and payment gateways, to prevent potential vulnerabilities.
4. **Avoid Ignoring Cold Storage**: Implement a cold storage solution for storing a significant portion of users' crypto assets offline to prevent hacking attempts.
5. **Avoid Overlooking KYC and AML Compliance**: Implement robust Know Your Customer (KYC) and Anti-Money Laundering (AML) procedures to prevent fraud and illegal activities on the exchange.
6. **Avoid Insufficient Security Audits**: Regularly conduct security audits, penetration tests, and code reviews to identify and fix vulnerabilities in the exchange.
7. **Avoid Neglecting Server Security**: Secure the server environment with firewalls, intrusion detection systems, and regular security updates to prevent unauthorized access.
8. **Avoid Allowing Weak or No Two-Factor Authentication**: Enable two-factor authentication (2FA) for all user accounts to add an extra layer of security.
9. **Avoid Exposing Sensitive Data**: Ensure that sensitive data, such as transaction details and user balances, is not exposed to unauthorized users.
10. **Avoid Delaying Security Updates**: Promptly apply security patches and updates to the Codono source code and all related libraries to address any known vulnerabilities.
By avoiding these pitfalls and taking a proactive approach to security, you can enhance the safety of your crypto exchange and build trust among users, ultimately contributing to the success of your platform. |
import {View, Text, TextInput, Pressable, Image} from 'react-native';
import React, {useState} from 'react';
import {styles} from './styles';
import EyeIcon from '../../../assets/eye.png';
import EyeIconClose from '../../../assets/eye_closed.png';
const Input = ({label, placeholder, isPassword, value, onChangeText}) => {
const [isPasswordVisible, setPasswordVisible] = useState(false);
const toggleEyeIcon = () => {
setPasswordVisible(!isPasswordVisible);
};
return (
<View style={styles.container}>
<Text style={styles.label}>{label}</Text>
<View style={styles.inputContainer}>
<TextInput
maxLength={isPassword ? 6 : 30}
value={value}
onChangeText={onChangeText}
style={styles.input}
secureTextEntry={isPassword && !isPasswordVisible}
placeholder={placeholder}
/>
{isPassword ? (
<Pressable onPress={toggleEyeIcon}>
<Image
style={styles.eyeIcon}
source={isPasswordVisible ? EyeIcon : EyeIconClose}
/>
</Pressable>
) : null}
</View>
</View>
);
};
export default React.memo(Input); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Create Product</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
table {
border-collapse: collapse; /* Menggabungkan border */
width: 100%; /* Menentukan lebar tabel */
}
th,
td {
border: 1px solid #ddd; /* Menambahkan border pada setiap sel */
padding: 8px; /* Menambahkan padding di dalam sel */
}
th {
background-color: #f2f2f2; /* Memberikan warna latar belakang pada header */
text-align: left; /* Menyetel teks agar rata kiri */
}
</style>
</head>
<body>
<header class="bg-white flex justify-between items-center p-4 shadow">
<div>
<h1 class="text-3xl">Simple header</h1>
</div>
<div>
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Home
</button>
<button class="bg-transparent hover:text-blue-700 text-blue-500 font-semibold py-2 px-4 rounded">
Features
</button>
<button class="bg-transparent hover:text-blue-700 text-blue-500 font-semibold py-2 px-4 rounded">
Pricing
</button>
<button class="bg-transparent hover:text-blue-700 text-blue-500 font-semibold py-2 px-4 rounded">
FAQs
</button>
<button class="bg-transparent hover:text-blue-700 text-blue-500 font-semibold py-2 px-4 rounded">
Pricing
</button>
</div>
</header>
<div class="container mx-auto">
<div class="flex justify-center mt-4">
<img src="./assets/Tailwind_CSS_Logo.svg.png" alt="" />
</div>
<div class="flex flex-col items-center">
<h1 class="text-3xl py-4">Create Product</h1>
<p class="pb-4 text-center">
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Minus quidem
ipsum facere alias itaque animi dicta natus. Eos quasi sed corporis ex
voluptas commodi assumenda maxime maiores ab culpa reiciendis dicta
numquam a molestiae nesciunt placeat necessitatibus cum, ullam
delectus ad praesentium, provident vel! Sed rem nemo consequuntur
natus incidunt?
</p>
</div>
<div class="px-10 mx-10 mb-10">
<form id="formCreateProduct">
<h1 class="text-2xl">Detail Product</h1>
<div class="flex flex-col py-2">
<label for="" class="pb-1">Product Name</label>
<input type="text" name="ProductName" id="productName" class="w-1/2 px-4 py-2 rounded-md border border-gray-300 outline-none focus:border-gray-400"/>
<small id="productNameError" class="error"></small>
</div>
<div class="flex flex-col py-2">
<label for="" class="pb-1">Product Category</label>
<select class="w-1/3 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded-md leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="productCategory">
<option></option>
<option>Pakaian</option>
<option>Alat Tulis</option>
</select>
</div>
<div class="flex flex-col py-2">
<div class="flex flex-col py-2">
<label for="">Product Freshness</label>
<select class="w-1/3 border border-gray-200 text-gray-700 py-3 px-4 pr-8 rounded-md leading-tight focus:outline-none focus:bg-white focus:border-gray-500" id="productFreshness">
<option></option>
<option>New</option>
<option>Refurbished</option>
</select>
</div>
<label for="description" class="pt-1">Additional Description</label>
<div class="mt-2">
<textarea id="about" name="about" rows="3" class="block w-full rounded-md border border-gray-300 p-3 text-gray-900 shadow-sm">
</textarea>
</div>
</div>
<div class="flex flex-col py-2">
<label for="price">Product Price :</label>
<input type="text" name="ProductPrice" id="productPrice" placeholder="Rp 100.000" class="border border-gray-300 p-2 rounded-md"/>
<small id="productPriceError" class="error"></small>
</div>
<div class="flex justify-center mt-2 pb-10">
<button id="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded w-full">
Submit
</button>
</div>
</form>
<div>
<table id="tableData">
</table>
</div>
</div>
</div>
<script>
const form = document.getElementById('formCreateProduct');
const tableBody = document.getElementById('tableData'); // Assuming you have a table with an ID of 'tableData'
let headerAdded = false;
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent default form submission
const productName = document.getElementById('productName').value;
const productCategory = document.getElementById('productCategory').value;
const productFreshness = document.getElementById('productFreshness').value;
const productDescription = document.getElementById('about').value;
const productPrice = document.getElementById('productPrice').value;
// Validate data (optional)
// You can add validation logic here to ensure required fields are filled and data is in the correct format
const checkProductName = () => {
const value = productNameElement.value;
const symbolPattern = /[!@#$%^&*(),.?":{}|<>]/;
console.log(value.length);
if (value.length === 0) {
alert("Product Name Kosong");
} else if (value.length > 5 ) {
alert("Product Name Terlalu Panjang")
} else if (symbolPattern.test(value)) {
alert("Product Name tidak boleh mengandung karakter simbol");
}
};
// Validasi Product Price
const checkProductPrice = () => {
const value = productPriceElement.value;
if (value.length < 4) {
alert("Product Price Terlalu Pendek");
console.log(value);
}
};
// Create table row elements
const headerRow = document.createElement("tr");
const nameHeader = document.createElement("th");
const categoryHeader = document.createElement("th");
const freshnessHeader = document.createElement("th");
const descriptionHeader = document.createElement("th");
const priceHeader = document.createElement("th");
const tableRow = document.createElement('tr');
const nameCell = document.createElement('td');
const categoryCell = document.createElement('td');
const freshnessCell = document.createElement('td');
const descriptionCell = document.createElement('td');
const priceCell = document.createElement('td');
if (!headerAdded) {
const headerRow = document.createElement("tr");
const nameHeader = document.createElement("th");
const categoryHeader = document.createElement("th");
const freshnessHeader = document.createElement("th");
const descriptionHeader = document.createElement("th");
const priceHeader = document.createElement("th");
// Set cell content
nameHeader.textContent = "Product Name";
categoryHeader.textContent = "Product Category"
freshnessHeader.textContent = "Product Freshness"
descriptionHeader.textContent = "Product Description";
priceHeader.textContent = "Product Price";
// Append cells to the table row
headerRow.appendChild(nameHeader);
headerRow.appendChild(categoryHeader);
headerRow.appendChild(freshnessHeader);
headerRow.appendChild(descriptionHeader);
headerRow.appendChild(priceHeader);
tableBody.appendChild(headerRow);
// Append the table row to the table body
tableBody.appendChild(tableRow);
headerAdded = true; // Set flag to prevent further header creation
}
nameCell.textContent = productName;
categoryCell.textContent = productCategory;
freshnessCell.textContent = productFreshness;
descriptionCell.textContent = productDescription;
priceCell.textContent = productPrice;
tableRow.appendChild(nameCell);
tableRow.appendChild(categoryCell);
tableRow.appendChild(freshnessCell);
tableRow.appendChild(descriptionCell);
tableRow.appendChild(priceCell);
tableBody.appendChild(tableRow);
// Clear form (optional)
// You can uncomment the following line to clear the form after submission
// form.reset();
});
</script>
</body>
</html> |
// Copyright 2021 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only
import { assert } from 'chai';
import dataInterface from '../../sql/Client';
import { UUID } from '../../types/UUID';
import type { UUIDStringType } from '../../types/UUID';
import type { MessageAttributesType } from '../../model-types.d';
const {
removeAll,
_getAllMessages,
saveMessages,
saveMessage,
searchMessages,
} = dataInterface;
function getUuid(): UUIDStringType {
return UUID.generate().toString();
}
describe('sql/fullTextSearch', () => {
beforeEach(async () => {
await removeAll();
});
it('returns messages matching query', async () => {
assert.lengthOf(await _getAllMessages(), 0);
const now = Date.now();
const conversationId = getUuid();
const ourUuid = getUuid();
const message1: MessageAttributesType = {
id: getUuid(),
body: 'message 1 - generic string',
type: 'outgoing',
conversationId,
sent_at: now - 20,
received_at: now - 20,
timestamp: now - 20,
};
const message2: MessageAttributesType = {
id: getUuid(),
body: 'message 2 - unique string',
type: 'outgoing',
conversationId,
sent_at: now - 10,
received_at: now - 10,
timestamp: now - 10,
};
const message3: MessageAttributesType = {
id: getUuid(),
body: 'message 3 - generic string',
type: 'outgoing',
conversationId,
sent_at: now,
received_at: now,
timestamp: now,
};
await saveMessages([message1, message2, message3], {
forceSave: true,
ourUuid,
});
assert.lengthOf(await _getAllMessages(), 3);
const searchResults = await searchMessages('unique');
assert.lengthOf(searchResults, 1);
assert.strictEqual(searchResults[0].id, message2.id);
message3.body = 'message 3 - unique string';
await saveMessage(message3, { ourUuid });
const searchResults2 = await searchMessages('unique');
assert.lengthOf(searchResults2, 2);
assert.strictEqual(searchResults2[0].id, message3.id);
assert.strictEqual(searchResults2[1].id, message2.id);
});
it('excludes messages with isViewOnce = true', async () => {
assert.lengthOf(await _getAllMessages(), 0);
const now = Date.now();
const conversationId = getUuid();
const ourUuid = getUuid();
const message1: MessageAttributesType = {
id: getUuid(),
body: 'message 1 - unique string',
type: 'outgoing',
conversationId,
sent_at: now - 20,
received_at: now - 20,
timestamp: now - 20,
};
const message2: MessageAttributesType = {
id: getUuid(),
body: 'message 2 - unique string',
type: 'outgoing',
conversationId,
sent_at: now - 10,
received_at: now - 10,
timestamp: now - 10,
isViewOnce: true,
};
const message3: MessageAttributesType = {
id: getUuid(),
body: 'message 3 - generic string',
type: 'outgoing',
conversationId,
sent_at: now,
received_at: now,
timestamp: now,
isViewOnce: true,
};
await saveMessages([message1, message2, message3], {
forceSave: true,
ourUuid,
});
assert.lengthOf(await _getAllMessages(), 3);
const searchResults = await searchMessages('unique');
assert.lengthOf(searchResults, 1);
assert.strictEqual(searchResults[0].id, message1.id);
message1.body = 'message 3 - unique string';
await saveMessage(message3, { ourUuid });
const searchResults2 = await searchMessages('unique');
assert.lengthOf(searchResults2, 1);
assert.strictEqual(searchResults2[0].id, message1.id);
});
it('excludes messages with storyId !== null', async () => {
assert.lengthOf(await _getAllMessages(), 0);
const now = Date.now();
const conversationId = getUuid();
const ourUuid = getUuid();
const message1: MessageAttributesType = {
id: getUuid(),
body: 'message 1 - unique string',
type: 'outgoing',
conversationId,
sent_at: now - 20,
received_at: now - 20,
timestamp: now - 20,
};
const message2: MessageAttributesType = {
id: getUuid(),
body: 'message 2 - unique string',
type: 'outgoing',
conversationId,
sent_at: now - 10,
received_at: now - 10,
timestamp: now - 10,
storyId: getUuid(),
};
const message3: MessageAttributesType = {
id: getUuid(),
body: 'message 3 - generic string',
type: 'outgoing',
conversationId,
sent_at: now,
received_at: now,
timestamp: now,
storyId: getUuid(),
};
await saveMessages([message1, message2, message3], {
forceSave: true,
ourUuid,
});
assert.lengthOf(await _getAllMessages(), 3);
const searchResults = await searchMessages('unique');
assert.lengthOf(searchResults, 1);
assert.strictEqual(searchResults[0].id, message1.id);
message1.body = 'message 3 - unique string';
await saveMessage(message3, { ourUuid });
const searchResults2 = await searchMessages('unique');
assert.lengthOf(searchResults2, 1);
assert.strictEqual(searchResults2[0].id, message1.id);
});
}); |
import prismadb from "@/lib/prismadb";
import { auth } from "@clerk/nextjs";
import { NextResponse } from "next/server";
export async function GET(
req: Request,
{
params,
}: {
params: { productId: string };
}
) {
try {
if (!params.productId) {
return new NextResponse("Product id is required", { status: 400 });
}
const product = await prismadb.product.findFirst({
where: {
id: params.productId,
},
include: {
images: true,
category: true,
size: true,
color: true,
},
});
return NextResponse.json(product);
} catch (error) {
console.log("PRODUCT_GET", error);
return new NextResponse("Internal error", { status: 500 });
}
}
export async function DELETE(
req: Request,
{
params,
}: {
params: { productId: string; storeId: string };
}
) {
try {
const { userId } = auth();
if (!userId) {
return new NextResponse("Unauthenticated!", { status: 400 });
}
if (!params.storeId) {
return new NextResponse("Store id is required", { status: 400 });
}
if (!params.productId) {
return new NextResponse("Product id is required", { status: 400 });
}
const store = await prismadb.store.findFirst({
where: {
id: params.storeId,
userId,
},
});
if (!store) {
return new NextResponse("Unauthorized", { status: 405 });
}
const product = await prismadb.product.delete({
where: {
id: params.productId,
},
});
return NextResponse.json(product);
} catch (error) {
console.log("PRODUCT_DELETE", error);
return new NextResponse("Internal error", { status: 500 });
}
}
export async function PATCH(
req: Request,
{
params,
}: {
params: { storeId: string; productId: string };
}
) {
try {
const { userId } = auth();
const body = await req.json();
const {
name,
images,
price,
categoryId,
sizeId,
colorId,
isFeatured,
isArchived,
} = body;
if (!userId) {
return new NextResponse("Unauthenticated!", { status: 400 });
}
if (!name) {
return new NextResponse("Name is required!", { status: 400 });
}
if (!price) {
return new NextResponse("Price is required!", { status: 400 });
}
if (!categoryId) {
return new NextResponse("Category is required!", { status: 400 });
}
if (!colorId) {
return new NextResponse("Color is required!", { status: 400 });
}
if (!sizeId) {
return new NextResponse("Size is required!", { status: 400 });
}
if (!images || !images.length) {
return new NextResponse("Images are required!", { status: 400 });
}
if (!params.storeId) {
return new NextResponse("Store id is required", { status: 400 });
}
const store = await prismadb.store.findFirst({
where: {
id: params.storeId,
userId,
},
});
if (!store) {
return new NextResponse("Unauthorized", { status: 405 });
}
await prismadb.product.update({
where: {
id: params.productId,
},
data: {
name,
price,
categoryId,
colorId,
sizeId,
isArchived,
isFeatured,
storeId: params.storeId,
images: {
deleteMany: {},
},
},
});
const product = await prismadb.product.update({
where: {
id: params.productId,
},
data: {
images: {
createMany: {
data: [...images.map((image: { url: string }) => image)],
},
},
},
});
return NextResponse.json(product);
} catch (error) {
console.log("PRODUCT_PATCH", error);
return new NextResponse("Internal error", { status: 500 });
}
} |
import React, { useEffect, useState, useRef, useCallback } from "react";
import { useSelector } from "react-redux";
import CodeApi from "apis/code-api";
import UnusualApi from "apis/unusual-api";
import SearchFormAll from "views/templates/manager/common/search/SearchFormAll";
console.debug("ManualSearchFormContainer.js");
export default function ManualSearchFormContainer({ onSearchCompany }) {
const now = new Date();
const user = useSelector((state) => state.session.user);
const comCode = user.mgr.groupComCode ? user.mgr.groupComCode : user.mgr.companyComCode;
const [defaultCompanyName, setDefaultCompanyName] = useState("");
const [companyName, setCompanyName] = useState("");
const [companyCode, setCompanyCode] = useState("");
const [deptName, setDeptName] = useState("");
const [deptCode, setDeptCode] = useState("");
const [userName, setUserName] = useState("");
const [userCode, setUserCode] = useState("");
const [startDate, setStartDate] = useState("");
const [endDate, setEndDate] = useState("");
const [opened, setOpened] = useState(false);
const [alertOpened, setAlertOpened] = useState(false);
const [errorMsg, setErrorMsg] = useState("");
let mgrType = "D";
if (user.mgr.companyComCode || user.mgr.groupComCode) mgrType = "I";
const childRef = useRef(null);
const modalOption = {
title: "특이사용자 검색",
okText: "확인",
cancelText: "취소",
};
const dateText = "기준 초과일";
useEffect(() => {
getCodeName(comCode);
}, []);
const getCodeName = async (params) => {
try {
const response = await CodeApi.getCodeList({
params: {
uCodeType: "COM_CODE",
uCodeVal1: comCode,
},
});
setDefaultCompanyName(comCode === "DKG" ? "전체" : response.data.response[0].uCodeName1);
} catch (e) {
console.error(e);
}
};
/**
* 날짜
*/
const startChangeDate = useCallback((e) => {
setStartDate(e.target.value);
}, []);
const endChangeDate = useCallback((e) => {
setEndDate(e.target.value);
}, []);
/**
* 유효성 검사
*/
const validation = () => {
let error = "";
if (!companyCode && !deptCode && !userCode && !startDate && !endDate) {
error = "검색항목을 넣어서 검색해주세요";
}
if (startDate > endDate) {
error = "종료일을 시작일 이전으로 선택해주세요";
}
if (startDate && !endDate) {
error = "검색 종료일자를 선택해주세요";
}
if (!startDate && endDate) {
error = "검색 시작일자를 선택해주세요";
}
// const diff = new Date(endDate).getTime() - new Date(startDate).getTime();
// const currDay = 24 * 60 * 60 * 1000;
// const currMonth = currDay * 30;
// const monthInterval = parseInt(diff / currMonth);
// if (monthInterval > 1) {
// error = "한달 이내로 검색해주세요";
// }
if (error) {
setErrorMsg(error);
openAlertModal();
return false;
}
return true;
};
/**
* Alert 모달 열기
*/
const openAlertModal = () => {
setAlertOpened(true);
};
/**
* Alert 모달 닫기
*/
const closeAlertModal = () => {
setAlertOpened(false);
};
/**
* Alert 확인버튼
*/
const onAlertDialogOkClick = () => {
setAlertOpened(false);
};
/**
* 모달 열기
*/
const openModal = () => {
setOpened(true);
};
/**
* 모달 닫기
*/
const closeModal = () => {
setOpened(false);
};
/**
* 검색 버튼 클릭
*/
const onSearch = async () => {
const valid = validation();
if (valid) {
try {
const response = await UnusualApi.getUnusualAll({
params: {
type: "L",
status: "N",
company: companyCode,
dept: deptCode,
user: userCode,
startDate: startDate,
endDate: endDate,
mgrType: mgrType,
},
});
onSearchCompany(response);
} catch (e) {
console.error(e);
}
}
};
const onClick = () => {
setCompanyName("");
setCompanyCode("");
setDeptName("");
setDeptCode("");
setUserName("");
setUserCode("");
openModal();
};
/**
* 잠금 처리 저장
*/
const onModalOkClick = () => {
const result = childRef.current.getValue();
setCompanyName(result.companyName);
setCompanyCode(result.companyCode);
setDeptName(result.deptName);
setDeptCode(result.deptCode);
setUserName(result.userName);
setUserCode(result.userCode);
setOpened(false);
};
return (
<SearchFormAll
alertOpened={alertOpened}
closeAlertModal={closeAlertModal}
onAlertDialogOkClick={onAlertDialogOkClick}
errorMsg={errorMsg}
defaultCompanyName={defaultCompanyName}
comCode={comCode}
companyName={companyName}
deptName={deptName}
userName={userName}
modalOption={modalOption}
onClick={onClick}
onSearch={onSearch}
opened={opened}
onModalOkClick={onModalOkClick}
onModalClose={closeModal}
startDate={startDate}
startChangeDate={startChangeDate}
endDate={endDate}
endChangeDate={endChangeDate}
dateText={dateText}
ref={childRef}
/>
);
} |
clc;
N = 64;
fs = 64000;
f1 = 3300;
f2 = 3700;
ts = 1/fs;
ind = 1;
x = zeros(1, N);
for n = 1:N
m = n - 1;
x(ind) = 8*sin(2*pi*f1*m*ts) + 6*sin(2*pi*f2*m*ts);
ind = ind + 1;
end
X = dft(x, N);
n = (0:N-1);
w_Ham = 0.54 - 0.46*cos(2*pi*n/(N-1));
x_Ham = x .* w_Ham;
X_Dft_Ham = dft(x_Ham, N);
t=0:N-1;
figure(1)
plot(t, x, 'b--o');
grid minor;
title('Time Domain Signal');
xlabel('Time (Sample)');
ylabel('Amplitude');
figure(2)
stem(t, abs(X));
grid minor;
title('Magnitude of DFT');
xlabel('Frequency Bin');
ylabel('Magnitude');
figure(3)
stem(t, w_Ham);
grid minor;
title('Hamming Window');
xlabel('n');
ylabel('Amplitude');
figure(4)
stem(t, x_Ham);
grid minor;
title('Multiplication of Hamming Window and Signal');
xlabel('n');
ylabel('Amplitude');
figure(5)
stem(t, abs(X_Dft_Ham));
grid minor;
title('Magnitude of DFT with Hamming Window');
xlabel('Frequency Bin');
ylabel('Magnitude');
function X = dft(x, N)
X = zeros(1, N);
for k = 0:N-1
X(k+1) = 0;
for n = 0:N-1
X(k+1) = X(k+1) + x(n+1) * exp(-1j* 2 * pi * k * n / N);
end
end
end |
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.licenses.LicenseFormFragment"
>
<data>
<variable
name="viewModel"
type="al.ahgitdevelopment.municion.ui.licenses.LicenseFormViewModel"
/>
</data>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/form_layout_margin"
>
<!--LICENSE NAME-->
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/form_license_name"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/form_fields_separation"
>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/license_lbl_name"
android:inputType="text|textCapSentences"
/>
</com.google.android.material.textfield.TextInputLayout>
<!--LICENSE NUMBER-->
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/form_license_number"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/form_fields_separation"
>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/license_lbl_number"
android:inputType="text|textCapSentences"
android:maxLength="@integer/max_num_licencia_length"
/>
</com.google.android.material.textfield.TextInputLayout>
<!--ISSUE DATE-->
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/form_license_date_issue"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/form_fields_separation"
>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:hint="@string/license_lbl_issue_date"
android:inputType="none"
android:onClick="@{viewModel::selectIssueDate}"
/>
</com.google.android.material.textfield.TextInputLayout>
<!--EXPIRY DATE-->
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/form_license_date_expiry"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/form_fields_separation"
>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:hint="@string/license_lbl_expiry_date"
android:inputType="none"
android:onClick="@{viewModel::selectExpiryDate}"
/>
</com.google.android.material.textfield.TextInputLayout>
<!--INSURANCE NUMBER-->
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/form_license_insurance_number"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/form_fields_separation"
>
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/license_lbl_insurance_number"
android:inputType="text|textCapSentences"
android:maxLength="@integer/max_poliza_seguro_licencia"
/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
</ScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/form_license_fab_save"
android:layout_width="wrap_content"
style="@style/FloatingActionButton"
android:layout_height="wrap_content"
android:onClick="@{viewModel::fabSaveLicenseClicked}"
app:srcCompat="@drawable/ic_save"
/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout> |
import 'package:cineverse/core/global/colors.dart';
import 'package:cineverse/core/global/fonts.dart';
import 'package:cineverse/core/global/global_var.dart';
import 'package:cineverse/core/global/helper.dart';
import 'package:cineverse/core/widget/custom_dialog.dart';
import 'package:cineverse/core/widget/custom_elevatedbutton.dart';
import 'package:cineverse/core/widget/custom_loader.dart';
import 'package:cineverse/core/widget/custom_outline_btn.dart';
import 'package:cineverse/core/widget/scroll_glow_remover.dart';
import 'package:cineverse/feature/changePassword/controller/change_password_controller.dart';
import 'package:cineverse/services/firebase/firebase.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class ChangePasswordView extends GetView<ChangePasswordController> {
const ChangePasswordView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
titleSpacing: 1,
title: Text(
'Change Password',
style: TextStyle(fontFamily: FF.alata),
),
),
body: Container(
margin: const EdgeInsets.all(10),
child: Form(
key: controller.changePasswordFormKey,
child: ScrollGlowRemover(
child: Obx(
() => ListView(children: [
vS(),
Row(
children: [
const Icon(Icons.password),
const SizedBox(
width: 20,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Old Password',
style: TextStyle(fontFamily: FF.alata)),
TextFormField(
autovalidateMode:
AutovalidateMode.onUserInteraction,
autofocus: true,
style: TextStyle(
fontFamily: FF.ubuntu, fontSize: 14),
obscureText: controller.showOldPass.value,
obscuringCharacter: "*",
decoration: InputDecoration(
hintText: 'Enter Old Password',
hintStyle: TextStyle(
fontFamily: FF.ubuntu, fontSize: 14),
suffixIcon: IconButton(
onPressed: () =>
controller.showOldPassFun(),
icon: controller.showOldPass.value
? const Icon(Icons.visibility)
: const Icon(
Icons.visibility_off))),
controller: controller.oldPassword,
validator: (value) =>
Validation.passwordValidator(value),
)
],
),
)
],
),
vS(),
Row(
children: [
const Icon(Icons.password),
const SizedBox(
width: 20,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('New Password',
style: TextStyle(fontFamily: FF.alata)),
TextFormField(
autovalidateMode:
AutovalidateMode.onUserInteraction,
autofocus: true,
style: TextStyle(
fontFamily: FF.ubuntu, fontSize: 14),
obscureText: controller.showNewPass.value,
obscuringCharacter: "*",
decoration: InputDecoration(
hintText: 'Enter New Password',
hintStyle: TextStyle(
fontFamily: FF.ubuntu, fontSize: 14),
suffixIcon: IconButton(
onPressed: () =>
controller.showNewPassFun(),
icon: controller.showNewPass.value
? const Icon(Icons.visibility)
: const Icon(
Icons.visibility_off))),
controller: controller.newPassword,
validator: (value) =>
Validation.passwordValidator(value),
)
],
),
)
],
),
vS(),
Row(
children: [
const Icon(Icons.password),
const SizedBox(
width: 20,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Confirm Password',
style: TextStyle(fontFamily: FF.alata)),
TextFormField(
autovalidateMode:
AutovalidateMode.onUserInteraction,
autofocus: true,
style: TextStyle(
fontFamily: FF.ubuntu, fontSize: 14),
obscureText: controller.showConfirmPass.value,
obscuringCharacter: "*",
decoration: InputDecoration(
hintText: 'Enter Confirm Password',
hintStyle: TextStyle(
fontFamily: FF.ubuntu, fontSize: 14),
suffixIcon: IconButton(
onPressed: () =>
controller.showConfirmPassFun(),
icon: controller.showConfirmPass.value
? const Icon(Icons.visibility)
: const Icon(
Icons.visibility_off))),
controller: controller.confirmPassword,
validator: (value) =>
Validation.confirmPasswordValidator(
password: controller.newPassword.text,
value: value!),
)
],
),
)
],
),
SizedBox(
height: Get.height * 0.05,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
CustomElevatedButton(
title: 'Update',
onPress: () {
if (controller.changePasswordFormKey.currentState!
.validate()) {
checkInternet(function: () {
if (controller.oldPassword.text ==
appData.password) {
CustomLoader(title: 'Changing Password')
.loader();
Fbase.updatePassword(
password: controller.newPassword.text)
.then((value) {
Get.back();
CustomDialog(
descText: 'Password Upated',
isDismissable: false,
btnOkOnPress: () {
logOut();
},
).success();
});
} else {
Get.snackbar(
'Warning', "Old password doesn't match ",
backgroundColor: Colors.red,
borderRadius: 5,
colorText: white,
snackPosition: SnackPosition.TOP,
animationDuration:
const Duration(milliseconds: 800));
}
});
}
},
),
const SizedBox(
width: 10,
),
CustomOutlineButton(
onPress: () => Get.back(),
)
],
)
]),
),
),
)));
}
} |
import React, {useState} from "react";
// models
import PaymentCard from "../../models/PaymentCard";
// functions
import {maskCardCvv, maskCardExpires, maskCardHolderName} from "./functions";
// components
import Input from "../form/Input";
import CardNumberInput from "./CardNumberInput";
// styles
import {
CreditCardView,
CreditCardForm,
} from "./styles";
import {Label} from "../../design";
import {Row, Col} from "react-bootstrap";
export default function CreditCard() {
const [submitted, setSubmitted] = useState(false);
const [inputs, setInputs] = useState(new PaymentCard());
function handleChange(event)
{
let {name, value} = event.target;
if(name === "expires") {
value = maskCardExpires(value);
}
if(name === "cvv") {
value = maskCardCvv(value);
}
if(name === "number" && event.brand) {
setInputs(inputs => ({...inputs, brand: event.brand}));
}
if(name === "holder_name") {
value = maskCardHolderName(value);
}
setInputs(inputs => ({...inputs, [name]: value}));
}
return (
<CreditCardView>
<CreditCardForm>
<Row>
<Col lg="12">
<Label htmlFor="number">Número do cartão</Label>
<CardNumberInput
id="number"
name="number"
value={inputs.number}
placeholder="0000 0000 0000 0000"
error={submitted && !inputs.number}
onChange={handleChange}
/>
</Col>
<Col lg="6">
<Label htmlFor="expires">Validade</Label>
<Input
id="expires"
name="expires"
type="text"
value={inputs.expires}
placeholder="MM/AA"
onChange={handleChange}
error={submitted && !inputs.expires}
/>
</Col>
<Col lg="6">
<Label htmlFor="cvv">CVV</Label>
<Input
id="cvv"
name="cvv"
type="text"
value={inputs.cvv}
placeholder="Código de Segurança"
onChange={handleChange}
error={submitted && !inputs.cvv}
/>
</Col>
<Col lg="12">
<Label htmlFor="holder_name">Nome do Titular</Label>
<Input
id="holder_name"
name="holder_name"
type="text"
value={inputs.holder_name}
placeholder="Como está no cartão"
onChange={handleChange}
error={submitted && !inputs.holder_name}
/>
</Col>
</Row>
</CreditCardForm>
</CreditCardView>
)
} |
import React,{useContext} from 'react'
import IngredientList from './IngredientList';
import { RecipeContext } from './App';
export default function Recipe(props) {
const {handleRecipeDelete,handleRecipeSelect} = useContext(RecipeContext)
const { id, name, cookTime, servings, instructions, ingredients } = props;
return (
<div className="recipe">
<div className="recipe__header">
<h3 className="recipe__title">{ name}</h3>
<div>
<button onClick={() => handleRecipeSelect(id)} className="btn btn--primary mr-1">Edit</button>
<button onClick={() => handleRecipeDelete(id)} className="btn btn--danger">Delete</button>
</div>
</div>
<div className="recipe__row">
<span className="recipe__label">Cook Time:</span>
<span className="recipe__value">{cookTime }</span>
</div>
<div className="recipe__row">
<span className="recipe__label">Servings:</span>
<span className="recipe__value">{servings }</span>
</div>
<div className="recipe__row">
<span className="recipe__label">Instructions:</span>
<div className="recipe__value recipe__instructions recipe__value--indented"> {instructions} </div>
</div>
<div className="recipe__row">
<span className="recipe__label"> Ingredients:</span>
<div className="recipe__value recipe__value--indented">
<IngredientList ingredients={ingredients} />
</div>
</div>
</div>
)
} |
import os
import random
import evaluate
import numpy as np
import pandas as pd
import torch
import wandb
from anytree import findall
from datasets import Dataset
from lrml_score import compute_lrml
from tqdm.auto import tqdm
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from lrml_utils import (fix_lrml_tokenisation, node_to_lrml, parse_to_tree,
resolve_expressions, reverse_move_and_or_to_data_node,
reverse_resolve_expressions)
metric = None
def get_splits(tokenizer, input_series, label_series, shuffle=False, test_size=0.1, max_length=1024):
dataset = transform_lists_to_ds(
tokenizer, input_series.tolist(), label_series.tolist(), max_length=max_length)
return dataset.train_test_split(test_size=test_size, shuffle=shuffle)
def get_doc_split(tokenizer, df, text, lrml, short=False):
if short:
train_index = df.loc[(~(df['file'].str.contains('G14VM1')) & ~(df['file'].str.contains('D1AS1')) & ~(
df['file'].str.contains('B2AS1'))) & (df['lrml'].str.len() < 2000)].index
valid_index = df.loc[((df['file'].str.contains('G14VM1')) | (df['file'].str.contains('D1AS1')) | (
df['file'].str.contains('B2AS1'))) & (df['lrml'].str.len() < 372)].index
else:
train_index = df.loc[(~(df['file'].str.contains('G14VM1')) & ~(df['file'].str.contains('D1AS1')) & ~(
df['file'].str.contains('B2AS1')))].index
valid_index = df.loc[((df['file'].str.contains('G14VM1')) | (df['file'].str.contains('D1AS1')) | (
df['file'].str.contains('B2AS1')))].index
train_ds = transform_lists_to_ds(
tokenizer, text[train_index].tolist(), lrml[train_index].tolist())
valid_ds = transform_lists_to_ds(
tokenizer, text[valid_index].tolist(), lrml[valid_index].tolist())
return {'train': train_ds, 'test': valid_ds}
def get_file_names_from_df(df):
return df['file'].str.split('-').apply(lambda x: x[1]).str.split('#').apply(lambda x: x[0])
def get_lrml_dataset(tokenizer, prefix='translate English to LegalRuleML: ', short=False):
lrml_df = pd.read_csv('data/lrml/lrml_v2.csv')
return get_doc_split(tokenizer, lrml_df, prefix + get_file_names_from_df(lrml_df) + ' ' + lrml_df['text'], fix_lrml_tokenisation(lrml_df['lrml']), short=short)
def transform_lists_to_ds(tokenizer, inputs, labels, max_length=1024):
input_tokens = tokenizer(inputs, truncation=True, max_length=max_length)
with tokenizer.as_target_tokenizer():
label_tokens = tokenizer(
labels, truncation=True, max_length=max_length)
return Dataset.from_dict({'input_ids': input_tokens.input_ids,
'attention_mask': input_tokens.attention_mask, 'labels': label_tokens.input_ids
})
def get_tokenizer_and_model(model_path, saved_model=None):
tokenizer = AutoTokenizer.from_pretrained(model_path)
if saved_model is not None:
model_path = saved_model
model = AutoModelForSeq2SeqLM.from_pretrained(model_path)
return tokenizer, model.cuda()
def postprocess_text(preds, labels):
preds = [pred.strip() for pred in preds]
labels = [[label.strip()] for label in labels]
return preds, labels
def remove_padded_values(decoded_preds, decoded_labels):
while decoded_preds and decoded_preds[-1] == '' and decoded_labels and decoded_labels[-1] == '':
decoded_preds.pop()
decoded_labels.pop()
return decoded_preds, decoded_labels
def compute_metrics(eval_preds, tokenizer, custom_postprocess=None):
global metric
preds, labels, *others = eval_preds
if isinstance(preds, tuple):
preds = preds[0]
if metric is None:
metric = evaluate.load('bleu')
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
decoded_others = [tokenizer.batch_decode(
i, skip_special_tokens=True) for i in others]
# Replace -100 in the labels as we can't decode them.
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)
decoded_preds, decoded_labels = remove_padded_values(
decoded_preds, decoded_labels)
old_labels = decoded_labels
old_preds = decoded_preds
# Some simple post-processing
if custom_postprocess:
decoded_preds, decoded_labels = custom_postprocess(
decoded_preds, decoded_labels)
else:
decoded_preds, decoded_labels = postprocess_text(
decoded_preds, decoded_labels)
lrml_metric = compute_lrml(
predictions=decoded_preds, references=decoded_labels, entity_weight=2, filter_empty=True)
if sum([len(i) for i in decoded_preds]) > 0:
lrml_metric.update(metric.compute(
predictions=decoded_preds, references=decoded_labels))
# wandb log as table decoded_inputs, decoded_preds, old_labels, old_preds
lrml_metric['predictions'] = wandb.Table(data=list(zip(decoded_others[0], decoded_labels, decoded_preds, old_labels, old_preds)), columns=[
'input', 'original label', 'original pred', 'IR label', 'IR pred'])
index = random.randint(0, len(decoded_preds)-1)
lrml_metric['RANDOM_PRED'] = old_preds[index]
lrml_metric['RANDOM_LABEL'] = old_labels[index]
lrml_metric['RANDOM_PRED_EVAL'] = decoded_preds[index]
lrml_metric['RANDOM_LABEL_EVAL'] = decoded_labels[index]
lrml_metric['RANDOM_INPUT'] = decoded_others[0][index]
if len(decoded_others) > 1:
lrml_metric['ir_change_ratio'] = len([j for i, j in enumerate(
old_preds) if j == decoded_others[1][i]])/len(old_preds)
return lrml_metric
def post_process_lrml(lrml, revert_and_or):
lrml = lrml.strip()
lrml = lrml[lrml.find('if('):]
lrml = lrml.replace('[', '(').replace(']', ')').replace(
'{', '(').replace('}', ')')
lrml = lrml.replace(').', ')')
lrml = fix_then(lrml)
if revert_and_or:
lrml = save_revert_and_or(lrml)
return lrml
def fix_then(lrml):
tree = parse_to_tree(lrml)
if len(tree.children) == 1:
thens = findall(tree, filter_=lambda x: ((x.name.strip() == 'then')))
if len(thens) > 0:
thens[0].parent = tree
return node_to_lrml(tree)
def save_revert_and_or(lrml):
if 'atom(' in lrml:
lrml = reverse_move_and_or_to_data_node(lrml)
else:
lrml = resolve_expressions(reverse_move_and_or_to_data_node(
reverse_resolve_expressions(lrml, fix_errors=True, prefix=' ')))
return lrml
def get_optimizer(model, lr, weight_decay):
# Optimizer
# Split weights in two groups, one with weight decay and the other not.
no_decay = ["bias", "LayerNorm.weight", "layer_norm.weight"]
optimizer_grouped_parameters = [
{
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
"weight_decay": weight_decay,
},
{
"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
"weight_decay": 0.0,
},
]
return torch.optim.AdamW(optimizer_grouped_parameters, lr=lr)
def report_best(metrics):
wandb.log({str(key) + '.max': val for key, val in metrics.items()})
def write_predictions(path, tokenizer, inputs, label_ids, predictions, metrics):
os.makedirs('predictions', exist_ok=True)
decoded_inputs = tokenizer.batch_decode(inputs, skip_special_tokens=True)
label_ids = np.where(label_ids != -100, label_ids, tokenizer.pad_token_id)
decoded_label_ids = tokenizer.batch_decode(
label_ids, skip_special_tokens=True)
decoded_predictions = tokenizer.batch_decode(
predictions, skip_special_tokens=True)
with open('predictions/' + path, 'w') as f:
f.write(str(metrics) + '\n\n')
for i in range(len(decoded_inputs)):
f.write('Scores: ' + str(compute_lrml(predictions=[decoded_predictions[i]], references=[decoded_label_ids[i]], entity_weight=2, filter_empty=True)) +
';\n Input: ' + decoded_inputs[i] + ';\n Label: ' + decoded_label_ids[i] + ';\n Prediction: ' + decoded_predictions[i] + '\n\n')
def padded_concat(tokenizer, tensor_list):
padded_tensor = torch.nested_tensor(
tensor_list).to_padded_tensor(tokenizer.pad_token_id)
return padded_tensor.reshape((-1, padded_tensor.shape[-1]))
def evaluate_lrml(tokenizer, model, data_loader, gen_kwargs, fp_16, custom_postprocess=None, predictions_path=None):
model.eval()
generated_list = []
label_list = []
input_list = []
eval_progress_bar = tqdm(range(len(data_loader)), leave=False)
for step, batch in enumerate(data_loader):
with torch.no_grad():
with torch.cuda.amp.autocast(enabled=fp_16):
generated_tokens = model.generate(
batch["input_ids"].cuda(),
attention_mask=batch["attention_mask"].cuda(),
**gen_kwargs
).cpu()
labels = batch["labels"].cpu()
input_ids = batch["input_ids"].cpu()
generated_list.append(generated_tokens)
label_list.append(labels)
input_list.append(input_ids)
eval_progress_bar.update(1)
eval_metric = compute_metrics(
(padded_concat(tokenizer, generated_list), padded_concat(tokenizer, label_list), padded_concat(tokenizer, input_list)), tokenizer, custom_postprocess)
if predictions_path:
write_predictions(path=predictions_path, tokenizer=tokenizer, inputs=padded_concat(tokenizer, input_list), label_ids=padded_concat(
tokenizer, label_list), predictions=padded_concat(tokenizer, generated_list), metrics=eval_metric)
eval_progress_bar.close()
print(eval_metric)
wandb.log(eval_metric)
return eval_metric |
#ifndef INPUT_HANDLER_H
#define INPUT_HANDLER_H
#include <iostream>
#include "INIReader.h"
class InputHandler
{
public:
InputHandler(std::string& inputFile, int run_num, long randSeed);
~InputHandler(){};
int read();
int L;
double J;
int noTemperatures;
double T_min;
double T_max;
int noSamples;
int sweepsBetweenSamples;
int equilibrationSweeps;
int runNo;
long randomSeed;
private:
std::string inputFileName;
};
InputHandler::InputHandler(std::string& inputFile, int run_num, long randSeed) : inputFileName(inputFile), runNo(run_num), randomSeed(randSeed)
{
}
int InputHandler::read()
{
INIReader reader(inputFileName);
if (reader.ParseError() != 0) {
return 1;
}
L = reader.GetInteger("Model_Parameters", "L", -1);
J = reader.GetReal("Model_Parameters", "J", -1);
noTemperatures = reader.GetInteger("Monte_Carlo_Parameters", "no_of_temperatures", -1);
T_min = reader.GetReal("Monte_Carlo_Parameters", "T_min", -1);
T_max = reader.GetReal("Monte_Carlo_Parameters", "T_max", -1);
noSamples = reader.GetInteger("Monte_Carlo_Parameters", "no_of_samples", -1);
equilibrationSweeps = reader.GetInteger("Monte_Carlo_Parameters", "equilibration_sweeps", -1);
sweepsBetweenSamples = reader.GetInteger("Monte_Carlo_Parameters", "sweeps_between_samples", -1);
return 0;
}
#endif |
# teachers/views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Teacher, LessonPlan, Subject, PlanDetails
from .forms import LessonPlanForm
from django.contrib.auth.decorators import login_required
from .forms import TeacherForm
from django.db.models import Count
from django.contrib.auth.forms import UserCreationForm
from django.db import models
@login_required
def view_profile(request):
teacher = Teacher.objects.get(user=request.user)
return render(request, 'teachers/view_profile.html', {'teacher': teacher})
@login_required
def update_profile(request):
teacher = Teacher.objects.get(user=request.user)
if request.method == 'POST':
form = TeacherForm(request.POST, instance=teacher)
if form.is_valid():
form.save()
return redirect('teachers:view_profile')
else:
form = TeacherForm(instance=teacher)
return render(request, 'teachers/update_profile.html', {'form': form})
def register(request):
if request.method == 'POST':
teacher_form = TeacherForm(request.POST)
if teacher_form.is_valid():
user = request.user
try:
# Attempt to get the teacher for the user
existing_teacher = Teacher.objects.get(user=user)
# If the user already has a teacher profile, inform the user
message = "You have already registered. You cannot register twice."
return render(request, 'message_template.html', {'message': message})
except Teacher.DoesNotExist:
# If the user doesn't have a teacher profile, proceed with registration
teacher = teacher_form.save(commit=False)
teacher.user = user
teacher.save()
messages.success(request, 'Registration successful!')
return redirect('teachers:view_profile')
else:
teacher_form = TeacherForm()
return render(request, 'teachers/register.html', {'teacher_form': teacher_form})
def lesson_plan_detail(request, pk):
lesson_plan = get_object_or_404(LessonPlan, pk=pk)
# You can add more context variables or customize the logic as needed
context = {'lesson_plan': lesson_plan}
return render(request, 'teachers/lesson_plan_detail.html', context)
@login_required
def dashboard(request):
try:
# Try to get the Teacher instance
teacher = Teacher.objects.get(user=request.user)
subjects = Subject.objects.filter(lessonplan__teacher=teacher)
except Teacher.DoesNotExist:
# If Teacher instance does not exist, display a message
message = "Welcome! Please fill in your profile details to get started."
return render(request, 'message_template.html', {'message': message})
# Fetch approved and pending lesson plans
approved_lesson_plans = LessonPlan.objects.filter(teacher=teacher, submission_status='approved')
pending_lesson_plans = LessonPlan.objects.filter(teacher=teacher, submission_status='pending')
# Chart data
total_lesson_plans = LessonPlan.objects.filter(teacher=teacher).count()
total_pending_plans = pending_lesson_plans.count()
total_approved_plans = approved_lesson_plans.count()
# Number of subjects to lesson plans
subjects_with_plans = Subject.objects.filter(lessonplan__teacher=teacher).annotate(num_plans=models.Count('lessonplan'))
# Number of teachers to one subject
subjects_with_teachers = Subject.objects.annotate(num_teachers=Count('lessonplan', distinct=True))
subject_names_teachers = [subject.title for subject in subjects_with_teachers]
num_teachers = [subject.num_teachers for subject in subjects_with_teachers]
# Subject with highest and lowest number of plans
subject_with_highest_plans = subjects_with_plans.order_by('-num_plans').first()
subject_with_lowest_plans = subjects_with_plans.order_by('num_plans').first()
# Subject with highest and lowest number of teachers
subject_with_highest_teachers = subjects_with_teachers.order_by('-num_teachers').first()
subject_with_lowest_teachers = subjects_with_teachers.order_by('num_teachers').first()
return render(request, 'teachers/dashboard.html', {
'teacher': teacher,
'subjects': subjects,
'approved_lesson_plans': approved_lesson_plans,
'pending_lesson_plans': pending_lesson_plans,
'total_lesson_plans': total_lesson_plans,
'total_pending_plans': total_pending_plans,
'total_approved_plans': total_approved_plans,
'subject_names': [subject.title for subject in subjects_with_plans],
'num_plans': [subject.num_plans for subject in subjects_with_plans],
'subject_with_highest_plans': subject_with_highest_plans,
'subject_with_lowest_plans': subject_with_lowest_plans,
'subject_names_teachers': subject_names_teachers,
'num_teachers': num_teachers,
'subject_with_highest_teachers': subject_with_highest_teachers,
'subject_with_lowest_teachers': subject_with_lowest_teachers,
})
@login_required
def create_lesson_plan(request):
if request.method == 'POST':
form = LessonPlanForm(request.POST)
if form.is_valid():
lesson_plan = form.save(commit=False)
lesson_plan.teacher = Teacher.objects.get(user=request.user)
lesson_plan.save()
return redirect('teachers:dashboard')
else:
form = LessonPlanForm()
return render(request, 'teachers/create_lesson_plan.html', {'form': form})
@login_required
def update_lesson_plan(request, lesson_plan_id):
lesson_plan = get_object_or_404(LessonPlan, id=lesson_plan_id, teacher__user=request.user)
if request.method == 'POST':
form = LessonPlanForm(request.POST, instance=lesson_plan)
if form.is_valid():
form.save()
return redirect('teachers:dashboard')
else:
form = LessonPlanForm(instance=lesson_plan)
return render(request, 'teachers/update_lesson_plan.html', {'form': form, 'lesson_plan': lesson_plan})
@login_required
def delete_lesson_plan(request, lesson_plan_id):
lesson_plan = get_object_or_404(LessonPlan, id=lesson_plan_id, teacher__user=request.user)
if request.method == 'POST':
lesson_plan.delete()
return redirect('teachers:dashboard')
return render(request, 'teachers/delete_lesson_plan.html', {'lesson_plan': lesson_plan}) |
<%--
权限管理
角色维护模块
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<%-- 包含head部分 --%>
<jsp:include page="/WEB-INF/jsp/common/head.jsp"/>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<div><a class="navbar-brand" style="font-size:32px;" href="${APP_PATH}/role/index.htm">众筹平台 - 角色维护</a></div>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<%-- 包含页面头部 --%>
<jsp:include page="/WEB-INF/jsp/common/top.jsp"/>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<div class="tree">
<%--包含左侧菜单页面--%>
<jsp:include page="/WEB-INF/jsp/common/menu.jsp"/>
</div>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
</div>
<div class="panel-body">
<form class="form-inline" role="form" style="float:left;">
<div class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">查询条件</div>
<input id="queryText" class="form-control has-success" type="text" placeholder="请输入查询条件">
</div>
</div>
<button onclick="queryPageRoleLike(0)" type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>
</form>
<button onclick="deleteRoleBatchBtn()" type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> 批量删除</button>
<button type="button" class="btn btn-primary" style="float:right;" onclick="window.location.href='${APP_PATH}/role/add.htm'"><i class="glyphicon glyphicon-plus"></i> 新增</button>
<br>
<hr style="clear:both;">
<div class="table-responsive">
<table class="table table-bordered">
<%--表格头部信息--%>
<thead>
<tr >
<th class="text-center" width="50">序号</th>
<th class="text-center" width="30"><input type="checkbox" id="checkboxAll"></th>
<th class="text-center" >名称</th>
<th class="text-center" width="200">操作</th>
</tr>
</thead>
<%--查询出的数据--%>
<tbody>
</tbody>
<%--分页导航条--%>
<tfoot>
<tr >
<td colspan="6" align="center">
<%--未使用pagination分页插件--%>
<%--<ul class="pagination"></ul>--%>
<%--使用pagination分页插件--%>
<%--显示分页的容器--%>
<div id="Pagination" class="pagination"></div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<%-- 包含src部分 --%>
<jsp:include page="/WEB-INF/jsp/common/src.jsp"/>
<%--入口函数--%>
<script type="text/javascript">
$(function () {
$(".list-group-item").click(function(){
if ( $(this).find("ul") ) {
$(this).toggleClass("tree-closed");
if ( $(this).hasClass("tree-closed") ) {
$("ul", this).hide("fast");
} else {
$("ul", this).show("fast");
}
}
});
showMenu();
//页面一跳转自动加载角色数据
queryPageRole(0);
});
</script>
<%-- 查询用户数据 --%>
<script>
function queryPageRole(pageIndex) {
$.ajax({
type : "POST",
data : {
"pageno" : pageIndex + 1,
"pagesize" : 8
},
url : "${APP_PATH}/role/doIndex.do",
beforeSend : function () {
loadingIndex = layer.msg('数据加载中...', {icon: 16});
return true;
},
success : function (result) {
layer.close(loadingIndex);
if (result.success){
//查询数据成功
var page = result.page;
var data = page.datas;
/*判断返回的集合中是否有数据*/
if (data.length == 0){
layer.msg("目前没有查询到角色信息");
return false;
}
var content = '';
/* 对后台返回的数据进行拼串展示 */
$.each(data,function(i,n){
content+='<tr>';
content+='<td class="text-center" >'+(i+1)+'</td>';
content+='<td class="text-center" ><input type="checkbox" id="'+n.id+'"></td>';
content+='<td class="text-center" >'+n.name+'</td>';
content+='<td class="text-center">';
content+='<button type="button" onclick="window.location.href=\'${APP_PATH}/role/assignPermission.htm?roleid='+n.id+'\'" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i>分配许可</button>';
content+='<button type="button" onclick="window.location.href=\'${APP_PATH}/role/update.htm?id='+n.id+'\'" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i>修改</button>';
content+='<button type="button" onclick="doDeleteRole('+n.id+',\''+n.name+'\')" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i>删除</button>';
content+='</td>';
content+='</tr>';
});
// 将拼接到的数据放入 tbody标签的指定位置
$("tbody").html(content);
// 创建分页
$("#Pagination").pagination(page.totalsize, {
num_edge_entries: 2, //边缘页数
num_display_entries: 4, //主体页数
callback: queryPageRole, //当前函数
items_per_page:8, //每页显示多少条
current_page :(page.pageno-1), //当前页
prev_text : "上一页",
next_text : "下一页"
});
} else {
//查询数据失败
layer.msg(result.message);
}
},
error : function () {
layer.msg("数据加载失败");
}
});
}
</script>
<%--模糊查询--%>
<script>
function queryPageRoleLike(pageIndex) {
$.ajax({
type : "POST",
data : {
"pageno" : pageIndex + 1,
"pagesize" : 8,
"queryText" : $("#queryText").val()
},
url : "${APP_PATH}/role/doLike.do",
beforeSend : function () {
loadingIndex = layer.msg('数据加载中...', {icon: 16});
return true;
},
success : function (result) {
layer.close(loadingIndex);
if (result.success){
//查询数据成功
var page = result.page;
var data = page.datas;
/*判断返回的集合中是否有数据*/
if (data.length == 0){
layer.msg("没有您要查询的用户信息");
return false;
}
var content = '';
/* 对后台返回的数据进行拼串展示 */
$.each(data,function(i,n){
content+='<tr>';
content+='<td class="text-center" >'+(i+1)+'</td>';
content+='<td class="text-center" ><input type="checkbox" id="'+n.id+'"></td>';
content+='<td class="text-center" >'+n.name+'</td>';
content+='<td class="text-center">';
content+='<button type="button" onclick="window.location.href=\'${APP_PATH}/role/assignPermission.htm?roleid='+n.id+'\'" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i>分配权限</button>';
content+='<button type="button" onclick="window.location.href=\'${APP_PATH}/role/update.htm?id='+n.id+'\'" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i>修改</button>';
content+='<button type="button" onclick="doDeleteRole('+n.id+',\''+n.name+'\')" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i>删除</button>';
content+='</td>';
content+='</tr>';
});
// 将拼接到的数据放入 tbody标签的指定位置
$("tbody").html(content);
// 创建分页
$("#Pagination").pagination(page.totalsize, {
num_edge_entries: 2, //边缘页数
num_display_entries: 4, //主体页数
callback: queryPageRoleLike, //当前函数
items_per_page:8, //每页显示多少条
current_page :(page.pageno-1), //当前页
prev_text : "上一页",
next_text : "下一页"
});
} else {
//查询数据失败
layer.msg(result.message);
}
},
error : function () {
layer.msg("数据加载失败");
}
});
}
</script>
<%-- 单条数据删除功能 --%>
<script>
function doDeleteRole(id,name) {
layer.confirm("确认删除["+name+"]角色?", {icon: 3, title: '提示'}, function (cindex) {
$.ajax({
type : "POST",
data : {
"id" : id
},
url : "${APP_PATH}/role/doDelete.do",
beforeSend : function () {
layer.close(cindex);
loadingIndex = layer.msg('数据删除中...', {icon: 16});
//对表单数据进行校验
return true;
},
success : function (result) {
layer.close(loadingIndex);
if (result.success) {
loadingIndex = layer.msg('数据删除成功,正在更新数据...', {icon: 16});
//设置定时,让提示框显示一定时间
setTimeout(function () {{window.location.href="${APP_PATH}/role/index.htm"}},1000);
}else {
layer.msg(result.message);
}
},
error : function () {
layer.msg("数据删除失败");
}
});
}, function (cindex) {
layer.close(cindex);
})
}
</script>
<%--实现复选框的联动效果--%>
<script>
$("#checkboxAll").click(function () {
var checkedStatus = this.checked;
//通过后代元素设置input的chenkbox属性
$("tbody tr td input[type='checkbox']").prop("checked",checkedStatus);
});
</script>
<%--批量删除--%>
<script>
function deleteRoleBatchBtn() {
//获取被选中的复选框数据的id值
var selectCheckbox = $("tbody tr td input:checked");
//判断是否有选中的数据
if (selectCheckbox.length==0) {
layer.msg("请选择要删除的用户");
return false;
}
//遍历id数组,进行循环拼串
var idStr = "";
$.each(selectCheckbox,function (i,n) {
if (i != 0) {
idStr += "&";
}
idStr += "id="+n.id;
});
//alert(idStr);
layer.confirm("确认删除这些用户?", {icon: 3, title: '提示'}, function (cindex) {
$.ajax({
type : "POST",
data : idStr,
url : "${APP_PATH}/role/doDeleteBatch.do",
beforeSend : function () {
layer.close(cindex);
loadingIndex = layer.msg('数据删除中...', {icon: 16});
//对表单数据进行校验
return true;
},
success : function (result) {
layer.close(loadingIndex);
if (result.success) {
loadingIndex = layer.msg('数据删除成功,正在更新数据...', {icon: 16});
//设置定时,让提示框显示一定时间
setTimeout(function () {{window.location.href="${APP_PATH}/role/index.htm"}},1000);
}else {
layer.msg(result.message);
}
},
error : function () {
layer.msg("数据删除失败");
}
});
}, function (cindex) {
layer.close(cindex);
})
}
</script>
</body>
</html> |
'use client';
import { useState, useEffect } from 'react';
import { useMiProvider } from '/src/context/context.js';
import Link from 'next/link';
export default function AdminTicketsPage() {
const [tickets, setTickets] = useState([]);
const [filtro, setFiltro] = useState('Pendientes');
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
if (filtro === 'Todos') {
obtenerTodosLosTickets();
} else if (filtro === 'Pendientes') {
obtenerTicketsPendientes();
}
}, [filtro]);
const obtenerTodosLosTickets = async () => {
setIsLoading(true);
try {
const response = await fetch('http://127.0.0.1:8000/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'estudiante_id': 144 }),
});
if (response.ok) {
const data = await response.json();
setTickets(data);
console.log('Data extraidaTODOSOK: ', data);
} else {
const error = await response.text();
console.log('Data extraidaTODOSNOTOK: ', error);
}
} catch (error) {
console.error('Error: ', error);
} finally {
setIsLoading(false);
}
};
const obtenerTicketsPendientes = async () => {
setIsLoading(true);
try {
const response = await fetch('http://127.0.0.1:8000/pendientes/', {
method: 'POST',
});
if (response.ok) {
const data = await response.json();
setTickets(data);
console.log('Data extraidaPendientesOK: ', data);
} else {
const error = await response.text();
console.log('Data extraidaPendientesNOTOK: ', error);
}
} catch (error) {
console.error('Error: ', error);
} finally {
setIsLoading(false);
}
};
return (
<div className="flex-1 p-4">
<h1 className="title" style={{ fontSize: '2rem', fontWeight: 'bold', color: '#333', marginBottom: '20px', textAlign: 'center' }}>
Visualización de Tickets
</h1>
{/*Botones*/}
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: '20px' }}>
<button
onClick={() => setFiltro('Todos')}
style={{
margin: '0 10px',
padding: '10px 20px',
backgroundColor: filtro === 'Todos' ? '#ff6440' : '#ddd',
color: '#fff',
border: 'none',
borderRadius: '5px',
}}
>
Todos
</button>
<button
onClick={() => setFiltro('Pendientes')}
style={{
margin: '0 10px',
padding: '10px 20px',
backgroundColor: filtro === 'Pendientes' ? '#ff6440' : '#ddd',
color: '#fff',
border: 'none',
borderRadius: '5px',
}}
>
Pendientes
</button>
</div>
<div className="flex-container" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px' }}>
{isLoading ? (
<p>Cargando tickets...</p>
) : (
filtro === 'Pendientes' && (
tickets.length === 0 ? (
<p>No hay tickets pendientes.</p>
) : (
<div style={{ width: '80%', backgroundColor: '#f0f0f0', padding: '20px', borderRadius: '10px' }}>
{tickets.map(ticket => (
<div key={ticket.id} style={{ borderBottom: '1px solid #ddd', padding: '10px 0', marginTop: '20px' }}>
<h3 style={{ marginBottom: '5px' }}>{ticket.asunto}</h3>
<p><strong>Periodo:</strong> {ticket.seccion.periodo.codigo}</p>
<p><strong>Curso:</strong> {ticket.curso_nombre}</p>
<p><strong>Sección:</strong> {ticket.seccion.codigo} - {ticket.seccion.profesor.nombres}</p>
<p><strong>Comentario:</strong> {ticket.comentario}</p>
<p><strong>Archivo:</strong> {ticket.archivo}</p>
<p><strong>Fecha de Envío:</strong> {new Date(ticket.fecha_envio).toLocaleString()}</p>
<Link href={`./ticketEspecifico?id=${ticket.id}`}>
<button style={{ marginTop: '10px', padding: '10px 20px', backgroundColor: '#007bff', color: '#fff', border: 'none', borderRadius: '5px' }}>
Más información
</button>
</Link>
</div>
))}
</div>
)
)
)}
</div>
<div className="flex-container" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px' }}>
{isLoading ? (
<p>Cargando tickets...</p>
) : (
filtro === 'Todos' && (
tickets.length === 0 ? (
<p>No hay tickets disponibles.</p>
) : (
<div style={{ width: '80%', backgroundColor: '#f0f0f0', padding: '20px', borderRadius: '10px' }}>
{tickets.map(ticket => (
<div key={ticket.id} style={{ borderBottom: '1px solid #ddd', padding: '10px 0', marginTop: '20px' }}>
<h3 style={{ marginBottom: '5px' }}>{ticket.asunto}</h3>
<p><strong>Periodo:</strong> {ticket.seccion.periodo.codigo}</p>
<p><strong>Curso:</strong> {ticket.curso_nombre}</p>
<p><strong>Sección:</strong> {ticket.seccion.codigo} - {ticket.seccion.profesor.nombres}</p>
<p><strong>Comentario:</strong> {ticket.comentario}</p>
<p><strong>Archivo:</strong> {ticket.archivo}</p>
<p><strong>Fecha de Envío:</strong> {new Date(ticket.fecha_envio).toLocaleString()}</p>
<p><strong>Estado establecido:</strong> {new Date(ticket.fecha_envio).toLocaleString()}</p>
<Link href={`./ticketEspecifico?id=${ticket.id}`}>
<button style={{ marginTop: '10px', padding: '10px 20px', backgroundColor: '#007bff', color: '#fff', border: 'none', borderRadius: '5px' }}>
Más información
</button>
</Link>
</div>
))}
</div>
)
)
)}
</div>
</div>
);
} |
import { Box, Button, Flex, Heading, Text, VStack, useColorModeValue } from '@chakra-ui/react';
import { ReactElement } from 'react';
interface CardProps {
heading: string;
description: string;
icon: ReactElement;
href: string;
}
export const CardComponent = ({ heading, description, icon }: CardProps) => {
return (
<Box borderWidth='2px' rounded={'lg'} overflow='hidden' p={'30px 20px'}>
<VStack align={'start'} spacing={'20px'}>
<Flex
w={16}
h={16}
align={'center'}
justify={'center'}
color={'white'}
rounded={'full'}
bg={useColorModeValue('gray.100', 'gray.700')}>
{icon}
</Flex>
<VStack align={'start'}>
<Heading size='md'>{heading}</Heading>
<Text fontSize={'sm'}>{description}</Text>
</VStack>
<Button variant={'link'} colorScheme={'blue'} size={'sm'}>
Learn more
</Button>
</VStack>
</Box>
);
}; |
const http = require('http');
const fs = require('fs').promises;
const path = require('path');
// 문자열로 된 쿠키를 객체로 바꿔주는 함수
const parseCookies = (cookie = '') =>
cookie
.split(';')
.map(v => v.split('='))
.reduce((acc, [k, v]) => {
acc[k.trim()] = decodeURIComponent(v);
return acc;
}, {});
const session = {}; // 데이터 저장용 세션 객체 생성
http.createServer(async (req, res) => {
const cookies = parseCookies(req.headers.cookie);
if (req.url.startsWith('/login')) {
const url = new URL(req.url, 'http://localhost:8084'); // 상대 경로 앞에 붙여줄 base url
const name = url.searchParams.get('name'); // 쿼리스트링에서 name을 추출
const expires = new Date();
// 쿠키 유효 시간을 현재시간 + 5분으로 설정
expires.setMinutes(expires.getMinutes() + 5);
// 세션 사용하기
const uniqueInt = Date.now(); // 세션 키(세션 ID) 만들기: 현재 시간(고유한 값)을 사용해 임의로 생성
session[uniqueInt] = {
name,
expires
}; // 서버 메모리에 세션 저장
res.writeHead(302, { // 302: 리다이렉션
Location: '/', // 이 주소로 돌려보내라
'Set-Cookie': `session=${uniqueInt}; Expires=${expires.toGMTString()}; HttpOnly; Path=/`
}); // 브라우저에는 고유한 키 값만 보내서 쿠키에 저장(응답 헤더에 쿠키 부분 확인해보기)
res.end();
// 세션 쿠키가 존재하고, 만료 기간이 지나지 않았다면
} else if (cookies.session && session[cookies.session]?.expires > new Date()) { // 만료되면 쿠키에서 제거되겠지만 한번 더 엄격하게 검사
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(`${session[cookies.session].name}님 안녕하세요`);
} else {
try {
const data = await fs.readFile(path.join(__dirname, 'cookie2.html'));
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(data);
} catch (err) {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end(err.message);
}
}
})
.listen(8085, () => {
console.log('8085번 포트에서 서버 대기 중입니다!');
});
// 개념 이해를 돕기 위한 간단한 예제이므로 실제론 보안상 문제가 있음
// 실 서버에서는 세션을 직접 구현하지 않음
// 추후 6장에서 실무에서 세션을 어떻게 쓰는지(express-session) 다시 다룰 예정
// 여기까지 서버를 만들면서
// 노드에서 제공하는 방식(http 모듈)으로는 서버 코드가 너무 복잡하고, 유지 보수하기도 힘듦
// 코드를 깔끔하고 유지 보수하기 편하게 해주는 Express 프레임워크를 사용할 예정 |
require 'rails_helper'
describe "Recipes API" do
it "sends a list of recipes" do
WebMock.allow_net_connect!
WebMock.disable!
VCR.eject_cassette
VCR.turn_off!(:ignore_cassettes => true)
params = { country: "Japan" }
get '/api/v1/recipes', params: params
expect(response).to be_successful
recipes = JSON.parse(response.body, symbolize_names: true)
recipes[:data].each do |data|
expect(data).to have_key(:id)
expect(data[:id]).to eq(nil)
expect(data).to have_key(:type)
expect(data[:type]).to eq("recipe")
expect(data).to have_key(:attributes)
expect(data[:attributes]).to have_key(:title)
expect(data[:attributes][:title]).to be_a(String)
expect(data).to have_key(:attributes)
expect(data[:attributes]).to have_key(:url)
expect(data[:attributes][:url]).to be_a(String)
expect(data).to have_key(:attributes)
expect(data[:attributes]).to have_key(:country)
expect(data[:attributes][:country]).to eq(nil)
expect(data).to have_key(:attributes)
expect(data[:attributes]).to have_key(:image)
expect(data[:attributes][:image]).to be_a(String)
end
end
it "sends a list of recipes without these keys and attributes" do
WebMock.allow_net_connect!
WebMock.disable!
VCR.eject_cassette
VCR.turn_off!(:ignore_cassettes => true)
params = { country: "Japan" }
get '/api/v1/recipes', params: params
expect(response).to be_successful
recipes = JSON.parse(response.body, symbolize_names: true)
recipes[:data].each do |data|
expect(data).not_to have_key(:hits)
expect(data).not_to have_key(:recipe)
expect(data).not_to have_key(:uri)
expect(data).not_to have_key(:images)
expect(data).not_to have_key(:source)
end
end
end |
import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Observable} from 'rxjs';
import {ITeacher, Teacher} from '../model/Teacher';
import {tap} from 'rxjs/operators';
const TEACHER_API = '/server/api/manage/teachers';
const httpHeaders = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class TeacherService {
constructor(private http: HttpClient) { }
getAllTeachersResponse(): Observable<ITeacher[]> {
return this.http.get<ITeacher[]>(TEACHER_API).pipe(
tap(x => console.log(JSON.stringify(x[0])))
);
}
getTeacherResponse(teacherId: number): Observable<ITeacher> {
return this.http.get<ITeacher>(TEACHER_API + '/' + teacherId);
}
postTeacher(teacher: Teacher): Observable<ITeacher> {
return this.http.post<ITeacher>(TEACHER_API, JSON.stringify(teacher), httpHeaders);
}
putTeacher(teacher: Teacher): Observable<ITeacher> {
return this.http.put<ITeacher>(TEACHER_API + '/' + teacher.id, JSON.stringify(teacher), httpHeaders);
}
deleteTeacher(teacher: ITeacher): Observable<ITeacher> {
return this.http.delete<ITeacher>(TEACHER_API + '/' + teacher.id);
}
} |
import { StyleSheet, TouchableOpacity, Text, Image, View } from "react-native";
import useLocale from "../../hooks/useLocale";
import useDateTimer from "../../hooks/useDateTimer";
import useScreen from "../../hooks/useScreen";
import { Entypo, Feather } from "@expo/vector-icons";
import * as theme from "../../constants/theme";
export default function Passenger({ data: passenger }) {
const screen = useScreen();
const { i18n, lang } = useLocale();
const { value: date } = useDateTimer(passenger.lastLogin, lang, [lang]);
const styles = StyleSheet.create({
container: {
borderWidth: screen.getHorizontalPixelSize(1),
borderColor: "#ababab",
width: "100%",
borderRadius: 8,
justifyContent: "center",
paddingHorizontal: screen.getHorizontalPixelSize(10),
paddingVertical: screen.getVerticalPixelSize(15),
paddingBottom: screen.getVerticalPixelSize(25),
gap: screen.getVerticalPixelSize(7),
},
itemContainer: {
flexDirection: lang === "ar" ? "row-reverse" : "row",
alignItems: "center",
gap: screen.getHorizontalPixelSize(7),
},
icon: {
color: theme.primaryColor,
fontSize: screen.getResponsiveFontSize(30),
},
avatar: {
width: screen.getHorizontalPixelSize(30),
height: screen.getHorizontalPixelSize(30),
borderRadius: screen.getHorizontalPixelSize(100),
borderWidth: screen.getHorizontalPixelSize(1),
borderColor: "#ababab",
},
itemText: {
fontFamily: "cairo-600",
fontSize: screen.getResponsiveFontSize(14),
},
arDate: {
position: "absolute",
bottom: screen.getVerticalPixelSize(7),
left: screen.getHorizontalPixelSize(7),
fontSize: screen.getResponsiveFontSize(11),
fontFamily: "cairo-400",
},
enDate: {
position: "absolute",
bottom: screen.getVerticalPixelSize(7),
right: screen.getHorizontalPixelSize(7),
fontSize: screen.getResponsiveFontSize(11),
fontFamily: "cairo-400",
},
});
const getImageSource = (url) => {
return url
? { uri: url }
: require("../../assets/images/default-avatar.png");
};
return (
<TouchableOpacity style={styles.container}>
<View style={styles.itemContainer}>
<Image
source={getImageSource(passenger.avatarURL)}
resizeMode="contain"
style={styles.avatar}
/>
<Text style={styles.itemText}>
{passenger.firstName} {passenger.lastName}
</Text>
</View>
<View style={styles.itemContainer}>
<Entypo name="phone" style={styles.icon} />
<Text style={styles.itemText}>{passenger.phone.full}</Text>
</View>
<View style={styles.itemContainer}>
<Feather name="mail" style={styles.icon} />
<Text style={styles.itemText}>
{passenger.email || i18n("notSpecified")}
</Text>
</View>
<Text style={lang === "ar" ? styles.arDate : styles.enDate}>{date}</Text>
</TouchableOpacity>
);
} |
import { gql, useQuery } from '@apollo/client';
import React, { useState } from 'react';
import {
RestaurantsPageQuery,
RestaurantsPageQueryVariables,
} from '../../__generated__/graphql';
import { Restaurant } from '../../components/restaurant';
const RESTAURANTS_QUERY = gql`
query restaurantsPage($input: RestaurantsInput!) {
allCategories {
ok
error
categories {
id
name
coverImg
slug
restaurantCount
}
}
restaurants(input: $input) {
ok
error
totalPages
totalResults
results {
id
name
coverImg
category {
name
}
address
isPromoted
}
}
}
`;
export const Restaurants = () => {
const [page, setPage] = useState(1);
const { data, loading } = useQuery<
RestaurantsPageQuery,
RestaurantsPageQueryVariables
>(RESTAURANTS_QUERY, {
variables: {
input: {
page,
},
},
});
const onNextPageClick = () => setPage((current) => current + 1);
const onPrevPageClick = () => setPage((current) => current - 1);
return (
<div>
<form className="flex w-full items-center justify-center bg-gray-800 py-40">
<input
type="Search"
className="input w-3/12 rounded-md border-0"
placeholder="Search restaurants..."
/>
</form>
{!loading && (
<div className="mx-auto mt-8 max-w-screen-2xl pb-20">
<div className="mx-auto flex max-w-sm justify-around ">
{data?.allCategories.categories?.map((category) => (
<div className="group flex cursor-pointer flex-col items-center">
<div
className="h-16 w-16 rounded-full bg-cover group-hover:bg-gray-100"
style={{ backgroundImage: `url(${category.coverImg})` }}
></div>
<span className="mt-1 text-center text-sm font-medium">
{category.name}
</span>
</div>
))}
</div>
<div className="mt-16 grid grid-cols-3 gap-x-5 gap-y-10">
{data?.restaurants.results?.map((restaurant) => (
<Restaurant
id={restaurant.id + ''}
coverImg={restaurant.coverImg}
name={restaurant.name}
categoryName={restaurant.category?.name}
/>
))}
</div>
<div className="mx-auto mt-10 grid max-w-md grid-cols-3 items-center text-center">
{page > 1 ? (
<button
onClick={onPrevPageClick}
className="text-2xl font-medium focus:outline-none"
>
←
</button>
) : (
<div></div>
)}
<span>
Page {page} of {data?.restaurants.totalPages}
</span>
{page !== data?.restaurants.totalPages ? (
<button
onClick={onNextPageClick}
className="text-2xl font-medium focus:outline-none"
>
→
</button>
) : (
<div></div>
)}
</div>
</div>
)}
</div>
);
}; |
// Date: 11/28/22
//
// Author: Zai Santillan
// Github: @plskz
import SwiftUI
struct ContentView: View {
@State private var checkAmount = 0.0
@State private var numberOfPeople = 2
@State private var tipPercentage = 20
@FocusState var amountIsFocused: Bool
var tipPercentages = [0, 10, 15, 20, 25]
var totalPerPerson: Double {
let peopleCount = Double(numberOfPeople + 2)
let tipSelection = Double(tipPercentage)
let tipValue = checkAmount / 100 * tipSelection
let grandTotal = checkAmount + tipValue
let amountPerPerson = grandTotal / peopleCount
return amountPerPerson
}
var totalAmount: Double {
let tipSelection = Double(tipPercentage)
let tipValue = checkAmount / 100 * tipSelection
let grandTotal = checkAmount + tipValue
return grandTotal
}
// extra challenge
var localCurrency: FloatingPointFormatStyle<Double>.Currency {
.currency(code: Locale.current.currencyCode ?? "USD")
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Amount", value: $checkAmount, format: localCurrency)
.keyboardType(.decimalPad)
.focused($amountIsFocused)
Picker("Number of people", selection: $numberOfPeople) {
ForEach(2..<100) {
Text("\($0) people")
}
}
}
Section {
// challenge 3
if #available(iOS 16.0, *) {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(0..<101) {
Text("\($0) %")
}
}
.pickerStyle(.navigationLink)
} else {
Picker("Tip percentage", selection: $tipPercentage) {
ForEach(0..<101) {
Text("\($0) %")
}
}
}
} header: {
Text("How much tip do you want to leave?")
}
Section {
Text(totalPerPerson, format: localCurrency)
} header: {
// challenge 1
Text("Amount per person")
}
// challenge 2
Section {
Text(totalAmount, format: localCurrency)
.foregroundColor(tipPercentage == 0 ? .red : .black) // project 3 - challenge 1
} header: {
Text("Total amount")
}
}
.navigationTitle("WeSplit")
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") {
amountIsFocused = false
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.ball {
display: inline-block;
border: 1px solid black;
border-radius: 20px;
width: 40px;
height: 40px;
line-height: 40px;
font-size: 20px;
text-align: center;
margin-right: 20px;
}
</style>
</head>
<body>
<div id="result">추첨 결과는 ? </div>
<div id="bonus">보너스: </div>
<script>
//아래 알고리즘은 피셔-예이츠 셔플(Fishuer-Yates Shuffle)이라고 함. 모든 숫자를 랜덤으로 섞이게 하는 알고리즘
const candidate = Array(45).fill().map((v,i) => i + 1); // v가 들어간 자리가 element자리고 여기서 v라는 매개변수는 쓰이지 않았는데 왜 들어간걸까
// 요소가 45개인 빈 배열은 선언 후 fill.map을 사용해 인덱스값 +1을 넣어줌(candidate[0]이 1이 될 수 있도록
const shuffle = []; //candidate의 요소가 무작위로 들어갈 배열을 선언
while (candidate.length>0) { //candidate의 길이가 1이 될 때 까지 아래 내용을 반복
const random = Math.floor(Math.random() * candidate.length) //무작위 인덱스 뽑기 caididae의 숫자만 조정하면 건들 필요 없게 만듬
const spliceArray = candidate.splice(random, 1); //위의 무작위 값을 condidate에서 빼서 spilceArray에 넣어주는 과정
const value = spliceArray[0]; // spliceArray배열의 index[0]을 value라는 변수로 지정
shuffle.push(value); // 위 값을 shuffle배열에 넣어줌
} // random이라는 변수로 숫자를 무작위로 뽑고 -> 그 수를 cadidate에서 spliceArray로 가져온 후 -> spliceArray에 들어간 값을 다시 shuffle에 넣어줌
//결과적으로 shuffle에 1~45가 무작위로 들어가게 해주는 과정
console.log(shuffle);
// 위의 와일문을 for문으로 바꾸는 법
// for (let i = candidate.length; i > 0; i--) {
// const random = Math.floor(Math.random() * i);
// const spliceArray = candidate.splice(random, 1);
// const value = spliceArray[0];
// shuffle.push(value);
// } // 결론 : while문은 조건이 간단하면 쓰기가 편하고 조건이 복잡할 땐 for문이 좋다.
// 팁 : while은 내가 몇 번 반복할지 정확히 모를 떄 쓰기 좋다. for문은 내가 몇번 반복해야하는지 횟수, 처음과 끝을 알아야 하기 때문
// 팁2: 만약 while문에 증감연산자가 들어가겠다 싶으면 그냥 for문을 쓰는 게 좋음
// 배열 원본이 안 변하는 메서드 : map과 slice는 복사해서 가져오는 느낌이고 splice같은 건 잘라서 가져옴 slice(시작요소, 끝요소) 인데, 시작요소는 포함하고 끝 요소는 포함하지않음.
// ※주의 splice는 (시작할 인덱스, 그로부터 몇 개)인데 slice는 (시작할 인덱스, 끝 인덱스)임 slice 끝 요소에 -1을 쓰면 뒤에서부터 한개, -(숫자)로 뒤에서부터도 셀 수 있음
//sort메서드를 사용할 경우 원본이 수정됨. 문제가 될 요지가 있다. 그래서 array.slice()으로 똑같은 걸 가져와서 거기에다가 sort하는 걸 추천
//팁 3: 사전순 정렬을 하고싶다면 sort((a,b) => a.localeCompare(b))를 사용하면됨. 내림차순은 a와b순서를 바꿔주면 됨.
const winBalls = shuffle.slice(0, 6).sort((a,b) => a - b); // shuffle에서 0번 인덱스부터 5번 인덱스까지 복사한 후 그걸 sort하고 오름차순으로 정렬한 걸 변수 winBalls에 넣음
const bonus = shuffle[6]; // 변수 bonus에는 shuffle의 6번 인덱스를 넣음
console.log(winBalls, bonus);
const $result = document.querySelector('#result');
const $bonus = document.querySelector('#bonus');
const showBall = (number, $target) =>{ // 매개변수의 이름은 딱히 상관이 없음. a여도 됨
const $ball = document.createElement('div');
$ball.className = 'ball';
$ball.textContent = number;
$target.appendChild($ball);
// 셀프체크
if ( $ball.textContent >= 40) {
$ball.style.backgroundColor = "green";
$ball.style.color = "white"
} else if ($ball.textContent < 40 && $ball.textContent >= 30 ) {
$ball.style.backgroundColor = "blue";
$ball.style.color = "white"
} else if ($ball.textContent < 30 && $ball.textContent >= 20) {
$ball.style.backgroundColor = "yellow";
} else if ($ball.textContent < 20 && $ball.textContent >= 10 ) {
$ball.style.backgroundColor = "orange";
} else if ($ball.textContent < 10) {
$ball.style.backgroundColor = "red";
$ball.style.color = "white"
}
// 셀프체크
};
//$ball이라는 div를 만들어주고, 거기에 ball이라는 클래스 네임을 붙임. #ball에 들어가는 내용은 winBalls의 인덱스. 그 후 result가 출력할 수 있도록 어펜드차일드를 해줌
for (let i = 0; i < 6; i++) {
setTimeout(() => {
showBall(winBalls[i], $result);
}, (i+1) * 1000); // [0,1,2,3,4,5]를 [1000,2000,3000,4000,5000,6000]으로 바꿔줌
}
setTimeout(() => {
showBall(bonus, $bonus);
}, 7000);
// setTimeout(() => {
// showBall(winBalls[0], $result);
// }, 1000);
// // 중복되는 부분은 콜백함수로 뺴버리고 매개변수를 줘서 중복을 해소할 수 있다.
// //이대로 복사해서 값만 바뀐 여러개를 만들면 편하지만 중복코드가 되기떄문에 바꿔줘야함...
//closer,scope - var와 let의 차이 *클로저 문제란 함수와 함수 바깥의 있는 변수의 문제. var와 비동기(셋인터벌, 셋타임아웃등)가 만나면 벌어진다.
// 일반적으로 let을 쓰는게 좋고 var는 사실상 더 이상 쓸 필요가 없지만 과거에 작성된 코드들을 볼 때 var가 필요할 때가 있음.
// var는 함수 스코프를 가졌고 const,let은 블록 스코프를 가졌다. 스코프란 변수에 접근 가능한 범위
// 함수 스코프 ex
// function b() {
// var a = 1;
// }
// console.log(a);
//이거 에러 뜸 var는 함수 스코프이기때문에 함수 밖에서 부르면 접근이 안 되는 거임 var도 함수 안 혹은 바깥의 모든 접근을 차단함
// 블록스코프는 블록 바깥에서의 접근이나 바깥으로의 접근을 차단함 블록 안에 고정됐다고 할 수 있음. 그래서 for,while등의 괄호와 사용할 때 이상이 없는 것
// for문은 동기이고 settimeout은 비동기임 ★결론 : 걍 let써라
</script>
</body>
</html> |
package com.ironhack.studentcatalogservice.service.impl;
import com.ironhack.studentcatalogservice.client.GradesDataService;
import com.ironhack.studentcatalogservice.client.StudentInfoService;
import com.ironhack.studentcatalogservice.model.*;
import com.ironhack.studentcatalogservice.service.interfaces.CatalogServiceInterface;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
@Slf4j
public class CatalogService implements CatalogServiceInterface {
@Autowired
private StudentInfoService studentInfoService;
@Autowired
private GradesDataService gradesDataService;
public Catalog getCatalog(String courseCode) {
// You need to create some of the methods used here in the client package for it to work
Course course = gradesDataService.getCourseByCourseCode(courseCode);
CourseGrade courseGrades = gradesDataService.getCourseGrades(courseCode);
Catalog catalog = new Catalog();
catalog.setCourseName(course.getCourseName());
List<StudentGrade> studentGrades = new ArrayList<>();
for (Grade grade : courseGrades.getGrades()) {
Student student = studentInfoService.getStudentInfo(grade.getStudentId());
studentGrades.add(new StudentGrade(student.getName(), student.getAge(), grade.getGrade()));
}
catalog.setStudentGrades(studentGrades);
return catalog;
}
} |
/*
* author: ADMathNoob
* created: 04/21/21 09:48:16
* problem: https://codeforces.com/contest/1516/problem/E
*/
/*
g++ 1516E.cpp -D_DEBUG -std=c++11 -Wl,--stack=268435456 -Wall -Wfatal-errors -ggdb && gdb a
g++ 1516E.cpp -D_DEBUG -std=c++11 -Wl,--stack=268435456 -O3 -Wall -Wfatal-errors
*/
#include <bits/stdc++.h>
using namespace std;
template <typename T>
T inverse(T a, T m) {
T u = 0, v = 1;
while (a != 0) {
T t = m / a;
m -= t * a;
swap(a, m);
u -= t * v;
swap(u, v);
}
assert(m == 1);
return u;
}
template <typename T>
class Modular {
public:
using Type = typename decay<decltype(T::value)>::type;
constexpr Modular() : value() {}
template <typename U>
Modular(const U& x) {
value = normalize(x);
}
template <typename U>
static Type normalize(const U& x) {
Type v;
if (-mod() <= x && x < mod())
v = static_cast<Type>(x);
else
v = static_cast<Type>(x % mod());
if (v < 0) v += mod();
return v;
}
const Type& operator()() const { return value; }
template <typename U>
explicit operator U() const { return static_cast<U>(value); }
constexpr static Type mod() { return T::value; }
Modular& operator+=(const Modular& other) {
if ((value += other.value) >= mod()) value -= mod();
return *this;
}
Modular& operator-=(const Modular& other) {
if ((value -= other.value) < 0) value += mod();
return *this;
}
template <typename U>
Modular& operator+=(const U& other) { return *this += Modular(other); }
template <typename U>
Modular& operator-=(const U& other) { return *this -= Modular(other); }
Modular& operator++() { return *this += 1; }
Modular& operator--() { return *this -= 1; }
Modular operator++(int) {
Modular result(*this);
*this += 1;
return result;
}
Modular operator--(int) {
Modular result(*this);
*this -= 1;
return result;
}
Modular operator-() const { return Modular(-value); }
template <typename U = T>
typename enable_if<is_same<typename Modular<U>::Type, int>::value, Modular>::type& operator*=(const Modular& rhs) {
#ifdef _WIN32
uint64_t x = static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value);
uint32_t xh = static_cast<uint32_t>(x >> 32), xl = static_cast<uint32_t>(x), d, m;
asm(
"divl %4; \n\t"
: "=a"(d), "=d"(m)
: "d"(xh), "a"(xl), "r"(mod()));
value = m;
#else
value = normalize(static_cast<int64_t>(value) * static_cast<int64_t>(rhs.value));
#endif
return *this;
}
template <typename U = T>
typename enable_if<is_same<typename Modular<U>::Type, long long>::value, Modular>::type& operator*=(const Modular& rhs) {
long long q = static_cast<long long>(static_cast<long double>(value) * rhs.value / mod());
value = normalize(value * rhs.value - q * mod());
return *this;
}
template <typename U = T>
typename enable_if<!is_integral<typename Modular<U>::Type>::value, Modular>::type& operator*=(const Modular& rhs) {
value = normalize(value * rhs.value);
return *this;
}
Modular& operator/=(const Modular& other) { return *this *= Modular(inverse(other.value, mod())); }
friend const Type& abs(const Modular& x) { return x.value; }
template <typename U>
friend bool operator==(const Modular<U>& lhs, const Modular<U>& rhs);
template <typename U>
friend bool operator<(const Modular<U>& lhs, const Modular<U>& rhs);
template <typename V, typename U>
friend V& operator>>(V& stream, Modular<U>& number);
private:
Type value;
};
template <typename T>
bool operator==(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value == rhs.value; }
template <typename T, typename U>
bool operator==(const Modular<T>& lhs, U rhs) { return lhs == Modular<T>(rhs); }
template <typename T, typename U>
bool operator==(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) == rhs; }
template <typename T>
bool operator!=(const Modular<T>& lhs, const Modular<T>& rhs) { return !(lhs == rhs); }
template <typename T, typename U>
bool operator!=(const Modular<T>& lhs, U rhs) { return !(lhs == rhs); }
template <typename T, typename U>
bool operator!=(U lhs, const Modular<T>& rhs) { return !(lhs == rhs); }
template <typename T>
bool operator<(const Modular<T>& lhs, const Modular<T>& rhs) { return lhs.value < rhs.value; }
template <typename T>
Modular<T> operator+(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U>
Modular<T> operator+(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) += rhs; }
template <typename T, typename U>
Modular<T> operator+(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) += rhs; }
template <typename T>
Modular<T> operator-(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U>
Modular<T> operator-(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T, typename U>
Modular<T> operator-(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) -= rhs; }
template <typename T>
Modular<T> operator*(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U>
Modular<T> operator*(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T, typename U>
Modular<T> operator*(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) *= rhs; }
template <typename T>
Modular<T> operator/(const Modular<T>& lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U>
Modular<T> operator/(const Modular<T>& lhs, U rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U>
Modular<T> operator/(U lhs, const Modular<T>& rhs) { return Modular<T>(lhs) /= rhs; }
template <typename T, typename U>
Modular<T> power(const Modular<T>& a, const U& b) {
assert(b >= 0);
Modular<T> x = a, res = 1;
U p = b;
while (p > 0) {
if (p & 1) res *= x;
x *= x;
p >>= 1;
}
return res;
}
template <typename T>
bool IsZero(const Modular<T>& number) {
return number() == 0;
}
template <typename T>
string to_string(const Modular<T>& number) {
return to_string(number());
}
// U == std::ostream? but done this way because of fastoutput
template <typename U, typename T>
U& operator<<(U& stream, const Modular<T>& number) {
return stream << number();
}
// U == std::istream? but done this way because of fastinput
template <typename U, typename T>
U& operator>>(U& stream, Modular<T>& number) {
typename common_type<typename Modular<T>::Type, long long>::type x;
stream >> x;
number.value = Modular<T>::normalize(x);
return stream;
}
constexpr int md = (int) 1e9 + 7;
using Mint = Modular<std::integral_constant<decay<decltype(md)>::type, md>>;
vector<Mint> fact(1, 1);
vector<Mint> inv_fact(1, 1);
Mint C(int n, int k) {
if (k < 0 || k > n) {
return 0;
}
while ((int) fact.size() < n + 1) {
fact.push_back(fact.back() * (int) fact.size());
inv_fact.push_back(1 / fact.back());
}
return fact[n] * inv_fact[k] * inv_fact[n - k];
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, k;
cin >> n >> k;
vector<Mint> n_choose(2 * k + 1);
n_choose[0] = 1;
for (int i = 1; i <= 2 * k; i++) {
n_choose[i] = n_choose[i - 1] * (n + 1 - i) / i;
}
vector<vector<Mint>> f(2 * k + 1, vector<Mint>(k + 1));
f[0][0] = 1;
for (int x = 1; x <= 2 * k; x++) {
for (int c = 1; c <= x / 2; c++) {
if (x >= 2) {
f[x][c] += f[x - 2][c - 1] * (x - 1);
}
f[x][c] += f[x - 1][c] * (x - 1);
}
}
vector<Mint> for_exact(2 * k + 1);
for (int x = 0; x <= 2 * k; x++) {
for (int c = 0; c <= x / 2; c++) {
for_exact[x - c] += n_choose[x] * f[x][c];
}
}
// for (int j = 0; j <= 2 * k; j++) {
// cerr << for_exact[j] << '\n';
// }
// cerr << '\n';
vector<Mint> ans(k + 1);
for (int j = 0; j <= k; j++) {
ans[j] = for_exact[j];
if (j >= 2) {
ans[j] += ans[j - 2];
}
}
for (int j = 1; j <= k; j++) {
if (j > 1) {
cout << ' ';
}
cout << ans[j];
}
cout << '\n';
return 0;
} |
import { Link, useNavigate } from 'react-router-dom';
import { z } from 'zod';
import { signUpSchema } from '../validations/AuthValidation';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useAppDispatch, useAppSelector } from '../redux/store';
import { signUpFailure, signUpStart, signUpSuccess } from '../redux/user/userSlice';
import OAuth from '../components/OAuth';
const baseUrl = "/api/v1"
type SignupValueTypes = z.infer<typeof signUpSchema>
export default function Signup() {
const {register, handleSubmit, formState: { errors, isValid, isDirty, isSubmitting }} = useForm<SignupValueTypes>({
defaultValues: {
username: "",
email: "",
password: ""
},
resolver: zodResolver(signUpSchema),
mode: "all"
});
const isDisabled = !isDirty || !isValid || isSubmitting;
const navigate = useNavigate();
const dispatch = useAppDispatch();
const error = useAppSelector((state) => state.user.error);
const handleSignup = async (signupdata: SignupValueTypes) => {
try {
dispatch(signUpStart());
const response = await fetch(`${baseUrl}/auth/signup`, {
method: "POST",
body: JSON.stringify(signupdata),
headers: {
'Content-Type': "application/json"
}
});
const { message, data } = await response.json();
if(!response.ok) {
dispatch(signUpFailure(message));
}
dispatch(signUpSuccess(data))
return navigate('/', { replace: true });
} catch (error) {
dispatch(signUpFailure((error as any)?.message));
} finally {
setTimeout(() => {dispatch(signUpFailure(""))}, 9000);
}
}
return (
<div className='min-h-screen w-full lg:max-w-lg mx-auto p-3 '>
<div className="w-full mt-40">
<h1 className='text-3xl text-center font-semibold my-7'>SignUp</h1>
<form className='flex flex-col gap-4' onSubmit={handleSubmit(handleSignup)}>
<input type="text" autoComplete='on' {...register("username")} id="username" placeholder='Username' className='bg-slate-100 p-3 rounded-lg' />
{errors.username?.message && <p className='text-sm text-red-600 '> {errors.username?.message} </p>}
<input type="email" autoComplete='on' {...register("email")} id="email" placeholder='Email' className='bg-slate-100 p-3 rounded-lg' />
{errors.email?.message && <p className='text-sm text-red-600 '> {errors.email?.message} </p>}
<input type="password" autoComplete='on' {...register("password")} id="password" placeholder='Password' className='bg-slate-100 p-3 rounded-lg' />
{errors.password?.message && <p className='text-sm text-red-600 '> {errors.password?.message} </p>}
<button disabled={isDisabled} className="disabled:cursor-no-drop bg-slate-700 text-white p-3 rounded-lg uppercase hover:opacity-95 disabled:opacity-80">
{isSubmitting ? "Loading..." : "Signup"}
</button>
<OAuth />
</form>
<div className="flex items-center justify-center gap-2 mt-5 ">
<p>Have an acount?</p>
<Link to="/signin" >
<span className="text-blue-500">Signin</span>
</Link>
</div>
{error && <p className='text-sm text-red-600 mt-5 text-center bg-red-200 p-2 rounded'> {error} </p>}
</div>
</div>
)
} |
setwd("F:/desktop/Online learning course/Coursera_Google_Analytics/Bellabeat/bellabeat1")
library(gridExtra)
library(factoextra)
library(mclust)
library(ggpubr)
library(ggplot2)
library(dplyr)
library(stringr)
library(ggplot2)
library(tidyverse)
library(lubridate)
library(skimr)
library(SimDesign)
library(chron)
library(ggcorrplot)
colnames(minuteSleep)[6]<- "ActivityDate"
# colnames(day_sleep)[7]<- "ActivityDate"
# day_sleep_cp <- day_sleep
minuteSleep <- minuteSleep %>% subset(ActivityDate >= "2016-04-12" &
ActivityDate <="2016-05-12")
#
# min(day_sleep$Date)
# max(day_sleep$Date)
# min(daily_activity$ActivityDate)
# max(daily_activity$ActivityDate)
# min(day_sleep_cp$ActivityDate)
# max(day_sleep_cp$ActivityDate)
# min(minuteSleep$ActivityDate)
# max(minuteSleep$ActivityDate)
#
day_sleep_cp <-
merge(
minuteSleep %>%
group_by(Id,ActivityDate) %>%
mutate(TotalTimeInBed=as.numeric(difftime(time,lag(time),units="mins"))) %>%
replace(is.na(.),0) %>%
mutate(TotalTimeInBed=ifelse(TotalTimeInBed>1,0,1)) %>%
summarise(TotalTimeInBed=sum(TotalTimeInBed)),
minuteSleep %>%
group_by(Id,ActivityDate) %>%
mutate(TotalSleepRecords=n_distinct(logId)) %>%
replace(is.na(.),0) %>%
summarise(TotalSleepRecords=max(TotalSleepRecords)),
by = c("Id","ActivityDate"))
anti_join(day_sleep[,],day_sleep_cp[,])
day_sleep_cp <- left_join(day_sleep_cp,
minuteSleep %>%
group_by(Id,ActivityDate) %>%
filter(value==1) %>%
mutate(TotalMinutesAsleep=n()) %>%
replace(is.na(.),0) %>%
summarise(TotalMinutesAsleep=mean(TotalMinutesAsleep)))
day_sleep_cp <- clean_narrow_data(day_sleep_cp,deparse(substitute(day_sleep_cp)))
day_sleep_cp[,5] <- day_sleep_cp[,5] %>% replace_na(0)
t1 <- day_sleep[,c(1,5:7)] %>% group_by(Id,ActivityDate) %>% summarise(n())
t2 <- day_sleep_cp[,c(1,2,6,7)] %>% group_by(Id,ActivityDate) %>% summarise(n())
anti_join(t1,t2)
rm(t1,t2)
# ,day_sleep,minuteSleep)
#############################################################################
# install.packages("summarytools")
# install.packages("dataMaid")
print(dfSummary(minuteSleep),file="abc.html")
makeDataReport(da_sleep,render=FALSE)
explore(da_sleep)
da_sleep <- inner_join(daily_activity,day_sleep_cp)
head(which(is.na(da_sleep), arr.ind=TRUE))
# 1844505072
quantile(ceiling(day_sleep_cp$TotalMinutesAsleep/60))
da_sleep <- da_sleep %>%
mutate(scluster =case_when(
TotalMinutesAsleep< quantile(ceiling(TotalMinutesAsleep),0.25) ~"Short Sleeper",
TotalMinutesAsleep>=quantile(ceiling(TotalMinutesAsleep),0.25)&
TotalMinutesAsleep<=quantile(ceiling(TotalMinutesAsleep),0.75) ~"Perfect Sleepers",
TotalMinutesAsleep>quantile(ceiling(TotalMinutesAsleep),0.75) ~"Long Sleepers"
),awake_min = TotalTimeInBed - TotalMinutesAsleep)
quantile(da_sleep$TotalMinutesAsleep/60)
# LEFTOUT
da_sleep %>% ggplot(aes(x=TotalTimeInBed/60,y=round(TotalMinutesAsleep/60,2)))+
geom_jitter()+
facet_grid(~TotalSleepRecords)+
scale_y_continuous(breaks = seq(0, 13, len = 13))+
scale_x_continuous(breaks = seq(0, 16, by = 1))
x11()
da_sleep[which(is.na(da_sleep)),]
da_sleep %>% ggplot(aes(x=TotalTimeInBed/60,y=round(TotalMinutesAsleep/60,2)))+
geom_jitter()+
facet_grid(~mcluster)+
scale_y_continuous(breaks = seq(0, 13, len = 13))+
scale_x_continuous(breaks = seq(0, 16, by = 1))+
geom_hline(data = da_sleep %>%
group_by(mcluster) %>%
summarise(MN=mean(TotalMinutesAsleep/60)),
aes(yintercept = MN), col = "purple", linetype = 2,show.legend = TRUE)+
geom_text(data = da_sleep %>%
group_by(mcluster) %>%
summarise(MN=mean(TotalMinutesAsleep/60)),
aes(0,MN,label=round(MN,2),vjust=0,hjust=0))+
geom_hline(data = da_sleep ,
aes(yintercept = mean(TotalMinutesAsleep/60)),
col = "red", linetype = 1,show.legend = TRUE)+
geom_text(data = da_sleep %>%
summarise(MN=mean(TotalMinutesAsleep/60)),
aes(0,MN,label=round(MN,2),vjust=0,hjust=-1))
da_sleep %>%
ggplot(aes(x=(TotalTimeInBed/60),y=round((TotalMinutesAsleep/60),2)))+
geom_jitter()+
facet_grid(day~mcluster)+
scale_y_continuous(breaks = seq(0, 13, len = 8))+
geom_hline(data = (da_sleep %>%
group_by(mcluster) %>%
summarise(MN=mean(TotalMinutesAsleep/60))),
aes(yintercept = MN), col = "red", linetype = 1,show.legend = TRUE)+
geom_vline(data = da_sleep %>%
group_by(mcluster) %>%
summarise(MN=mean(TotalTimeInBed/60)),
aes(xintercept = MN), col = "blue", linetype = 1,show.legend = TRUE)
# da_sleep %>% select(19:22) %>% summary()
# da_sleep %>% filter(scluster==1) %>% select(19:22) %>% summary()
# da_sleep %>% filter(scluster==2) %>% select(19:22) %>% summary()
# da_sleep %>% filter(scluster==3) %>% select(19:22) %>% summary()
# library(plotly)
x11()
ggplotly(
da_sleep %>%
ggplot(aes(x=TotalTimeInBed/60,y=TotalMinutesAsleep/60)) +
# ggplot(aes(y=mean(TotalTimeInBed/60-TotalMinutesAsleep/60),x=scluster,fill=scluster))+
geom_jitter()+
facet_grid(mcluster~scluster)+
geom_hline(data = da_sleep %>%
group_by(scluster,mcluster) %>%
summarise(MN=mean(TotalMinutesAsleep/60)),
aes(yintercept = MN), col = "red", linetype = 1,show.legend = TRUE)+
geom_vline(data = da_sleep %>%
group_by(scluster,mcluster) %>%
summarise(MN=mean(TotalTimeInBed/60)),
aes(xintercept = MN), col = "blue", linetype = 1,show.legend = TRUE)+
geom_vline(data = da_sleep %>%
summarise(MN=mean(TotalTimeInBed/60)),
aes(xintercept = MN), col = "black", linetype = 2,show.legend = TRUE)+
geom_hline(data = da_sleep %>%
summarise(MN=mean(TotalMinutesAsleep/60)),
aes(yintercept = MN), col = "black", linetype = 2,show.legend = TRUE)+
scale_y_continuous(breaks = seq(0, 13, len = 13))+
scale_x_continuous(breaks = seq(0, 16, len = 6))
)
x11()
library(ggalt)
# install.packages("ggalt")
library(dplyr)
da_sleep %>%
group_by(mcluster,st,scluster) %>% distinct() %>%
summarise(total_calories= mean(Calories)) %>%
mutate(total_calories=round(total_calories/1000,2)) %>%
ggplot(aes(x=st,y=total_calories))+#,fill=factor(scluster)) +
geom_lollipop(horizontal =FALSE,
point.colour = "blue"
)+
# geom_col(aes(fill=factor(scluster)))+
facet_grid(scluster~factor(mcluster))+
geom_text(aes(label =(total_calories)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1.0,hjust=0.5))+
labs(y="Avg CAlories Burnt(000)")
da_sleep$sleep_efficiency <- da_sleep$TotalMinutesAsleep / da_sleep$TotalTimeInBed
#######################################
ggarrange(
da_sleep %>%
filter(mcluster=="Very Active") %>%
group_by(scluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=reorder(st,total_efficiency*100),y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(scluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Long Sleepers")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(scluster=="Short Sleeper") %>%
group_by(mcluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=st,y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Short Sleepers")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(scluster=="Perfect Sleepers") %>%
group_by(mcluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=st,y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Perfect Sleepers")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),ncol = 1,nrow = 3)
ggarrange(
da_sleep %>%
filter(mcluster=="Very Active") %>%
group_by(scluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=reorder(st,total_efficiency*100),y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(scluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Very Active USer")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(mcluster=="Fairly Active") %>%
group_by(scluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=reorder(st,total_efficiency*100),y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(scluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Fairly Active User")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(mcluster=="Lightly Active") %>%
group_by(scluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=reorder(st,total_efficiency*100),y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(scluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Lightly Active USer")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(mcluster=="Sedentary") %>%
group_by(scluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=reorder(st,total_efficiency*100),y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(scluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Sedentary User")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
ncol = 2,nrow = 2)
#################################################
x11()
ggarrange(
ggarrange(
da_sleep %>%
filter(scluster=="Long Sleepers") %>%
group_by(mcluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=st,y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Long Sleepers")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(scluster=="Short Sleeper") %>%
group_by(mcluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=st,y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Short Sleepers")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(scluster=="Perfect Sleepers") %>%
group_by(mcluster,st) %>%
summarise(total_efficiency= round(mean(sleep_efficiency),2)) %>%
ggplot(aes(x=st,y=total_efficiency*100)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_efficiency*100)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Sleep Efficiency")+
theme(axis.text.x = element_blank())+
ggtitle("Perfect Sleepers")+
coord_polar(theta = "y",start=0)+
theme(axis.text.y = element_blank()),ncol = 1,nrow = 3,align = "v"),
ggarrange(
da_sleep %>%
filter(scluster=="Long Sleepers") %>%
group_by(mcluster,st) %>%
summarise(total_awake= round(mean(TotalTimeInBed - TotalMinutesAsleep),2)) %>%
ggplot(aes(x=st,y=total_awake)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_awake)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Total_Awake")+
theme(axis.text.x = element_blank())+
ggtitle("Long Sleepers")+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(scluster=="Short Sleeper") %>%
group_by(mcluster,st) %>%
summarise(total_awake= round(mean(TotalTimeInBed - TotalMinutesAsleep),2)) %>%
ggplot(aes(x=st,y=total_awake)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_awake)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Total_Awake")+
theme(axis.text.x = element_blank())+
ggtitle("Short Sleepers")+
theme(axis.text.y = element_blank()),
da_sleep %>%
filter(scluster=="Perfect Sleepers") %>%
group_by(mcluster,st) %>%
summarise(total_awake= round(mean(TotalTimeInBed - TotalMinutesAsleep),2)) %>%
ggplot(aes(x=st,y=total_awake)) +
geom_col(aes(fill=st))+
facet_grid(~factor(mcluster))+
geom_text(aes(label =(total_awake)), vjust = -0.2, size = 3,
position = position_dodge(0.9))+
theme(axis.text.x = element_text(angle =90,vjust=1,hjust=0.5))+
labs(y="Total_Awake")+
theme(axis.text.x = element_blank())+
ggtitle("Perfect Sleepers")+
theme(axis.text.y = element_blank())
,ncol = 1,nrow = 3,align = "v"))
##################################################################################
# daily_acti_min_sleep <- merge(daily_activity,minuteSleep,all.y=TRUE )
da_mi_sleep <- right_join(da_sleep,minuteSleep)
head(which(is.na(da_mi_sleep), arr.ind=TRUE))
da_mi_sleep <- da_mi_sleep %>%
mutate(status=case_when(
value==1 ~"Asleep",
value==2 ~"Restless",
value==3 ~"Awake"
)) %>% select(-c("value"))
da_mi_sleep <- left_join(da_mi_sleep, da_mi_sleep %>%
group_by(Id,ActivityDate,status) %>% count()
)
colnames(da_mi_sleep)[29] <- "Minutes"
# da_mi_sleep <- da_mi_sleep %>% select(-c(27)) %>% distinct()
# da_mi_sleep %>% spread(key = "status",value = "n")
head(which(is.na(da_mi_sleep), arr.ind=TRUE))
# t <- da_mi_sleep %>%
# group_by(mcluster,scluster,st,status) %>%
# summarise(mt=mean(Minutes)) %>% distinct()
# t1 <- da_mi_sleep %>%
# group_by(mcluster,scluster,st) %>%
# summarise(mt=mean(TotalTimeInBed)) %>% distinct()
#
x11()
ggarrange(
# x11()
da_mi_sleep %>%
select(-c(27)) %>%
distinct() %>%
group_by(mcluster,scluster,st,status) %>%
summarise(ttb=round(mean(Minutes/60),3)) %>%
# filter(status=="Awake" || status=="Restless") %>%
ggplot(aes(x=scluster,y=ttb)) +
# geom_boxplot()+
geom_bar(stat="identity",aes(fill=status),position = "dodge")+
facet_grid(st~mcluster)+
geom_text(aes(label = sprintf("%2.1f", ttb),fill=status),
size = 3,
position = position_dodge(width = 1),
hjust=-0.23)+coord_flip()+
ylab("MINS Sleep Status mins")+
xlab("Sleeper Type"),
# x11()
da_mi_sleep %>%
select(-c(27)) %>%
distinct() %>%
group_by(mcluster,scluster,st) %>%
#
summarise(ttb=round(mean(TotalTimeInBed/60),3)) %>%
#
# filter(status=="Awake" || status=="Restless") %>%
ggplot(aes(x=scluster,y=ttb)) +
# geom_boxplot()+
geom_bar(stat="identity",position = "dodge")+
facet_grid(st~mcluster)+
geom_text(aes(label = sprintf("%2.1f", ttb)),
size = 3,
position = position_dodge(width = 1),
hjust=-0.23)+coord_flip()+
ylab("total time in bed hours")+
xlab("Sleeper Type")
)
da_mi_sleep %>% group_by(scluster,st) %>% distinct () %>% summarise(ct=n())
head(which(is.na(da_mi_sleep), arr.ind=TRUE))
x11()
da_mi_sleep %>%
select(-c(27)) %>%
distinct() %>%
group_by(scluster,st) %>%
summarise(mt=mean(TotalTimeInBed/60)) %>%
ggplot(aes(x=scluster,y=mt))+
geom_col()+
facet_grid(~st)+
geom_text(aes(label = sprintf("%2.1f", mt)),
size = 3,
position = position_dodge(width = 1),
hjust=1,vjust=-1)+
scale_y_continuous(labels = function(x) format(x, scientific = FALSE))+
ylab("Total time in bed")
#################################################
# REMAINING TO ADD IN RMD
ggarrange(
da_mi_sleep %>%
# mutate(hr=hour(time)) %>%
group_by(day,mcluster,scluster) %>% distinct() %>%
# filter(str_detect(st,"Average")) %>%
summarise(dist=round(mean(TotalDistance),2)) %>%
ggplot(aes(x=scluster,y=dist)) +
geom_col(position="dodge")+
facet_grid(day~mcluster)+
# facet_grid(mcluster~scluster)+
scale_y_continuous(labels = function(x) format(x, scientific = FALSE))+
coord_flip()+
scale_fill_viridis_c()+
geom_text(aes(label = sprintf("%2.1f", dist)),
size = 3,
position = position_dodge(width = 1),
hjust=-0.23),
da_mi_sleep %>%
# mutate(hr=hour(time)) %>%
group_by(day,mcluster,scluster) %>% distinct() %>%
# filter(str_detect(st,"Average")) %>%
summarise(cal=round(mean(Calories/1000),2)) %>%
ggplot(aes(x=scluster,y=cal)) +
geom_col(position="dodge")+
facet_grid(day~mcluster)+
scale_fill_viridis(discrete=TRUE)+
# facet_grid(mcluster~scluster)+
scale_y_continuous(labels = function(x) format(x, scientific = FALSE))+
geom_text(aes(label = sprintf("%2.1f", cal)),
size = 3,
position = position_dodge(width = 1),
hjust=-0.23)+
coord_flip()+
ylab("Calories Burnt")+
theme(axis.text.x = element_text(angle =90,vjust=1.0,hjust=0.5))
) |
#include "cofffileheader.h"
namespace pe
{
CoffFileHeader::CoffFileHeader(const char *file_header_data)
{
SetUpCoffFileHeaderVector(file_header_data);
}
void CoffFileHeader::SetUpCoffFileHeaderVector(const char *file_header_data)
{
int offset = 0;
file_header_vector_.clear();
file_header_vector_.push_back(
Field{"Machine",
MemoryToUint16(file_header_data + offset),
2}
);
offset += 2;
file_header_vector_.push_back(
Field{"NumberOfSections",
MemoryToUint16(file_header_data + offset),
2}
);
offset += 2;
file_header_vector_.push_back(
Field{"TimeDateStamp",
MemoryToUint32(file_header_data + offset),
4}
);
offset += 4;
file_header_vector_.push_back(
Field{"PointerToSymbolTable",
MemoryToUint32(file_header_data + offset),
4}
);
offset += 4;
file_header_vector_.push_back(
Field{"NumberOfSymbols",
MemoryToUint32(file_header_data + offset),
4}
);
offset += 4;
file_header_vector_.push_back(
Field{"SizeOfOptionalHeader",
MemoryToUint16(file_header_data + offset),
2}
);
offset += 2;
file_header_vector_.push_back(
Field{"Characteristics",
MemoryToUint16(file_header_data + offset),
2}
);
offset += 2;
}
Field CoffFileHeader::GetFieldByName(const std::string &name)
{
for (auto& ele: file_header_vector_)
{
if (ele.name == name)
{
return ele;
}
}
return Field();
}
std::string CoffFileHeader::ToString(int pad)
{
std::string s;
std::string pad_str(pad * 4, ' ');
for (auto& ele: file_header_vector_)
{
s.append(pad_str + ele.name + ": " + ToHex(ele.value) + "\n");
}
s.append("\n");
return s;
}
} |
import numpy as np
import matplotlib.pyplot as plt
import random
import time
from math import sqrt, inf
def is_collision(point, obstacles, rect_obstacle):
for center, radius in obstacles:
if sqrt((center[0] - point[0]) ** 2 + (center[1] - point[1]) ** 2) <= radius:
return True
x, y = point
if rect_obstacle[0][0] <= x <= rect_obstacle[3][0] and rect_obstacle[0][1] <= y <= rect_obstacle[1][1]:
return True
return False
def nearest_node(nodes, point):
nearest = None
min_dist = inf
for node in nodes:
dist = sqrt((node[0] - point[0]) ** 2 + (node[1] - point[1]) ** 2)
if dist < min_dist:
nearest = node
min_dist = dist
return nearest
def steer(from_node, to_point, step_size, obstacles, rect_obstacle):
direction = np.arctan2(to_point[1] - from_node[1], to_point[0] - from_node[0])
new_point = (from_node[0] + step_size * np.cos(direction), from_node[1] + step_size * np.sin(direction))
return new_point if not is_collision(new_point, obstacles, rect_obstacle) else None
def connect(start_tree, goal_tree, step_size, obstacles, rect_obstacle):
last_node = None
while True:
nearest = nearest_node(start_tree, last_node if last_node else goal_tree[-1])
new_point = steer(nearest, goal_tree[-1], step_size, obstacles, rect_obstacle)
if new_point is None:
return last_node # Can't extend further towards the goal_tree
start_tree[new_point] = nearest
last_node = new_point
if new_point == goal_tree[-1]:
return new_point # Trees have connected
def build_rrt_connect(start, goal, grid_size, step_size, max_iterations, obstacles, rect_obstacle):
start_tree, goal_tree = {start: None}, {goal: None}
for i in range(max_iterations):
if i % 2 == 0: # Alternate between expanding the start_tree and goal_tree
random_point = (random.randint(0, grid_size - 1), random.randint(0, grid_size - 1))
if is_collision(random_point, obstacles, rect_obstacle):
continue
nearest = nearest_node(start_tree.keys(), random_point)
new_point = steer(nearest, random_point, step_size, obstacles, rect_obstacle)
if new_point:
start_tree[new_point] = nearest
if connect(start_tree, goal_tree, step_size, obstacles, rect_obstacle) == goal:
return start_tree, goal_tree
else:
random_point = (random.randint(0, grid_size - 1), random.randint(0, grid_size - 1))
if is_collision(random_point, obstacles, rect_obstacle):
continue
nearest = nearest_node(goal_tree.keys(), random_point)
new_point = steer(nearest, random_point, step_size, obstacles, rect_obstacle)
if new_point:
goal_tree[new_point] = nearest
if connect(goal_tree, start_tree, step_size, obstacles, rect_obstacle) == start:
return start_tree, goal_tree
return start_tree, goal_tree # May return incomplete trees if no path found
def reconstruct_path(trees, start, goal):
# Combine paths from start to meeting point and from goal to meeting point
meeting_point = trees[1][goal]
path = [meeting_point]
while path[-1] != start:
path.append(trees[0][path[-1]])
path.reverse()
current = meeting_point
while current != goal:
current = trees[1][current]
path.append(current)
return path
def main():
grid_size = 100
start = (10, 10)
goal = (90, 90)
step_size = 2 # Smaller step size for more detailed path
max_iterations = 10000
obstacles = [((30, 30), 10), ((50, 50), 10), ((70, 10), 10)]
rect_obstacle = [(60, 70), (100, 70), (100, 80), (60, 80)]
start_time = time.time()
start_tree, goal_tree = build_rrt_connect(start, goal, grid_size, step_size, max_iterations, obstacles, rect_obstacle)
path = reconstruct_path((start_tree, goal_tree), start, goal)
end_time = time.time()
print(f"Path planning took {end_time - start_time} seconds")
plt.figure(figsize=(12, 12))
for point, parent in start_tree.items():
if parent:
plt.plot([point[0], parent[0]], [point[1], parent[1]], 'r-')
for point, parent in goal_tree.items():
if parent:
plt.plot([point[0], parent[0]], [point[1], parent[1]], 'b-')
for obstacle in obstacles:
circle = plt.Circle(obstacle[0], obstacle[1], radius=obstacle[1], color='k', fill=True)
plt.gca().add_patch(circle)
rect = plt.Rectangle(rect_obstacle[0], rect_obstacle[1][0] - rect_obstacle[0][0], rect_obstacle[2][1] - rect_obstacle[0][1], color='k', fill=True)
plt.gca().add_patch(rect)
plt.plot(*zip(*path), marker='o', color='g', markersize=5, linestyle='-', linewidth=2, label='RRT-Connect Path')
plt.plot(start[0], start[1], 'go', markersize=10, label="Start")
plt.plot(goal[0], goal[1], 'ro', markersize=10, label="Goal")
plt.xlim(0, grid_size)
plt.ylim(0, grid_size)
plt.title('RRT-Connect Path Planning\nTotal steps: {len(path)}')
plt.legend()
plt.grid(True)
plt.show()
if __name__ == "__main__":
main() |
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Manipulando o DOM - Aula 1</title>
<link rel="stylesheet" href="./style.css">
<style>
* {
margin: 0;
padding: 0;
}
body {
background: var(--cor-fundo);
color: var(--cor-fonte);
font-family: 'Cinzel', serif;
font-size: 38px;
user-select: none;
transition: 2s;
}
.container {
height: 90vh;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.trono {
background-image: url("https://caelum-online-public.s3.amazonaws.com/1369-alura-mais-dark-mode/trono-preto.png");
background-size: cover;
width: 450px;
height: 350px;
margin-bottom: 30px;
position: relative;
top: 10%;
right: 5%;
}
.texto{
padding: 5px;
width: 30%;
}
.botao{
padding: 5px;
font-size: 1rem;
font-weight: 700;
cursor: pointer;
}
.botao:hover{
border: 2px solid red;
}
</style>
</head>
<body>
<!-- fonte -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@600&display=swap" rel="stylesheet">
<!-- fonte -->
<section class="container">
<label for="texto">Troque o Texto</label>
<input type="text" name="textoN" id="textoN" class="texto">
<div class="trono"></div>
<p id="texto">O inverno está chegando</p>
<button class="botao">Clique!</button>
</section>
<script>
let text = document.querySelector('#texto');
let bot = document.querySelector('.botao');
let textoNovo = document.querySelector('#textoN');
function textoTrocado (){
return textoNovo.value;
}
bot.onclick = trocar;
function trocar(){
text.innerHTML = textoTrocado();
}
</script>
</body>
</html> |
#!/usr/bin/python3
""" rectange class """
class Rectangle:
"""define a rectangle"""
def __init__(self, width=0, height=0):
"""initializes the rectangle"""
self.width = width
self.height = height
@property
def width(self):
"""getter for the private instance attribute width"""
return self.__width
@width.setter
def width(self, value):
"""setter for the private instance attribute width"""
if not isinstance(value, int):
raise TypeError("width must be an integer")
if value < 0:
raise ValueError("width must be >= 0")
self.__width = value
@property
def height(self):
"""getter for the private instance attribute height"""
return self.__height
@height.setter
def height(self, value):
"""setter for the private instance attribute height"""
if not isinstance(value, int):
raise TypeError("height must be an integer")
if value < 0:
raise ValueError("height must be >= 0")
self.__height = value
def area(self):
"""Public instance method for area"""
return self.__width * self.__height
def perimeter(self):
"""Public instance method for perimeter"""
if self.__width == 0 or self.__height == 0:
return 0
return 2 * (self.__width + self.__height)
def __str__(self):
"""returns printable string representation of the rectangle"""
string = ""
if self.__width != 0 and self.__height != 0:
string += "\n".join("#" * self.__width
for j in range(self.__height))
return string |
from moveit_commander import MoveGroupCommander
from moveit_msgs.msg import RobotTrajectory
from planner.ur3e_hande import UR3e_Hande
from planner.workstation import Workstation
ARM_GROUP_NAME = "arm"
GRIPPER_GROUP_NAME = "gripper"
class Planner:
def __init__(self):
self.ur3e_hande = UR3e_Hande()
self.workstation = Workstation()
self.move_group_arm = MoveGroupCommander(ARM_GROUP_NAME)
self.move_group_gripper = MoveGroupCommander(GRIPPER_GROUP_NAME)
def plan_ptp(self, move_group: MoveGroupCommander, start_state, pose_type, pose):
move_group.set_start_state(start_state)
if pose_type == 'pose':
move_group.set_pose_target(pose)
if pose_type == 'name':
move_group.set_named_target(pose)
trajectory = move_group.plan()
if not trajectory:
return
return trajectory[1]
def plan_lin(self, move_group: MoveGroupCommander, robot, pose):
move_group.set_start_state(robot.state)
waypoints = [robot.pose, pose]
trajectory = move_group.compute_cartesian_path(waypoints, 0.005, 0.0)
if not trajectory:
return
return trajectory[0]
def get_robot_trajectory(self, move_type: str, pose_type: str, pose) -> RobotTrajectory:
if move_type.lower() == 'ptp':
trajectory = self.plan_ptp(self.move_group_arm, self.ur3e_hande.robot.state, pose_type, pose)
if move_type.lower() == 'lin':
trajectory = self.plan_lin(self.move_group_arm, self.ur3e_hande.robot, pose)
self.ur3e_hande.update_robot(trajectory.joint_trajectory.points[-1].positions, pose)
return trajectory
def get_gripper_trajectory(self, pose_type, pose) -> RobotTrajectory:
trajectory = self.plan_ptp(self.move_group_gripper, self.ur3e_hande.gripper.state, pose_type, pose)
self.ur3e_hande.update_gripper(trajectory.joint_trajectory.points[-1].positions)
return trajectory
def reset(self):
self.ur3e_hande.reset()
self.move_group_arm = MoveGroupCommander(ARM_GROUP_NAME)
self.move_group_gripper = MoveGroupCommander(GRIPPER_GROUP_NAME) |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Permissions } from '@shared/types';
import { AuthGuard } from '../auth';
import { EditTruckComponent, ListTruckComponent } from './pages';
const rootRoutes: Routes = [
{
path: '',
redirectTo: 'list',
pathMatch: 'full'
},
{
path: 'list',
component: ListTruckComponent,
canActivate: [AuthGuard],
data: {
breadcrumb: 'List',
permission: Permissions.Truck.View
}
},
{
path: 'add',
component: EditTruckComponent,
canActivate: [AuthGuard],
data: {
breadcrumb: 'Add',
permission: Permissions.Truck.Create
}
},
{
path: 'edit/:id',
component: EditTruckComponent,
canActivate: [AuthGuard],
data: {
breadcrumb: 'Edit',
permission: Permissions.Truck.Edit
}
},
];
@NgModule({
imports: [RouterModule.forChild(rootRoutes)],
exports: [RouterModule],
})
export class TruckRoutingModule {} |
import React from 'react';
import NextLink from 'next/link';
import { LineItem } from '@Types/cart/LineItem';
import { CurrencyHelpers } from 'helpers/currencyHelpers';
import { useFormat } from 'helpers/hooks/useFormat';
import { BUNDLE_ATTRIBUTE_NAME, getBundledPrice, getSelectedBundleLabel } from 'helpers/utils/bundleItemsHelpers';
import Image from 'frontastic/lib/image';
export function OrderLineItem({ lineItem }) {
const { formatMessage: formatProductMessage } = useFormat({ name: 'product' });
const discount = (() => {
const discountValue = lineItem.discountedPrice?.centAmount || lineItem.discounts?.[0]?.discountedAmount?.centAmount;
return !discountValue ? 0 : lineItem.price?.centAmount - discountValue;
})();
const bundles = lineItem.variant?.attributes?.[BUNDLE_ATTRIBUTE_NAME];
return (
<tr>
<td className="py-2 pr-8">
<div className="flex items-center">
<Image
src={lineItem.variant.images[0]}
alt={lineItem.name}
className="mr-6 h-16 w-16 rounded object-cover object-center"
/>
<div>
<div className="text-ellipsis-150 font-medium text-gray-900 dark:text-light-100">{lineItem.name}</div>
{!!bundles?.length && (
<div className="mt-2 flex flex-col text-xs">
{bundles.map((bundle: LineItem) => (
<div className="td-other-details td-details__sku" key={bundle.lineItemId}>
<label className="">{`${bundle.name}: `}</label>
<span className="text-xs">{getSelectedBundleLabel(bundle.variant, bundle.name)}</span>
</div>
))}
</div>
)}
<div className="mt-1 dark:text-light-100 sm:hidden">
{CurrencyHelpers.formatForCurrency(
CurrencyHelpers.addCurrency(
lineItem.price,
CurrencyHelpers.formatToMoney(getBundledPrice(lineItem) / 100),
),
)}
</div>
</div>
</div>
</td>
<td className="hidden py-2 pr-8 dark:text-light-100 sm:table-cell">
<span className={!!discount ? 'line-through' : ''}>
{' '}
{CurrencyHelpers.formatForCurrency(
CurrencyHelpers.addCurrency(lineItem.price, CurrencyHelpers.formatToMoney(getBundledPrice(lineItem) / 100)),
)}
</span>
{!!discount && <span className="ml-2">{CurrencyHelpers.formatForCurrency(discount)}</span>}
</td>
<td className="hidden py-2 pr-8 dark:text-light-100 sm:table-cell">{lineItem.count}</td>
<td className="hidden py-2 pr-8 dark:text-light-100 sm:table-cell">
{CurrencyHelpers.formatForCurrency(
CurrencyHelpers.addCurrency(
lineItem.totalPrice,
CurrencyHelpers.formatToMoney(getBundledPrice(lineItem) / 100),
),
)}
</td>
<td className="whitespace-nowrap py-2 text-right font-medium dark:text-light-100">
<NextLink href={lineItem._url || ''}>
<a className="text-accent-400">
{formatProductMessage({
id: 'lineItem.view',
defaultMessage: 'View product',
})}
<span className="sr-only">, {lineItem.name}</span>
</a>
</NextLink>
</td>
</tr>
);
} |
import math
from enum import Enum
import numpy as np
import glotlib
NVERTICES = 500000
Xi = np.arange(NVERTICES) * 2 * math.pi / (NVERTICES - 1)
H_BOUNDS = [311, 312, 313]
V_BOUNDS = [131, 132, 133]
COLORS = [
(0, 0.8, 0.2, 1),
(0.8, 0.2, 0, 1),
(0.8, 0, 0.2, 1),
]
AMP_RATES = [
1.0,
3.5,
0.35,
]
THICK_RATES = [
0.1,
0.2,
0.5,
]
Xs = [ar * Xi for ar in AMP_RATES]
class ViewMode(Enum):
HORIZONTAL = 1
VERTICAL = 2
class Window(glotlib.Window):
def __init__(self):
super().__init__(900, 650, msaa=4)
self.series = []
self.view_mode = ViewMode.HORIZONTAL
for bounds, color, X in zip(H_BOUNDS, COLORS, Xs):
p = self.add_plot(bounds, limits=(0, -1, 2 * math.pi, 1))
Y = np.sin(X)
self.series.append(p.add_lines(X=Xi, Y=Y, color=color, width=1))
self.add_label((.1, 12.1 / 13), 'tcdc_6_2000014_n4.csv')
self.fps_label = self.add_label((0.01, 0.01), '')
def _set_mode_vertical(self):
if self.view_mode == ViewMode.VERTICAL:
return
for bounds, p in zip(V_BOUNDS, self.plots):
p.set_bounds(bounds)
self.view_mode = ViewMode.VERTICAL
def _set_mode_horizontal(self):
if self.view_mode == ViewMode.HORIZONTAL:
return
for bounds, p in zip(H_BOUNDS, self.plots):
p.set_bounds(bounds)
self.view_mode = ViewMode.HORIZONTAL
def handle_key_press(self, key):
if key == glotlib.KEY_ESCAPE:
if self.view_mode == ViewMode.HORIZONTAL:
self._set_mode_vertical()
else:
self._set_mode_horizontal()
self.mark_dirty()
def update_geometry(self, t):
for s, tr, X in zip(self.series, THICK_RATES, Xs):
Y = np.sin(X + t)
s.set_y_data(Y)
s.width = 2 * (np.sin(2 * math.pi * tr * t) + 1) + 1
fps = glotlib.get_fps()
if fps is not None:
self.fps_label.set_text('FPS: %.1f' % fps)
else:
self.fps_label.set_text('FPS: Unknown')
return True
def main():
Window()
glotlib.animate()
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.