text
stringlengths
184
4.48M
import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; // Redux Setup import { configureStore, applyMiddleware, compose } from "@reduxjs/toolkit"; import { rootReducer } from "./reducers"; import { Provider } from "react-redux"; import thunk from "redux-thunk"; import { BrowserRouter } from "react-router-dom"; const composeEnchancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = configureStore( { reducer: rootReducer }, composeEnchancer(applyMiddleware(thunk)) ); ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <Provider store={store}> <BrowserRouter> <App /> </BrowserRouter> </Provider> </React.StrictMode> );
# # This file is part of Jedi-Plugin-Session # # This software is copyright (c) 2013 by celogeek <me@celogeek.com>. # # This is free software; you can redistribute it and/or modify it under # the same terms as the Perl 5 programming language system itself. # package Jedi::Plugin::Session::Backend::SQLite; # ABSTRACT: Backend storage for SQLite use strict; use warnings; our $VERSION = '0.05'; # VERSION use Time::Duration::Parse; use Sereal qw/encode_sereal decode_sereal/; use Path::Class; use Carp; use Jedi::Plugin::Session::Backend::SQLite::DB; use DBIx::Class::Migration; use Moo; has 'database' => ( is => 'ro', coerce => sub { my ($db) = @_; my $dbfile = file($db); $dbfile->dir->mkpath; return _prepare_database($dbfile); } ); has 'expires_in' => ( is => 'ro', default => sub { 3 * 3600 }, coerce => sub { parse_duration( $_[0] ) } ); ## no critic (NamingConventions::ProhibitAmbiguousNames) sub get { my ( $self, $uuid ) = @_; return if !defined $uuid; my $resultset = $self->database->resultset('Session'); my $now = time; my $data = $resultset->find($uuid); my $session; if ( defined $data ) { if ( $data->expire_at > $now ) { return if !eval { $session = decode_sereal( $data->session ); 1 }; } else { $resultset->search( { expire_at => { '<=' => $now } } ) ->delete_all; } } return $session; } sub set { my ( $self, $uuid, $value ) = @_; return if !defined $uuid; my $session = encode_sereal($value); $self->database->resultset('Session')->update_or_create( { id => $uuid, expire_at => time + $self->expires_in, session => $session } ); return 1; } # PRIVATE sub _prepare_database { my ($dbfile) = @_; my @connect_info = ( "dbi:SQLite:dbname=" . $dbfile->stringify ); my $schema = Jedi::Plugin::Session::Backend::SQLite::DB->connect(@connect_info); my $migration = DBIx::Class::Migration->new( schema => $schema, ); $migration->install_if_needed; $migration->upgrade; return $schema; } 1; __END__ =pod =head1 NAME Jedi::Plugin::Session::Backend::SQLite - Backend storage for SQLite =head1 VERSION version 0.05 =head1 BUGS Please report any bugs or feature requests on the bugtracker website https://github.com/celogeek/perl-jedi-plugin-session/issues When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 AUTHOR celogeek <me@celogeek.com> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by celogeek <me@celogeek.com>. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut
import { IO } from '@funkia/io'; import { accum, Behavior, Future, performStream, runNow, sinkFuture, Stream, toPromise, when, } from '@funkia/hareactive'; import { Action, newLogger, reactionLoop, setLogLevel, startDeploymentService, startOffersRuntime, startResourcesService, } from '.'; import * as yargs from 'yargs'; import { Level, Logger } from 'pino'; import * as YAML from 'yaml'; import fs from 'fs'; export enum TimestampType { UPTIME = 'event_uptime', DEPLOY = 'event_deploy', UPDATE = 'event_update', } export enum TimestampPeriod { START = 'start', END = 'end', } export const globalVariables = { execution_expe_dir: '', logDirTimestamp: '', assemblyName: '', reconfigurationName: '', }; type timestampDictType = { [timestampType: string]: { [timestampPeriod: string]: number; }; }; const allTimestampsDict: timestampDictType = {}; export const registerTimeValue = ( timestampType: TimestampType, timestampPeriod: TimestampPeriod ): void => { if (timestampPeriod === TimestampPeriod.START) { if (timestampType in allTimestampsDict) { throw new Error( `Register time value start error: ${timestampType} for ${TimestampPeriod.START} already registered` ); } allTimestampsDict[timestampType] = {}; allTimestampsDict[timestampType][TimestampPeriod.START] = new Date().getTime() / 1000; } else { if (!(timestampType in allTimestampsDict)) { throw new Error(`Register time value end error: ${timestampType} never registered`); } if (TimestampPeriod.END in allTimestampsDict[timestampType]) { throw new Error( `Register time value start error: ${timestampType} for ${TimestampPeriod.END} already registered` ); } allTimestampsDict[timestampType][TimestampPeriod.END] = new Date().getTime() / 1000; } }; export const registerEndAllTimeValues = (logger: Logger): void => { logger.info('Registing end times'); for (const timestampName in allTimestampsDict) { if (!(TimestampPeriod.END in allTimestampsDict[timestampName])) { logger.info(`Register end time for: ${timestampName}`); allTimestampsDict[timestampName][TimestampPeriod.END] = new Date().getTime() / 1000; } } logger.info('Done'); }; export const registerTimeValuesInFile = (logger: Logger): void => { logger.info('Writing file here: ' + globalVariables.logDirTimestamp); const reconfigurationDir = `${globalVariables.execution_expe_dir}/${globalVariables.reconfigurationName}`; const fileName = `${reconfigurationDir}/${globalVariables.assemblyName}_${globalVariables.logDirTimestamp}.yaml`; const yamlStr = YAML.stringify(allTimestampsDict); try { if (!fs.existsSync(reconfigurationDir)) fs.mkdirSync(reconfigurationDir); // eslint-disable-next-line no-empty } catch {} fs.writeFileSync(fileName, yamlStr); logger.info('Done writing file'); }; type RuntimeOptions = { deploymentName: string; deploymentHost: string; deploymentPort: number; heartbeatInterval: number; resourcesHost: string; resourcesPort: number; logLevel: Level; }; const getOptions = (defaults: Partial<RuntimeOptions>): RuntimeOptions => yargs.options({ deploymentName: { alias: 'n', default: defaults.deploymentName || 'deployment', description: 'Name of the deployment (used for identification with other deployments).', }, deploymentHost: { alias: 'dh', default: defaults.deploymentHost || '0.0.0.0', description: 'Host of the µs deployment service.', }, deploymentPort: { alias: 'dp', default: defaults.deploymentPort || 19952, description: 'Port of the µs deployment service.', }, resourcesHost: { alias: 'rh', default: defaults.deploymentHost || '127.0.0.1', description: 'Host of the µs resources service.', }, resourcesPort: { alias: 'rp', default: defaults.resourcesPort || 19951, description: 'Port of the µs resources service.', }, heartbeatInterval: { alias: 'hi', default: defaults.heartbeatInterval || 5, description: 'Heartbeat interval on connections between deployments in seconds.', }, logLevel: { alias: 'v', default: defaults.logLevel || 'info', description: 'Log level: "fatal", "error", "warn", "info", "debug", or "trace". Only affects default logger.', }, }).argv as RuntimeOptions; let exitCode = 0; export const setExitCode = (newExitCode: number): void => { exitCode = newExitCode; }; export const runDeployment = <S>( initOperation: IO<S>, operations: (action: Action) => (state: S) => IO<S>, nextAction: (offerUpdates: Stream<void>) => Behavior<Behavior<Future<Action>>>, options: Partial<RuntimeOptions> & { logger?: Logger; disableExit?: true } = {} ): Promise<S> => { const opts = getOptions(options || {}); setLogLevel(opts.logLevel); const logger = options.logger || newLogger('runtime'); logger.info('running deployment'); const setup = async () => { const [resourcesService, deploymentService] = await Promise.all([ startResourcesService( opts.resourcesHost, opts.resourcesPort, logger.child({ c: 'resources service' }) ), startDeploymentService( opts.deploymentHost, opts.deploymentPort, logger.child({ c: 'deployment service' }) ), ]); const initialized = sinkFuture<void>(); const offersRuntime = await startOffersRuntime( deploymentService, resourcesService, initialized, opts.deploymentName, opts.heartbeatInterval, logger.child({ c: 'offers runtime' }) ); const [stackActions, completed] = reactionLoop( initOperation, operations, nextAction(offersRuntime.inboundOfferUpdates), logger.child({ c: 'reaction loop' }) ); runNow( performStream(stackActions) .flatMap((actions) => accum(() => true, false, actions)) .flatMap(when) ).subscribe(() => initialized.resolve()); const finalStack = await toPromise(completed); logger.info('wait everything'); await Promise.all([ resourcesService.stop(), deploymentService.stop(), offersRuntime.stop(), ]); logger.info('end of run deployment'); return finalStack; }; return setup() .catch((err) => { logger.error(err, 'Deployment error'); process.exit(1); }) .finally(() => { registerEndAllTimeValues(logger); registerTimeValuesInFile(logger); logger.info('---------------------- Going to sleep --------------------------------\n'); if (!options.disableExit) process.exit(exitCode); }); };
import ast import csv import datetime as dt import os import numpy as np def sigmoid(x): """ Apply sigmoid function. """ return np.exp(x) / (1 + np.exp(x)) def dict_to_matrix(data: dict) -> np.ndarray: # convert dict into matrix user_ids = data['user_id'] question_ids = data['question_id'] is_correct = data['is_correct'] # create a Ns * Nq matrix matrix = np.empty((np.max(user_ids) + 1, np.max(question_ids) + 1)) matrix[:] = np.nan matrix[user_ids, question_ids] = is_correct return matrix def load_csv(path) -> dict: # A helper function to load the csv file. if not os.path.exists(path): raise Exception("The specified path {} does not exist.".format(path)) # Initialize the data. data = { "user_id": [], "question_id": [], "is_correct": [] } # Iterate over the row to fill in the data. with open(path, "r") as csv_file: reader = csv.reader(csv_file) for row in reader: try: data["question_id"].append(int(row[0])) data["user_id"].append(int(row[1])) data["is_correct"].append(int(row[2])) except ValueError: # Pass first row. pass except IndexError: # is_correct might not be available. pass return data def load_student_meta_data(root_dir="../data") -> dict: path = os.path.join(root_dir, "student_meta.csv") if not os.path.exists(path): raise Exception("The specified path {} does not exist.".format(path)) # Initialize the data. data = { "user_id": [], "gender": [], "dob": [], "premium_pupil": [] } # Iterate over the row to fill in the data. with open(path, "r") as csv_file: reader = csv.reader(csv_file) next(reader) for row in reader: data["user_id"].append(int(row[0])) data["gender"].append(int(row[1])) if row[2] != '': actual_date = dt.datetime.fromisoformat(row[2]) start_date = dt.datetime.fromtimestamp(0) days = (actual_date - start_date).days / 365 data['dob'].append(days) else: data['dob'].append(float('nan')) if row[3] != '': data["premium_pupil"].append(float(row[3])) else: data["premium_pupil"].append(0.) return data def process_student_meta_data(data: dict) -> dict: result = {} dobs = np.array(data['dob'], dtype='float32') mean_dob = np.nanmean(dobs) dobs[np.isnan(dobs)] = mean_dob dob_factors = sigmoid(-(mean_dob - dobs)) user_ids = data['user_id'] genders = data['gender'] pps = data['premium_pupil'] for i in range(len(user_ids)): result[user_ids[i]] = [genders[i], dob_factors[i], pps[i]] return result def load_question_meta_data(root_dir="../data") -> dict[int: list[int]]: path = os.path.join(root_dir, "question_meta.csv") if not os.path.exists(path): raise Exception("The specified path {} does not exist.".format(path)) data = {} # Iterate over the row to fill in the data. with open(path, "r") as csv_file: reader = csv.reader(csv_file) next(reader) for row in reader: question_id = int(row[0]) data[question_id] = np.array([0] * 388, dtype='float32') subjects = ast.literal_eval(row[1]) data[question_id][subjects] = 1 return data def get_average_correct(data: dict): is_correct = np.array(data['is_correct']) return is_correct.sum() / len(is_correct)
function mesh = meshSetup(mesh,k) % meshSetup computes required fields on the mesh for the virtual element % method % % SYNOPSIS: mesh = meshSetup(mesh,k) % % INPUT: mesh: mesh structure (nodes, elements and boundary nodes) % k: degree for local spaces (k>1) % % OUTPUT: mesh: struct with the following new fields: % edges: list of edge connectivity on the mesh % dof: local to global mapping of dof % bdDOF: global dof on the boundary of the domain % % AUTHOR: Juan G. Calvo and collaborators, 2021 nNodes = size(mesh.verts,1); % global number of nodes nVerts = cellfun(@numel,mesh.elems); % vertices per element % create array with all edges [e1 e2] (smaller index first) e1 = cell2mat(mesh.elems); e2 = cell2mat(cellfun(@(y)y([2:end,1]),mesh.elems,'UniformOutput',0)); [edges,index] = sort([e1 e2],2); signEdges = index(:,2)-index(:,1); % reversed edges [mesh.edges, ~, indexEdges] = unique(edges,'rows'); numEdges = size(mesh.edges,1); % global number of edges % find edges on boundary uniqueEdges = hist(indexEdges,1:size(mesh.edges,1))'; edgesBd = uniqueEdges==1; edgesBd = nNodes+(find(edgesBd)-1)*(k-1)+repmat(1:k-1,sum(edgesBd),1); mesh.bdDOF = sort([mesh.bndry; edgesBd(:)]); % create array with global dof for each element index = [0 cumsum(nVerts)']; for j = 1:size(mesh.elems,1) range = index(j)+1:index(j+1); increment = repmat(1:k-1,nVerts(j),1); % reverse order on edges that changed orientation sign = signEdges(range); increment(sign<0,:) = fliplr(increment(sign<0,:)); % find global dof for local vertices, edges and moments dofVert=mesh.elems{j}; dofEdgs=(nNodes+(indexEdges(range)-1)*(k-1)+increment)'; dofElem=nNodes+numEdges*(k-1)+(j-1)*k*(k-1)/2+(1:k*(k-1)/2)'; mesh.dof{j} = [dofVert; dofEdgs(:); dofElem]; end end
# How to get video orientation for assets Video dimension (width x height) cannot be fetched from Google Ads API. There are several ways to get this data into App Reporting Pack: 1. [Get video orientation from asset names](#get-video-orientation-from-asset-names) 1. [Get video orientation from YouTube Data API](#get-video-orientation-from-youtube-data-api) 1. [Use placeholders](#use-placeholders) ## Get video orientation from asset names If you have a consistent naming for your videos you extract width and height from asset name. Let's consider the following example: 1. You have a video titled `my_video_1000x1000_concept_name.mp4` 2. Video dimension (width x height) is `1000x1000` 3. In order to get this values we need: 1. Split video name by `_` delimiter 2. Identify the position of (width x height) (if starting from 0 it's position 2) 3. Split video dimension by `x` delimiter App Reporting Pack interactive installer will ask all these questions when performing the solution deployment. Alternatively you can add the following section into your `app_reporting_pack.yaml` config file: ``` scripts: video_orientation: mode: regex element_delimiter: '_' orientation_position: '2' orientation_delimiter: 'x' ``` ## Get video orientation from YouTube Data API If getting data from video names is impossible you can always fetch video dimension directly from YouTube Data API. > Fetching data from YouTube API requires authorization - you can follow steps at > [Setup YouTube Data API access](#setup-youtube-data-api-access). App Reporting Pack interactive installer will ask to provide full path to `youtube_config.yaml` file Alternatively you can add the following section into your `app_reporting_pack.yaml` config file: ``` scripts: video_orientation: mode: youtube youtube_config_path: youtube_config.yaml ``` ### Setup YouTube Data API access You can fetch video orientation from YouTube Data API. This data only available to that video's owner. In order to get access to video orientation details you need to be properly authorized. 1. Create file `youtube_config.yaml` with the following elements. ``` client_id: client_secret: refresh_token: ``` 2. Setup Google Cloud project and OAuth client id Create an OAuth credentials (for the first time you'll need to create a concent screen either). Please note you need to generate OAuth2 credentials for **desktop application**. Copy `client_id` and `client_secret` to `youtube_config.yaml`. First you need to download [oauth2l](https://github.com/google/oauth2l) tool ("oauth tool"). For Windows and Linux please download [pre-compiled binaries](https://github.com/google/oauth2l#pre-compiled-binaries), for MacOS you can install via Homebrew: `brew install oauth2l`. As soon as you generated OAuth2 credentials: * Click the download icon next to the credentials that you just created and save file to your computer * Copy the file name under which you saved secrets file - `~/client_secret_XXX.apps.googleusercontent.com.json` where XXX will be values specific to your project (or just save it under `client_secret.json` name for simplicity) * Run desktop authentication with downloaded credentials file using oauth2l in the same folder where you put the downloaded secret file (assuming its name is client_secret.json): ``` oauth2l fetch --credentials ./client_secret.json --scope youtube --output_format refresh_token ``` * Copy a refresh token from the output and add to `youtube_config.yaml` ## Use placeholders If it's not possible to get video dimensions from both video names or YouTube Data API App Reporting Pack will generate the placeholders - each video will have `Unknown` video orientation. You can explicitly add the following section into your `app_reporting_pack.yaml` config file to specify that you're working with placeholders: ``` scripts: video_orientation: mode: placeholders ```
# DocumentOperationsDemoApp Document upload, download operations with Spring Boot DB and Local Storage Dosya İşlemleri ( Yükleme İndirme Güncelleme Silme ) Projesi Kullanıcı tarafından yüklenecek olan dosyalara ait bilgiler ( isim, uzantı, boyut, path ) Veritabanı üzerinde tutulmaktadır. Kullanıcı tarafından yüklenecek olan dosyalar local depolama alanında bir dosya path’inde tutulmaktadır. Bu dosyaların tutulduğu path statik olarak girilmiştir. Class üzerinden değiştirilebilir. Yüklenecek olan dosyalar için boyut ve dosya tipi kontrolü yapılmıştır. Formata uymayan dosyalar veritabanına kaydolmayacaktır. Access token için hardcoded Username : testuser Pass : test123 şeklinde login apisi token dönmektedir. Api erişimi JWT ile güvenli hale getirilmiş olup, default bir kullanıcı tanımlanmıştır. Bu kullanıcıya ait username ve password bilgileri girilerek response olarak bir Token dönmektedir. API çağırımları Headers’a Authorization : token set edilerek yapılmalıdır. Dosyaya erişim URL ve Byte[] üzerinden sağlanabilmektedir. Dosyaların tüm bilgileri tek seferde dönmektedir. Dosya Id ye göre Local depolama alanından ve Veritabanı üzerinden silinmektedir. Dosya Id ye göre değiştirilmek istendiğinde API çağırımı sırasında veritabanı ve local depolama alanı üzerinde bulunan path üzerinde değiştirilmektedir. Swagger projeye entegre edilmiştir. Projeye ait API çağırımlarını temsilen Postman üzerinden atılan istekler aşağıda resimlerde paylaşılmıştır. Upload Document API'sinin Postman Üzerinde Request Response Bilgisi Status = 200 ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/346e615f-6c6e-4fce-86e2-380717569883) Upload Document API'sinin Postman Üzerinde Request Response Bilgisi Status = 400 Uygunsuz Format Hatası ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/beb8af78-77c3-48d1-b6b7-7e33dbf574e3) Kaydedilen dosyaların Database ve Local Storage alanında kayıtlı durumu ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/8ff78b39-bb5a-475c-8be7-c0629203c594) Database'den okunan Dosyalara ait bilgiler ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/a7043cc7-02d7-4c0d-931a-b663d9308d7b) Database'den okunan dosyanın Byte[] tipinde dönmüş hali ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/c2adac73-f6a5-414c-b95e-eb45798bcbec) Delete Document APİSİ Response ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/a834e65d-4f31-4d22-8272-3c3ef16bdf20) Delete Document APISI DB and Local Storage Kontrolü ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/fa6dd8cc-f573-4f28-8a16-e616fc21d9f3) Swagger ![image](https://github.com/mcanyilmaz/DocumentOperationsDemoApp/assets/26096319/e503352a-86ea-4e22-be72-70d96164be08) Postman API Çağırımı Örnek Request Response Pair; { "info": { "_postman_id": "bcfde7a9-676b-4a21-8e48-0e3a8b1ec9c9", "name": "Document Upload And Download Demo Project", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [ { "name": "uploadDocument", "request": { "method": "GET", "header": [], "url": { "raw": "http://localhost:8080/v2/uploadDocument/", "protocol": "http", "host": [ "localhost" ], "port": "8080", "path": [ "v2", "uploadDocument", "" ] } }, "response": [] }, { "name": "getDocumentByName", "request": { "method": "GET", "header": [], "url": { "raw": "http://localhost:8080/v2/getDocumentByName/", "protocol": "http", "host": [ "localhost" ], "port": "8080", "path": [ "v2", "getDocumentByName", "" ] } }, "response": [] }, { "name": "deleteDocumentById", "request": { "method": "Delete", "header": [], "url": { "raw": "http://localhost:8080/v2/deleteDocumentById/", "protocol": "http", "host": [ "localhost" ], "port": "8080", "path": [ "v2", "deleteDocumentById", "" ] } }, "response": [] }, { "name": "getAllDocument", "request": { "method": "GET", "header": [], "url": { "raw": "http://localhost:8080/v2/getAllDocument/", "protocol": "http", "host": [ "localhost" ], "port": "8080", "path": [ "v2", "getAllDocument", "" ] } }, "response": [] }, { "name": "updateDocument", "request": { "method": "POST", "header": [], "url": { "raw": "http://localhost:8080/v2/updateDocument/", "protocol": "http", "host": [ "localhost" ], "port": "8080", "path": [ "v2", "updateDocument", "" ] } }, "response": [] }, { "name": "Login", "request": { "method": "POST", "header": [], "url": { "raw": "http://localhost:8080/auth/login/", "protocol": "http", "host": [ "localhost" ], "port": "8080", "path": [ "auth", "login", "" ] } }, "response": [] } ] }
import React, {useState, useRef, MouseEvent} from 'react'; import PropTypes from 'prop-types'; import { ClickAwayListener, IconButton, MenuItem, MenuList, Paper, Popper, Theme, Typography, withStyles } from '@material-ui/core'; import MoreHorizIcon from '@material-ui/icons/MoreHoriz'; import { editMenuStyles } from '../styles/edit-menu-styles'; type EditMenuProps = { menuItems: string[]; classes: any } const EditMenu = (props: EditMenuProps) => { const { menuItems, classes } = props; const [open, setOpen] = useState(false); const anchorRef = useRef<HTMLButtonElement>(null); const handleToggle = () => { setOpen((prevOpen) => !prevOpen); }; const handleClose = (event: MouseEvent<EventTarget>) => { const target = event.target; if (anchorRef.current && target instanceof Node && anchorRef.current.contains(target)) { return; } setOpen(false); }; return ( <div> <IconButton className={open ? classes.openBtn : ''} ref={anchorRef} aria-controls={open ? 'menu-list-grow' : undefined} aria-haspopup="true" size="small" onClick={handleToggle} > <MoreHorizIcon/> </IconButton> <Popper className={classes.popper} open={open} anchorEl={anchorRef.current} disablePortal> <Paper> <ClickAwayListener onClickAway={handleClose}> <MenuList autoFocusItem={open} id="menu-list-grow" > {menuItems.map((item, index) => ( <MenuItem key={index}> <Typography variant="body2">{item}</Typography> </MenuItem> ))} </MenuList> </ClickAwayListener> </Paper> </Popper> </div> ); }; EditMenu.propTypes = { menuItems: PropTypes.array.isRequired }; EditMenu.defaultProps = {}; export default withStyles((theme: Theme) => editMenuStyles(theme))(EditMenu);
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix from sklearn import metrics from sklearn.metrics import ConfusionMatrixDisplay # Importar la base de datos featuredata archivo = "caracteristicas/featuredata.xlsx" base_datos = pd.read_excel(archivo) print(base_datos) # Obtener el grafico de dispersion valoresAspec = base_datos[['AspectRatio']] valoresDuracion = base_datos[['Duration']] ax = plt.scatter(x=valoresAspec, y=valoresDuracion) plt.xlabel("Aspect Ratio") plt.ylabel("Duration") plt.title("Grafico de dispersion") plt.show() # Mejorar el grafico de dispersion ax2 = sns.scatterplot(x="AspectRatio", y="Duration", hue="Character", data=base_datos) plt.savefig("caracteristicas/grafico.png") # Importar datos de test archivo3 = "caracteristicas/testdata.xlsx" base_datos2 = pd.read_excel(archivo3) print(base_datos2) # Asignar las columnas de los archivos en excel X_text = base_datos2[['AspectRatio', 'Duration']].values Y_text = base_datos2[['Character']] X_train = base_datos[['AspectRatio', 'Duration']] Y_train = base_datos[['Character']].values # Generar el modelo usando el algoritmo KNN n_neighbors = 15 knn = KNeighborsClassifier(n_neighbors, weights='uniform') knn.fit(X_train, Y_train) # Predecir los valores de test prediccion = knn.predict(X_text) print(prediccion, '\n') # Evaluar el modelo isCorrect = prediccion == base_datos2['Character'] print(isCorrect, '\n') # Imprimir la precisión del modelo print("Precisión del modelo de entrenamiento: {:.2f}".format( knn.score(X_train, Y_train))) print("Precisión del conjunto de evaluación {:.2f}".format( knn.score(X_text, Y_text))) print(confusion_matrix(Y_text, prediccion), '\n') confusion_matrix = metrics.confusion_matrix(Y_text, prediccion) cm_display = ConfusionMatrixDisplay( confusion_matrix=confusion_matrix, display_labels=['J', 'M', 'V']) cm_display.plot() plt.show() # Generar un reporte de clasiicación print(metrics.classification_report(Y_text, prediccion)) # Grafica de sensibilidad knn_range = range(1, 20) scores = [] for k in knn_range: knn = KNeighborsClassifier(n_neighbors=k) knn.fit(X_train, Y_train) scores.append(knn.score(X_text, Y_text)) plt.figure() plt.xlabel('k') plt.ylabel('accuracy') plt.scatter(knn_range, scores) plt.xticks([0, 5, 10, 15, 20]) plt.show()
import { Card, CardHeader, CardBody, CardFooter, Typography, } from "@material-tailwind/react"; import PropTypes from "prop-types"; import { getBgColor, // estos 2 jalan los colores necesarios del contexto getTextColor, useMaterialTailwindController, getTypography, getTypographybold } from "@/context"; {/* esta carta es para la informacion de los usuarios*/ } export function CustomerCard({ name, description, footer }) { const controller = useMaterialTailwindController(); const theme = controller; {/* En los className llaman a la función que esta manejando el background o el color de texto */ } return ( <Card className={`border border-blue-gray-100 shadow-sm ${getBgColor("background-cards")}`}> <CardBody className="p-4 text-right"> <Typography /*variant="h4"*/ className={`text-justify text-[1.5rem] ${getTypographybold()} ${getTextColor("dark")}`}> Customer data </Typography> <Typography variant="paragraph" className={`text-[1rem] text-justify ${getTypography()} ${getTextColor("gray")}`}> <span className={` ${getTypographybold()} ${getTextColor("dark")}`}>Name of Customer: </span>{name} </Typography> <Typography variant="paragraph" className={`text-[1rem] text-justify ${getTypography()} ${getTextColor("gray")}`}> <span className={`text-justify ${getTypographybold()} ${getTextColor("dark")}`}>Condition: </span> {description} </Typography> </CardBody> {footer && ( <CardFooter className={`border-t border-blue-gray-50 p-4 ${getTypography()} ${getTextColor("dark")}`}> {footer} </CardFooter> )} </Card> ); } export function CustomerSentimentCard({ sentiment, rating, recommendation }) { const controller = useMaterialTailwindController(); const theme = controller; {/* En los className llaman a la función que esta manejando el background o el color de texto */ } return ( <Card className={`border border-blue-gray-100 shadow-sm ${getBgColor("background-cards")}`}> <CardBody className="p-4 text-right"> <Typography /*variant="h4"*/ className={`text-justify text-[1.5rem] ${getTypographybold()} ${getTextColor("dark")}`}> Customer data </Typography> <Typography variant="paragraph" className={`text-[1rem] text-justify ${getTypography()} ${getTextColor("gray")}`}> <span className={` ${getTypographybold()} ${getTextColor("dark")}`}>Costumer Sentiment Rating: </span>{sentiment} </Typography> <Typography variant="paragraph" className={`text-[1rem] text-justify ${getTypography()} ${getTextColor("gray")}`}> <span className={`text-justify ${getTypographybold()} ${getTextColor("dark")}`}>Agent Rating based of metrics: </span> {rating} </Typography> </CardBody> <CardFooter className={`border-t border-blue-gray-50 p-4 ${getTypography()} ${getTextColor("dark")}`}> {recommendation} </CardFooter> </Card> ); } CustomerCard.defaultProps = { color: "blue", footer: null, }; CustomerCard.propTypes = { color: PropTypes.oneOf([ "white", "blue-gray", "gray", "brown", "deep-orange", "orange", "amber", "yellow", "lime", "light-green", "green", "teal", "cyan", "light-blue", "blue", "indigo", "deep-purple", "purple", "pink", "red", ]), icon: PropTypes.node.isRequired, title: PropTypes.node.isRequired, value: PropTypes.node.isRequired, footer: PropTypes.node, }; CustomerCard.displayName = "/src/widgets/cards/statistics-card.jsx"; export function Lexcard({ recomendation, footer }) { return ( <Card className={`border shadow-sm ${getBgColor("background-cards")}`}> <CardBody className="p-4 text-right"> <Typography /*variant="h4"*/ className={`text-[1.5rem] ${getTypographybold()} text-justify ${getTextColor("dark")}`} > Al.n, your virtual assistant: </Typography> <Typography variant="paragraph" className={`text-[1rem] p-1 text-justify ${getTypography()} ${getTextColor("dark")}`}> {recomendation} </Typography> </CardBody> {footer && ( <CardFooter className="border-t border-blue-gray-50 p-4"> {footer} </CardFooter> )} </Card> ); } Lexcard.defaultProps = { color: "blue", footer: null, }; Lexcard.propTypes = { color: PropTypes.oneOf([ "white", "blue-gray", "gray", "brown", "deep-orange", "orange", "amber", "yellow", "lime", "light-green", "green", "teal", "cyan", "light-blue", "blue", "indigo", "deep-purple", "purple", "pink", "red", ]), icon: PropTypes.node.isRequired, title: PropTypes.node.isRequired, value: PropTypes.node.isRequired, footer: PropTypes.node, }; Lexcard.displayName = "/src/widgets/cards/statistics-card.jsx"; export default CustomerCard; Lexcard;
import { Box, Button, Grid, List, ListItemText, Typography } from "@mui/material" import { FooterTitle, SubscripeTf } from "../../styles/footer"; import { Colors } from "../../styles/theme"; import FacebookIcon from '@mui/icons-material/Facebook'; import TwitterIcon from '@mui/icons-material/Twitter'; import InstagramIcon from '@mui/icons-material/Instagram'; import SendIcon from '@mui/icons-material/Send'; import { Stack } from "@mui/system"; function Footer() { return( <Box sx={{ background: Colors.shaft, color: Colors.white, mt: 4, p: { xs:4, md:10 }, pt: 12, pb: 12, fontSize: { xs:'12px', md:'14px' } }} > <Grid container spacing={2} justifyContent='center'> <Grid item xs={12} sm={12} md={6} lg={4}> <FooterTitle variant="body1">About us</FooterTitle> <Typography variant="caption2"> Lorem ipsum dolor sit amet cons adipisicing elit sed do eiusm tempor incididunt ut labor et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </Typography> <Box sx={{ color: Colors.dove_gray, mt: 4, }} > <FacebookIcon sx={{ mr: 1}} /> <TwitterIcon sx={{ mr: 1}} /> <InstagramIcon /> </Box> </Grid> <Grid item xs={12} sm={4} md={6} lg={2}> <FooterTitle variant="body1">information</FooterTitle> <List disablePadding> <ListItemText> <Typography variant="caption2" lineHeight={2}>About us</Typography> </ListItemText> <ListItemText> <Typography variant="caption2" lineHeight={2}>Order Tracking</Typography> </ListItemText> <ListItemText> <Typography variant="caption2" lineHeight={2}>Privacy & Policy</Typography> </ListItemText> <ListItemText> <Typography variant="caption2" lineHeight={2}>Terms & Conditions</Typography> </ListItemText> </List> </Grid> <Grid item xs={12} sm={4} md={6} lg={2}> <FooterTitle variant="body1">my account</FooterTitle> <List disablePadding> <ListItemText> <Typography variant="caption2" lineHeight={2}>Login</Typography> </ListItemText> <ListItemText> <Typography variant="caption2" lineHeight={2}>MyCart</Typography> </ListItemText> <ListItemText> <Typography variant="caption2" lineHeight={2}>My Account</Typography> </ListItemText> <ListItemText> <Typography variant="caption2" lineHeight={2}>Wishlist</Typography> </ListItemText> </List> </Grid> <Grid item xs={12} sm={4} md={6} lg={4}> <FooterTitle variant="body1">newsletter</FooterTitle> <Stack> <SubscripeTf variant="standard" label='Email Address' color="primary" /> <Button startIcon={<SendIcon />} sx={{ mt: 4, mb: 4, }} variant='contained' > Subscribe </Button> </Stack> </Grid> </Grid> </Box> ) } export default Footer
function temperature = asatemp(optimValues,options) %SATEMPERATUREFCNTEMPLATE Template to write custom temperature function % TEMPERATURE = SATEMPERATUREFCNTEMPLATE(optimValues,options) updates the % current temperature % % OPTIMVALUES is a structure containing the following information: % x: current point % fval: function value at x % bestx: best point found so far % bestfval: function value at bestx % temperature: current temperature % iteration: current iteration % t0: start time % k: annealing parameter 'k' % % OPTIONS: options object created by using OPTIMOPTIONS. % Copyright 2006-2015 The MathWorks, Inc. % The body of this function should simply return a new temperature vector % The new temperature will generally depend on either % options.InitialTemperature or optimValues.temperature and on % optimValues.k % temperature = options.InitialTemperature./log(optimValues.k); tempRatioScale = 1.0e-5; tempAnnealScale = 100.0; currentx = optimValues.x; nvar = numel(currentx); m = -log(tempRatioScale); n = log(tempAnnealScale); c = m.*exp(-n ./ nvar); % Make sure temperature is of same length as optimValues.k (nvars) temperature = options.InitialTemperature.*exp(-c.*optimValues.k.^(1/nvar));
import { useState, useEffect } from 'react'; import { Select } from 'antd'; import type { SelectProps } from 'antd'; import { Button, Form } from 'antd'; import { Divider } from 'antd'; import axios from 'axios'; import { getUserPrefrencesURL } from '../services/api'; import { ContentLoader, Spinner } from '../components/Loader/Loader'; import { Col, Row } from 'antd'; import { message } from 'antd'; const options: SelectProps['options'] = []; for (let i = 10; i < 36; i++) { options.push({ label: i.toString(36) + i, value: i.toString(36) + i, }); } const layout = { labelCol: { span: 4 }, wrapperCol: { span: 16 }, }; interface SourceType { id : number , slug : string , title : string , description : string , } interface CategoryType { id : number , title : string } export default function Profile () { const [sources, setSources] = useState([]); const [categories, setCategories] = useState([]); const [userSources, setUserSources] = useState<string[]>([]); const [userCategories, setUserCategories] = useState<string[]>([]); const [loading, setLoading] = useState(true); const [formSubmitLoading , setFormSubmitLoading] = useState(false); const [messageApi, contextHolder] = message.useMessage(); const showSuccessMessage = () => { messageApi.success('Successfully Saved Changes!'); }; const handleSourcesChange = (value: string[]) => { //console.log(`selected ${value}`); setUserSources(value); }; const handleCategoriesChange = (value: string[]) => { //console.log(`selected ${value}`); setUserCategories(value); }; const handleSubmit = () => { setFormSubmitLoading(true); //console.log(`userSources : ` , userSources); //console.log(`userCategories : ` , userCategories); const access_token = localStorage.getItem('access_token'); axios.put( getUserPrefrencesURL , { sources : userSources , categories : userCategories , } , { headers: { Authorization: `Bearer ${access_token}`, }, }).then( (_) => { //console.log(response.data); showSuccessMessage(); }).catch(AxiosError => { console.error('updatePrefrences failed:', AxiosError.response?.request.response); }) .catch(error => { console.error('updatePrefrences failed:', error); }) .finally( () => { setFormSubmitLoading(false); }); } useEffect(() => { const access_token = localStorage.getItem('access_token'); axios.post( getUserPrefrencesURL , null, { headers: { Authorization: `Bearer ${access_token}`, }, }) .then( response => { const { sources , categories , user_sources , user_categories } = response.data; setSources(sources); setCategories(categories); setUserSources(user_sources.map((item : SourceType) => item.id)); setUserCategories(user_categories.map((item : CategoryType) => item.id)); }) .catch(AxiosError => { console.error('getPrefrences failed:', AxiosError.response?.request.response); }) .catch(error => { console.error('getPrefrences failed:', error); }) .finally(() => { setLoading(false); }); return () => { // cleanup }; }, []); if(loading) { return <> <Divider orientation="left">Profile Settings</Divider> <ContentLoader> <Spinner></Spinner> </ContentLoader> </>; } return ( <> {contextHolder} <Divider orientation="left">Profile Settings</Divider> <Form {...layout} style={{ maxWidth: 600 }} > <Form.Item label="Sources"> <Select mode="multiple" allowClear style={{ width: '100%' }} placeholder="Please select" defaultValue={userSources} onChange={handleSourcesChange} options={sources.map((source : SourceType) => ({ label: source.title, value: source.id }))} /> </Form.Item> <Form.Item label="Categories"> <Select mode="multiple" allowClear style={{ width: '100%' }} placeholder="Please select" defaultValue={userCategories} onChange={handleCategoriesChange} options={categories.map((category : CategoryType) => ({ label: category.title, value: category.id }))} /> </Form.Item> <Form.Item> <Row gutter={16}> <Col xs={{ span : 0 }} sm={{ span : 6 }} ></Col> <Button type="primary" loading={formSubmitLoading} onClick={() => handleSubmit()} > Save Changes </Button> </Row> </Form.Item> </Form> </> ) }
/* * Copyright © 2022 Mark Raynsford <code@io7m.com> https://www.io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.aradine.tests; import com.io7m.aradine.instrument.spi1.ARI1PortId; import com.io7m.aradine.instrument.spi1.ARI1PortInputAudioType; import java.nio.DoubleBuffer; import java.util.Objects; public final class ARI1PortInputAudio implements ARI1PortInputAudioType { private DoubleBuffer inputBuffer; private final ARI1PortId id; public ARI1PortInputAudio( final ARI1PortId inId, final int sizeInitial) { this.id = Objects.requireNonNull(inId, "inName"); this.inputBuffer = DoubleBuffer.allocate(sizeInitial); } /** * @return The current input buffer */ public DoubleBuffer buffer() { return this.inputBuffer; } @Override public ARI1PortId id() { return this.id; } /** * Set a new buffer size. * * @param newValue The new size */ public void setBufferSize( final int newValue) { this.inputBuffer = DoubleBuffer.allocate(newValue); } @Override public double read( final int frame) { return this.inputBuffer.get(frame); } }
import React, { useState, useEffect } from "react"; import ShipmentsList from "./ShipmentsList"; import ClientList from "./ClientList"; const EmployeeDashboard = () => { const [employees, setEmployees] = useState([]); useEffect(() => { const fetchEmployees = async () => { try { const response = await fetch( "http://localhost:3001/users?role=employee" ); const data = await response.json(); setEmployees(data); } catch (error) { console.error("Error fetching employees:", error); } }; fetchEmployees(); }, []); return ( <div className="flex justify-between p-8"> {/* Employee Users Section */} <div className="w-1/2"> <h1 className="text-3xl font-bold mb-4">Employee Dashboard</h1> <ul className="list-disc pl-4"> {employees.map((employee) => ( <li key={employee._id} className="mb-2"> {employee.email} </li> ))} </ul> <br /> {employees.length > 0 && ( <ShipmentsList userEmail={employees[0].email} /> )} </div> {/* Client Users Section */} <div className="w-1/2"> <ClientList /> </div> </div> ); }; export default EmployeeDashboard;
import React from 'react'; import { ThemeProvider } from 'styled-components'; import ThemeDefault from './config/themes/themeDefault'; import { GlobalStyles } from './config/globalStyles/globalStyles'; import Stack from './components/stack/stack'; //import Card from './components/card/card'; //import Grid from './components/grid/grid'; import Button from './components/button/button'; import Typography from './components/typography/typography'; import Icon from './components/icon/icon'; //import Divider from './components/divider/divider'; import AppBar from './components/appbar/appbar'; import Container from './components/container/container'; // flex-direction: row | row-reverse | column | column-reverse; // justify-content: flex-start | flex-end | center | space-between | space-around | space-evenly | start | end | left | right ... + safe | unsafe; // flex-wrap: nowrap | wrap | wrap-reverse; // align-items: stretch | flex-start | flex-end | center | baseline | first baseline | last baseline | start | end | self-start | self-end + ... safe | unsafe; {/* <Grid variant="container" direction="row" gap="5" spacing="0" justify='space-around'> <Grid variant="item" order="1" xs="12" sm="12" md="6" lg="3"> <Card backgroundcolor="green" color="fff" height='250'>Card 1</Card> </Grid> <Grid variant="item" order="2" xs="12" sm="12" md="6" lg="3"> <Card backgroundcolor="red" color="fff" height='250'>Card 2</Card> </Grid> <Grid variant="item" order="3" xs="12" sm="12" md="12" lg="3"> <Card backgroundcolor="yellow" color="fff" height='250'>Card 3</Card> </Grid> <Grid variant="item" order="4" xs="12" sm="12" md="12" lg="3"> <Card backgroundcolor="blue" color="fff" height='250'>Card 4</Card> </Grid> <Grid variant="item" order="5" xs="12" sm="12" md="12" lg="3"> <Card backgroundcolor="purple" color="fff" height='250'>Card 5</Card> </Grid> <Grid variant="item" order="6" xs="12" sm="12" md="12" lg="3"> <Card backgroundcolor="orange" color="fff" height='250'>Card 6</Card> </Grid> </Grid> <Typography variant='headline_1' color='black'>Headline 1</Typography> <Typography variant='headline_2' color='black'>Headline 2</Typography> <Typography variant='headline_3' color='black'>Headline 3</Typography> <Typography variant='headline_4' color='black'>Headline 4</Typography> <Typography variant='headline_5' color='black'>Headline 5</Typography> <Typography variant='headline_6' color='black'>Headline 6</Typography> <Typography variant='subtitle_1' color='black'>Subtitle 1</Typography> <Typography variant='subtitle_2' color='black'>Subtitle 2</Typography> <Typography variant='body_1' color='black'>Body 1</Typography> <Typography variant='body_2' color='black'>Body 2</Typography> <Typography variant='caption' color='black'>Caption</Typography> <Typography variant='overline' color='black'>Overline</Typography> <br></br> <Icon size='normal' color='black' icon='coffee'></Icon> <Card backgroundcolor="fff"height='250'> <Typography variant='headline_6' color='black'>Headline 6</Typography> <Divider variant="list" type="subheader" subheader="subheader"></Divider> <br></br> <Typography variant='headline_6' color='black'>Headline 6</Typography> <Divider variant="vertical"></Divider> <Typography variant='headline_6' color='black'>Headline 6</Typography> </Card> */} const App: React.FC = () => { return ( <ThemeProvider theme={ThemeDefault}> <GlobalStyles /> <AppBar variant='regular' color="red"> <Stack direction="row" spacing="4" xs="12" sm="12" md="12" lg="12" alignItems="center"> <Icon icon="coffee" size="mini"></Icon> <Typography>AppBar</Typography> <Button>Hello</Button> </Stack> </AppBar> <Container> <Stack direction="row" spacing="10" xs="12" sm="12" md="12" lg="12"> <Button>Hello</Button> <Button>Hello</Button> <Button>Hello</Button> </Stack> </Container> </ThemeProvider> ); } export default App;
import React, { useRef, useState, useEffect } from "react"; import { connect } from "react-redux"; import Swal from "sweetalert2"; import colors from "../assets/styles/colors"; import checkPassword from "../utils/checkPassword"; import axios from "../api"; import { logoutRequest } from "../actions"; import { Grid, FormControl, TextField, Button, Backdrop, CircularProgress, } from "@mui/material"; function Login(props) { const [form, setForm] = useState({ firstName: "", secondName: "", lastName: "", secondSurname: "", email: "", password: "", }); const [loading, setLoading] = useState(false); const singupButton = useRef(); const [validate, setValidate] = useState({ password: { error: false } }); const { user, history } = props; useEffect(() => { if (user) { setLoading(true); valida(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const valida = async () => { await axios .get(`/users/${user?.data_user?.id}`) .then((res) => { setLoading(false); history.push("/dashboard"); }) .catch(() => { setLoading(false); logoutRequest(); window.location.reload(); }); }; const handleInput = (event) => { if (event.target.name === "password") { if (event.target.value === "" || checkPassword(event.target.value)) { singupButton.current.disabled = false; setValidate({ ...validate, password: { error: false } }); Swal.close(); } else { singupButton.current.disabled = true; setValidate({ ...validate, password: { error: true, }, }); !validate.password.error && Swal.mixin({ toast: true, position: "bottom-start", }).fire({ icon: "error", title: "La contraseña debe tener mínimo entre 8 y 15 caracteres,\n una letra minúscula, una mayúscula, un número y un carácter especial.", }); } } setForm({ ...form, [event.target.name]: event.target.value, }); }; const handleSubmit = (e) => { e.preventDefault(); if (form.password !== form.passwordConfirmation) { return Swal.fire({ icon: "info", text: "Las contraseñas ingresadas no coinciden", showConfirmButton: false, timer: 3000, }); } setLoading(true); axios({ url: `/users/sign-up`, method: "post", data: { primer_nombre: form.firstName, segundo_nombre: form.secondName, primer_apellido: form.lastName, segundo_apellido: form.secondSurname, correo: form.email, password: form.password, }, }) .then((res) => { setLoading(false); const { data } = res; if (data) { Swal.fire({ icon: "success", text: "Se ha registrado exitosamente.", showConfirmButton: false, timer: 3000, }).then(() => { props.history.push("/sign-in"); }); } }) .catch(() => { setLoading(false); Swal.fire({ icon: "error", text: "Ya existe una cuenta con este correo", showConfirmButton: false, timer: 3000, }); }); }; return ( <div style={{ ...useStylesMUI.container }}> <div> <h1 style={{ textAlign: "center", marginBottom: "40px", marginTop: 0 }}> Registro de usuario </h1> <form onSubmit={handleSubmit}> <Grid container spacing={2} direction="column"> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> <TextField required label="Primer nombre" name="firstName" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} value={form.firstName} /> </FormControl> </Grid> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> <TextField label="Segundo nombre" name="secondName" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} value={form.secondName} /> </FormControl> </Grid> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> <TextField required label="Primer apellido" name="lastName" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} value={form.lastName} /> </FormControl> </Grid> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> <TextField label="Segundo apellido" name="secondSurname" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} value={form.secondSurname} /> </FormControl> </Grid> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> <TextField required label="Correo electónico" name="email" type="email" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} value={form.email} /> </FormControl> </Grid> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> <TextField required label="Contraseña" name="password" type="password" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} error={validate.password.error} /> </FormControl> </Grid> <Grid item xs={12}> <FormControl sx={{ width: "100%" }}> {validate.password.error && ( <span style={{ ...useStylesMUI.text_password_error }}> {validate.password.message} </span> )} <TextField required label="Confirme la contraseña" name="passwordConfirmation" type="password" variant="outlined" onChange={handleInput} InputProps={{ classes: { root: { borderRadius: "20px" }, notchedOutline: { borderWidth: 2, borderColor: colors.primary, }, focused: { borderColor: colors.primary }, }, }} /> </FormControl> </Grid> </Grid> <div> <Button ref={singupButton} variant="contained" size="small" sx={useStylesMUI.button} type="submit" > Registrase </Button> <br /> <span> ¿Ya tienes una cuenta? &nbsp; <span style={{ fontWeight: "bold", textDecoration: "underline", cursor: "pointer", }} onClick={() => { props.history.push("/sign-in"); }} > Inicia sesión aquí. </span> </span> </div> </form> </div> <Backdrop sx={useStylesMUI.backdrop} open={loading}> <CircularProgress color="inherit" /> </Backdrop> </div> ); } const useStylesMUI = { container: { display: "flex", justifyContent: "center", alignItems: "center", margin: "2px 10px", }, root: { marginTop: "2em", }, button: { margin: "0.5em", color: "white", backgroundColor: colors.primary, borderRadius: 5, padding: "9px 40px", width: "95%", "&:hover": { color: "black", backgroundColor: colors.secondary, }, }, backdrop: { zIndex: 3000, color: "#fff", }, text_password_error: { marginBottom: "5px", color: "#f4443b", fontSize: "0.9em", maxWidth: "fit-content", textAlign: "justify", }, }; const mapStateToProps = (state) => { return { user: state.user, }; }; const mapDispatchToProps = { logoutRequest }; export default connect(mapStateToProps, mapDispatchToProps)(Login);
package com.taotao.service.impl; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.taotao.common.utils.FtpUtil; import com.taotao.common.utils.IDUtils; import com.taotao.service.PictureService; /** * 图片上传服务 * <p>Title: PictureServiceImpl</p> * <p>Description: </p> * <p>Company: www.itcast.com</p> * @author 入云龙 * @date 2015年9月4日下午2:50:42 * @version 1.0 */ @Service public class PictureServiceImpl implements PictureService { @Value("${FTP_ADDRESS}") private String FTP_ADDRESS; @Value("${FTP_PORT}") private Integer FTP_PORT; @Value("${FTP_USERNAME}") private String FTP_USERNAME; @Value("${FTP_PASSWORD}") private String FTP_PASSWORD; @Value("${FTP_BASE_PATH}") private String FTP_BASE_PATH; @Value("${IMAGE_BASE_URL}") private String IMAGE_BASE_URL; @Override public Map uploadPicture(MultipartFile uploadFile) { Map resultMap = new HashMap<>(); try { //生成一个新的文件名 //取原始文件名 String oldName = uploadFile.getOriginalFilename(); //生成新文件名 //UUID.randomUUID(); String newName = IDUtils.genImageName(); newName = newName + oldName.substring(oldName.lastIndexOf(".")); //图片上传 String imagePath = new DateTime().toString("/yyyy/MM/dd"); boolean result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream()); //返回结果 if(!result) { resultMap.put("error", 1); resultMap.put("message", "文件上传失败"); return resultMap; } resultMap.put("error", 0); resultMap.put("url", IMAGE_BASE_URL + imagePath + "/" + newName); return resultMap; } catch (Exception e) { resultMap.put("error", 1); resultMap.put("message", "文件上传发生异常"); return resultMap; } } }
package de.emir.rcp.manager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import javax.swing.SwingUtilities; import de.emir.rcp.jobs.DelegateProgressMonitor; import de.emir.rcp.jobs.IJob; import de.emir.rcp.jobs.IJobFinishedHandler; import de.emir.rcp.manager.util.PlatformUtil; import de.emir.rcp.ui.utils.dialogs.ProgressDialog; import de.emir.tuml.ucore.runtime.extension.IService; import de.emir.tuml.ucore.runtime.logging.ULog; import io.reactivex.rxjava3.disposables.Disposable; import io.reactivex.rxjava3.functions.Consumer; import io.reactivex.rxjava3.subjects.BehaviorSubject; import io.reactivex.rxjava3.subjects.PublishSubject; /** * Manages the execution of jobs. Should be used for prolonged tasks to prevent UI locks. * * @author fklein * */ public class JobManager implements IService { private BlockingQueue<JobData> queue = new LinkedBlockingQueue<>(); private List<JobData> runningJobs = Collections.synchronizedList(new ArrayList<JobData>()); private PublishSubject<JobData> addRunningJobSubject = PublishSubject.create(); private PublishSubject<JobData> removeRunningJobSubject = PublishSubject.create(); public JobManager() { initJobThread(); } public Disposable subscribeRunningJobAdded(Consumer<JobData> c) { return addRunningJobSubject.subscribe(c); } public Disposable subscribeRunningJobRemoved(Consumer<JobData> c) { return removeRunningJobSubject.subscribe(c); } private void initJobThread() { Thread t = new Thread(() -> { while (true) { try { JobData entry = queue.take(); IJob job = entry.job; if (job.isBlocking()) { runJob(entry); } else { Thread t2 = new Thread(() -> runJob(entry)); t2.start(); } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.setDaemon(true); t.start(); } public List<JobData> getRunningJobs() { return runningJobs; } /** * Adds a job to the queue and executes it. * * @param job */ public void schedule(IJob job) { schedule(job, null); } /** * Adds a job to the queue and executes it. * * @param job * @param cb * A callback, fired when job is completed */ public void schedule(IJob job, IJobFinishedHandler cb) { JobData jd = new JobData(); jd.job = job; if (cb != null) { jd.addHandler(cb); } jd.monitor = new DelegateProgressMonitor(); try { queue.put(jd); } catch (InterruptedException e) { ULog.error(e); } } private void runJob(JobData jd) { IJob job = jd.job; addRunningJob(jd); if (job.isBlocking() == true || job.isBackground() == false) { showDialogForRunningJob(jd); } try { job.run(jd.monitor); IJobFinishedHandler[] fhs = jd.getFinishHandler(); // Execute desc because job dialog should be closed first and is always added last for (int i = fhs.length - 1; i >= 0; i--) { fhs[i].finished(job); } } catch (Exception | LinkageError er) { er.printStackTrace(); } removeRunningJob(jd); } public void showDialogForRunningJob(JobData rjd) { ProgressDialog dialog = new ProgressDialog(PlatformUtil.getWindowManager().getMainWindow(), rjd); dialog.setCancelListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { rjd.requestCancel(); } }); IJobFinishedHandler finishHandler = j -> { try { SwingUtilities.invokeAndWait(dialog::close); } catch (InvocationTargetException | InterruptedException e1) { ULog.error(e1); } }; // Remove the finish handler closing the dialog if it is manually closed dialog.setCloseListener(e -> rjd.removeHandler(finishHandler)); rjd.monitor.addDelegate(dialog); rjd.addHandler(finishHandler); SwingUtilities.invokeLater(dialog::open); } private void addRunningJob(JobData rjd) { synchronized (runningJobs) { runningJobs.add(rjd); } addRunningJobSubject.onNext(rjd); } private void removeRunningJob(JobData rjd) { synchronized (runningJobs) { runningJobs.remove(rjd); } removeRunningJobSubject.onNext(rjd); } public class JobData { public IJob job; public DelegateProgressMonitor monitor; private boolean isCancelRequested = false; private BehaviorSubject<Boolean> cancelRequestSubject = BehaviorSubject.createDefault(false); private List<IJobFinishedHandler> finishHandler = Collections.synchronizedList(new ArrayList<>()); public void addHandler(IJobFinishedHandler h) { synchronized (finishHandler) { finishHandler.add(h); } } public void removeHandler(IJobFinishedHandler h) { synchronized (finishHandler) { finishHandler.remove(h); } } public Disposable subscribeCancelRequest(Consumer<Boolean> c) { return cancelRequestSubject.subscribe(c); } public IJobFinishedHandler[] getFinishHandler() { IJobFinishedHandler[] result = null; synchronized (finishHandler) { result = finishHandler.toArray(new IJobFinishedHandler[0]); } return result; } public void requestCancel() { if (isCancelRequested == false) { isCancelRequested = true; cancelRequestSubject.onNext(true); job.cancel(); } } } }
import React from "react"; import { Link } from "gatsby"; import { FiArrowRightCircle } from "react-icons/fi"; interface RecipeCardProps { title: string; path: string; description: string; image: string; } const RecipeCard = ({ title, path, description, image }: RecipeCardProps) => { return ( <Link to={path}> <div className="card has-border-radius"> <div style={{ padding: 20, display: "flex", justifyContent: "space-between", alignItems: "center", }} > <div> <p className="title is-6" style={{ marginBottom: 5 }}> {title} </p> <p className="subtitle is-6 is-marginless">{description}</p> </div> <FiArrowRightCircle size={24} /> </div> <div className="card-image"> <figure className="image is-4by3"> <img src={image} alt={title} /> </figure> </div> </div> </Link> ); }; export default RecipeCard;
// Copyright (C) 2019 Bernhard Isemann, oe3bia // // Copyright (C) 2021 Jon Beniston, M7RCE // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation as version 3 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License V3 for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program. If not, see <http://www.gnu.org/licenses/>. // #ifndef INCLUDE_RADIOCLOCKSINK_H #define INCLUDE_RADIOCLOCKSINK_H #include <QVector> #include <QDateTime> #include "dsp/channelsamplesink.h" #include "dsp/phasediscri.h" #include "dsp/nco.h" #include "dsp/interpolator.h" #include "dsp/firfilter.h" #include "dsp/fftfactory.h" #include "dsp/fftengine.h" #include "dsp/fftwindow.h" #include "util/movingaverage.h" #include "util/doublebufferfifo.h" #include "util/messagequeue.h" #include "radioclocksettings.h" #include <vector> #include <iostream> #include <fstream> class ChannelAPI; class RadioClock; class ScopeVis; class RadioClockSink : public ChannelSampleSink { public: RadioClockSink(RadioClock *radioClock); ~RadioClockSink(); virtual void feed(const SampleVector::const_iterator& begin, const SampleVector::const_iterator& end); void setScopeSink(ScopeVis* scopeSink); void applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force = false); void applySettings(const RadioClockSettings& settings, bool force = false); void setMessageQueueToChannel(MessageQueue *messageQueue) { m_messageQueueToChannel = messageQueue; } void setChannel(ChannelAPI *channel) { m_channel = channel; } double getMagSq() const { return m_magsq; } void getMagSqLevels(double& avg, double& peak, int& nbSamples) { if (m_magsqCount > 0) { m_magsq = m_magsqSum / m_magsqCount; m_magSqLevelStore.m_magsq = m_magsq; m_magSqLevelStore.m_magsqPeak = m_magsqPeak; } avg = m_magSqLevelStore.m_magsq; peak = m_magSqLevelStore.m_magsqPeak; nbSamples = m_magsqCount == 0 ? 1 : m_magsqCount; m_magsqSum = 0.0f; m_magsqPeak = 0.0f; m_magsqCount = 0; } private: struct MagSqLevelsStore { MagSqLevelsStore() : m_magsq(1e-12), m_magsqPeak(1e-12) {} double m_magsq; double m_magsqPeak; }; ScopeVis* m_scopeSink; // Scope GUI to display debug waveforms RadioClock *m_radioClock; RadioClockSettings m_settings; ChannelAPI *m_channel; int m_channelSampleRate; int m_channelFrequencyOffset; NCO m_nco; Interpolator m_interpolator; Real m_interpolatorDistance; Real m_interpolatorDistanceRemain; double m_magsq; double m_magsqSum; double m_magsqPeak; int m_magsqCount; MagSqLevelsStore m_magSqLevelStore; MessageQueue *m_messageQueueToChannel; MovingAverageUtil<Real, double, 80> m_movingAverage; //!< Moving average has sharpest step response of LPFs MovingAverageUtil<Real, double, 10*RadioClockSettings::RADIOCLOCK_CHANNEL_SAMPLE_RATE> m_thresholdMovingAverage; // Average over 10 seconds (because VVWB markers are 80% off) int m_data; //!< Demod data before clocking int m_prevData; //!< Previous value of m_data int m_sample; //!< For scope, indicates when data is sampled int m_lowCount; //!< Number of consecutive 0 samples int m_highCount; //!< Number of consecutive 1 samples int m_periodCount; //!< Counts from 1-RADIOCLOCK_CHANNEL_SAMPLE_RATE bool m_gotMinuteMarker; //!< Minute marker has been seen int m_second; //!< Which second we are in int m_timeCode[61]; //!< Timecode from data in each second QDateTime m_dateTime; //!< Decoded date and time int m_secondMarkers; //!< Counts number of second markers that have been seen Real m_threshold; //!< Current threshold for display on scope Real m_linearThreshold; //!< settings.m_threshold as a linear value rather than dB RadioClockSettings::DST m_dst; //!< Daylight savings time status // MSF demod state int m_timeCodeB[61]; // TDF demod state PhaseDiscriminators m_phaseDiscri; // FM demodulator int m_zeroCount; MovingAverageUtil<Real, double, 10> m_fmDemodMovingAverage; int m_bits[4]; ComplexVector m_sampleBuffer[RadioClockSettings::m_scopeStreams]; static const int m_sampleBufferSize = 60; int m_sampleBufferIndex; // WWVB state bool m_gotMarker; //!< Marker in previous second void processOneSample(Complex &ci); MessageQueue *getMessageQueueToChannel() { return m_messageQueueToChannel; } void sampleToScope(Complex sample); int bcd(int firstBit, int lastBit); int bcdMSB(int firstBit, int lastBit, int skipBit1=0, int skipBit2=0); int xorBits(int firstBit, int lastBit); bool evenParity(int firstBit, int lastBit, int parityBit); bool oddParity(int firstBit, int lastBit, int parityBit); void dcf77(); void tdf(Complex &ci); void msf60(); void wwvb(); }; #endif // INCLUDE_RADIOCLOCKSINK_H
GOLANG编译器源码流程分析及控制指令集的方法 一、工具准备 GOLANG编译器的代码主要位于cmd/compile目录下,但代码量较多,调用关系复杂,为了便于快速分析,利用go-package-plantuml工具先把代码转化为UML图,然后根据UML图从整体上自上而下地分析。 参考了文档:https://studygolang.com/articles/9719 来生成UML图,但在实践的过程中,需要进行一些修改才跑得通,记录如下: 1、搭建好go的环境 下载go源码、编译go1.4、编译go1.10最新版本,此处不再赘述。 2、安装go-package-plantuml工具 首先下载代码(https://gitee.com/jscode/go-package-plantuml),然后把go-package-plantuml拷贝到实验室机器的$GOROOT/src目录下。因为我们实验室的机器无法直接访问外网,所以还需要修改一下代码: diff --git a/main.go b/main.go index 97143de..5ab63e1 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,7 @@ package main import ( - "git.oschina.net/jscode/go-package-plantuml/codeanalysis" + "go-package-plantuml/codeanalysis" log "github.com/Sirupsen/logrus" "fmt" "github.com/jessevdk/go-flags" 最后安装go-package-plantuml即可: # go install go-package-plantuml 3、安装plantuml工具 由于sourceforge在公司里面无法访问,所以找了一条曲线下载的方法,在github的一个开源项目上,下载plantuml的压缩包:https://github.com/jvantuyl/sublime_diagram_plugin/tree/master/diagram 下载plantuml.1.2018.1.jar。 此外,由于centos自带的Graphviz版本太老,绘制uml图会有问题,需要下载最新的源码(https://graphviz.gitlab.io/_pages/Download/Download_source.html),然后再编译、安装。 4,工具使用 1)生成go代码的UML文本文件 使用go-package-plantuml,分析/home/go/go_main/src/cmd/compile目录的代码,生成uml的文本文件。命令如下: go-package-plantuml --codedir /home/go/go_main/src/cmd/compile --gopath /home/go/go_main --outputfile /tmp/result go-package-plantuml有bug,指定的输出outfile不生效,始终生成到/tmp/uml.txt文件中。 2)根据UML文本文件生成图片 使用plantuml解析上一步生成的uml.txt,生成svg格式的图片。命令如下: java -jar plantuml.1.2018.1.jar ./all_uml.txt -tsvg 3)最终得到的UML图的svg文件如下 二、GOLANG编译过程简介 和传统的编译器一样,功能也分为4个阶段: 1、词法和语法分析 代码在cmd/compile/internal/syntax目录下,经过这一阶段的处理后,生成语法树。 Syntax对外提供的接口为Parse,其含义如下: // Parse parses a single Go source file from src and returns the corresponding // syntax tree. If there are errors, Parse will return the first error found, // and a possibly partially constructed syntax tree, or nil if no correct package // clause was found. The base argument is only used for position information. // // If errh != nil, it is called with each error encountered, and Parse will // process as much source as possible. If errh is nil, Parse will terminate // immediately upon encountering an error. // // If a PragmaHandler is provided, it is called with each pragma encountered. // // If a FilenameHandler is provided, it is called to process each filename // encountered in //line directives. // // The Mode argument is currently ignored. func Parse(base *src.PosBase, src io.Reader, errh ErrorHandler, pragh PragmaHandler, fileh FilenameHandler, mode Mode) (_ *File, first error) 传入单个的go文件,经词法分析、语法分析之后,返回语法树,语法树是存贮到File中的。File结构体又是node结构体的子类。涉及的部分结构体的关系截图: Parse函数的内部实现,涉及到source、scanner等父类,以及声明(Decl,包括变量声明VarDecl、类型声明TypeDecl等)、语句(Stmt,包括返回值语句ReturnStmt、代码块BlockStmt、赋值语句AssignStmt、分支BranchStmt等等)。后继有时间再具体分析。 在编译器的主函数中,词法、语法分析对应的入口代码段如下: src/cmd/compile/internal/gc/main.go, Main主函数: timings.Start("fe", "parse") lines := parseFiles(flag.Args()) timings.Stop() 2、类型检查 对上一步构造出的语法树进行若干次类型检查。代码主要是对语法树中的节点(即Node数据结构),调用typecheck函数: // typecheck type checks node n. // The result of typecheck MUST be assigned back to n, e.g. // n.Left = typecheck(n.Left, top) func typecheck(n *Node, top int) *Node 比如下面的调用: // Phase 1: const, type, and names and types of funcs. ...... timings.Start("fe", "typecheck", "top1") for i := 0; i < len(xtop); i++ { n := xtop[i] if op := n.Op; op != ODCL && op != OAS && op != OAS2 && (op != ODCLTYPE || !n.Left.Name.Param.Alias) { xtop[i] = typecheck(n, Etop) } } // Phase 2: Variable assignments. // To check interface assignments, depends on phase 1. // Don't use range--typecheck can add closures to xtop. timings.Start("fe", "typecheck", "top2") for i := 0; i < len(xtop); i++ { n := xtop[i] if op := n.Op; op == ODCL || op == OAS || op == OAS2 || op == ODCLTYPE && n.Left.Name.Param.Alias { xtop[i] = typecheck(n, Etop) } } 入口调用的代码段大同小异,都是根据各种条件的组合情况,反复调用typecheck函数。而typecheck函数的实现细节很多,这里只是进行流程梳理,暂不进行细节分析。 3、中间代码生成 GOLANG使用SSA(Static Single Assignment)作为中间语言。 src/cmd/compile/internal/gc/main.go, Main主函数中的入口如下: // Prepare for SSA compilation. // This must be before peekitabs, because peekitabs // can trigger function compilation. initssaconfig() // Just before compilation, compile itabs found on // the right side of OCONVIFACE so that methods // can be de-virtualized during compilation. Curfn = nil peekitabs() // Phase 8: Compile top level functions. // Don't use range--walk can add functions to xtop. timings.Start("be", "compilefuncs") fcount = 0 for i := 0; i < len(xtop); i++ { n := xtop[i] if n.Op == ODCLFUNC { funccompile(n) fcount++ } } timings.AddEvent(fcount, "funcs") 函数调用关系如下: funccompile -> compileSSA -> buildssa 而buildssa把语法树节点的Node转化为ssa.Func,其描述如下: // buildssa builds an SSA function for fn. func buildssa(fn *Node, worker int) *ssa.Func ssa.Func是一个比较核心的数据结构,表示一个函数,它和很多数据结构都有关联。 // A Func represents a Go func declaration (or function literal) and its body. // This package compiles each Func independently. // Funcs are single-use; a new Func must be created for every compiled function. 4、机器指令生成 和上一步的入口是一样的,funccompile -> compileSSA , compileSSA函数里面,先调用buildssa生成中间代码,然后再调用genssa把中间代码放入Progs结构中,最后调用Flush生成机器指令: // compileSSA builds an SSA backend function, // uses it to generate a plist, // and flushes that plist to machine code. // worker indicates which of the backend workers is doing the processing. func compileSSA(fn *Node, worker int) { f := buildssa(fn, worker) if f.Frontend().(*ssafn).stksize >= maxStackSize { largeStackFramesMu.Lock() largeStackFrames = append(largeStackFrames, fn.Pos) largeStackFramesMu.Unlock() return } pp := newProgs(fn, worker) genssa(f, pp) pp.Flush() // fieldtrack must be called after pp.Flush. See issue 20014. fieldtrack(pp.Text.From.Sym, fn.Func.FieldTrack) pp.Free() } Progs.Flush的定义如下: // Flush converts from pp to machine code. func (pp *Progs) Flush() { plist := &obj.Plist{Firstpc: pp.Text, Curfn: pp.curfn} obj.Flushplist(Ctxt, plist, pp.NewProg, myimportpath) } obj已经属于汇编器。Progs表示函数中的指令,也是一个比较核心的数据结构,可以根据它生成机器指令。 // Progs accumulates Progs for a function and converts them into machine code. 三、ARM控制指令集的方法 上面对GOLANG的代码流程进行了大体的分析,现在结合ARM结构,分析GOLANG是如何控制指令集的。 ARM架构的指令集有ARMv5、ARMv6、ARMv7等,同样的go代码,在不同的架构下,需要生成不同的机器指令。前面的语法分析、类型检查、中间代码生成和机器指令生成,只需要在第三步和第四步进行修改,就可以实现这个功能。 1、在全局变量中引入了GOARM变量来标识指令集 可以看到这是一个通用的方法,ARM、x86、MIPS等架构都有各自的变量,来保存各自的指令集: var ( defaultGOROOT string // set by linker GOROOT = envOr("GOROOT", defaultGOROOT) GOARCH = envOr("GOARCH", defaultGOARCH) GOOS = envOr("GOOS", defaultGOOS) GO386 = envOr("GO386", defaultGO386) GOARM = goarm() GOMIPS = gomips() Version = version ) 2、GOLANG工具链制作时,生成文件,保存GOARM的值 // mkzbootstrap writes cmd/internal/objabi/zbootstrap.go: // // package objabi // // const defaultGOROOT = <goroot> // const defaultGO386 = <go386> // const defaultGOARM = <goarm> // const defaultGOMIPS = <gomips> // const defaultGOOS = runtime.GOOS // const defaultGOARCH = runtime.GOARCH // const defaultGO_EXTLINK_ENABLED = <goextlinkenabled> // const version = <version> // const stackGuardMultiplier = <multiplier value> // const goexperiment = <goexperiment> // // The use of runtime.GOOS and runtime.GOARCH makes sure that // a cross-compiled compiler expects to compile for its own target // system. That is, if on a Mac you do: // // GOOS=linux GOARCH=ppc64 go build cmd/compile // // the resulting compiler will default to generating linux/ppc64 object files. // This is more useful than having it default to generating objects for the // original target (in this example, a Mac). func mkzbootstrap(file string) { var buf bytes.Buffer fmt.Fprintf(&buf, "// Code generated by go tool dist; DO NOT EDIT.\n") fmt.Fprintln(&buf) fmt.Fprintf(&buf, "package objabi\n") fmt.Fprintln(&buf) fmt.Fprintf(&buf, "import \"runtime\"\n") fmt.Fprintln(&buf) fmt.Fprintf(&buf, "const defaultGO386 = `%s`\n", go386) fmt.Fprintf(&buf, "const defaultGOARM = `%s`\n", goarm) fmt.Fprintf(&buf, "const defaultGOMIPS = `%s`\n", gomips) fmt.Fprintf(&buf, "const defaultGOOS = runtime.GOOS\n") fmt.Fprintf(&buf, "const defaultGOARCH = runtime.GOARCH\n") fmt.Fprintf(&buf, "const defaultGO_EXTLINK_ENABLED = `%s`\n", goextlinkenabled) fmt.Fprintf(&buf, "const version = `%s`\n", findgoversion()) fmt.Fprintf(&buf, "const stackGuardMultiplier = %d\n", stackGuardMultiplier()) fmt.Fprintf(&buf, "const goexperiment = `%s`\n", os.Getenv("GOEXPERIMENT")) writefile(buf.String(), file, writeSkipSame) } 3、Go启动的时候,还可以通过环境变量的方式,更改GOARM的值 // xinit handles initialization of the various global state, like goroot and goarch. func xinit() { b := os.Getenv("GOROOT") if b == "" { fatalf("$GOROOT must be set") } goroot = filepath.Clean(b) ...... b = os.Getenv("GOARM") if b == "" { b = xgetgoarm() } goarm = b ...... 4、编译go程序的时候,通过GOARM的取值,来标识不同的指令集 envOr函数优先从环境变量中读取,如果为空,再从工具链制作时生成的文本文件中读取。 func goarm() int { switch v := envOr("GOARM", defaultGOARM); v { case "5": return 5 case "6": return 6 case "7": return 7 } // Fail here, rather than validate at multiple call sites. log.Fatalf("Invalid GOARM value. Must be 5, 6, or 7.") panic("unreachable") } 5、编译go程序、生成指令的是偶,根据GOARM的值,选择不同的指令 SSA的规则文件中的部分代码片段如下: // count trailing zero for ARMv5 and ARMv6 // 32 - CLZ(x&-x - 1) (Ctz32 <t> x) && objabi.GOARM<=6 -> (RSBconst [32] (CLZ <t> (SUBconst <t> (AND <t> x (RSBconst <t> [0] x)) [1]))) // count trailing zero for ARMv7 (Ctz32 <t> x) && objabi.GOARM==7 -> (CLZ <t> (RBIT <t> x)) 6、运行时库,也是根据GOARM来选择指令的 运行时库中的部分代码片段如下: // armPublicationBarrier is a native store/store barrier for ARMv7+. // On earlier ARM revisions, armPublicationBarrier is a no-op. // This will not work on SMP ARMv6 machines, if any are in use. // To implement publicationBarrier in sys_$GOOS_arm.s using the native // instructions, use: // // TEXT ·publicationBarrier(SB),NOSPLIT,$-4-0 // B runtime·armPublicationBarrier(SB) // TEXT runtime·armPublicationBarrier(SB),NOSPLIT,$-4-0 MOVB runtime·goarm(SB), R11 CMP $7, R11 BLT 2(PC) WORD $0xf57ff05e // DMB ST RET 可以看到,ARM架构通过引入GOARM变量,可以在编译时选择不同的指令,也可以在运行时库中自动选择不同的指令。GOARM变量的值是再制作GOLANG工具链的时候写入到文件中的,而且还可以通过环境变量,在运行的时候动态修改GOARM的值。 四、控制ppc大端e6500指令集的方法 我们可以参考ARM的实现,通过添加GOPPC变量来控制指令集。具体实现如下: 1、引入了GOPPC环境变量,使用它来标识CPU类型: diff --git a/src/cmd/dist/build.go b/src/cmd/dist/build.go index 49ed800..9aaf33c 100644 --- a/src/cmd/dist/build.go +++ b/src/cmd/dist/build.go @@ -31,6 +31,7 @@ var ( goarm string go386 string gomips string + goppc string goroot string goroot_final string goextlinkenabled string @@ -145,6 +146,9 @@ func xinit() { } gomips = b + b = os.Getenv("GOPPC") + goppc = b + if p := pathf("%s/src/all.bash", goroot); !isfile(p) { fatalf("$GOROOT is not set correctly or not exported\n"+ "\tGOROOT=%s\n"+ diff --git a/src/cmd/internal/objabi/util.go b/src/cmd/internal/objabi/util.go index eafef6b..92e4924 100644 --- a/src/cmd/internal/objabi/util.go +++ b/src/cmd/internal/objabi/util.go @@ -27,6 +27,7 @@ var ( GO386 = envOr("GO386", defaultGO386) GOARM = goarm() GOMIPS = gomips() + GOPPC = goppc() Version = version ) @@ -53,6 +54,25 @@ func gomips() string { panic("unreachable") } +type CpuType uint + +const ( + PpcDefault CpuType = iota + PpcE6500 +) + +func goppc() CpuType { + switch v := envOr("GOPPC", defaultGOPPC); v { + case "e6500": + return PpcE6500 + case "": + return PpcDefault + } + // Fail here, rather than validate at multiple call sites. + log.Fatalf("Invalid GOPPC value. Must be e6500 or empty.") + panic("unreachable") +} + 2、golang工具链制作成功后,把当前的GOPPC环境变量的值持久化到文件中 diff --git a/src/cmd/dist/buildruntime.go b/src/cmd/dist/buildruntime.go index 5cbcd81..b8240cd 100644 --- a/src/cmd/dist/buildruntime.go +++ b/src/cmd/dist/buildruntime.go @@ -44,6 +44,7 @@ func mkzversion(dir, file string) { // const defaultGO386 = <go386> // const defaultGOARM = <goarm> // const defaultGOMIPS = <gomips> +// const defaultGOPPC = <goppc> // const defaultGOOS = runtime.GOOS // const defaultGOARCH = runtime.GOARCH // const defaultGO_EXTLINK_ENABLED = <goextlinkenabled> @@ -71,6 +72,7 @@ func mkzbootstrap(file string) { fmt.Fprintf(&buf, "const defaultGO386 = `%s`\n", go386) fmt.Fprintf(&buf, "const defaultGOARM = `%s`\n", goarm) fmt.Fprintf(&buf, "const defaultGOMIPS = `%s`\n", gomips) + fmt.Fprintf(&buf, "const defaultGOPPC = `%s`\n", goppc) fmt.Fprintf(&buf, "const defaultGOOS = runtime.GOOS\n") fmt.Fprintf(&buf, "const defaultGOARCH = runtime.GOARCH\n") fmt.Fprintf(&buf, "const defaultGO_EXTLINK_ENABLED = `%s`\n", goextlinkenabled) 3、Golang主分支代码已经删掉了对于PPC64大端的支持,需要回退。 需要回退如下补丁: https://github.com/golang/go/commit/7f5302560424b9ff219dbf217801615fef3b1f38 https://github.com/golang/go/commit/a9e76a2583ce24c1773e81310dc208e51f641983 https://github.com/golang/go/commit/1f57372cb1c2c96254bb16fdb41295d0c37f33d5 https://github.com/golang/go/commit/cc306c2d2c77b988e0321f14ab1951c26d8fa070 https://github.com/golang/go/commit/81e73292faf10c0f7cda5b6614e3909c17cf4f31 https://github.com/golang/go/commit/40e25895e3ab998033cc9f7086332d046c7f608a https://github.com/golang/go/commit/be943df58860e7dec008ebb8d68428d54e311b94 回退补丁之后,新增了一个OldArch变量来表示是否PPC64大端(目前PPC64大端只有E6500处理器): diff --git a/src/cmd/compile/internal/ssa/config.go b/src/cmd/compile/internal/ssa/config.go index ae6caee..5576dec 100644 --- a/src/cmd/compile/internal/ssa/config.go +++ b/src/cmd/compile/internal/ssa/config.go @@ -37,6 +37,7 @@ type Config struct { nacl bool // GOOS=nacl use387 bool // GO386=387 SoftFloat bool // + OldArch bool // True for older versions of architecture, e.g. true for PPC64BE, false for PPC64LE NeedsFpScratch bool // No direct move between GP and FP register sets BigEndian bool // sparsePhiCutoff uint64 // Sparse phi location algorithm used above this #blocks*#variables score @@ -216,7 +217,9 @@ func NewConfig(arch string, types Types, ctxt *obj.Link, optimize bool) *Config c.hasGReg = true c.noDuffDevice = objabi.GOOS == "darwin" // darwin linker cannot handle BR26 reloc with non-zero addend case "ppc64": + c.OldArch = true c.BigEndian = true + c.NeedsFpScratch = true fallthrough case "ppc64le": c.PtrSize = 8 通过OldArch变量来控制是否生成E6500处理器支持的指令。 4、和ARM的实现方案相比,OldArch是冗余的。我们可以把它删掉,利用第一步中的GOPPC环境变量来达到同样的目的。 部分代码修改如下: diff --git a/src/cmd/compile/internal/ssa/config.go b/src/cmd/compile/internal/ssa/config.go index 5576dec..d7202d6 100644 --- a/src/cmd/compile/internal/ssa/config.go +++ b/src/cmd/compile/internal/ssa/config.go @@ -37,7 +37,6 @@ type Config struct { nacl bool // GOOS=nacl use387 bool // GO386=387 SoftFloat bool // - OldArch bool // True for older versions of architecture, e.g. true for PPC64BE, false for PPC64LE NeedsFpScratch bool // No direct move between GP and FP register sets BigEndian bool // sparsePhiCutoff uint64 // Sparse phi location algorithm used above this #blocks*#variables score @@ -217,7 +216,6 @@ func NewConfig(arch string, types Types, ctxt *obj.Link, optimize bool) *Config c.hasGReg = true c.noDuffDevice = objabi.GOOS == "darwin" // darwin linker cannot handle BR26 reloc with non-zero addend case "ppc64": - c.OldArch = true c.BigEndian = true c.NeedsFpScratch = true fallthrough diff --git a/src/cmd/compile/internal/ssa/gen/PPC64.rules b/src/cmd/compile/internal/ssa/gen/PPC64.rules index 91c8dc3..eb09efd 100644 --- a/src/cmd/compile/internal/ssa/gen/PPC64.rules +++ b/src/cmd/compile/internal/ssa/gen/PPC64.rules @@ -57,15 +57,15 @@ (Div64F x y) -> (FDIV x y) // Lowering float <-> int -(Cvt32to32F x) && config.OldArch -> (FRSP (FCFID (Xi2f64 (SignExt32to64 x)))) -(Cvt32to64F x) && config.OldArch -> (FCFID (Xi2f64 (SignExt32to64 x))) -(Cvt64to32F x) && config.OldArch -> (FRSP (FCFID (Xi2f64 x))) -(Cvt64to64F x) && config.OldArch -> (FCFID (Xi2f64 x)) +(Cvt32to32F x) && objabi.GOPPC == objabi.PpcE6500 -> (FRSP (FCFID (Xi2f64 (SignExt32to64 x)))) +(Cvt32to64F x) && objabi.GOPPC == objabi.PpcE6500 -> (FCFID (Xi2f64 (SignExt32to64 x))) +(Cvt64to32F x) && objabi.GOPPC == objabi.PpcE6500 -> (FRSP (FCFID (Xi2f64 x))) +(Cvt64to64F x) && objabi.GOPPC == objabi.PpcE6500 -> (FCFID (Xi2f64 x)) -(Cvt32Fto32 x) && config.OldArch -> (Xf2i64 (FCTIWZ x)) -(Cvt32Fto64 x) && config.OldArch -> (Xf2i64 (FCTIDZ x)) -(Cvt64Fto32 x) && config.OldArch -> (Xf2i64 (FCTIWZ x)) -(Cvt64Fto64 x) && config.OldArch -> (Xf2i64 (FCTIDZ x)) +(Cvt32Fto32 x) && objabi.GOPPC == objabi.PpcE6500 -> (Xf2i64 (FCTIWZ x)) +(Cvt32Fto64 x) && objabi.GOPPC == objabi.PpcE6500 -> (Xf2i64 (FCTIDZ x)) +(Cvt64Fto32 x) && objabi.GOPPC == objabi.PpcE6500 -> (Xf2i64 (FCTIWZ x)) +(Cvt64Fto64 x) && objabi.GOPPC == objabi.PpcE6500 -> (Xf2i64 (FCTIDZ x)) (Cvt32to32F x) -> (FCFIDS (MTVSRD (SignExt32to64 x))) (Cvt32to64F x) -> (FCFID (MTVSRD (SignExt32to64 x))) @@ -749,8 +749,8 @@ // Use register moves instead of stores and loads to move int<->float values // Common with math Float64bits, Float64frombits -(MOVDload [off] {sym} ptr (FMOVDstore [off] {sym} ptr x _)) && !config.OldArch -> (MFVSRD x) -(FMOVDload [off] {sym} ptr (MOVDstore [off] {sym} ptr x _)) && !config.OldArch -> (MTVSRD x) +(MOVDload [off] {sym} ptr (FMOVDstore [off] {sym} ptr x _)) && objabi.GOPPC != objabi.PpcE6500 -> (MFVSRD x) +(FMOVDload [off] {sym} ptr (MOVDstore [off] {sym} ptr x _)) && objabi.GOPPC != objabi.PpcE6500 -> (MTVSRD x) (FMOVDstore [off] {sym} ptr (MTVSRD x) mem) -> (MOVDstore [off] {sym} ptr x mem) (MOVDstore [off] {sym} ptr (MFVSRD x) mem) -> (FMOVDstore [off] {sym} ptr x mem) 经过上述修改,我们已经可以通过GOPPC环境变量来控制编译器生成的指令了。 5、遗留问题 经过上面4步的修改,已经可以控制编译器生成的指令了。但是运行时库中的指令还没有控制住。
# ICaRuS Scoring {% hint style="success" %} _**We use this to** .... **so that we can** ...._ &#x20; {% endhint %} ICaRuS scoring is a prioritisation method built on concepts like WSJF and the GIST framework. It takes into account the impact areas that business are currently focused on and uses a mathematical calculation to arrive at a number that can be used to prioritise against other Opportunities.&#x20; ## How to Calculate <a href="#icarusscoring-howtocalculate" id="icarusscoring-howtocalculate"></a> <figure><img src="../../.gitbook/assets/image (1) (2).png" alt=""><figcaption></figcaption></figure> ## Deciding A Score <a href="#icarusscoring-decidingascore" id="icarusscoring-decidingascore"></a> ### Impact Score <a href="#icarusscoring-impactscore" id="icarusscoring-impactscore"></a> ### Confidence Score <a href="#icarusscoring-confidencescore" id="icarusscoring-confidencescore"></a> ### Risk Score <a href="#icarusscoring-riskscore" id="icarusscoring-riskscore"></a> ### Size Score <a href="#icarusscoring-sizescore" id="icarusscoring-sizescore"></a> ## Scoring Matrix <a href="#icarusscoring-scoringmatrix" id="icarusscoring-scoringmatrix"></a> Scores range between 6 and 30 with 6 being the worst and 30 the best.&#x20; <figure><img src="../../.gitbook/assets/image (27) (1) (1) (1).png" alt=""><figcaption></figcaption></figure> | Opportunity | ICaRuS Score | MoSCoW | Impact | | Confidence | Risk | Size | | | | | | -------------------- | ------------ | ------ | ------ | -- | ---------- | ---- | ---- | ------------ | ---------- | ---- | ---- | | | | | CX | EX | TX | SX | BX | Impact Score | Confidence | Risk | Size | | Opportunity - Worst | 6.0 | Might | 1 | 1 | 1 | 1 | 1 | 5 | 1 | 1 | 20 | | Opportunity - Could | 13.4 | Could | 2 | 2 | 2 | 2 | 2 | 10 | 3 | 3 | 8 | | Opportunity - Should | 19.0 | Should | 3 | 3 | 3 | 3 | 3 | 15 | 3 | 5 | 5 | | Opportunity - Best | 30.0 | Must | 4 | 4 | 4 | 4 | 4 | 20 | 5 | 5 | 1 | ## Exceptions to the Rule As in sports and in politics, there are often times when we defer to a "Captain's Call".&#x20; These are Opportunities that need to be pursued even if they are not scoring highly. These should be kept to a minimum and come with inherent risks.&#x20;
package bouquet; import static org.junit.jupiter.api.Assertions.*; import colors.Color; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import flowers.Flower; public class FlowerBouquetTest { private FlowerBouquet bouquet; private Flower rose; private Accessory ribbon; @BeforeEach public void setUp() { bouquet = new FlowerBouquet(); Color roseColor = new Color("Red"); // Припустимо, що у вас є клас Color rose = new Flower("Red Rose", roseColor, 12.0, 5, 14); ribbon = new Accessory("Gold Ribbon", 2.0); } @Test public void testAddFlower() { bouquet.addFlower(rose); assertEquals(1, bouquet.getFlowers().size()); assertEquals("Red Rose", bouquet.getFlowers().get(0).getName()); } @Test public void testAddAccessory() { bouquet.addAccessory(ribbon); assertEquals(1, bouquet.getAccessories().size()); assertEquals("Gold Ribbon", bouquet.getAccessories().get(0).getName()); } @Test public void testCalculateTotalPrice() { bouquet.addFlower(rose); bouquet.addAccessory(ribbon); assertEquals(14.0, bouquet.calculateTotalPrice(), 0.01); } @Test public void testDescribe() { bouquet.addFlower(rose); bouquet.addAccessory(ribbon); assertDoesNotThrow(() -> bouquet.describe()); } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>expRegulares</title> <script> var ejemplos = [ /* opcion por defecto */ 'selecciona', '', /* sobre texto3 que es una pagina web */ '/title="[ a-zA-Z0-9]+"/g', 'extraer patrones de una pagina web', '/title="([ a-zA-Z0-9]+)"/', 'extraer nombre del hoteles de una cadena', '/ingresó/', 'busca un texto', '/ingreso/', 'busca un texto', '/\\d+/g', 'hay texto', '/\\w+/', 'primer corchete', '/(/g', 'buscar todos los ( o )', '/[(,)]/', 'buscar todos los ; o . o ,', '', 'todos los espacios en blancos', '/\\s+/g', 'buscar cuantos puntos hay en el texto', '/[.]/g', 'lo mismo, ultima aparicion', '/lo mismo/', 'lo mismo todas las apariciones', '/lo mismo/g', 'buscar todas las cifras numéricas', '/\\d+/g', ]; //Algunas expresiones regulares que se piden en el ejercicio //eliminar el ultimo caracter del texto // //eliminar el ultimo de una palabra //string = string.replace(/\\w/$/, ""); // eliminar el primer caracter de una palabra // //- eliminar el primero del texto // //reemplazar los puntos por comas entre dos numeros //string.replace(",","."); //string.replace(/[,]/, "."); //añadir un cero a la izquierda a todos los numeros //hacer un split por una lista de caracteres function principal() { /* Ejemplos directos de uso de march y uso de /g /gm - /g es una sola cadena incluidos saltos de linea - /m hay tantas cadenas como lineas separadas por \n - /g busca en toda la cadena - /gm busca en cada linea */ console.log('hola ktal\nhola ktal'.match(/l/)); // buscar l console.log('hola ktal\nhola ktal'.match(/l/g)); // buscar todas las l console.log('hola ktal\nhola ktal'.match(/l$/)); // busa terminado en l console.log('hola ktal\nhola ktal'.match(/l$/gm)); // buscar terminado en l en cada linea console.log('hola k tal\nhola k tal'.match(/\b\w+\b/g)); // buscar palabras limpiar(); cargarFichero(document.getElementById('fileFichero').files[0]); //console.log(document.getElementById('fileFichero')); cargarEjemplos(); document.getElementById('fileFichero').addEventListener('change', leerArchivo, false); document.getElementById('textoExp').addEventListener('click', clickReg, false); document.getElementById('botonRun').addEventListener('click', run, false); document.getElementById('selector').addEventListener('change', cambiaSelector); } function limpiar() { document.getElementById('textoSalida').value = ''; //document.getElementById('textoExp').value='escribe aqui tu expresion ..'; document.getElementById('textoTitulo').value = ''; } function cambiaSelector() { var ele1 = document.getElementById('selector'); var ele2 = document.getElementById('textoExp'); var ele3 = document.getElementById('textoTitulo'); if (ele1.selectedIndex == 0) { limpiar(); } else { ele2.value = ele1.options[ele1.selectedIndex].text; ele3.value = ele1.options[ele1.selectedIndex].value; } } function clickReg() { /* if (document.getElementById('selector').selectedIndex==0){ document.getElementById('textoExp').value=''; } */ } function cargarEjemplos() { var ele2 = document.getElementById('textoExp'); ele2.value = ''; var ele = document.getElementById('selector'); var reemplazar = document.getElementById('selector-reemplazar'); //ele.addEventListener('change',cambiaSelector); for (j = 0; j < ejemplos.length; j = j + 2) { var opcion = document.createElement('option'); opcion.value = ejemplos[j + 1]; opcion.text = ejemplos[j]; ele.add(opcion); //console.log(j,opcion,ele); } for (j = 0; j < ejemplos.length; j = j + 2) { var opcion = document.createElement('option'); opcion.value = ejemplos[j + 1]; opcion.text = ejemplos[j]; ele.add(opcion); //console.log(j,opcion,ele); } } function cargarFichero(archivo) { if (!archivo) { return; } var lector = new FileReader(); // objeto para leer el fichero lector.onload = function (e) { // callback con el evento de carga del archivo var contenido = e.target.result; mostrarContenido(contenido); //leerResultado(lector.result); }; lector.readAsText(archivo); } function leerArchivo(e) { // esta funcion lee un archivo de texto local y lo deja en la variable contenido cargarFichero(e.target.files[0]); } function mostrarContenido(contenido) { // usar el dom para mostrar el contenido //console.log('ccc:',contenido); var elemento = document.getElementById('textoEntrada'); elemento.value = contenido; // refresca en pantalla elemento.innerHTML = contenido; // necesario para el dom // https://stackoverflow.com/questions/19986290/should-i-use-innerhtml-or-value-for-textarea } function leerResultado(a) { // leer la entrada y procesar var t = a.split('\n'); for (i = 0; i < t.length; i++) { var linea = t[i].split(','); for (j = 0; j < linea.length; j++) { //console.log(i,j,linea[j]); } } } function run() { // construir la expresion regular var f = document.getElementById('textoExp').value.split('/'); //console.log(f); var er = new RegExp(f[1], f[2]); //console.log('RegExp ',er); //var x=document.getElementById('textoEntrada').innerHTML.match(er); //textContent no escapa las html entities var x = document.getElementById('textoEntrada').value.match(er); //console.log(':',x,'',er,'',document.getElementById('textoEntrada').value); //var x=er.exec(document.getElementById('textoEntrada').textContent); //console.log('DDD ',document.getElementById('textoEntrada').textContent); //console.log('DDD ',er,':',x); var txt = 0; if (x != null) { txt = x.length + ' \n' + x } //console.log('XXX ',txt); document.getElementById('textoSalida').value = 'encontre ' + txt; } window.onload = principal; </script> <style> #textoTitulo { margin-top: 4px; /* separacion de la anterior linea */ } textarea, #textoTitulo { width: 614px; /* mismo que la linea anterior*/ } select, button { position: relative; /* alinear los botones verticalmente */ top: -2px; } #botonRun { position: relative; top: 0px; } </style> </head> <body> <h3>Archivo de entrada</h3> <!-- carga del archivo --> <input type="file" id="fileFichero" /> <h3>Entrada</h3> <textarea id="textoEntrada"></textarea> <h3>Expresion regular</h3> <select id='selector'></select> <input id="textoExp" type="text"></input> <button id="botonRun">match</button> <input id="textoTitulo" readonly="true" type="text"></input> <h3>Expresion regular: reemplazar:</h3> <select id='selector-reemplazar'></select> <input id="textoExp" type="text"></input> <button id="botonRun">match</button> <input id="textoTitulo" readonly="true" type="text"></input> <h3>Salida</h3> <textarea id="textoSalida"></textarea> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>touch events vs pointer events</title> <style> pre { font-size: 48pt; } #split { display: flex; width: 100%; user-select: none; --webkit-user-select: none; /* FUCK YOU SAFARI! It's 2023! */ } #left, #right { flex: 1 1 50%; height: 400px; min-width: 0; position: relative; overflow: hidden; } #left { background: yellow; } #right { background: pink; } #touch, #pointer { position: absolute; display: flex; justify-content: center; align-items: center; width: 60px; height: 60px; } #touch { background-color: teal; color: white; } #pointer { background-color: purple; color: white; } </style> </head> <body> <pre> some lines to take space </pre> <button type="button">click</button> <div id="split"> <div id="left"> <div id="touch" style="left: 50px; top: 50px;"><div>Touch</div></div> </div> <div id="right"> <div id="pointer" style="left: 50px; top: 50px;"><div>Pointer</div></div> </div> </div> <pre> some lines to take lots and lots and lots of space so the page will scroll </pre> </body> <script> 'use strict'; const px = v => `${v}px`; const clamp = (v, min, max) => Math.min(max, Math.max(min, v)); console.log('init'); { const touchElem = document.querySelector('#touch'); let elemStartX; let elemStartY; let mouseStartX; let mouseStartY; function onTouchMove(e) { e.preventDefault(); console.log('touchMove', e.touches[0].clientX); const deltaX = e.touches[0].clientX - mouseStartX; const deltaY = e.touches[0].clientY - mouseStartY; touchElem.style.left = px(clamp(elemStartX + deltaX, 0, touchElem.parentElement.clientWidth - touchElem.clientWidth)); touchElem.style.top = px(clamp(elemStartY + deltaY, 0, touchElem.parentElement.clientHeight - touchElem.clientHeight)); } function onTouchEnd() { console.log('touchEnd'); window.removeEventListener('touchmove', onTouchMove); window.removeEventListener('touchend', onTouchEnd); } function onTouchStart(e) { e.preventDefault(); console.log('touchStart'); mouseStartX = e.touches[0].clientX; mouseStartY = e.touches[0].clientY; elemStartX = parseInt(touchElem.style.left); elemStartY = parseInt(touchElem.style.top); window.addEventListener('touchmove', onTouchMove, {passive: false}); window.addEventListener('touchend', onTouchEnd); } touchElem.addEventListener('touchstart', onTouchStart, {passive: false}); } { const pointerElem = document.querySelector('#pointer'); let elemStartX; let elemStartY; let mouseStartX; let mouseStartY; function onPointerMove(e) { e.preventDefault(); console.log('pointerMove', e.clientX); const deltaX = e.clientX - mouseStartX; const deltaY = e.clientY - mouseStartY; pointerElem.style.left = px(clamp(elemStartX + deltaX, 0, pointerElem.parentElement.clientWidth - pointerElem.clientWidth)); pointerElem.style.top = px(clamp(elemStartY + deltaY, 0, pointerElem.parentElement.clientHeight - pointerElem.clientHeight)); } function onPointerUp() { console.log('pointerUp'); window.removeEventListener('pointermove', onPointerMove); window.removeEventListener('pointerup', onPointerUp); } function onPointerDown(e) { e.preventDefault(); console.log('pointerDown'); mouseStartX = e.clientX; mouseStartY = e.clientY; elemStartX = parseInt(pointerElem.style.left); elemStartY = parseInt(pointerElem.style.top); window.addEventListener('pointermove', onPointerMove, {passive: false}); window.addEventListener('pointerup', onPointerUp); } pointerElem.addEventListener('pointerdown', onPointerDown, {passive: false}); } console.log('end'); </script> </html>
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ProductComponent } from './product/product/product.component'; import { ProductDetailComponent } from './product-detail/product-detail/product-detail.component'; import { ProductOverviewComponent } from './product-overview/product-overview.component'; import { ProductSpecComponent } from './product-spec/product-spec.component'; const routes: Routes = [ { path: "products",component:ProductComponent, children: [ {path:"detail/:id", component:ProductDetailComponent ,children:[ {path:"",redirectTo:"overview", pathMatch:"full"}, {path:"overview",component:ProductOverviewComponent}, {path: "spec", component: ProductSpecComponent} ]} ] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
import "./Skills.scss"; import { useState, useEffect } from "react"; import { motion } from "framer-motion"; import { client, urlFor } from "../../client"; import { AppWrap, MotionWrap } from "../../wrapper"; import { Tooltip } from "react-tooltip"; import React from "react"; const Skills = () => { const [skills, setSkills] = useState([]); const [experience, setExperience] = useState([]); useEffect(() => { client.fetch('*[_type == "skills"]').then((data) => setSkills(data)); client .fetch('*[_type == "experiences"]') .then((data) => setExperience(data)); }, []); return ( <> <h2 className="head-text"> Skills <span>&</span> Experience </h2> <div className="app__skills-container"> <motion.div className="app__skills-list"> {skills.map((skill, index) => ( <motion.div whileInView={{ opacity: [0, 1] }} transition={{ duration: 0.5 }} className="app__skills-item app__flex" key={`skill-${skill.name + index}`} > <div className="app__flex" style={{ backgroundColor: `${skill.bgColor}` }} > <img src={urlFor(skill.icon)} alt={skill.name} /> </div> <p className="p-text">{skill.name}</p> </motion.div> ))} </motion.div> <motion.div className="app__skills-exp"> {experience.map((exp, index) => ( <motion.div className="app__skills-exp-item" key={`${exp.year + index}`} > <div className="app__skills-exp-year"> <p className="bold-text">{exp.year}</p> </div> <motion.div className="app__skills-exp-works"> {exp.works.map((work, index) => ( <div key={`${work.name + index}`}> <motion.div className="app__skills-exp-work" whileInView={{ opacity: [0, 1] }} transition={{ duration: 0.5 }} data-tooltip-id={work.name} data-tooltip-content={work.desc} > <h4 className="bold-text">{work.name}</h4> <p className="p-text">{work.company}</p> </motion.div> <Tooltip id={work.name} /> </div> ))} </motion.div> </motion.div> ))} </motion.div> </div> </> ); }; export default AppWrap( MotionWrap(Skills, "app__skills"), "skills", "app__primarybg" );
import { EditFilled, UserOutlined } from '@ant-design/icons'; import { Avatar, Card, Space, Tabs, Typography, Table, Flex, Form, Input, Switch, Skeleton, Button, Tooltip, Modal } from 'antd'; import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { getProfile } from '../actions/profile'; import useAuth from '../hooks/useAuth'; import { MdEmail, MdPassword } from 'react-icons/md'; import { RiLeafLine } from 'react-icons/ri'; import EditProfile from '../components/EditProfile'; const Profile = () => { const dispatch = useDispatch(); const { loading, success, error, user } = useSelector((state) => state.userProfile); const userInfo = useAuth(); const userId = userInfo.UserInfo.id; console.log(userId); const [form] = Form.useForm(); const [isModalVisible, setIsModalVisible] = useState(false); useEffect(() => { if (userId) { dispatch(getProfile(userId)); } }, [dispatch, userId]); useEffect(() => { if (user) { form.setFieldsValue({ username: user.username, email: user.email, password: user.password, role: user.role, active: user.active, bio: user.profile?.bio || 'N/A' }); } }, [user, form]); if (loading) return <Skeleton active />; if (error) return <div>Error: {error}</div>; const profileData = user || { username: 'N/A', email: 'N/A', role: 'N/A', active: 'N/A', profile: { bio: 'N/A', wallet: 0 } }; const walletData = profileData.profile ? [ { key: '1', title: 'Balance', value: `£${profileData.profile.wallet}` }, { key: '2', title: 'Available Balance', value: '£0.00' }, { key: '3', title: 'Withdrawal Limit', value: '£0.00' }, { key: '4', title: 'Withdrawal Fee', value: '£0.00' }, { key: '5', title: 'Withdrawal Status', value: 'Active' } ] : []; const columns = [ { title: 'Title', dataIndex: 'title', key: 'title', align: 'left' }, { title: 'Value', dataIndex: 'value', key: 'value' } ]; const showModal = () => { setIsModalVisible(true); }; const handleCancel = () => { setIsModalVisible(false); }; return ( <div> <Typography.Title level={2}>Profile</Typography.Title> <div className='d-block d-md-flex gap-3 ' > <Card className='mb-3 px-5 py-2' align="center" style={{ borderRadius: '10px', height: '200px' }}> <div > <Avatar icon={<UserOutlined />} size={100} /> <div className="d-block"> <p>{profileData.email}</p> <p className='text-muted'>{profileData.role}</p> </div> </div> </Card> <Card className=' w-100 w-md-50' > <div className="d-flex align-items-center justify-content-end px-3"> <Button type='ghost' onClick={showModal}> <Tooltip title="Edit Profile"> <EditFilled style={{ fontSize: '20px', color: 'green' }} /> </Tooltip> </Button> </div> <Tabs defaultActiveKey="1" className='w-100 col-12 '> <Tabs.TabPane tab="Profile" key="1"> <Form form={form} layout="vertical"> <Form.Item label="Username" name="username" className="w-100"> <Input size="large" prefix={<UserOutlined />} placeholder="Enter your username" readOnly /> </Form.Item> <Form.Item label="Email" name="email" className="w-100"> <Input size="large" type="email" prefix={<MdEmail style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Enter your email" readOnly /> </Form.Item> <Form.Item label="Role" name="role" className="w-100"> <Input size="large" prefix={<RiLeafLine style={{ color: 'green', fontSize: '20px' }} />} placeholder="Enter your role" readOnly /> </Form.Item> <Form.Item label="Active" name="active" valuePropName="checked" className="w-100"> <Switch checkedChildren="Active" unCheckedChildren="Inactive" disabled checked={profileData.active} style={{ backgroundColor: profileData.active ? 'green' : undefined }} /> </Form.Item> <Form.Item label="Bio" name="bio" className="w-100"> <Input.TextArea size="large" placeholder="Enter your bio" readOnly /> </Form.Item> </Form> </Tabs.TabPane> <Tabs.TabPane tab="Transactions" key="3"> <Typography.Title level={5}>E-Wallet</Typography.Title> <Table dataSource={walletData} columns={columns} pagination={false} className='w-100' /> </Tabs.TabPane> </Tabs> </Card> </div> <Modal title="Edit Profile" visible={isModalVisible} onCancel={handleCancel} width={800} bodyStyle={{ padding: 0, height: '80vh', overflow: 'auto' }} footer={null} > <EditProfile user={user} /> </Modal> </div> ); }; export default Profile;
/* 695. Max Area of Island */ function maxAreaOfIsland(grid: number[][]): number { // Empty grid if (grid.length === 0 && grid[0].length === 0) return 0; const m = grid.length, n = grid[0].length; let maxArea = 0; let islandCounter = 0; const dfs = (m: number, n: number, i: number, j: number) => { if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1) return; grid[i][j] = -1; // Marked as visited islandCounter++; dfs(m, n, i + 1, j); dfs(m, n, i - 1, j); dfs(m, n, i, j + 1); dfs(m, n, i, j - 1); } for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { if (grid[i][j] === 1) { islandCounter = 0; dfs(m, n, i, j); maxArea = Math.max(islandCounter,maxArea); } } } return maxArea; };
const express = require("express"); const cors = require("cors"); const mysql = require("mysql"); const app = express(); app.use(express.json()); app.use(cors()); // Connect to DB const connection = mysql.createConnection({ host: "localhost", user: "root", password: "", database: "aisugaming", }); connection.connect((error) => { if (error) { console.log("Error connecting to database = ", error); return; } console.log("Database connected successfully!"); }); // Import route files const user_routes = require("./routes/user_routes"); const game_routes = require("./routes/game_routes"); const content_routes = require("./routes/content_routes"); const character_routes = require("./routes/character_routes"); const star_routes = require("./routes/star_routes"); const element_routes = require("./routes/element_routes"); const path_routes = require("./routes/path_routes"); const basic_routes = require("./routes/basic_routes"); const skill_routes = require("./routes/skill_routes"); const ultimate_routes = require("./routes/ultimate_routes"); const talent_routes = require("./routes/talent_routes"); const technique_routes = require("./routes/technique_routes"); // Use routes app.use(user_routes); app.use(game_routes); app.use(content_routes); app.use(character_routes); app.use(star_routes); app.use(element_routes); app.use(path_routes); app.use(basic_routes); app.use(skill_routes); app.use(ultimate_routes); app.use(talent_routes); app.use(technique_routes); app.listen(3000, () => console.log("Server is running on port 3000"));
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../screens/product_detail_screen.dart'; import '../providers/product.dart'; import '../providers/cart.dart'; import '../providers/auth.dart'; class ProductsItem extends StatelessWidget { // final String id; // final String title; // final String imageUrl; const ProductsItem({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final product = Provider.of<Product>(context, listen: false); final cart = Provider.of<Cart>(context, listen: false); final authData = Provider.of<Auth>(context, listen: false); return ClipRRect( borderRadius: BorderRadius.circular(15), child: GridTile( footer: GridTileBar( backgroundColor: Colors.black54, leading: Consumer<Product>( builder: (ctx, product, child) => IconButton( icon: Icon( product.isFavorite ? Icons.favorite : Icons.favorite_border, color: Theme.of(context).colorScheme.secondary, ), onPressed: () { product.toggleFavoriteStatus(authData.token, authData.userId); }, ), ), title: Text( product.title, textAlign: TextAlign.center, ), trailing: IconButton( icon: Icon( Icons.shopping_cart, color: Theme.of(context).colorScheme.secondary, ), onPressed: () { cart.addItem( product.id, product.price, product.title, ); ScaffoldMessenger.of(context).hideCurrentSnackBar(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( duration: const Duration(seconds: 2), content: const Text( 'Item added to the cart!', ), action: SnackBarAction( label: 'Undo', onPressed: () { cart.removeSingleItem(product.id); }), ), ); }, ), ), child: GestureDetector( onTap: () { Navigator.of(context).pushNamed( ProductDetailScreen.routeName, arguments: product.id, ); }, child: Image.network( product.imageUrl, fit: BoxFit.cover, ), ), ), ); } }
package io.github.lawseff.aoc2023.substring import io.github.lawseff.aoc2023.asInput import org.junit.jupiter.api.Test import kotlin.test.assertEquals class FirstLastDigitProblemSolverTest { private val solver = FirstLastDigitProblemSolver() @Test fun `should sum numbers, consisting of first and last digit`() { val input = """ 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet """.asInput() val sum = solver.sumNumbersFromFirstLastDigits(input) assertEquals(142, sum) } @Test fun `should sum numbers, consisting of first and last digit or digit as word`() { val input = """ two1nine eightwothree abcone2threexyz xtwone3four 4nineeightseven2 zoneight234 7pqrstsixteen """.asInput() val sum = solver.sumNumbersFromFirstLastAlphaDigits(input) assertEquals(281, sum) } }
import React, {useState, useEffect} from 'react' import Swal from 'sweetalert2'; import MealService from '../../services/MealService' import { Modal, Button } from 'react-bootstrap' import { Link, useNavigate, useParams } from 'react-router-dom'; import {editItem, deleteItem, deleteAllItems} from '../../store-redux/cart/cartSlice' import { useDispatch, useSelector } from 'react-redux'; import EditItemQuantityComponent from './EditItemQuantityComponent'; import InsertDetailsNotLoggedComponent from './InsertDetailsNotLoggedComponent'; import './CartComponent.css'; const CartComponent = () => { const dispatch = useDispatch(); const navigate = useNavigate(); const [showEdit, setShowEdit] = useState(false); const [showInsertDetails, setShowInsertDetails] = useState(false); const [id, setId] = useState(0); const [item, setItem] = useState(null); const [itemQuantity, setItemQuantity] = useState(1); const [address, setAddress] = useState(''); const [phoneNumber, setPhoneNumber] = useState(''); var finalPriceVar; const [finalPrice, setFinalPrice] = useState(0); const itemsFromCart = useSelector((state) => state.cart); const itemsFromCartFinalOrder = { itemsFromCart, address, phoneNumber, finalPrice, setAddress, setPhoneNumber }; let itemsFromCartData; //ako nije ulogovan mora da unese adresu i br telefona const itemObjToStore = { item, itemQuantity} useEffect(() => { console.log("itemsfromcart" + JSON.stringify(itemsFromCart)); }, []) const handleShowEdit = (itemFromCart) => { setShowEdit(true); setId(null); //mora ovako da se setuje, kada se vrsi izmena, nakon toga zapamti id od starog pa radi izmenu setItem(itemFromCart); setItemQuantity(itemFromCart.quantity) }; const handleCloseEdit = () => { setShowEdit(false); setItem(null) } const alertAreYouSureDelete = (id) =>{ Swal.fire({ title: 'Are you sure?', text: "If you click yes, items will be deleted!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.isConfirmed) { dispatch(deleteItem(id)); Swal.fire( 'Deleted!', 'Item has been deleted!', 'success' ) } }) } const submitFinalOrder = () =>{ //moze i bez ove provere za token jer svakako ova metoda se poziva samo nakon unosenja adrese i broja telefona u modalu kada korisnik nije ulogovan if((localStorage.token === null || localStorage.token === undefined) && (address.trim() === "" || phoneNumber.trim() === "")){ alertInvalidInput("Invalid input, please insert address and phone number"); } else if((localStorage.token === null || localStorage.token === undefined) && !isValidNumber(phoneNumber)){ alertInvalidInput("Invalid phone number or it has less than 5 digits"); } else{ alertAreYouSureFinalOrder(); } } const alertInvalidInput = (message) =>{ Swal.fire({ icon: 'error', title: 'Oops...', text: message, }) } const isValidNumber = (input) => { // ^\d{5,}$: Uses a regular expression to ensure that the input consists of at least 5 digits. // Here's a breakdown: // ^: Asserts the start of the string. // \d{5,}: Matches at least 5 digits (\d is a shorthand for a digit, and {5,} means at least 5 occurrences). // $: Asserts the end of the string. if(isNaN(input) || /^\d{5,}$/.test(input) === false){ return false; } else{ return true; } } const checkIfLoggedInBeforeSubmit = () =>{ if(localStorage.token === null || localStorage.token === undefined){ handleShowInsertDetails(); } else{ alertAreYouSureFinalOrder(); } } const handleShowInsertDetails = () =>{ sumFinalPrice(); setFinalPrice(finalPriceVar); setShowInsertDetails(true); } const handleCloseInsertDetails = () =>{ setShowInsertDetails(false); setAddress(''); setPhoneNumber(''); } const alertAreYouSureFinalOrder = () =>{ sumFinalPrice(); setFinalPrice(finalPriceVar); let textStr; if(localStorage.token === null || localStorage.token === undefined){ textStr = "Final price is: "+ finalPriceVar.toFixed(2) + " RSD! If you click yes, you will make final order!"; itemsFromCartData = { itemsFromCart, address, phoneNumber, finalPrice: finalPriceVar}; } else{ textStr = "Final price is: "+ finalPriceVar.toFixed(2) + " RSD (10% OFF)! If you click yes, you will make final order!"; itemsFromCartData = { itemsFromCart, finalPrice: finalPriceVar}; } Swal.fire({ title: 'Are you sure?', text: textStr, icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, make it!' }).then((result) => { if (result.isConfirmed) { sendFinalOrderAndHandleRepsonseFromServer(itemsFromCartData); } else{ finalPriceVar = 0; } }) } const sendFinalOrderAndHandleRepsonseFromServer = (finalOrderDetails) =>{ MealService.sendItemsForFinalOrder(finalOrderDetails).then((response) =>{ const responseFromServer = response.data; //ako je response razlicit od 0, znaci da je uspesno upisan final order i prosledjen id, po defaultu je 0 if(responseFromServer != 0){ dispatch(deleteAllItems()); // bude undefined u stvari, null == undefined ce biti true, null === undefined je false. mogu i proveriti samo sa == null if(localStorage.token === null || localStorage.token === undefined){ handleCloseInsertDetails(); alertFinalOrderStringCheckInfo(responseFromServer); } else{ alertSuccess("Successfully ordered items!"); setTimeout(() => navigate("/my-active-final-orders"), 1500); } } else{ alertInvalidInput("Failed to make final order! Try again!"); } }) } const sumFinalPrice = () =>{ finalPriceVar = 0; if(localStorage.token == null || localStorage.token == ''){ for(let i=0; i<itemsFromCart.length; i++){ console.log(itemsFromCart[i].mealPrice); finalPriceVar += itemsFromCart[i].mealPrice*itemsFromCart[i].quantity; } } else{ for(let i=0; i<itemsFromCart.length; i++){ finalPriceVar += (itemsFromCart[i].mealPrice)*0.9*itemsFromCart[i].quantity; } } } const editItemQuantity = () =>{ dispatch(editItem(itemObjToStore)); handleCloseEdit(); alertSuccess("Successfully edited item quantity!"); } const alertSuccess = (message) =>{ Swal.fire({ position: 'top', icon: 'success', title: message, showConfirmButton: false, timer: 1500 }); } const alertFinalOrderStringCheckInfo = (finalOrderId) =>{ let linkStr = "/final-order/"+finalOrderId; let textStr = "localhost:3000/final-order/"+finalOrderId; Swal.fire({ title: 'Successfully ordered items! You can check status opening this link', icon: 'success', html: `<a href=${linkStr}>${textStr}</a>`, showCloseButton: true, focusConfirm: false, confirmButtonText: '<i class="fa fa-thumbs-up"></i> Okay!', confirmButtonAriaLabel: 'Thumbs up, great!', }) } return ( <> <div className='cart-main-container'> {itemsFromCart.length !== 0 ? <div className='cart-title'> Items from cart <svg className='cart-icon-svg-title' xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 576 512"><path d="M0 24C0 10.7 10.7 0 24 0H69.5c22 0 41.5 12.8 50.6 32h411c26.3 0 45.5 25 38.6 50.4l-41 152.3c-8.5 31.4-37 53.3-69.5 53.3H170.7l5.4 28.5c2.2 11.3 12.1 19.5 23.6 19.5H488c13.3 0 24 10.7 24 24s-10.7 24-24 24H199.7c-34.6 0-64.3-24.6-70.7-58.5L77.4 54.5c-.7-3.8-4-6.5-7.9-6.5H24C10.7 48 0 37.3 0 24zM128 464a48 48 0 1 1 96 0 48 48 0 1 1 -96 0zm336-48a48 48 0 1 1 0 96 48 48 0 1 1 0-96z"/></svg> </div> : <div className='cart-title'>Cart is empty</div> } {itemsFromCart.length !== 0 && <div className='cart-container'> { itemsFromCart.map((itemFromCart) => { return( <div className='cart-item-container'> <div className='item-image-container'> <img className='item-meal-pic' src={"data:image/png;base64," + itemFromCart.mealImage} alt=''/> </div> <div className='item-info-container'> <div className='item-name-container'> <div className='item-name-text'> {itemFromCart.mealName} </div> <div className='item-type-text'> ({itemFromCart.mealTypeName}) </div> </div> <div className='item-description'> {itemFromCart.mealDescription} </div> <div className='item-price'> {itemFromCart.mealPrice},00 RSD </div> <div className='item-quantity'> x{itemFromCart.quantity} </div> </div> <div className='item-action-container'> <svg className='action-icon-mobile update' onClick={() =>handleShowEdit(itemFromCart)} xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512"><path d="M471.6 21.7c-21.9-21.9-57.3-21.9-79.2 0L362.3 51.7l97.9 97.9 30.1-30.1c21.9-21.9 21.9-57.3 0-79.2L471.6 21.7zm-299.2 220c-6.1 6.1-10.8 13.6-13.5 21.9l-29.6 88.8c-2.9 8.6-.6 18.1 5.8 24.6s15.9 8.7 24.6 5.8l88.8-29.6c8.2-2.7 15.7-7.4 21.9-13.5L437.7 172.3 339.7 74.3 172.4 241.7zM96 64C43 64 0 107 0 160V416c0 53 43 96 96 96H352c53 0 96-43 96-96V320c0-17.7-14.3-32-32-32s-32 14.3-32 32v96c0 17.7-14.3 32-32 32H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h96c17.7 0 32-14.3 32-32s-14.3-32-32-32H96z"/></svg> <div className='button-icon-container update' onClick={() =>handleShowEdit(itemFromCart)}> <button className='btn-action update' >Update</button> <svg className='action-icon update' xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512"><path d="M471.6 21.7c-21.9-21.9-57.3-21.9-79.2 0L362.3 51.7l97.9 97.9 30.1-30.1c21.9-21.9 21.9-57.3 0-79.2L471.6 21.7zm-299.2 220c-6.1 6.1-10.8 13.6-13.5 21.9l-29.6 88.8c-2.9 8.6-.6 18.1 5.8 24.6s15.9 8.7 24.6 5.8l88.8-29.6c8.2-2.7 15.7-7.4 21.9-13.5L437.7 172.3 339.7 74.3 172.4 241.7zM96 64C43 64 0 107 0 160V416c0 53 43 96 96 96H352c53 0 96-43 96-96V320c0-17.7-14.3-32-32-32s-32 14.3-32 32v96c0 17.7-14.3 32-32 32H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h96c17.7 0 32-14.3 32-32s-14.3-32-32-32H96z"/></svg> </div> <svg className='action-icon-mobile delete' onClick={() => alertAreYouSureDelete(itemFromCart.mealId)} xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 448 512"><path d="M135.2 17.7L128 32H32C14.3 32 0 46.3 0 64S14.3 96 32 96H416c17.7 0 32-14.3 32-32s-14.3-32-32-32H320l-7.2-14.3C307.4 6.8 296.3 0 284.2 0H163.8c-12.1 0-23.2 6.8-28.6 17.7zM416 128H32L53.2 467c1.6 25.3 22.6 45 47.9 45H346.9c25.3 0 46.3-19.7 47.9-45L416 128z"/></svg> <div className='button-icon-container delete' onClick={() => alertAreYouSureDelete(itemFromCart.mealId)}> <button className='btn-action delete' >Delete</button> <svg className='action-icon delete' xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 448 512"><path d="M135.2 17.7L128 32H32C14.3 32 0 46.3 0 64S14.3 96 32 96H416c17.7 0 32-14.3 32-32s-14.3-32-32-32H320l-7.2-14.3C307.4 6.8 296.3 0 284.2 0H163.8c-12.1 0-23.2 6.8-28.6 17.7zM416 128H32L53.2 467c1.6 25.3 22.6 45 47.9 45H346.9c25.3 0 46.3-19.7 47.9-45L416 128z"/></svg> </div> </div> </div> ) }) } {itemsFromCart.length !== 0 && <button className="btn-send-final-order" onClick={() => checkIfLoggedInBeforeSubmit()}> Send final order <svg className='icon-send-final-order' xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512"><path d="M498.1 5.6c10.1 7 15.4 19.1 13.5 31.2l-64 416c-1.5 9.7-7.4 18.2-16 23s-18.9 5.4-28 1.6L284 427.7l-68.5 74.1c-8.9 9.7-22.9 12.9-35.2 8.1S160 493.2 160 480V396.4c0-4 1.5-7.8 4.2-10.7L331.8 202.8c5.8-6.3 5.6-16-.4-22s-15.7-6.4-22-.7L106 360.8 17.7 316.6C7.1 311.3 .3 300.7 0 288.9s5.9-22.8 16.1-28.7l448-256c10.7-6.1 23.9-5.5 34 1.4z"/></svg> </button>} </div>} </div> <Modal show={showEdit} onHide={handleCloseEdit} dialogClassName="modalCustomEdit" className="d-flex align-items-center justify-content-center"> <Modal.Header closeButton> <Modal.Title>Edit quantity</Modal.Title> </Modal.Header> <Modal.Body> <EditItemQuantityComponent itemFromCart={item} itemQuantity={itemQuantity} setItemQuantity={setItemQuantity} /> </Modal.Body> <Modal.Footer> <Button variant="primary" onClick={()=>editItemQuantity()}>Save changes</Button> <Button variant="secondary" onClick={handleCloseEdit}>Close</Button> </Modal.Footer> </Modal> <Modal show={showInsertDetails} onHide={handleCloseInsertDetails} dialogClassName="modalCustomInsertDetails" className="d-flex align-items-center justify-content-center"> <Modal.Header closeButton> <Modal.Title>Insert neccessary details</Modal.Title> </Modal.Header> <Modal.Body> <InsertDetailsNotLoggedComponent details={itemsFromCartFinalOrder} /> </Modal.Body> <Modal.Footer> <Button variant="primary" onClick={() => submitFinalOrder()}>Confirm final order</Button> <Button variant="secondary" onClick={handleCloseInsertDetails}>Close</Button> </Modal.Footer> </Modal> </> ) } export default CartComponent
using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Threading.Tasks; using Aula7.Api.Models; using Aula7.Api.Test.Setup; using AutoFixture; using FluentAssertions; using Newtonsoft.Json; using Xunit; namespace Aula7.Api.Test.IntegrationTest; public class GenericControllerIntegrationTest : IClassFixture<GenericFactory> { private readonly GenericFactory _genericFactory; public GenericControllerIntegrationTest(GenericFactory genericFactory) { _genericFactory = genericFactory; } [Fact] public async Task Try_CreateUser() { #region Arrange var client = _genericFactory.CreateClient(); var repository = _genericFactory.TestRepository; var user = new User() { Id = 1, Name = "Jonatas" }; var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); #endregion #region Act var response = await client.PostAsync("api/Generic/SaveUser", content); var statusCode = response.StatusCode; var userCreated = await response.Content.ReadFromJsonAsync<User>(); var userRepository = repository.GetById(1); #endregion #region Assert statusCode.Should().Be(HttpStatusCode.OK); userCreated?.Should().NotBeNull(); userCreated.Should().BeEquivalentTo(user); userRepository.Should().NotBeNull(); userRepository.Should().BeEquivalentTo(user); #endregion } }
package com.kenshine.chatnew.server; import com.kenshine.chatnew.protocol.MessageCodecSharable; import com.kenshine.chatnew.protocol.ProcotolFrameDecoder; import com.kenshine.chatnew.server.handler.*; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.handler.timeout.IdleStateHandler; import lombok.extern.slf4j.Slf4j; @Slf4j public class ChatServer { public static void main(String[] args) { NioEventLoopGroup boss = new NioEventLoopGroup(); NioEventLoopGroup worker = new NioEventLoopGroup(); LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG); MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable(); // 登录处理器 LoginRequestMessageHandler loginRequestMessageHandler = new LoginRequestMessageHandler(); // 单聊处理器 final ChatRequestMessageHandler chatRequestMessageHandler = new ChatRequestMessageHandler(); // 创建群聊 GroupCreateRequestMessageHandler groupCreateMessageHandler = new GroupCreateRequestMessageHandler(); // 处理群聊聊天 GroupChatRequestMessageHandler groupChatMessageHandler = new GroupChatRequestMessageHandler(); // 处理加入群聊 GroupJoinMessageHandler groupJoinMessageHandler = new GroupJoinMessageHandler(); // 处理退出群聊 GroupQuitMessageHandler groupQuitMessageHandler = new GroupQuitMessageHandler(); // 处理查看群成员 GroupMembersMessageHandler groupMembersMessageHandler = new GroupMembersMessageHandler(); // 退出 QuitHandler quitHandler = new QuitHandler(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.group(boss, worker); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //编解码器 ch.pipeline().addLast(new ProcotolFrameDecoder()); ch.pipeline().addLast(LOGGING_HANDLER); ch.pipeline().addLast(MESSAGE_CODEC); //连接假死处理 5s内未读到数据,会触发READ_IDLE事件 ch.pipeline().addLast(new IdleStateHandler(5, 0, 0)); // 添加双向处理器,负责处理READER_IDLE事件 ch.pipeline().addLast(new ChannelDuplexHandler() { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // 获得事件 IdleStateEvent event = (IdleStateEvent) evt; // 判断是否读事件 相等则触发读空闲事件 if (event.state() == IdleState.READER_IDLE) { log.debug("已经5S没有读到数据了,连接断开"); // 断开连接 ctx.channel().close(); } } }); ch.pipeline().addLast(loginRequestMessageHandler); //添加入站处理器 处理登录消息 ch.pipeline().addLast(chatRequestMessageHandler); //单聊处理器 ch.pipeline().addLast(groupCreateMessageHandler); //创建群处理器 ch.pipeline().addLast(groupChatMessageHandler); //群聊处理 ch.pipeline().addLast(groupJoinMessageHandler); //加群处理 ch.pipeline().addLast(groupQuitMessageHandler); //退群处理 ch.pipeline().addLast(groupMembersMessageHandler); //查看群成员 ch.pipeline().addLast(quitHandler); //退出群聊 } }); Channel channel = serverBootstrap.bind(8080).sync().channel(); channel.closeFuture().sync(); } catch (InterruptedException e) { log.error("server error", e); } finally { boss.shutdownGracefully(); worker.shutdownGracefully(); } } }
<?php namespace App\Jobs; use GuzzleHttp\Client; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class SendMessageToSlack implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; /** * Create a new job instance. * * @return void */ public $payload; public $type; public function __construct($payload, $type = 'error') { $this->payload = $payload; $this->type = $type; } /** * Execute the job. * * @return void */ public function handle() { try { $url_slack = config('slack.slack_error_url'); if ($this->type == 'log') { $url_slack = config('slack.slack_log_url'); } if (empty($url_slack)) { Log::error("Not found url slack in job SendMessageToSlack"); return; } if (is_array($this->payload) || is_object($this->payload)) { $this->payload = json_encode($this->payload); } if (empty($this->payload)) { return; } $client = new Client(); $data = [ "type" => "mrkdwn", 'text' => $this->payload ]; $res = $client->post($url_slack, [ 'json' => $data ]); if ($res->getStatusCode() !== 200) { throw new \Exception($res->getReasonPhrase()); } } catch (\Exception $e) { Log::error("Send message slack error: {$e->getMessage()}"); print_r($e->getMessage()); } } }
package mindswap.academy.supplier.model; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.*; import mindswap.academy.address.model.Address; import mindswap.academy.stock.model.StockRequest; import java.util.List; @Entity (name = "Supplier" ) public class Supplier { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private int nif; private int phoneNumber; @OneToMany(mappedBy = "supplier") private List<Address> addresses; @ManyToMany private List<SupplierCategory> categories; @OneToMany @JsonIgnore private List<StockRequest> stockRequests; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNif() { return nif; } public void setNif(int nif) { this.nif = nif; } public int getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(int phoneNumber) { this.phoneNumber = phoneNumber; } public List<StockRequest> getStockRequests() { return stockRequests; } public void setStockRequests(List<StockRequest> stockRequests) { this.stockRequests = stockRequests; } public List<SupplierCategory> getCategories() { return categories; } public void setCategories(List<SupplierCategory> categories) { this.categories = categories; } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } public static SupplierBuilder builder() { return new SupplierBuilder(); } public static final class SupplierBuilder{ private final Supplier supplier; SupplierBuilder() { supplier = new Supplier(); } public SupplierBuilder withId(Long id){ supplier.setId(id); return this; } public SupplierBuilder withName(String name){ supplier.setName(name); return this; } public SupplierBuilder withNif(int nif){ supplier.setNif(nif); return this; } public SupplierBuilder withPhoneNumber(int phoneNumber){ supplier.setPhoneNumber(phoneNumber); return this; } public SupplierBuilder withAddress(List<Address> addresses){ supplier.setAddresses(addresses); return this; } public SupplierBuilder withSupplierCategory(List<SupplierCategory> supplierCategory){ supplier.setCategories(supplierCategory); return this; } public SupplierBuilder withStockRequest(List<StockRequest> stockRequests){ supplier.setStockRequests(stockRequests); return this; } public Supplier build(){ return supplier; } } }
package com.common.enumerate; public enum DoorCode { Door1("门牙塔1", 1), Door2("门牙塔2", 2); // 成员变量 private String name; private int index; // 构造方法 private DoorCode(String name, int index) { this.name = name; this.index = index; } public static String getName(int index) { for (DoorCode dt : DoorCode.values()) { if (dt.getIndex() == index) { return dt.name; } } return null; } public static DoorCode getType(int index) { for (DoorCode dt : DoorCode.values()) { if (dt.getIndex() == index) { return dt; } } return null; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } }
<!DOCTYPE html> <html lang="en" xmlns:th ="http://www.thymeleaf.org"> <head th:replace="fragments/head :: head"> <body class="sub_page"> <div class="hero_area"> <header th:replace="fragments/header :: header"> </div> <!-- about section --> <section class="about_section layout_padding"> <div class="container "> <div class="post"> <h3> <a th:text="${post.title}">Title</a></h3> <h5 th:text="'Author: ' + ${post.account.firstName} + ' | Created at: ' + ${#temporals.format(post.createdAt, 'yyyy-MM-dd HH:mm')} + ' | Updated on: ' + ${#temporals.format(post.updatedOn, 'yyyy-MM-dd HH:mm')}" ></h5> <p th:utext="${post.body}">body</p> <hr color="grey"/> <div sec:authorize="isAuthenticated()" th:if="${isOwner}"> <a th:href="@{'/posts/' + ${post.postId} + '/edit'}" class="btn btn-secondary btn-lg active" role="button" aria-pressed="true">Edit</a> </div> </div> </div> </section> <!-- end about section --> <footer th:replace="fragments/footer :: footer"> </body> </html>
/** * Simulation of one axis of an inverted pendulum. */ #define dp(x) std::cout << #x<<':' << x << std::endl #include <iostream> #include <signal.h> #include <fstream> #include <random> #include <cmath> #include "linux_src/DataPuffer.h" #include "linux_src/Regulator.h" #define L 0.3 #define inv_L 1 / L #define small_g 9.80665 #define CAMERA_DT 0.0333 // Time between Camera inputs [s] #define CAMERA_QUEUE_SIZE 4 // size of Camera Buffer [1] #define LIDAR_DT 0.1 // Time between Lidar inputs [s] #define LIDAR_QUEUE_SIZE 0 // size of Lidar Buffer [1] class Pencil_Sim { //maximum stepsize double dt_max; //RingBuffer als Queue verwendet RingBuffer<double> Camera_Sensor_Buffer{CAMERA_QUEUE_SIZE}; RingBuffer<double> LIDAR_Sensor_Buffer{LIDAR_QUEUE_SIZE}; Regulator* regulator; double next_lidar_time = LIDAR_DT; // time of the next Lidar data double next_camera_time = CAMERA_DT; // time of the next camera data // Which sensor will be updated in the current cicle bool update_lidar; bool update_camera; double x[4] = {0, 0, 0.1, 0}; // state double dx[4]; // derivative of the state with noise double y[2] = {0, 0}; // last recorded Measurements with measurement noise //double Q[4] = {0, 0, 0, 0}; // no process noise //double R[2] = {0, 0}; // no measurement noise double Q[4] = {1e-4, 1e-4, 1e-7, 1e-7}; // process noise (gets added to state) double R[2] = {5e-4, 5e-2}; // measurement noise (gets added to sensor measurements) std::default_random_engine random_engine[6]; // initialize noise distributions std::normal_distribution<double> normal_Q0; std::normal_distribution<double> normal_Q1; std::normal_distribution<double> normal_Q2; std::normal_distribution<double> normal_Q3; std::normal_distribution<double> normal_R0; std::normal_distribution<double> normal_R1; // 0, 1-4, 5-6 // dt,x[0-3],y[0-1] std::array<double,5> line_x; std::array<double,5> line_x_hat; std::array<double,2> line_measured_p; std::array<double,2> line_measured_theta; std::array<double,2> line_e; std::array<double,2> line_u; std::vector<std::array<double, 5>> save_vector_x; std::vector<std::array<double, 5>> save_vector_x_hat; std::vector<std::array<double, 2>> save_vector_measured_p; std::vector<std::array<double, 2>> save_vector_measured_theta; std::vector<std::array<double, 2>> save_vector_e; std::vector<std::array<double, 2>> save_vector_u; template<size_t T> void save_vector(std::vector<std::array<double,T>> save_vector, std::string filename){ std::stringstream ss; std::ofstream of; of.open(filename, std::ios::out); for (int i = 0; i < save_vector.size(); i++) { for (size_t j = 0; j < T-1; j++) { ss << save_vector.at(i)[j] << ','; } ss << save_vector.at(i)[T-1] << std::endl; } of << ss.str(); of.close(); } template<size_t T> void dump_vector_to_file(std::vector<std::array<double,T>> save_vector, std::string filename) { std::ofstream of; of.open(filename, std::ios::out | std::ios::binary); const char *ptr = (const char *)&(save_vector); int size = sizeof(save_vector); of.write(ptr, size); of.close(); } public: int iteration = 0; double simulation_time = 0; double J = 0; double time_since_last_measurement; // set standard deviation and initialize sensorBuffers and random engines Pencil_Sim(double dt_max, Regulator * regulator, int seed = 1) : normal_Q0(0, sqrt(Q[0])), normal_Q1(0, sqrt(Q[1])), normal_Q2(0, sqrt(Q[2])), normal_Q3(0, sqrt(Q[3])), normal_R0(0, sqrt(R[0])), normal_R1(0, sqrt(R[1])) { if(dt_max <= 0){ std::cerr << "please select a reasonable timeinterval :)\n"; } this->regulator = regulator; this->dt_max = dt_max; for (int i = 0; i < 6; i++) random_engine[i].seed(i + seed); } //for some reason I cant capture [this] in a lamda passed as default arguemntwhy but this works i guess... void next_measurement(double u) { //default:100hz next_measurement(u, [this](int iteration){return ((iteration%(int)(1/(this->dt_max*100)))==0);}); } bool next_state(double u, double* next_state){ dx[0] = x[1] + normal_Q0(random_engine[0]); dx[1] = u + normal_Q1(random_engine[1]); dx[2] = x[3] + normal_Q2(random_engine[2]); dx[3] = 1.5 * (small_g * sin(x[2]) + u * cos(x[2])) * inv_L + normal_Q3(random_engine[3]); x[0] += dt_max * dx[0]; x[1] += dt_max * dx[1]; x[2] += dt_max * dx[2]; x[3] += dt_max * dx[3]; if(iteration++%1000==0){ line_u[0] = simulation_time; line_u[1] = u; save_vector_u.push_back(line_u); line_x[0] = simulation_time; line_x[1] = x[0]; line_x[2] = x[1]; line_x[3] = x[2]; line_x[4] = x[3]; save_vector_x.push_back(line_x); } if(x[2] <= -M_PI) x[2] += 2*M_PI; if(x[2] > M_PI) x[2] -= 2*M_PI; next_state = x; simulation_time += dt_max; regulator->recieve_state(x); return x[2]>-0.5*M_PI&&x[2]<0.5*M_PI; } void next_measurement(double u, std::function<bool(int)> save_x_or_nah) { // set time and save which sensor recieves new values double dt; double time_after_next_step; update_camera = false; update_lidar = false; while(!(update_camera||update_lidar)){ //this variable is not set in stone for the next cycle! it might change depending on when the sensors are supposed to measure :) time_after_next_step = simulation_time + dt_max; /**calculate dt: * if there is not supposed to be a measurement in ]simulation_time;simulation_time+dt_max] * dt = dt_max * Otherwise dt is calculated such that the next measurement occurs at simulation_time + dt */ //no updates by default to make the if statement more readable update_camera = false; update_lidar = false; //check which sensor has is measuring next (could be both) if(next_camera_time == next_lidar_time){ if(next_camera_time <= time_after_next_step){ //both update. could compare to next_lidar_time as well since they are equal time_after_next_step = next_camera_time; update_camera = true; update_lidar = true; } }else if(next_camera_time < next_lidar_time){ if(next_camera_time <= time_after_next_step){//camera updates time_after_next_step = next_camera_time; update_camera = true; } }else{ if(next_lidar_time <= time_after_next_step){//lidar update time_after_next_step = next_lidar_time; update_lidar = true; } }; dt = time_after_next_step - simulation_time; // apply Euler method dx[0] = x[1] + normal_Q0(random_engine[0]); dx[1] = u + normal_Q1(random_engine[1]); dx[2] = x[3] + normal_Q2(random_engine[2]); dx[3] = 1.5 * (small_g * sin(x[2]) + u * cos(x[2])) * inv_L + normal_Q3(random_engine[3]); x[0] += dt * dx[0]; x[1] += dt * dx[1]; x[2] += dt * dx[2]; x[3] += dt * dx[3]; simulation_time = time_after_next_step; //check which sensors measure the state //kinda ugly with all that copied code might wanna do that properly... but it works i guess if (update_lidar) { //set next measurement time next_lidar_time += LIDAR_DT; //no Queue -> cant set and get anything :) if(LIDAR_QUEUE_SIZE!=0){ //retrieve oldest value if(LIDAR_Sensor_Buffer.get(y[0],LIDAR_QUEUE_SIZE-1)==-1) //if the queue is not full, no measurement should be taken update_lidar = false; else{ line_measured_p[0] = simulation_time; line_measured_p[1] = y[0]; save_vector_measured_p.push_back(line_measured_p); regulator->recieve_pos(y[0]); regulator->get_x_hat(&line_x_hat[1]); line_x_hat[0]=simulation_time; save_vector_x_hat.push_back(line_x_hat); } //write new value into buffer LIDAR_Sensor_Buffer.set(x[0] + normal_R0(random_engine[4])); } else{ y[0] = x[0] + normal_R0(random_engine[4]); line_measured_p[0] = simulation_time; line_measured_p[1] = y[0]; save_vector_measured_p.push_back(line_measured_p); regulator->recieve_pos(y[0]); regulator->get_x_hat(&line_x_hat[1]); line_x_hat[0]=simulation_time; save_vector_x_hat.push_back(line_x_hat); } } if (update_camera) { //set next measurement time next_camera_time += CAMERA_DT; if(CAMERA_QUEUE_SIZE!=0){ //retrieve oldest value if(Camera_Sensor_Buffer.get(y[1],CAMERA_QUEUE_SIZE-1)==-1) update_camera = false; else{ line_measured_theta[0] = simulation_time; line_measured_theta[1] = y[1]; save_vector_measured_theta.push_back(line_measured_theta); regulator->recieve_angle(y[1]); regulator->get_x_hat(&line_x_hat[1]); line_x_hat[0]=simulation_time; save_vector_x_hat.push_back(line_x_hat); } //write new value into buffer Camera_Sensor_Buffer.set(x[2] + normal_R1(random_engine[5])); }else { y[1] = x[2] + normal_R1(random_engine[5]); line_measured_theta[0] = simulation_time; line_measured_theta[1] = y[1]; save_vector_measured_theta.push_back(line_measured_theta); regulator->recieve_angle(y[1]); regulator->get_x_hat(&line_x_hat[1]); line_x_hat[0]=simulation_time; save_vector_x_hat.push_back(line_x_hat); } } line_x[0] = simulation_time; line_x[1] = x[0]; line_x[2] = x[1]; line_x[3] = x[2]; line_x[4] = x[3]; if(save_x_or_nah(iteration++)) save_vector_x.push_back(line_x); }//exit if measuerement was taken //square difference of x and x_hat double e = 0.0; for(int i = 1;i<5;i++) e += (line_x[i]-line_x_hat[i])*(line_x[i]-line_x_hat[i]); line_e[0] = simulation_time; line_e[1] = e; save_vector_e.push_back(line_e); J += e*(simulation_time-time_since_last_measurement); time_since_last_measurement = simulation_time; } void save(std::string filename_state, std::string filename_measurement_p, std::string filename_measurement_theta, std::string filename_state_hat, std::string filename_e) { save_vector(save_vector_x, filename_state); save_vector(save_vector_measured_p, filename_measurement_p); save_vector(save_vector_measured_theta, filename_measurement_theta); save_vector(save_vector_x_hat, filename_state_hat); save_vector(save_vector_e,filename_e); } //writes the bits into a file. data_size.csv contains information about the length void dump_to_file(std::string filename_state, std::string filename_measurement_p, std::string filename_measurement_theta, std::string filename_x_hat, std::string filename_size = "data_size.csv") { dump_vector_to_file(save_vector_x, filename_state); dump_vector_to_file(save_vector_measured_p, filename_measurement_p); dump_vector_to_file(save_vector_measured_theta, filename_measurement_theta); dump_vector_to_file(save_vector_x_hat, filename_x_hat); /** * format: * save_vector_x.size() * save_vector_x_hat.size() * save_vector_measured_p.size() * save_vector_measured_theta.size() */ std::stringstream ss; std::ofstream of; of.open(filename_size, std::ios::out); ss << save_vector_x.size() << '\n'; ss << save_vector_x_hat.size() << '\n'; ss << save_vector_measured_p.size() << '\n'; ss << save_vector_measured_theta.size() << '\n'; of << ss.str(); of.close(); } };
import { api } from "~/utils/api"; import "~/styles/globals.css"; import Head from "next/head"; import { ClerkProvider } from "@clerk/nextjs"; import type { AppProps } from "next/app"; import "../utils/i18n"; import { viVN, enUS } from "@clerk/localizations"; import { useRouter } from "next/router"; import TopNav from "~/components/NavBar/TopNav"; import Footer from "~/components/Footer/Footer"; function MyApp({ Component, pageProps }: AppProps) { const router = useRouter(); const { locale } = router; // Choose the appropriate Clerk localization based on the current locale const clerkLocalization = locale === "vi" ? viVN : enUS; return ( <ClerkProvider localization={clerkLocalization} {...pageProps}> <Head> <title>Skillspoke</title> <meta name="description" content="" /> <link rel="icon" href="/favicon.ico" /> </Head> <div className="flex flex-col "> <TopNav /> <div className="mx-auto w-screen"> <div className="flex-grow"> <Component {...pageProps} /> </div> </div> <Footer /> </div> </ClerkProvider> ); } export default api.withTRPC(MyApp);
import React from 'react'; import Highlight, { defaultProps } from 'prism-react-renderer'; import { Element } from '@codesandbox/components'; import css from '@styled-system/css'; import { useAppState } from 'app/overmind'; import { withTheme } from 'styled-components'; import { makeTheme } from '@codesandbox/common/lib/utils/makeTheme'; export const Code = withTheme(({ value, language, theme }) => { const state = useAppState(); const defaultLanguage = () => { const template = state.editor.currentSandbox.template; if (template === 'create-react-app') { return 'jsx'; } return 'js'; }; return value ? ( <Highlight {...defaultProps} code={value} language={language || defaultLanguage()} // @ts-ignore theme={makeTheme(theme.vscodeTheme)} > {({ className, style, tokens, getLineProps, getTokenProps }) => ( <Element as="pre" paddingX={4} paddingY={2} marginY={2} className={className} style={style} css={css({ fontSize: 3, whiteSpace: 'pre-wrap', maxHeight: 400, overflow: 'scroll', fontFamily: "'MonoLisa', menlo, monospace", '*': { wordBreak: 'break-all', }, })} > {tokens.map((line, i) => ( <Element {...getLineProps({ line, key: i })}> {line.map((token, key) => ( <Element as="span" {...getTokenProps({ token, key })} /> ))} </Element> ))} </Element> )} </Highlight> ) : null; });
import { CategoryDraft, TCategoryDraft, } from '@commercetools-test-data/category'; import { KeyReference, LocalizedString, } from '@commercetools-test-data/commons'; import { ProductTypeDraft, type TProductTypeDraft, } from '@commercetools-test-data/product-type'; import { TaxCategoryDraft, type TTaxCategoryDraft, } from '@commercetools-test-data/tax-category'; import * as ProductVariantDraft from '../../../../product-variant/product-variant-draft'; import * as ProductDraft from '../../../product-draft'; import type { TProductDraftBuilder } from '../../../types'; const standardTaxCategory = TaxCategoryDraft.presets.sampleDataGoodStore .standardTaxCategory() .build<TTaxCategoryDraft>(); const naturaRugProductTypeDraft = ProductTypeDraft.presets.sampleDataGoodStore .furnitureAndDecor() .build<TProductTypeDraft>(); const rugsDraft = CategoryDraft.presets.sampleDataGoodStore .rugs() .build<TCategoryDraft>(); const roomDecorDraft = CategoryDraft.presets.sampleDataGoodStore .roomDecor() .build<TCategoryDraft>(); const homeDecorDraft = CategoryDraft.presets.sampleDataGoodStore .homeDecor() .build<TCategoryDraft>(); const naturaRug = (): TProductDraftBuilder => ProductDraft.presets .empty() .key('natura-rug') .name( LocalizedString.presets .empty() ['en-GB']('Natura Rug') ['de-DE']('Natura Teppich') ['en-US']('Natura Rug') ) .description( LocalizedString.presets .empty() ['en-GB']( 'A round area rug made of natural fibers is a type of rug that is circular in shape and made from materials that are found in nature. Natural fibers commonly used for this type of rug include jute, sisal, seagrass, and bamboo. These rugs have a rustic and organic feel due to the use of natural materials, which can add warmth and texture to a space. The neutral tones of these fibers also make them versatile and able to complement a range of decor styles, from bohemian to coastal to farmhouse. The texture and thickness of a round area rug made of natural fibers can vary depending on the material used. For example, jute and sisal have a rougher texture and thinner pile, while seagrass and bamboo have a smoother texture and thicker pile. The construction of these rugs is often done by hand, which adds to their unique and one-of-a-kind quality. The weaving or braiding technique used to create the rug can also add visual interest to the design, such as with a herringbone or chevron pattern. A round area rug made of natural fibers can be used in a variety of spaces, from living rooms to bedrooms to dining areas. They are especially popular in bohemian and coastal decor styles, where they can add a relaxed and laid-back vibe to the space. Overall, a round area rug made of natural fibers is a stylish and eco-friendly choice for anyone looking to add texture and warmth to their home decor.' ) ['de-DE']( 'Ein runder Teppich aus Naturfasern ist ein kreisförmiger Teppich, der aus Materialien hergestellt wird, die in der Natur vorkommen. Zu den Naturfasern, die üblicherweise für diese Art von Teppichen verwendet werden, gehören Jute, Sisal, Seegras und Bambus. Durch die Verwendung natürlicher Materialien haben diese Teppiche einen rustikalen und organischen Charakter, der einem Raum Wärme und Struktur verleihen kann. Die neutralen Farbtöne dieser Fasern machen sie außerdem vielseitig einsetzbar und passen zu einer Reihe von Einrichtungsstilen, von Bohème über Küsten- bis hin zu Landhausstil. Die Textur und Dicke eines runden Teppichs aus Naturfasern kann je nach verwendetem Material variieren. Jute und Sisal haben beispielsweise eine rauere Struktur und einen dünneren Flor, während Seegras und Bambus eine glattere Textur und einen dickeren Flor haben. Die Herstellung dieser Teppiche erfolgt häufig in Handarbeit, was zu ihrer Einzigartigkeit beiträgt. Auch die Web- oder Flechttechnik, mit der der Teppich hergestellt wird, kann das Design optisch aufwerten, z. B. durch ein Fischgräten- oder Chevron-Muster. Ein runder Teppich aus Naturfasern kann in einer Vielzahl von Räumen verwendet werden, vom Wohnzimmer über das Schlafzimmer bis zum Essbereich. Besonders beliebt sind sie im Bohème- und Küsten-Stil, wo sie dem Raum eine entspannte und lockere Atmosphäre verleihen können. Insgesamt ist ein runder Teppich aus Naturfasern eine stilvolle und umweltfreundliche Wahl für alle, die ihrer Einrichtung Textur und Wärme verleihen möchten.' ) ['en-US']( 'A round area rug made of natural fibers is a type of rug that is circular in shape and made from materials that are found in nature. Natural fibers commonly used for this type of rug include jute, sisal, seagrass, and bamboo. These rugs have a rustic and organic feel due to the use of natural materials, which can add warmth and texture to a space. The neutral tones of these fibers also make them versatile and able to complement a range of decor styles, from bohemian to coastal to farmhouse. The texture and thickness of a round area rug made of natural fibers can vary depending on the material used. For example, jute and sisal have a rougher texture and thinner pile, while seagrass and bamboo have a smoother texture and thicker pile. The construction of these rugs is often done by hand, which adds to their unique and one-of-a-kind quality. The weaving or braiding technique used to create the rug can also add visual interest to the design, such as with a herringbone or chevron pattern. A round area rug made of natural fibers can be used in a variety of spaces, from living rooms to bedrooms to dining areas. They are especially popular in bohemian and coastal decor styles, where they can add a relaxed and laid-back vibe to the space. Overall, a round area rug made of natural fibers is a stylish and eco-friendly choice for anyone looking to add texture and warmth to their home decor.' ) ) .slug( LocalizedString.presets .empty() ['en-GB']('natura-rug') ['de-DE']('natura-teppich') ['en-US']('natura-rug') ) .productType( KeyReference.presets.productType().key(naturaRugProductTypeDraft.key!) ) .publish(true) .taxCategory( KeyReference.presets.taxCategory().key(standardTaxCategory.key!) ) .masterVariant( ProductVariantDraft.presets.sampleDataGoodStore.naturaRug01() ) .categories([ KeyReference.presets.category().key(rugsDraft.key!), KeyReference.presets.category().key(roomDecorDraft.key!), KeyReference.presets.category().key(homeDecorDraft.key!), ]); export default naturaRug;
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { loginUser } from '@play.app/types/Auth/loginUser'; import { Store } from '@ngxs/store'; import { Login } from '../../@store/Actions/auth.actions'; import { Router } from '@angular/router'; import { faSignIn } from '@fortawesome/free-solid-svg-icons'; import { MatDialog } from '@angular/material/dialog'; import { Subscription } from 'rxjs'; import { ForgotPasswordDialogComponent } from '../../@dialogs/auth/forgot-password-dialog/forgot-password-dialog.component'; import { TrialDialogComponent } from '../../@dialogs/trial/trial-dialog.component'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'play-app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit, OnDestroy { login_image: string; loading = false; faSignIn = faSignIn; dialog_subscription: Subscription | undefined; capsOn = false; form = new FormGroup({ email: new FormControl('', [Validators.required, Validators.email]), password: new FormControl('', [ Validators.required, Validators.minLength(6), ]), }); constructor( public store: Store, private router: Router, private dialog: MatDialog, public toastr: ToastrService ) { this.login_image = this.chooseLoginImage(); } ngOnInit(): void { //this.recaptchaService.execute(); this.store .select((state) => state.auth.token) .subscribe((token) => { if (token) { //redirect user to {base url}/user/profile this.router.navigate(['/user']).then(() => { return; }); } }); } /** * @description function to choose a random login image * @returns {string} - the random login image */ forgotPasswordDialog() { this.dialog.open(ForgotPasswordDialogComponent, { width: '400px', }); } /** * @description function to open the trial dialog */ showTrialDialog() { this.dialog.open(TrialDialogComponent, { width: '500px', }); } chooseLoginImage(): string { //get a random number between 1 and 16 const randomNumber = Math.floor(Math.random() * 16) + 1; //set the image path return `assets/Images/Login/login-${randomNumber}.webp`; } /** * @description function to login the user */ login() { try { this.loading = true; //if form is invalid show message if (this.form.invalid) { this.toastr.error(); return; } //build the login user object const loginUser: loginUser = { email: this.form.value.email || '', password: this.form.value.password || '', }; this.store.dispatch(new Login(loginUser)).subscribe({ next: () => { this.router.navigate(['user/dashboard']).then(() => { return; }); }, error: (e) => { //if response code is 400 transform to BadRequestResponse if (e.status === 400) { //show toast message this.toastr.error( 'Verify your credentials', 'Something went wrong', { timeOut: 3000, } ); this.loading = false; //clear password field this.form.controls.password.setValue(''); } else { throw e; } }, complete: () => { this.loading = false; }, }); } catch (err) { console.log(err); this.loading = false; } } ngOnDestroy(): void { if (this.dialog_subscription) { this.dialog_subscription.unsubscribe(); } } }
import { Contract } from '@algorandfoundation/tealscript'; type Contact = { name: string; phone: string }; // eslint-disable-next-line no-unused-vars class TupleInBox extends Contract { contacts = BoxMap<Address, Contact>(); me = GlobalStateKey<Contact>(); setMyContact(name: string, phone: string): void { const contact: Contact = { name: name, phone: phone }; this.me.value = contact; this.contacts(this.txn.sender).value = contact; } addContact(addr: Address, name: string, phone: string): void { const contact: Contact = { name: name, phone: phone }; this.contacts(addr).value = contact; } updateContactField(addr: Address, field: string, value: string): void { if (field === 'name') { this.contacts(addr).value.name = value; } else if (field === 'phone') { this.contacts(addr).value.phone = value; } else throw Error('invalid field'); } verifyContactName(addr: Address, name: string): void { assert(this.contacts(addr).value.name === name); } }
package dao; import model.Jogo; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Date; import java.util.ArrayList; import java.util.List; /** * Classe JogoDAO, manipula o banco de dados. * * @javadoc */ public class JogoDAO extends DAO { public JogoDAO() { super(); conectar(); } public void finalize() { close(); } /** * Método responsavel por gerar sql e inserir. * */ public boolean insert(Jogo jogo) { boolean status = false; try { String sql = "INSERT INTO jogo (nome, preco) " + "VALUES ('" + jogo.getNome() + "', " + jogo.getPreco() + ");"; System.out.println(sql); PreparedStatement st = conexao.prepareStatement(sql); st.executeUpdate(); st.close(); status = true; } catch (SQLException u) { throw new RuntimeException(u); } return status; } /** * Método responsavel por selecionar tudo de um usuario. * */ public Jogo get(int id) { Jogo jogo = null; try { Statement st = conexao.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); String sql = "SELECT * FROM jogo WHERE id="+id; ResultSet rs = st.executeQuery(sql); if(rs.next()){ jogo = new Jogo(rs.getInt("id"), rs.getString("nome"), (float)rs.getDouble("preco")); } st.close(); } catch (Exception e) { System.err.println(e.getMessage()); } return jogo; } public List<Jogo> get() { return get(""); } /** * Método responsavel por selecionar o jogo ordenado por ID. * */ public List<Jogo> getOrderByID() { return get("id"); } /** * Método responsavel por selecionar o jogo ordenado por nome. * */ public List<Jogo> getOrderBynome() { return get("nome"); } /** * Método responsavel por selecionar o jogo ordenado por preco. * */ public List<Jogo> getOrderByPreco() { return get("preco"); } private List<Jogo> get(String orderBy) { List<Jogo> jogos = new ArrayList<Jogo>(); try { Statement st = conexao.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); String sql = "SELECT * FROM jogo" + ((orderBy.trim().length() == 0) ? "" : (" ORDER BY " + orderBy)); ResultSet rs = st.executeQuery(sql); while(rs.next()) { Jogo p = new Jogo(rs.getInt("id"), rs.getString("nome"), (float)rs.getDouble("preco")); jogos.add(p); } st.close(); } catch (Exception e) { System.err.println(e.getMessage()); } return jogos; } /** * Método responsavel por atualizar um jogo. * */ public boolean update(Jogo jogo) { boolean status = false; try { String sql = "UPDATE jogo SET nome = '" + jogo.getNome() + "', " + "preco = " + jogo.getPreco() + " " + "WHERE id =" + jogo.getID(); System.out.println(sql); PreparedStatement st = conexao.prepareStatement(sql); st.executeUpdate(); st.close(); status = true; } catch (SQLException u) { throw new RuntimeException(u); } return status; } /** * Método responsavel por deletar um jogo. * */ public boolean delete(int id) { boolean status = false; try { Statement st = conexao.createStatement(); st.executeUpdate("DELETE FROM jogo WHERE id = " + id); st.close(); status = true; } catch (SQLException u) { throw new RuntimeException(u); } return status; } }
pub fn solution(input: &str) -> u32 { let mut grid = Grid::from(input); grid.tilt_north(); let mut sum = 0; let mut load = grid.tiles.len(); for tile_row in &grid.tiles { for tile in tile_row { if tile == &Tile::RoundRock { sum += load; } } load -= 1; } sum as u32 } /// /// Grid /// struct Grid { tiles: Vec<Vec<Tile>>, } impl Grid { fn tilt_north(&mut self) { for column_index in 0..self.tiles[0].len() { for row_index in 0..self.tiles.len() { let mut north_available_tile = None; for temp_row_index in (0..row_index).rev() { if &self.tiles[temp_row_index][column_index] == &Tile::Empty { north_available_tile = Some(temp_row_index); continue; } break; } if let Some(north_available_tile) = north_available_tile { if &self.tiles[row_index][column_index] == &Tile::RoundRock { self.tiles[row_index][column_index] = Tile::Empty; self.tiles[north_available_tile][column_index] = Tile::RoundRock; } }; } } } } impl From<&str> for Grid { fn from(value: &str) -> Self { let tiles = value .lines() .map(|line| { line.chars() .map(|char| match char { '.' => Tile::Empty, '#' => Tile::CubeRock, 'O' => Tile::RoundRock, _ => unreachable!(), }) .collect() }) .collect(); Self { tiles } } } impl std::fmt::Debug for Grid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for row in &self.tiles { for tile in row { let tile = match tile { Tile::Empty => '.', Tile::CubeRock => '#', Tile::RoundRock => 'O', }; write!(f, "{}", tile)?; } writeln!(f, "")?; } Ok(()) } } /// /// Tile /// #[derive(Debug, PartialEq, Eq)] enum Tile { Empty, CubeRock, RoundRock, }
const {Personaje, Pelicula}= require("../db"); const Sequelize = require('sequelize'); const buscarPersonajeNombre = async (req, res) => { try { const { name } = req.query; const dbPersonaje = await Personaje.findAll({ attributes: ['nombre', 'imagen', 'edad', 'peso', 'historia', 'peliculaAsociada'], where: Sequelize.where( Sequelize.fn('LOWER', Sequelize.col('nombre')), 'LIKE', `%${name.toLowerCase()}%` ), }); if (dbPersonaje.length === 0) { return res.status(400).send(`No hay personaje con el nombre: ${name}`); } const personajesConPesoDecimal = dbPersonaje.map(personaje => ({ ...personaje.dataValues, peso: parseFloat(personaje.peso) })); return res.status(200).json(personajesConPesoDecimal); } catch (error) { res.status(404).send(error.message); } }; const buscarPersonajeEdad = async (req, res) => { try { const { age } = req.query; const dbPersonaje = await Personaje.findAll({ attributes: ['nombre', 'imagen', 'edad', 'peso', 'historia', 'peliculaAsociada'], where: { edad: age } }); if (dbPersonaje.length === 0) { return res.status(400).send(`No hay personajes con la edad: ${age}`); } const personajesConPesoDecimal = dbPersonaje.map(personaje => ({ ...personaje.dataValues, peso: parseFloat(personaje.peso) })); return res.status(200).json(personajesConPesoDecimal); } catch (error) { res.status(404).send(error.message); } }; const buscarPersonajePeso = async (req, res) => { try { const { weight } = req.query; const dbPersonaje = await Personaje.findAll({ attributes: ['nombre', 'imagen', 'edad', 'peso', 'historia', 'peliculaAsociada'], where: { peso: weight } }); if (dbPersonaje.length === 0) { return res.status(400).send(`No hay personajes el peso: ${weight}`); } const personajesConPesoDecimal = dbPersonaje.map(personaje => ({ ...personaje.dataValues, peso: parseFloat(personaje.peso) })); return res.status(200).json(personajesConPesoDecimal); } catch (error) { res.status(404).send(error.message); } }; const buscarPersonajePelicula = async (req, res) => { try { const { idMovie } = req.query; const dbPersonaje = await Personaje.findAll({ attributes: ['nombre', 'imagen', 'edad', 'peso', 'historia', 'peliculaAsociada'], include: { model: Pelicula, attributes: [], where: { id: idMovie } }, }); if (dbPersonaje.length === 0) { return res.status(400).send(`No hay Pelicula con el id: ${idMovie}`); } const personajesConPesoDecimal = dbPersonaje.map(personaje => ({ ...personaje.dataValues, peso: parseFloat(personaje.peso) })); return res.status(200).json(personajesConPesoDecimal); } catch (error) { res.status(404).send(error.message); } }; module.exports = { buscarPersonajeNombre, buscarPersonajeEdad, buscarPersonajePeso, buscarPersonajePelicula }
using System; using System.Collections.Generic; using System.Linq; namespace PluginDeMo_v2.F1_2023.Participants { public class TyreSet { // Participant-related variables Participant Participant { get; set; } public TyreSet PreviousTyreSet { get; set; } = null; // Variables related to fitting public float OdometerAtFitting { get; set; } public float TyreWearAtFitting { get; set; } public int LapNumberAtFitting { get; set; } = 0; public float LapsSinceFitting => (CurrentLapNumber - LapNumberAtFitting) // laps since fitting + (Participant.LapData.m_lapDistance / TrackLength); // fraction of current lap // Variables related to wear public float Wear => Participant.CarDamageData.m_tyresWear.Max(); // wear public Dictionary<int, float> WearByLap { get; set; } = new Dictionary<int, float>(); // wear by lap public float StintWear => Wear - TyreWearAtFitting; // wear since fitting public float WearLastLap => WearByLap.ContainsKey(CurrentLapNumber) && WearByLap.ContainsKey(CurrentLapNumber - 1) ? WearByLap[CurrentLapNumber] - WearByLap[CurrentLapNumber - 1] : 0; // wear last lap public float WearPerDistance => StintWear / StintOdometer; // wear per m public float AverageWearPerLap => WearPerDistance * TrackLength; // wear per lap based wear per m and track length // Variables related to odometer public float SessionOdometer => Participant.LapData.m_totalDistance; // distance since session start public float StintOdometer => SessionOdometer - OdometerAtFitting; // distance since fitting // Variables related to track length public float TrackLength => Participant.Session.PacketSessionData.m_trackLength; // distance of a lap // Variables related to pit stop window public byte PitStopWindowIdealLap => Participant.Session.PacketSessionData.m_pitStopWindowIdealLap > 0 ? Participant.Session.PacketSessionData.m_pitStopWindowIdealLap : Participant.Session.NumLaps; // ideal lap for pit stop, num laps if no data public byte PitStopWindowLatestLap => Participant.Session.PacketSessionData.m_pitStopWindowLatestLap > 0 ? Math.Min( Participant.Session.PacketSessionData.m_pitStopWindowLatestLap, Participant.Session.NumLaps ) // i guess latest lap is sometimes higher than num laps for some reason, clipping it to num laps : Participant.Session.NumLaps; // latest lap for pit stop, num laps if no data public float WearAtIdealPitLap { get; set; } // wear at ideal pit lap public float WearAtLatestPitLap { get; set; } // wear at latest pit lap public byte ArtificialPredictedPitLap { get; set; } // artificial predicted pit lap based on real window and gausian distribution // Variables related to current lap public int CurrentLapNumber { get; set; } = 0; // current lap number public float WearAtStartOfLap => WearByLap.ContainsKey(CurrentLapNumber) ? WearByLap[CurrentLapNumber] : 0; // wear at start of lap public TyreSet(Participant participant, TyreSet previousTyreSet = null) { Participant = participant; PreviousTyreSet = previousTyreSet; FitTyreSet(); Update(); // artificial predicted pit lap byte pitWindowSize = (byte)(PitStopWindowLatestLap - PitStopWindowIdealLap); byte artificialEarliestPitLap = (byte)(PitStopWindowIdealLap - (pitWindowSize / 2)); ArtificialPredictedPitLap = (byte)( (byte) Math.Round( Utility.GaussianRandom( mean: pitWindowSize / 2, // mean stdDev: pitWindowSize / 6, // std dev Participant.Session.Randomizer ) ) + artificialEarliestPitLap ); } public void FitTyreSet() { OdometerAtFitting = Participant.LapData.m_totalDistance; TyreWearAtFitting = Participant.CarDamageData.m_tyresWear.Max(); LapNumberAtFitting = Participant.CurrentLapNumber; } public float WearAtDistance(float distance) { return Wear + (distance - SessionOdometer) * WearPerDistance; } public void Update() { //// new lap if (Participant.CurrentLapNumber != CurrentLapNumber) { CurrentLapNumber = Participant.CurrentLapNumber; WearByLap.Add(CurrentLapNumber, Wear); } // track length data exists if (TrackLength == 0) return; //// pit stop window WearAtIdealPitLap = WearAtDistance(PitStopWindowIdealLap * TrackLength); WearAtLatestPitLap = WearAtDistance(PitStopWindowLatestLap * TrackLength); ArtificialPredictedPitLap = (byte)Math.Max(CurrentLapNumber, ArtificialPredictedPitLap); // in case the predicted pit lap is before the current lap } public struct Tyres { public const string FrontLeft = "FrontLeft"; public const string FrontRight = "FrontRight"; public const string RearLeft = "RearLeft"; public const string RearRight = "RearRight"; } public static string[] TyresArray = new string[] { Tyres.RearLeft, Tyres.RearRight, Tyres.FrontLeft, Tyres.FrontRight }; // uint8 m_visualTyreCompound; // F1 visual (can be different from actual compound) // // 16 = soft, 17 = medium, 18 = hard, 7 = inter, 8 = wet // // F1 Classic – same as above // // F2 ‘19, 15 = wet, 19 – super soft, 20 = soft // // 21 = medium , 22 = hard public string VisualTyreName { get { switch (Participant.CarStatusData.m_visualTyreCompound) { case 16: return "soft"; case 17: return "medium"; case 18: return "hard"; case 7: return "inter"; case 8: return "wet"; case 15: return "wet"; case 19: return "super soft"; case 20: return "soft"; case 21: return "medium"; case 22: return "hard"; default: return "unknown"; } } } } }
/** * Takes input from user about mail details & outputs service cost information or error based on input * * @author Iris Carrigg * @version 8/31/2022 */ import java.util.Date; import java.util.Scanner; public class Project1 { public static void main ( String[] args ) { //follow the instructions in the comments exactly //do not delete the comments //1. DATE AND TIME YOU FIRST START WORKING ON THIS ASSIGNMENT (date AND time): <-------------------- //ANSWER: 8/31/2022 10:49AM <-------------------- System.out.println( "Welcome to the Ankh-Morpork Post Office!" ); //2. declare a scanner object, call it keyboard; you'll have to import the Scanner class too Scanner keyboard = new Scanner(System.in); //3. ask the user what (s)he's shipping today System.out.print("Are you shipping a letter or a package? "); String typeOfMail; //4. read the input in the typeOfMail variable typeOfMail = keyboard.next(); //5. trim the typeOfMail of leading and trailing spaces typeOfMail = typeOfMail.trim(); //6. make typeOfMail all lower case letters typeOfMail = typeOfMail.toLowerCase(); //this is logic that says "if you're not shipping a letter //or a package, terminate the program with a message //and an error code of -1" if ( !typeOfMail.equals( "package" ) && !typeOfMail.equals( "letter" ) ){ System.out.println( "We don't ship " + typeOfMail + ". Goodbye." ); System.exit( -1 ); } //7. create a Mail object with the standard constructor Mail mail = new Mail(); //8. set type of mail instance variable in the mail object mail.setType(typeOfMail); //9. ask the user how many pieces of that type of mail they're sending System.out.printf("How many %ss are you mailing? ",mail.getType() ); int piecesOfMail = 0; //10. read the user input about how many pieces of mail they're // sending in the piecesOfMail variable declared above piecesOfMail = keyboard.nextInt(); //this code checks if the number of mail pieces entered is valid if ( typeOfMail.equals( "letter" ) && ( piecesOfMail <= 0 || piecesOfMail > 100 ) ){ System.out.println( piecesOfMail + " is not a valid number of letters. Goodbye." ); System.exit( -2 ); } else if ( typeOfMail.equals( "package" ) && ( piecesOfMail <= 0 || piecesOfMail > 10 ) ){ System.out.println( piecesOfMail + " is not a valid number of packages. Goodbye." ); System.exit( -3 ); } //11. set the units instance variable in the Mail object to piecesOfMail mail.setUnits(piecesOfMail); //this code prompts the user for destination input //reads the input and checks it for validity, then gives it back to you //when the line executes, the destination variable will hold the //string value of what you input for destination String destination = chooseDestination( keyboard ); //12. set the destination instance variable in the mail object mail.setDestination(destination); //this code calculates postage for you given the type of mail and destination //when the lione executes, the postage variable will hold the price of mail //the price doesn't uinclude tax double postage = calculatePostage( typeOfMail, destination ); //13. set the postageperUnit instance variable in the mail object mail.setPostagePerUnit(postage); //14. move to the printReceipt method below and finish it according to the directions printReceipt( mail ); } /* finish this method! <----------- * * printReceipt - this method prints the formatted receipt * * @param Mail mail - the Mail object with values set in the main * @return nothing */ public static void printReceipt( Mail mail ) { //15. all the user entered data read in the main should be in the object called mail // use getter methods from the Mail class with the mail object to print the formatted receipt //new Date object Date now = new Date(); System.out.println("....................................................."); System.out.printf(": Date: %s%17c%n:", now, ':'); System.out.printf("%52c%n: ", ':'); System.out.printf("PRODUCT & DESTINATION COST%17c%n: ",':',"---------------------------------------------",':'); System.out.printf("%s%6c%n: ","---------------------------------------------",':'); System.out.printf("%-3d %7ss to %-13s Price $%7.2f%7c%n: ", mail.getUnits(), mail.getType(), mail.getDestination(),mail.getPostagePerUnit() * mail.getUnits(), ':'); System.out.printf(" Tax $%7.2f%7c%n: ", (mail.getPostagePerUnit() * mail.getUnits()) * .06, ':'); System.out.printf(" TOTAL $%7.2f%7c%n:",(((mail.getPostagePerUnit() * mail.getUnits()) * .06) + (mail.getPostagePerUnit() * mail.getUnits())), ':'); System.out.printf("%52c%n: ", ':'); System.out.println("Thank you for using the Ankh-Morpork Post Office! :"); System.out.println("....................................................."); //16. delete the 3 instructions below when you're done } /* do not change this method! * * chooseDestination - this method checks for a valid destination * * @param Scanner kbrd - stream to read from keyboard * @return String - the destination of the cargo with the correct format */ private static String chooseDestination( Scanner kbrd ) { System.out.print( "Enter the destination: " ); String dest = kbrd.next(); switch ( dest.trim().toLowerCase() ) { case "ankh-morpork": return "Ankh-Morpork"; case "pseudopolis": return "Pseudopolis"; case "ueberwald": return "Ueberwald"; default: System.out.println( "We don't ship to " + dest + ". Goodbye." ); System.exit( -2 ); } return ""; } /* do not change this method! * * calculatePostage - this method calculates postage given the type and * detination of the cargo * * @param String type - the type of cargo * @param String dest - the destination * @return double - the price of cargo (without tax) */ private static double calculatePostage( String type, String dest ) { if ( dest.trim().equalsIgnoreCase( "Ankh-Morpork" ) && type.trim().equalsIgnoreCase( "letter" ) ) return 1.50; else if ( dest.trim().equalsIgnoreCase( "Ankh-Morpork" ) && type.trim().equalsIgnoreCase( "package" ) ) return 12.85; else if ( dest.trim().equalsIgnoreCase( "Pseudopolis" ) && type.trim().equalsIgnoreCase( "letter" ) ) return 13.12; else if ( dest.trim().equalsIgnoreCase( "Pseudopolis" ) && type.trim().equalsIgnoreCase( "package" ) ) return 40.20; else if ( dest.trim().equalsIgnoreCase( "Ueberwald" ) && type.trim().equalsIgnoreCase( "letter" ) ) return 50.00; else if ( dest.trim().equalsIgnoreCase( "Ueberwald" ) && type.trim().equalsIgnoreCase( "package" ) ) return 151.23; else{ System.out.println( "Something went wrong. Panic!" ); System.exit( -3 ); } return -1; } }
import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import IndividualAbridgedPost from "../AbridgedPostOne"; import { getSubredditPosts } from "../../store/posts"; import { useParams } from "react-router-dom"; import LoadingSpinner from "../LoadingSpinner"; import useInfiniteScrolling from "../../hooks/useInfiniteScrolling"; export default function SubredditPostsPreview({ user, subreddit, subreddits }) { const { subredditName } = useParams(); const dispatch = useDispatch(); const [isLoaded, setIsLoaded] = useState(false); const page = useInfiniteScrolling(); useEffect(() => { dispatch(getSubredditPosts(subredditName, page, 10)).then(() => setIsLoaded(true)); }, [dispatch, subredditName, page]); const posts = useSelector((state) => state.posts.Posts); let allPostsArr = Object.values(posts); const filteredPosts = allPostsArr; return ( isLoaded ? <> <div style={{ height: "30px", backgroundColor: "#dae0e6" }}></div> <div className="subreddit-short-main-container"> {filteredPosts .sort( (a, b) => b.id - a.id ) .map((post) => ( <IndividualAbridgedPost key={post.id} user={user} post={post} subreddit={subreddit} /> ))} </div> </> : <LoadingSpinner /> ); }
# Ionosphere Data Prediction ## Introduction This project aims to analyze radar data collected by a system in Goose Bay, Labrador, focusing on the ionosphere's behavior. Machine learning models Random Forest Classifier and Logistic Regression were used to classify radar returns as either "Good" or "Bad" based on their ionospheric patterns. The Random Forest Classifier achieved an accuracy of 98%, while Logistic Regression achieved 90%. ## Problem Statement This project addresses the binary classification problem of distinguishing between "Good" and "Bad" radar returns based on ionospheric behavior. ## About Dataset - Contains 34 features. - The 35th attribute classifies radar returns as "good" or "bad". - Consists of 351 instances. - Multivariate dataset with no missing values. ## Model Training and Selection ### Random Forest Classifier Random Forest Classifier is an ensemble learning method known for its robustness and ability to handle large datasets. By aggregating the predictions of multiple decision trees, it achieves high accuracy and is less prone to overfitting. In this project, it achieved an impressive accuracy of 98%, making it a reliable choice for classification tasks. #### Predictions <p align="center"> <img src="https://github.com/lexxus16/ionosphere_prediction/assets/69308391/7abd7e1a-0045-4d9b-acd4-5bb6ae3ddc4e" alt="Alt Text" width="500"/> </p> #### Metrics Score <p align="center"> <img src="https://github.com/lexxus16/ionosphere_prediction/assets/69308391/32358a5c-47bd-41ba-9374-679f2a46af97" alt="Alt Text" width="460"/> </p> ### Logistic Regression Logistic Regression is a simple yet powerful linear model commonly used for binary classification problems. It predicts the probability of an instance belonging to a certain class, making it interpretable and suitable for understanding feature importance. Despite its simplicity, logistic regression achieved a commendable accuracy of 90% in this project, showcasing its effectiveness in modeling binary outcomes. #### Predictions <p align="center"> <img src="https://github.com/lexxus16/ionosphere_prediction/assets/69308391/fdfeb183-3ebe-47e5-85ac-5bd0a62026bd" alt="Alt Text" width="500"/> </p> #### Metrics Score <p align="center"> <img src="https://github.com/lexxus16/ionosphere_prediction/assets/69308391/27961d4c-2a6d-4099-85d5-aa4cc58b8fe4" alt="Alt Text" width="430"/> </p> ## Contributing You are welcome to contribute to enhancing and improving this project. Contribute by: - Bug Reports: If you encounter any issues or unexpected behavior, please report them. - Feature Requests: Share ideas for new features or improvements by submitting a feature request.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>REZ</title> <style> *, *::before, *::after{ margin: 0; padding: 0; font-family: "Poppins", sans-serif; box-sizing: border-box; } .container{ background-color: blue; margin: 100px auto 70px; width: 600px; padding: 40px; color: white; } .search-box{ display: flex; justify-content: space-between; gap: 2rem; } .search-box input{ border: 0; outline: 0; flex: 1; font-size: 17px; padding-left: 8px; border-radius: 25px; } .search-box button{ outline: 0; border: 0; height: 60px; width: 60px; border-radius: 50%; } button img{ width: 20px; } .weather{ text-align: center; margin: 2rem 0; } .weather h1{ font-size: 80px; } .weather h2{ font-size: 40px; } .lower-section{ margin: 2rem 0; display: flex; justify-content: space-between; } .inner{ display: flex; } .lower-section div{ margin-left: 1rem; font-size: 20px; } .error{ color: red; display: none; } </style> </head> <body> <div class="container"> <div class="search-box"> <input type="text" placeholder="Enter City Name" id="inputBox"> <button id="inputBtn"> <img src="images/search.png" alt=""> </button> </div> <div class="error">Invalid city name</div> <div class="weather"> <img src="images/rain.png" class="center-img" alt="" id="weatherIcon"> <h1 class="temp">22°c</h1> <h2 class="city">New York</h2> <div class="lower-section"> <div class="inner"> <img src="images/humidity.png" alt=""> <div> <p class="humidity">50%</p> <p>Humidity</p> </div> </div> <div class="inner"> <img src="images/wind.png" alt=""> <div> <p class="wind">15 Km/h</p> <p>Wind Speed</p> </div> </div> </div> </div> </div> <script> const weatherIcon = document.getElementById("weatherIcon"); const inputBox = document.getElementById("inputBox"); const inputBtn = document.getElementById("inputBtn"); const url = "https://api.openweathermap.org/data/2.5/weather?units=metric?&q="; const apiKey = ""; async function checkWeather(city){ const response = await fetch(url + city + `&appid=${apiKey}`); if (response.status == 404) { document.querySelector(".error").style.display = "block"; document.querySelector(".weather").style.display = "none"; } else{ let data = await response.json(); document.querySelector(".city").innerHTML = data.name; document.querySelector(".temp").innerHTML = Math.round(data.main.temp) + " °c"; document.querySelector(".humidity").innerHTML = data.main.humidity + " %"; document.querySelector(".wind").innerHTML = data.wind.speed + " Km/h"; if (data.weather[0].main == "Clouds") { weatherIcon.src = "images/clouds.png"; } else if (data.weather[0].main == "Rain") { weatherIcon.src = "images/rain.png"; } else if (data.weather[0].main == "Drizzle") { weatherIcon.src = "images/drizzle.png"; } else if (data.weather[0].main == "Mist") { weatherIcon.src = "images/mist.png"; } else if (data.weather[0].main == "Clear") { weatherIcon.src = "images/clear.png"; } document.querySelector(".error").style.display = "none"; document.querySelector(".weather").style.display = "block"; } } inputBtn.addEventListener("click", ()=>{ checkWeather(inputBox.value); }); </script> </body> </html>
local lsp_zero = require('lsp-zero') local ls = require("luasnip") require('mason').setup({}) require('mason-lspconfig').setup({ ensure_installed = { 'tsserver', 'rust_analyzer', 'eslint', 'lua_ls', 'clangd' }, handlers = { lsp_zero.default_setup, lua_ls = function() local lua_opts = lsp_zero.nvim_lua_ls() require('lspconfig').lua_ls.setup(lua_opts) end, } }) local cmp = require('cmp') local cmp_select = { behavior = cmp.SelectBehavior.Select } local mapping = cmp.mapping.preset.insert({ ['<C-p>'] = cmp.mapping.select_prev_item(cmp_select), ['<C-n>'] = cmp.mapping.select_next_item(cmp_select), ['<C-y>'] = cmp.mapping.confirm({ select = true }), ['<C-Space>'] = cmp.mapping.complete(), ["<CR>"] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Insert, select = true, } }) lsp_zero.on_attach(function(client, bufnr) local opts = { buffer = bufnr, remap = false } vim.keymap.set("n", "gd", function() vim.lsp.buf.definition() end, opts) vim.keymap.set("n", "K", function() vim.lsp.buf.hover() end, opts) vim.keymap.set("n", "<leader>vws", function() vim.lsp.buf.workspace_symbol() end, opts) vim.keymap.set("n", "<leader>vd", function() vim.diagnostic.open_float() end, opts) vim.keymap.set("n", "[d", function() vim.diagnostic.goto_next() end, opts) vim.keymap.set("n", "]d", function() vim.diagnostic.goto_prev() end, opts) vim.keymap.set("n", "<leader>vca", function() vim.lsp.buf.code_action() end, opts) vim.keymap.set("n", "<leader>vrr", function() vim.lsp.buf.references() end, opts) vim.keymap.set("n", "<leader>vrn", function() vim.lsp.buf.rename() end, opts) vim.keymap.set("i", "<C-h>", function() vim.lsp.buf.signature_help() end, opts) end) cmp.setup({ snippet = { expand = function(args) ls.lsp_expand(args.body) end, }, sources = { { name = "luasnip" }, { name = 'path' }, { name = 'nvim_lsp' }, { name = 'nvim_lua' }, }, formatting = lsp_zero.cmp_format(), mapping=mapping })
const { AppError, catchAsync, sendResponse } = require("../helpers/utils"); const LeaveBalance = require("../models/LeaveBalance"); const LeaveCategory = require("../models/LeaveCategory"); const LeaveRequest = require("../models/LeaveRequest"); const Notification = require("../models/Notification"); const User = require("../models/User"); const { ADMIN_OFFICE, EMPLOYEE, MANAGER, NOTIFICATION_SUBMIT_LEAVE, NOTIFICATION_APPROVE_LEAVE, NOTIFICATION_REJECT_LEAVE, } = require("../variables/constants"); const firebaseAdmin = require("../firebaseSetup"); const leaveController = {}; leaveController.getCurrentUserLeaves = catchAsync(async (req, res, next) => { const allowedFilter = ["category", "status"]; // Get data from request const currentUserId = req.userId; let { page, limit, ...filter } = req.query; // Business Logic Validation Object.keys(filter).forEach((key) => { if (!allowedFilter.includes(key)) { throw new AppError( 400, `Query ${key} is not allowed`, "Get Current User Leaves Error" ); } }); // Process const filterConditions = [{ requestedUser: currentUserId, isDeleted: false }]; if (filter.status) { filterConditions.push({ status: filter.status }); } if (filter.category) { const userInfo = await User.findById(currentUserId); const category = await LeaveCategory.findOne({ $or: [ { targetType: "All", name: filter.category }, { targetType: "Role", targetRole: userInfo.role, name: filter.category, }, ], }); filterConditions.push({ category: category._id }); } const filterCriteria = filterConditions.length ? { $and: filterConditions } : {}; let currentPageLeavesList = []; let totalPages = 0; const count = await LeaveRequest.countDocuments(filterCriteria); const pendingCount = await LeaveRequest.countDocuments({ requestedUser: currentUserId, isDeleted: false, status: "pending", }); if (page && limit) { page = parseInt(page) || 1; limit = parseInt(limit) || 5; totalPages = Math.ceil(count / limit); const offset = limit * (page - 1); currentPageLeavesList = await LeaveRequest.find(filterCriteria) .populate("category") .populate("requestedUser") .sort({ fromDate: -1 }) .skip(offset) .limit(limit); } const fullLeavesList = await LeaveRequest.find({ ...filterCriteria, status: { $ne: "rejected" }, }) .populate("category") .populate("requestedUser") .sort({ fromDate: -1 }); // Response return sendResponse( res, 200, true, { fullLeavesList, currentPageLeavesList, totalPages, count, pendingCount }, null, "Get Current User Leaves Successfully" ); }); leaveController.getEmployeeLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; // Business Logic Validation const currentUser = await User.findById(currentUserId).populate("role"); // Process const filterConditions = [{ isDeleted: false, status: { $ne: "rejected" } }]; if (currentUser.role.name === MANAGER) { filterConditions.push({ assignedUser: currentUserId }); } const filterCriteria = filterConditions.length ? { $and: filterConditions } : {}; const leavesList = await LeaveRequest.find(filterCriteria) .populate("requestedUser") .populate("assignedUser") .populate("category"); // Response return sendResponse( res, 200, true, leavesList, null, "Get Employees Leaves Successfully" ); }); leaveController.getPendingLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; // Process const pendingLeave = await LeaveRequest.find({ assignedUser: currentUserId, status: "pending", isDeleted: false, }) .populate("assignedUser") .populate("requestedUser") .populate("category"); const totalPendingCount = await LeaveRequest.countDocuments({ assignedUser: currentUserId, status: "pending", isDeleted: false, }); // Response return sendResponse( res, 200, true, { pendingLeave, totalPendingCount }, null, "Get Pending Leave Successfully" ); }); leaveController.getSingleLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; const selectedRequestId = req.params.requestId; // Business Logic Validation - Process const currentUser = await User.findById(currentUserId).populate("role"); const selectedRequest = await LeaveRequest.findOne({ _id: selectedRequestId, isDeleted: false, }).populate("category"); if (!selectedRequest) throw new AppError( 400, "Leave request not found", "Get Single Leave Error" ); if ( currentUser.role.name === EMPLOYEE && selectedRequest.requestedUser.toString() !== currentUserId ) throw new AppError(403, "Access denied", "Get Single Leave Error"); if ( currentUser.role.name === MANAGER && selectedRequest.requestedUser.toString() !== currentUserId && selectedRequest.assignedUser.toString() !== currentUserId ) throw new AppError(403, "Access denied", "Get Single Leave Error"); // Response return sendResponse( res, 200, true, selectedRequest, null, "Get Single Leave Successfully" ); }); leaveController.getCurrentUserLeaveBalance = catchAsync( async (req, res, next) => { // Get data from request const currentUserId = req.userId; // Process const leaveBalance = await LeaveBalance.find({ user: currentUserId, }).populate("leaveCategory"); leaveBalance.sort( (a, b) => a.leaveCategory.displayOrder - b.leaveCategory.displayOrder ); const totalUsedSum = leaveBalance.reduce( (sum, item) => sum + item.totalUsed, 0 ); const totalHadSum = leaveBalance.reduce( (sum, item) => sum + item.totalAvailable, 0 ); const totalRemainingSum = totalHadSum - totalUsedSum; // Response return sendResponse( res, 200, true, { leaveBalance, totalUsedSum, totalHadSum, totalRemainingSum }, null, "Get Current User Leave Balance Successfully" ); } ); leaveController.createLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; let { categoryName, fromDate, toDate, type, reason } = req.body; // Business Logic Validation let requestor = await User.findById(currentUserId).populate("reportTo"); if (!requestor) throw new AppError(400, "User not found", "Create Leave Request Error"); // Check leave category const category = await LeaveCategory.findOne({ name: categoryName, $or: [{ targetRole: requestor.role }, { targetRole: { $exists: false } }], }); if (!category) throw new AppError(400, "Category not found", "Create Leave Request Error"); // // Logic for date const formattedFromDate = new Date(fromDate); const formattedToDate = new Date(toDate); // Check logic fromDate and toDate if (formattedFromDate > formattedToDate) throw new AppError( 400, "FromDate cannot be later than toDate", "Create Leave Request Error" ); // Calculate total leave days let totalDaysLeave = 0; if (type === "full") { totalDaysLeave = Math.ceil( (formattedToDate - formattedFromDate) / (1000 * 60 * 60 * 24) ); } else { totalDaysLeave = 0.5; } // Check leave balance let leaveBalance = await LeaveBalance.findOne({ user: currentUserId, leaveCategory: category._id, }).populate("leaveCategory"); const toralRemaining = leaveBalance.totalAvailable - leaveBalance.totalUsed; if (toralRemaining < totalDaysLeave && categoryName !== "unpaid_leave") throw new AppError( 400, "Insufficient leave balance", "Create Leave Request Error" ); // Check apply previous date const today = new Date(); const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); if (formattedFromDate < yesterday) throw new AppError( 400, "Leave cannot be applied for previous time", "Create Leave Request Error" ); // Check apply overlap const overlapRequest = await LeaveRequest.find({ requestedUser: currentUserId, status: { $ne: "rejected" }, isDeleted: false, $or: [ // Check if document's date range overlaps with or includes request date range . { fromDate: { $lte: formattedToDate }, toDate: { $gte: formattedFromDate }, }, //checks if the document's date range includes or ends on requestToDate. { fromDate: { $lte: formattedToDate }, toDate: { $gte: formattedToDate }, }, //checks if the document's date range includes or begins on requestFromDate. { fromDate: { $lte: formattedFromDate }, toDate: { $gte: formattedFromDate }, }, ], }); if (overlapRequest.length !== 0) throw new AppError( 400, "Leave cannot be applied twice for the same day", "Create Leave Request Error" ); // Process const leaveRequest = await LeaveRequest.create({ requestedUser: currentUserId, assignedUser: requestor.reportTo, category: category._id, fromDate: formattedFromDate, toDate: formattedToDate, type, totalDays: totalDaysLeave, reason, }); // Update Leave Balance leaveBalance.totalUsed += totalDaysLeave; await leaveBalance.save(); // Create notification const notiMessage = NOTIFICATION_SUBMIT_LEAVE; await Notification.create({ targetUser: requestor.reportTo, leaveRequest: leaveRequest._id, type: "leave_submit", message: notiMessage, }); // Send noti to firebase const fcmTokensList = requestor.reportTo.fcmTokens; fcmTokensList.forEach(async (currentFcmToken) => { const message = { notification: { title: "Notification", body: "You have new notification", }, token: currentFcmToken, }; const response = await firebaseAdmin.messaging().send(message); }); // Response return sendResponse( res, 200, true, leaveRequest, null, "Create Leave Request Successfully" ); }); leaveController.updateLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; const requestId = req.params.requestId; let { categoryName, fromDate, toDate, type, reason } = req.body; // Business Logic Validation let requestor = await User.findById(currentUserId).populate("role"); if (!requestor) throw new AppError(400, "User not found", "Update Leave Request Error"); let selectedRequest = await LeaveRequest.findById(requestId).populate( "category" ); if (!selectedRequest) throw new AppError( 400, "Leave Request not found", "Update Leave Request Error" ); if (selectedRequest.status !== "pending") throw new AppError( 400, "Only pending request can be editted ", "Update Leave Request Error" ); if (requestor.role.name !== "admin office") { if (selectedRequest.requestedUser.toString() !== currentUserId) { if (selectedRequest.assignedUser.toString() !== currentUserId) { throw new AppError( 400, "Permission Required", "Update Leave Request Error" ); } } } // Check leave category const category = await LeaveCategory.findOne({ name: categoryName, $or: [{ targetRole: requestor.role }, { targetRole: { $exists: false } }], }); if (!category) throw new AppError(400, "Category not found", "Create Leave Request Error"); // Logic for date const formattedFromDate = new Date(fromDate); const formattedToDate = new Date(toDate); // Check logic fromDate and toDate if (formattedFromDate > formattedToDate) throw new AppError( 400, "FromDate cannot be later than toDate", "Create Leave Request Error" ); // Calculate total leave days let totalDaysLeave = 0; if (type === "full") { totalDaysLeave = Math.ceil( (formattedToDate - formattedFromDate) / (1000 * 60 * 60 * 24) ); } else { totalDaysLeave = 0.5; } // Check apply previous date const today = new Date(); const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); if (formattedFromDate < yesterday) throw new AppError( 400, "Leave cannot be applied for previous time", "Create Leave Request Error" ); // Check apply overlap const overlapRequest = await LeaveRequest.find({ requestedUser: currentUserId, status: { $ne: "rejected" }, isDeleted: false, _id: { $ne: selectedRequest._id }, $or: [ // Check if document's date range overlaps with or includes request date range . { fromDate: { $lte: formattedToDate }, toDate: { $gte: formattedFromDate }, }, //checks if the document's date range includes or ends on requestToDate. { fromDate: { $lte: formattedToDate }, toDate: { $gte: formattedToDate }, }, //checks if the document's date range includes or begins on requestFromDate. { fromDate: { $lte: formattedFromDate }, toDate: { $gte: formattedFromDate }, }, ], }); if (overlapRequest.length !== 0) throw new AppError( 400, "Leave cannot be applied twice for the same day", "Create Leave Request Error" ); // Check leave balance if (selectedRequest.category.name === categoryName) { let leaveBalance = await LeaveBalance.findOne({ user: selectedRequest.requestedUser, leaveCategory: selectedRequest.category, }).populate("leaveCategory"); const toralRemainingUpdated = leaveBalance.totalAvailable - leaveBalance.totalUsed + selectedRequest.totalDays; if (toralRemainingUpdated < totalDaysLeave) throw new AppError( 400, "Insufficient leave balance", "Create Leave Request Error" ); // Update Leave Balance leaveBalance.totalUsed = leaveBalance.totalUsed - selectedRequest.totalDays + totalDaysLeave; await leaveBalance.save(); } else { let leaveBalanceOld = await LeaveBalance.findOne({ user: selectedRequest.requestedUser, leaveCategory: selectedRequest.category, }).populate("leaveCategory"); let leaveBalanceNew = await LeaveBalance.findOne({ user: selectedRequest.requestedUser, leaveCategory: category._id, }).populate("leaveCategory"); const toralRemainingNew = leaveBalanceNew.totalAvailable - leaveBalanceNew.totalUsed; if (toralRemainingNew < totalDaysLeave) throw new AppError( 400, "Insufficient leave balance", "Create Leave Request Error" ); // Update Leave Balance leaveBalanceOld.totalUsed -= selectedRequest.totalDays; leaveBalanceNew.totalUsed += totalDaysLeave; await leaveBalanceOld.save(); await leaveBalanceNew.save(); } // Update request selectedRequest.category = category._id; selectedRequest.fromDate = formattedFromDate; selectedRequest.toDate = formattedToDate; selectedRequest.type = type; selectedRequest.totalDays = totalDaysLeave; selectedRequest.reason = reason; await selectedRequest.save(); // Response return sendResponse( res, 200, true, selectedRequest, null, "Update Leave Request Successfully" ); }); leaveController.deleteLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; const requestId = req.params.requestId; // Business Logic Validation let requestor = await User.findById(currentUserId).populate("role"); if (!requestor) throw new AppError(400, "User not found", "Delete Leave Request Error"); let selectedRequest = await LeaveRequest.findById(requestId).populate( "requestedUser" ); if (!selectedRequest) throw new AppError( 400, "Leave Request not found", "Delete Leave Request Error" ); if (selectedRequest.status !== "pending") throw new AppError( 400, "Only pending request can be deleted ", "Delete Leave Request Error" ); if (requestor.role.name !== ADMIN_OFFICE) { if (selectedRequest.requestedUser._id.toString() !== currentUserId) { if (selectedRequest.assignedUser.toString() !== currentUserId) { throw new AppError( 400, "Permission Required", "Delete Leave Request Error" ); } } } let deletedRequest = await LeaveRequest.findOneAndUpdate( { _id: requestId, }, { isDeleted: true }, { new: true } ); // Update Leave Balance let leaveBalance = await LeaveBalance.findOne({ user: selectedRequest.requestedUser._id, leaveCategory: selectedRequest.category, }); leaveBalance.totalUsed -= selectedRequest.totalDays; await leaveBalance.save(); // Update notification await Notification.findOneAndDelete({ leaveRequest: requestId }); // Response return sendResponse( res, 200, true, deletedRequest, null, "Delete Leave Request Successfully" ); }); leaveController.approveLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; const requestId = req.params.requestId; // Business Logic Validation let approvedUser = await User.findById(currentUserId).populate("role"); let selectedRequest = await LeaveRequest.findById(requestId).populate( "requestedUser" ); if (!selectedRequest) throw new AppError( 400, "Leave Request not found", "Approve Leave Request Error" ); if (selectedRequest.status !== "pending") throw new AppError( 400, "Only pending request can be approved ", "Approve Leave Request Error" ); if (approvedUser.role.name !== ADMIN_OFFICE) { if (selectedRequest.assignedUser.toString() !== currentUserId) { throw new AppError( 400, "Permission Required", "Approve Leave Request Error" ); } } // Approve selectedRequest.status = "approved"; await selectedRequest.save(); const notiMessage = NOTIFICATION_APPROVE_LEAVE; await Notification.create({ targetUser: selectedRequest.requestedUser._id, leaveRequest: selectedRequest._id, type: "leave_approve", message: notiMessage, }); // Send noti to firebase const fcmTokensList = selectedRequest.requestedUser.fcmTokens; if (fcmTokensList.length !== 0) { fcmTokensList.forEach(async (currentFcmToken) => { const message = { notification: { title: "Notification", body: "You have new notification", }, token: currentFcmToken, }; const response = await firebaseAdmin.messaging().send(message); }); } // Response return sendResponse( res, 200, true, selectedRequest, null, "Approve Leave Request Successfully" ); }); leaveController.rejectLeave = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; const requestId = req.params.requestId; // Business Logic Validation let rejectedUser = await User.findById(currentUserId).populate("role"); let selectedRequest = await LeaveRequest.findById(requestId).populate( "requestedUser" ); if (!selectedRequest) throw new AppError( 400, "Leave Request not found", "Reject Leave Request Error" ); if (selectedRequest.status !== "pending") throw new AppError( 400, "Only pending request can be rejected ", "Reject Leave Request Error" ); if (rejectedUser.role.name !== ADMIN_OFFICE) { if (selectedRequest.assignedUser.toString() !== currentUserId) { throw new AppError( 400, "Permission Required", "Reject Leave Request Error" ); } } let requestor = await User.findById(selectedRequest.requestedUser._id); // Update Leave Balance let leaveBalance = await LeaveBalance.findOne({ user: requestor._id, leaveCategory: selectedRequest.category, }); leaveBalance.totalUsed -= selectedRequest.totalDays; await leaveBalance.save(); // Reject selectedRequest.status = "rejected"; await selectedRequest.save(); const notiMessage = NOTIFICATION_REJECT_LEAVE; await Notification.create({ targetUser: selectedRequest.requestedUser._id, leaveRequest: selectedRequest._id, type: "leave_reject", message: notiMessage, }); // Send noti to firebase const fcmTokensList = selectedRequest.requestedUser.fcmTokens; if (fcmTokensList.length !== 0) { fcmTokensList.forEach(async (currentFcmToken) => { const message = { notification: { title: "Notification", body: "You have new notification", }, token: currentFcmToken, }; const response = await firebaseAdmin.messaging().send(message); }); } // Response return sendResponse( res, 200, true, selectedRequest, null, "Reject Leave Request Successfully" ); }); leaveController.getLeaveByMonth = catchAsync(async (req, res, next) => { // Get data from request const currentUserId = req.userId; const { year } = req.params; let totalApprovedLeave = 0; const startPeriod = new Date(`${year}-01-01`); const endPeriod = new Date(`${year}-12-31`); // Business Logic Validation const currentUser = await User.findById(currentUserId).populate("role"); const filterConditions = [ { status: "approved", $and: [ { fromDate: { $gte: startPeriod } }, { fromDate: { $lte: endPeriod } }, ], }, ]; if (currentUser.role.name === MANAGER) { filterConditions.push({ assignedUser: currentUserId }); } const filterCriteria = filterConditions.length ? { $and: filterConditions } : {}; const leaveRequests = await LeaveRequest.find(filterCriteria); const monthLabels = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const totalLeaveByMonth = Array.from({ length: 12 }, (_, month) => ({ label: monthLabels[month], data: 0, })); for (let month = 1; month <= 12; month++) { let daysTakenNextMonth = 0; const totalLeaveTakenInMonth = leaveRequests.reduce( (total, leaveRequest) => { let fromDate = new Date(leaveRequest.fromDate); fromDate = new Date(fromDate.toUTCString()); let toDate = new Date(leaveRequest.toDate); toDate = new Date(toDate.toUTCString()); if (fromDate.getMonth() === month - 1) { if (fromDate.getMonth() === toDate.getMonth()) { total += leaveRequest.totalDays; } else { const isFullDay = leaveRequest.type === "full"; const daysTaken = new Date(year, month, 0).getDate() - fromDate.getDate() + 1; total += isFullDay ? daysTaken : daysTaken * 0.5; daysTakenNextMonth += toDate.getDate() - new Date(year, month, 1).getDate() + 1; } } return total; }, 0 ); totalLeaveByMonth[month - 1].label = monthLabels[month - 1]; totalLeaveByMonth[month - 1].data += totalLeaveTakenInMonth; const nextMonthIndex = month % 12; if (month !== 12) { totalLeaveByMonth[nextMonthIndex].data += daysTakenNextMonth; } totalApprovedLeave += totalLeaveTakenInMonth + daysTakenNextMonth; } // Response return sendResponse( res, 200, true, { totalLeaveByMonth, totalApprovedLeave }, null, "Get Leave By Month Successfully" ); }); module.exports = leaveController;
package users import ( "carpool-btc/internal/app/models" "carpool-btc/internal/app/utils" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" "net/http" "os" "time" ) type Params struct { EmailAddress *string `json:"email_address,omitempty"` Password *string `json:"password,omitempty"` ConfirmPassword *string `json:"confirm_password,omitempty"` WalletAddress *string `json:"wallet_address,omitempty"` } func Login(c *gin.Context) { var userInput Params if err := c.ShouldBindJSON(&userInput); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid user data", "detail": err.Error(), }) return } user, token, err := walletAddress(userInput) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "error": "Failed to login", "details": err.Error(), }) return } c.Header("Authorization", *token) c.JSON(http.StatusOK, user) return } func walletAddress(ui Params) (*models.User, *string, error) { var id int64 queryString := "SELECT id FROM users u WHERE u.wallet_address = ($1)" err := utils.DB.QueryRow(queryString, *ui.WalletAddress).Scan(&id) type ResetTokenPayload struct { WalletAddress string } resetTokenPayload := ResetTokenPayload{ WalletAddress: *ui.WalletAddress, } token, tokenErr := generateJWTToken(resetTokenPayload, time.Now().Add(time.Hour*24*30).Unix()) if tokenErr != nil { return nil, nil, err } user, err := GetUserWithWallet(*ui.WalletAddress) if err != nil { return nil, nil, err } return user, token, nil } func generateJWTToken(payload any, expTime int64) (*string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "sub": payload, "exp": expTime, }) tokenString, err := token.SignedString([]byte(os.Getenv("JWT_SECRET"))) if err != nil { return nil, err } return &tokenString, nil }
/* * bodySystemCpu.cu * * Created on: Dec 4, 2013 * Author: alex * */ #include "bodySystemCpu.cuh" /* ************************************************************************** * * bodySystemCpu : Public methods * ************************************************************************** */ void BodySystemCPU::update() { integrateSys(); } float4 *BodySystemCPU::getArray(BodyArray array) { switch (array) { default: case BODYSYSTEM_POSITION: return mPos; case BODYSYSTEM_VELOCITY: return mVel; case BODYSYSTEM_COLOR: return mColor; } } /* ************************************************************************** * * bodySystemCpu : Protected methods * ************************************************************************** */ void BodySystemCPU::_initialize() { mPos = new float4[mNumBodies]; mVel = new float4[mNumBodies]; mColor = new float4[mNumBodies]; mAcc = new float3[mNumBodies]; memset(mPos, 0, mNumBodies * sizeof(float4)); memset(mVel, 0, mNumBodies * sizeof(float4)); memset(mColor, 0, mNumBodies * sizeof(float4)); memset(mAcc, 0, mNumBodies * sizeof(float3)); } void BodySystemCPU::_finalize() { delete[] mPos; delete[] mVel; delete[] mColor; delete[] mAcc; } /* ************************************************************************** * * bodySystemCpu : Private methods * ************************************************************************** */ void BodySystemCPU::computeGrav() { // loop on every body \o/ for (int i = 0; i < mNumBodies; i++) { float3 acc = { 0, 0, 0 }; // for each body, we compute his interaction with each other for (int j = 0; j < mNumBodies; j++) bodyInterac(acc, mPos[i], mPos[j]); // the new acceleration mAcc[i] = acc; } } void BodySystemCPU::integrateSys() { computeGrav(); /* * we need those local variables make the computation easier * by dividing between mass and position/velocity */ float3 lpos, lvel; for (int i = 0; i < mNumBodies; ++i) { // we save the old values lpos.x = mPos[i].x; lpos.y = mPos[i].y; lpos.z = mPos[i].z; lvel.x = mVel[i].x; lvel.y = mVel[i].y; lvel.z = mVel[i].z; // new velocity = old velocity + acceleration * deltaTime lvel = lvel + scalevec(mAcc[i], DELTA_TIME); // new position = old position + velocity * deltaTime lpos = lpos + scalevec(lvel, DELTA_TIME); mPos[i].x = lpos.x; mPos[i].y = lpos.y; mPos[i].z = lpos.z; mVel[i].x = lvel.x; mVel[i].y = lvel.y; mVel[i].z = lvel.z; } } void BodySystemCPU::bodyInterac(float3& accel, float4 const& posFirst, float4 const& posSec) { float3 r; // the vector going from body 1 to 0 r.x = posSec.x - posFirst.x; r.y = posSec.y - posFirst.y; r.z = posSec.z - posFirst.z; // see gravity law accel = accel + scalevec(scalevec(r, (float) posSec.w * (float) pow(rsqrt(dot(r, r) + SOFTENINGSQUARED), 3)), 9.81f); }
const express = require('express'); const { v4: uuidv4 } = require('uuid'); const app = express(); app.use(express.json()); const customers = []; // Middleware function verifyExistentAccountCpf(request, response, next){ const { cpf } = request.headers; const customer = customers.find(customer => customer.cpf === cpf); if(!customer){ return response.status(400).json({error: "Customer not found"}); } request.customer = customer return next() } function getBalance(statement) { const balance = statement.reduce((acc, operation) => { if(operation.type === 'credit'){ return acc + operation.amount; } else { return acc - operation.amount; } }, 0) return balance; } app.post('/account', (request, response) => { const { cpf, name } = request.body; const customerAlreadyExists = customers .some(customer => customer.cpf === cpf) if(customerAlreadyExists){ return response.status(400).json({error: "Customer Already exists!"}); } customers.push({ cpf, name, id: uuidv4(), statement: [] }); return response.status(201).send(); }) // app.use(verifyExistentAccountCpf) todas as rotas abaixo desse vão passar // por esse middleware app.get('/statement', verifyExistentAccountCpf, (request, response) => { const { customer } = request; return response.json(customer.statement); }) app.post('/deposit', verifyExistentAccountCpf, (request, response) => { const { description, amount} = request.body; const { customer } = request; const statementOperation = { description, amount, created_at: new Date(), type: "credit" } customer.statement.push(statementOperation); return response.status(201).send(); }) app.post('/withdraw', verifyExistentAccountCpf, (request, response) => { const { amount } = request.body; const { customer } = request; const balance = getBalance(customer.statement); if(balance < amount){ return response.status(400).json({error: "insuficient funds!"}) } const statementOperation = { amount, created_at: new Date(), type: 'debit', } customer.statement.push(statementOperation) return response.status(201).send(); }) app.get('/statement/date', verifyExistentAccountCpf, (request, response) => { const { customer } = request; const { date } = request.query; const dateFormat = new Date(date + "00:00"); const statement = customer.statement .filter(statement => statement.created_at .toDateString() === new Date(dateFormat).toDateString()); return response.json(statement); }) app.listen(3333);
import java.util.ArrayList; import java.util.Scanner; public class AverageOfSelectedNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<String> list = new ArrayList<>(); System.out.println("Input numbers, type 'end' to stop"); while (true){ String input = scanner.nextLine(); if (input.equals("end")){ break; } list.add(input); } System.out.println("Print the average of the negative numbers or the positive numbers? (n/p)"); String selection = scanner.nextLine(); if (selection.equals("n")){ double average = list.stream() .mapToInt(value -> Integer.valueOf(value)) .filter(value -> (value < 0)) .average() .getAsDouble(); System.out.println("Average of the negative numbers: " + average); } if (selection.equals("p")){ double average = list.stream() .mapToInt(value -> Integer.valueOf(value)) .filter(value -> (value > 0)) .average() .getAsDouble(); System.out.println("Average of the positive numbers: " + average); } } }
#include <iostream> #include <string> #include <sstream> #include "TreeNode.hpp" #include "NodeStack.hpp" #include "StringStack.hpp" using namespace std; string removeDoubleNegation(string expression) { string result = expression; size_t length = expression.length(); for (size_t i = 0; i < length - 2; ++i) { if (result[i] == '~' && result[i + 2] == '~') { result.erase(i, 4); length -= 2; --i; } } return result; } string replaceVariablesWithValues(string x, string values) { // Substitui a variável pelo seu valor (para casos 1 ou 2 dígitos) string result = ""; unsigned long int i = 0; while (i < x.size()) { string result = ""; unsigned long int i = 0; while (i < x.size()) { if (isdigit(x[i])) { int num = 0; if (i + 1 < x.size() && isdigit(x[i + 1])) { num = (x[i] - '0') * 10 + (x[i + 1] - '0'); i += 2; } else { num = x[i] - '0'; i++; } if (num >= 0 && num <= 99 && num < values.size()) { result += values[num]; } else { result += to_string(num); } } else { result += x[i]; i++; } } return result; } } bool isOperator (string x) { if(x == "~" || x == "|" || x == "&"){ return true; } else { return false; } } int getOperatorPrecedence(string op){ if(op == "|") return 1; if(op == "&") return 2; if(op == "~") return 3; return 0; } float evaluate(float a, float b, string op){ if(op == "|") return a || b; if(op == "&") return a && b; return 0; } float evaluate(float b, string op){ if(op == "~") return !b; return 0; } TreeNode* buildInfixExpressionTree(string infix){ NodeStack st; StringStack op_st; stringstream ss(infix); string token; while (ss >> token){ if(token == "("){ op_st.push(token); } else if(token == ")"){ while(op_st.getTop() != "("){ TreeNode* node = new TreeNode(op_st.getTop()); op_st.pop(); if(node->val == "~"){ node->right = st.getTop(); st.pop(); } else{ node->right = st.getTop(); st.pop(); node->left = st.getTop(); st.pop(); } st.push(node); } op_st.pop(); } else if (isOperator(token)) { while (!op_st.isEmpty() && op_st.getTop() != "(" && getOperatorPrecedence(token) <= getOperatorPrecedence(op_st.getTop())) { TreeNode* node = new TreeNode(op_st.getTop()); op_st.pop(); if (node->val == "~") { node->right = st.getTop(); st.pop(); } else { node->right = st.getTop(); st.pop(); node->left = st.getTop(); st.pop(); } st.push(node); } op_st.push(token); } else { TreeNode* node = new TreeNode(token); st.push(node); } } while(!op_st.isEmpty()){ TreeNode* node = new TreeNode(op_st.getTop()); op_st.pop(); if (node->val == "~") { node->right = st.getTop(); st.pop(); } else { node->right = st.getTop(); st.pop(); node->left = st.getTop(); st.pop(); } st.push(node); } return st.getTop(); } float evaluateInfixExpressionTree(TreeNode* root) { if (!root) { return 0; } if (!root->left && !root->right) { return stof(root->val); } if (root->val == "|") { float left = evaluateInfixExpressionTree(root->left); float right = evaluateInfixExpressionTree(root->right); return left || right; } else if (root->val == "&") { float left = evaluateInfixExpressionTree(root->left); float right = evaluateInfixExpressionTree(root->right); return left && right; } else if (root->val == "~") { float right = evaluateInfixExpressionTree(root->right); return !right; // Inverte o valor } return 0; } float completeEvaluate(string expression, string values) { if(expression.size() > 1){ string result = replaceVariablesWithValues(expression, values); string result2 = removeDoubleNegation(result); TreeNode* result3 = buildInfixExpressionTree(result2); float result4 = evaluateInfixExpressionTree(result3); return result4; } else if (values[0] == '0') { return 0; } else { return 1; } } float satisfiability(string expression, string& values) { for(unsigned long int i = 0; i < values.size(); i++){ if(values[i] == 'a'){ string case0 = values; case0[i] = '0'; float resultCase0 = satisfiability(expression, case0); string case1 = values; case1[i] = '1'; float resultCase1 = satisfiability(expression, case1); if(resultCase0 == 1 && resultCase1 == 1){ return 1; } else { return 0; } } if(values[i] == 'e'){ string case0 = values; case0[i] = '0'; float resultCase0 = satisfiability(expression, case0); string case1 = values; case1[i] = '1'; float resultCase1 = satisfiability(expression, case1); if(resultCase0 == 1 && resultCase1 == 1){ values[i] = 'a'; return 1; } else if(resultCase0 == 1){ values = case0; return 1; } else if(resultCase1 == 1){ values = case1; return 1; } else { return 0; } } } return completeEvaluate(expression, values); } string changeEtoA (string values){ string result = values; for(unsigned long int i = 0; i < values.size(); i++){ if(values[i] == 'e'){ result[i] = 'a'; } } return result; } int main(int argc, char *argv[]){ string expression = argv[2]; string values = argv[3]; float result; switch (argv[1][1]) { case 'a': result = completeEvaluate(expression, values); cout << result << endl; break; case 's': result = satisfiability(expression, values); values = changeEtoA(values); if(result == 1){ cout << result << " " << values << endl; } else { cout << result << endl; } } return 0; }
package com.example.currencydisplay.screen import android.content.IntentFilter import android.graphics.drawable.GradientDrawable.Orientation import android.net.ConnectivityManager import android.os.Bundle import android.view.View import android.widget.ProgressBar import android.widget.TextView import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.example.currencydisplay.utils.InternetBroadCastReceiver import com.example.currencydisplay.R import com.example.currencydisplay.screen.rv.ExchangeRatesAdapter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class MainActivity: AppCompatActivity(){ private val viewModel by viewModels<MainViewModel>() @Inject lateinit var exchangeRatesAdapter: ExchangeRatesAdapter private lateinit var infoDateTextView: TextView private lateinit var errorMessageTextView: TextView private lateinit var exchangeRatesRV: RecyclerView private lateinit var loadingIndicator: ProgressBar private val internetBroadCastReceiver = InternetBroadCastReceiver { internetIsActive -> if (internetIsActive) viewModel.load() } override fun onAttachedToWindow() { val filter = IntentFilter().apply { addAction(ConnectivityManager.CONNECTIVITY_ACTION) } registerReceiver(internetBroadCastReceiver, filter) super.onAttachedToWindow() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) infoDateTextView = findViewById(R.id.info_date_text_view) errorMessageTextView = findViewById(R.id.error_message) exchangeRatesRV = findViewById(R.id.exchange_rate_recycler_view) loadingIndicator = findViewById(R.id.loading_indicator) setupRv() setupObservers() } private fun setupRv(){ exchangeRatesRV.apply { adapter = exchangeRatesAdapter layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) } } private fun setupObservers(){ lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED){ launch { setupScreenStateObserver() } viewModel.setupSync() } } } private suspend fun setupScreenStateObserver(){ viewModel.screenState.collect{ state -> when(state){ is CurrencyScreenState.Success -> { errorMessageTextView.visibility = View.INVISIBLE loadingIndicator.visibility = View.INVISIBLE infoDateTextView.text = "Последнее обновление: " + state.data.date exchangeRatesAdapter.setExchangeRatesList( state.data.exchangeRate.values.toList() ) } is CurrencyScreenState.Loading -> { errorMessageTextView.visibility = View.INVISIBLE loadingIndicator.visibility = View.VISIBLE } is CurrencyScreenState.Error -> { loadingIndicator.visibility = View.INVISIBLE errorMessageTextView.visibility = View.VISIBLE infoDateTextView.text = state.message } } } } override fun onDetachedFromWindow() { unregisterReceiver(internetBroadCastReceiver) super.onDetachedFromWindow() } }
package org.saled package data.pipeline.csv import data.structures.table.* import java.nio.file.Path import scala.collection.parallel.CollectionConverters.ImmutableIterableIsParallelizable import scala.io.{BufferedSource, Source} trait FromCsv { private val explodeCsvString: (String, String) => List[List[String]] = (delimiter: String, csvContent: String) => { val splitRows: List[String] = csvContent.split("\n").toList splitRows.par .map((r: String) => { r.split(delimiter).toList }) .toList } private val defineCsvSchema: (List[List[String]], CsvOptions) => Schema = (csv: List[List[String]], csvOptions: CsvOptions) => { if (csvOptions.hasSchema.nonEmpty) { csvOptions.hasSchema.get } else if (csvOptions.hasHeader.get) { val headerDDL = csv.head.map((c: String) => { s"$c String" }).mkString(",") val csvHeaderDDL: List[ColumnDefinition] = SchemaDDL.createSchema(headerDDL) SchemaBuilder().withSchema(csvHeaderDDL).build() } else { val csvInferredSchemaDDL: List[ColumnDefinition] = SchemaDDL.inferSchemaDDL(csv.head.size) SchemaBuilder().withSchema(csvInferredSchemaDDL).build() } } def fromCsv(csvString: String, csvOptions: CsvOptions): DataFrame = { val explodedCsv: List[List[String]] = explodeCsvString(csvOptions.hasSeparator.get, csvString) val tableSchema: Schema = defineCsvSchema(explodedCsv, csvOptions) val csv: List[List[String]] = { if (csvOptions.hasHeader.get) { explodedCsv.tail } else { explodedCsv } } ToDataFrame.createDataFrame(csv, tableSchema) } def fromCsv(csvPath: Path, csvOptions: CsvOptions): DataFrame = { val file: BufferedSource = Source.fromFile(csvPath.toUri) val fileContents: String = file.getLines().mkString("\n") fromCsv(fileContents, csvOptions) } }
// EXERCISE 7 // Return an array with a bank account object with the lowest balance but not broke ( balance > 0 ) // In case there is no account that has balance > 0 return an empty array // Array example: bankAccounts in /data/data.js // getClientWithLeastBalance(bankAccounts) => [{ name: 'SomeName', balance: 32, ... }] export function getClientWithLeastPositiveBalance(array) { let minBalance = Number.MAX_VALUE; let result = []; for (let account of array) { if (account.balance > 0 && account.balance < minBalance) { minBalance = account.balance; result = [account]; } else if (account.balance > 0 && account.balance === minBalance) { result.push(account); } } return result; } // === TEST YOURSELF === // Once you're finished run the test with "npm run test-7" // If the test has all tests passed, switch to the next exercise file // If any of the tests fails, refactor the code and run the test command after you've fixed the function
import React from "react"; import styled from "styled-components"; import { PancakeRoundIcon } from "../Svg"; import Text from "../Text/Text"; import Skeleton from "../Skeleton/Skeleton"; import { Colors } from "../../theme"; export interface Props { color?: keyof Colors; cakePriceUsd?: number; tokenAddress: string; tokenPriceDecimal: number; } const PriceLink = styled.a` display: flex; align-items: center; svg { transition: transform 0.3s; } :hover { svg { transform: scale(1.2); } } `; const CakePrice: React.FC<Props> = ({ cakePriceUsd, color = "textSubtle", tokenAddress, tokenPriceDecimal }) => { return cakePriceUsd ? ( <PriceLink href={`/swap?outputCurrency=${tokenAddress}`} target="_blank" > {/* <PancakeRoundIcon width="24px" mr="8px" /> */} <Text color={color} bold>{`$${cakePriceUsd.toFixed(tokenPriceDecimal)}`}</Text> </PriceLink> ) : ( <Skeleton width={80} height={24} /> ); }; export default React.memo(CakePrice);
import mongoose from "mongoose"; import validator from "validator"; import bcrypt from "bcrypt"; import jwt from "jsonwebtoken"; import crypto from "crypto"; import * as dotenv from "dotenv"; dotenv.config(); const schema = new mongoose.Schema({ name: { type: String, required: [true, "please enter your name"], }, email: { type: String, required: [true, "Please enter your email"], unique: [true, "Email already exist"], validate: validator.isEmail, }, password: { type: String, required: [true, "Please enter your Password"], minLength: [6, "Password must be at least 6 characters long"], select: false, }, address: { type: String, required: true, }, city: { type: String, required: true, }, country: { type: String, required: true, }, pinCode: { type: String, required: true, }, role: { type: String, enum: ["admin", "user"], default: "user", }, avatar: { public_id: String, url: String, }, // confirmPassword: { // type: String, // required: [true, 'Please confirm your password.'] // }, otp:Number, otp_expire:Date // passwordResetToken: String, // passwordResetTokenExpires: Date, }); schema.pre("save", async function (next) { if (!this.isModified("password")) return next(); this.password = await bcrypt.hash(this.password, 10); }); schema.methods.comparePassword = async function (candidatePassword) { const user = this; const match = await bcrypt.compare(candidatePassword, user.password); return match; }; schema.methods.generateToken = function () { return jwt.sign({ _id: this._id }, process.env.JWT_SECRET, { expiresIn: "3d", }); }; //Instance method schema.methods.createPasswordToken = function () { const resetToken = crypto.randomBytes(32).toString("hex"); this.passwordResetToken = crypto .createHash("sha256") .update(resetToken) .digest("hex"); this.passwordResetTokenExpires = Date.now() + 15 * 60 * 1000; console.log(resetToken, this.passwordResetToken); return resetToken; }; export const User = mongoose.model("User", schema);
/* * Copyright (c) 2022 Huawei Device Co., 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. */ #include "text_style.h" #include "typography_style.h" #include "gtest/gtest.h" #include <climits> #include <vector> #include <string> using namespace rosen; using namespace testing; using namespace testing::ext; namespace OHOS { class OH_Drawing_TypographyStyleTest : public testing::Test { }; /* * @tc.name: OH_Drawing_TypographyStyleTest001 * @tc.desc: test for creating TypographyStyle * @tc.type: FUNC */ HWTEST_F(OH_Drawing_TypographyStyleTest, OH_Drawing_TypographyStyleTest001, TestSize.Level1) { TypographyStyle typoStyle; TextStyle textstyle = typoStyle.GetTextStyle(); EXPECT_EQ(typoStyle.fontWeight_, textstyle.fontWeight_); EXPECT_EQ(typoStyle.fontStyle_, textstyle.fontStyle_); EXPECT_EQ(typoStyle.fontSize_, textstyle.fontSize_); EXPECT_EQ(typoStyle.locale_, textstyle.locale_); EXPECT_EQ(typoStyle.height_, textstyle.height_); EXPECT_EQ(typoStyle.hasHeightOverride_, textstyle.hasHeightOverride_); } /* * @tc.name: OH_Drawing_TypographyStyleTest002 * @tc.desc: test for TypographyStyle EffectiveAlign * @tc.type: FUNC */ HWTEST_F(OH_Drawing_TypographyStyleTest, OH_Drawing_TypographyStyleTest002, TestSize.Level1) { TypographyStyle typoStyle; typoStyle.textAlign_ = TextAlign::START; TextAlign textAlign = typoStyle.EffectiveAlign(); EXPECT_EQ(textAlign, TextAlign::LEFT); typoStyle.textAlign_ = TextAlign::END; textAlign = typoStyle.EffectiveAlign(); EXPECT_EQ(textAlign, TextAlign::RIGHT); typoStyle.textAlign_ = TextAlign::CENTER; textAlign = typoStyle.EffectiveAlign(); EXPECT_EQ(textAlign, TextAlign::CENTER); } }
import { Source, SchemaPointerSingle, DocumentLoader, SingleFileOptions, } from "@graphql-tools/utils"; /** * Additional options for loading from a JSON file */ export interface JsonFileLoaderOptions extends SingleFileOptions {} /** * This loader loads documents and type definitions from JSON files. * * The JSON file can be the result of an introspection query made against a schema: * * ```js * const schema = await loadSchema('schema-introspection.json', { * loaders: [ * new JsonFileLoader() * ] * }); * ``` * * Or it can be a `DocumentNode` object representing a GraphQL document or type definitions: * * ```js * const documents = await loadDocuments('queries/*.json', { * loaders: [ * new GraphQLFileLoader() * ] * }); * ``` */ export declare class JsonFileLoader implements DocumentLoader { loaderId(): string; canLoad( pointer: SchemaPointerSingle, options: JsonFileLoaderOptions ): Promise<boolean>; canLoadSync( pointer: SchemaPointerSingle, options: JsonFileLoaderOptions ): boolean; load( pointer: SchemaPointerSingle, options: JsonFileLoaderOptions ): Promise<Source>; loadSync( pointer: SchemaPointerSingle, options: JsonFileLoaderOptions ): Source; }
#include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #define _USE_MATH_DEFINES #include <cmath> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iostream> #include <iomanip> #include <iterator> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <tuple> #include <utility> #include <vector> using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() const int INF = 0x3f3f3f3f; const long long LINF = 0x3f3f3f3f3f3f3f3fLL; const double EPS = 1e-8; const int MOD = 1000000007; // const int MOD = 998244353; const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1}; // const int dy[] = {1, 1, 0, -1, -1, -1, 0, 1}, // dx[] = {0, -1, -1, -1, 0, 1, 1, 1}; struct IOSetup { IOSetup() { cin.tie(nullptr); ios_base::sync_with_stdio(false); cout << fixed << setprecision(20); cerr << fixed << setprecision(10); } } iosetup; /*-------------------------------------------------*/ struct UnionFind { UnionFind(int n) : data(n, -1) {} int root(int ver) { return data[ver] < 0 ? ver : data[ver] = root(data[ver]); } void unite(int ver1, int ver2) { ver1 = root(ver1); ver2 = root(ver2); if (ver1 != ver2) { if (data[ver1] > data[ver2]) swap(ver1, ver2); data[ver1] += data[ver2]; data[ver2] = ver1; } } bool same(int ver1, int ver2) { return root(ver1) == root(ver2); } int size(int ver) { return -data[root(ver)]; } private: vector<int> data; }; int main() { int n; cin >> n; vector<vector<int> > l(26); REP(i, n) { string s; cin >> s; vector<bool> exist(26, false); for (char c : s) exist[c - 'a'] = true; REP(j, 26) { if (exist[j]) l[j].emplace_back(i); } } UnionFind uf(n); REP(i, 26) { FOR(j, 1, l[i].size()) uf.unite(l[i][j - 1], l[i][j]); } set<int> roots; REP(i, n) roots.emplace(uf.root(i)); cout << roots.size() << '\n'; return 0; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title></title> <link rel="stylesheet" type="text/css" href="assets/styles.css" /> <script src="https://kit.fontawesome.com/4aa4b56328.js" crossorigin="anonymous" ></script> </head> <body> <div id="top-bar"> <div id="left-side"> <div id="logo-container"> <div id="logo-img-container"> <img src="assets/images/player-logo.png" /> </div> <div id="player-name"> <span>Beat</span> <h4>Box</h4> </div> </div> <div id="favourites"><a href="">Favourites</a></div> </div> <div id="right-side"> <div id="search-box"> <button id="search-icon" class="search-buttons"> <i class="fa-solid fa-magnifying-glass"></i> </button> <input placeholder="Search" /> <button id="audio-icon" class="search-buttons"> <i class="fa-solid fa-microphone"></i> </button> </div> <div id="notification-container"> <i class="fa-regular fa-bell"></i> </div> <div id="profile-img-container"> <img src="assets/images/cr7.jpg" /> </div> </div> </div> <main> <div id="main-content"> <section id="home-carousel"> <div id="carousel-display"> <div class="carousel-img-container"> <img src="assets/images/carousel-2.jpg" /> </div> <div id="mid-container" class="carousel-img-container"> <img src="assets/images/carousel-1.jpg" /> </div> <div class="carousel-img-container"> <img src="assets/images/carousel-5.jpg" /> </div> </div> </section> <section id="latest-release"> <h4 class="section-heading">Latest Release</h4> <div id="latest-release-container"> <div class="latest-release-item"> <a class="lat-rel-img" href="single-playlist.html" ><img src="assets/images/02NEWMUSIC-DERULO-superJumbo.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </a> <div class="song-details"> <h6 class="song-name">Wiggle</h6> <span>aug</span> </div> <div class="options"> <label for="latest-release-checkbox1" ><i class="fas fa-ellipsis-h"></i ></label> <input type="checkbox" id="latest-release-checkbox1" /> <div class="latest-release-dropdown"> <div class="drop-item"> <!-- if user clicks on play now button, he/she will be taken to the single playlist page --> <p> <i class="fas fa-play-circle"></i> <a href="Single Playlist Screen.html">Play Now</a> </p> </div> <div class="drop-item"> <p><i class="fas fa-list-ul"></i> Add to Queue</p> </div> <div class="drop-item"> <p><i class="fas fa-music"></i> Add to playlist</p> </div> <div class="drop-item"> <p><i class="fas fa-info-circle"></i> Get Info</p> </div> </div> </div> <div class="song-duration">4.06</div> </div> <div class="latest-release-item"> <a class="lat-rel-img" href="single-playlist.html" ><img src="assets/images/02NEWMUSIC-DERULO-superJumbo.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </a> <div class="song-details"> <h6 class="song-name">Wiggle</h6> <span>aug</span> </div> <div class="options"> <label for="latest-release-checkbox2" ><i class="fas fa-ellipsis-h"></i ></label> <input type="checkbox" id="latest-release-checkbox2" /> <div class="latest-release-dropdown"> <div class="drop-item"> <!-- if user clicks on play now button, he/she will be taken to the single playlist page --> <p> <i class="fas fa-play-circle"></i> <a href="Single Playlist Screen.html">Play Now</a> </p> </div> <div class="drop-item"> <p><i class="fas fa-list-ul"></i> Add to Queue</p> </div> <div class="drop-item"> <p><i class="fas fa-music"></i> Add to playlist</p> </div> <div class="drop-item"> <p><i class="fas fa-info-circle"></i> Get Info</p> </div> </div> </div> <div class="song-duration">4.06</div> </div> <div class="latest-release-item"> <a class="lat-rel-img" href="single-playlist.html" ><img src="assets/images/02NEWMUSIC-DERULO-superJumbo.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </a> <div class="song-details"> <h6 class="song-name">Wiggle</h6> <span>aug</span> </div> <div class="options"> <label for="latest-release-checkbox3" ><i class="fas fa-ellipsis-h"></i ></label> <input type="checkbox" id="latest-release-checkbox3" /> <div class="latest-release-dropdown"> <div class="drop-item"> <!-- if user clicks on play now button, he/she will be taken to the single playlist page --> <p> <i class="fas fa-play-circle"></i> <a href="Single Playlist Screen.html">Play Now</a> </p> </div> <div class="drop-item"> <p><i class="fas fa-list-ul"></i> Add to Queue</p> </div> <div class="drop-item"> <p><i class="fas fa-music"></i> Add to playlist</p> </div> <div class="drop-item"> <p><i class="fas fa-info-circle"></i> Get Info</p> </div> </div> </div> <div class="song-duration">4.06</div> </div> <div class="latest-release-item"> <a class="lat-rel-img" href="single-playlist.html" ><img src="assets/images/02NEWMUSIC-DERULO-superJumbo.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </a> <div class="song-details"> <h6 class="song-name">Wiggle</h6> <span>aug</span> </div> <div class="options"> <label for="latest-release-checkbox4" ><i class="fas fa-ellipsis-h"></i ></label> <input type="checkbox" id="latest-release-checkbox4" /> <div class="latest-release-dropdown"> <div class="drop-item"> <!-- if user clicks on play now button, he/she will be taken to the single playlist page --> <p> <i class="fas fa-play-circle"></i> <a href="Single Playlist Screen.html">Play Now</a> </p> </div> <div class="drop-item"> <p><i class="fas fa-list-ul"></i> Add to Queue</p> </div> <div class="drop-item"> <p><i class="fas fa-music"></i> Add to playlist</p> </div> <div class="drop-item"> <p><i class="fas fa-info-circle"></i> Get Info</p> </div> </div> </div> <div class="song-duration">4.06</div> </div> </div> </section> <section id="popular-artists"> <h4 class="section-heading">Popular Artists</h4> <div id="popular-artists-container"> <a class="artist-item" href="single-playlist.html"> <div class="artist-img-container"> <img src="assets/images/ar-rahman.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </div> <h6>Ar Rahman</h6> </a> <a class="artist-item" href="single-playlist.html"> <div class="artist-img-container"> <img src="assets/images/sid.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </div> <h6>Sid Sriram</h6> </a> <a class="artist-item" href="single-playlist.html"> <div class="artist-img-container"> <img src="assets/images/zayn.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </div> <h6>Zayn Malik</h6> </a> <a class="artist-item" href="single-playlist.html"> <div class="artist-img-container"> <img src="assets/images/ariji.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </div> <h6>Arijit Singh</h6> </a> <a class="artist-item" href="single-playlist.html"> <div class="artist-img-container"> <img src="assets/images/sonu.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </div> <h6>Sonu Nigam</h6> </a> <a class="artist-item" href="single-playlist.html"> <div class="artist-img-container"> <img src="assets/images/justin.jpg" /> <div class="play-btn"><i class="fa-solid fa-play"></i></div> </div> <h6>Justin Beiber</h6> </a> </div> </section> <section id="stations"> <div id="station-container"> <div id="station-logo-container"> <div id="station-logo-img-contaner"> <img src="assets/images/player-logo.png" /> </div> <span>Stations</span> </div> <div id="station-item-container"> <div id="love" class="station-item"> <span>Love</span> </div> <div id="retro" class="station-item"><span>Retro</span></div> <div id="chill" class="station-item"><span>Chill</span></div> <div id="workout" class="station-item"><span>Workout</span></div> <div id="rock" class="station-item"><span>Rock</span></div> <div id="pop" class="station-item"> <span>Pop</span> </div> </div> </div> </section> <section id="mood-carousel"> <div id="mood-carousel-container"> <div class="outer-div"> <div id="party" class="inner-div"> <span>Party</span> </div> </div> <div class="outer-div"> <div class="inner-div"> <span>Electronic</span> </div> </div> <div class="outer-div"> <div class="inner-div"> <span>Travel</span> </div> </div> </div> </section> <section id="latest-english"> <h4 class="section-heading">Latest English</h4> <div id="latest-english-container"> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-1.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-2.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-3.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-4.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-5.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-5.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> </div> </section> <section id="latest-hindi"> <h4 class="section-heading">Latest Hindi</h4> <div id="latest-english-container"> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-1.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-2.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-3.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-4.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-5.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> <div class="latest-item"> <div class="latest-img-container"> <img src="assets/images/english-5.jpg" /> </div> <div class="latest-song-details"> <h6 class="latest-song-name">Wiggle</h6> <span>aug</span> </div> </div> </div> </section> <section id="music-player"></section> </div> <aside> <div id="player-queue"> <div id="player-queue-header"> <h6 id="queue-heading">PlayList</h6> <div id="queue-options"> <div id="queue-dropdown-button"> <a>Queue <i class="fa-solid fa-angle-down"></i></a> </div> <div id="queue-dropdown-list"> <p><a href="">Play Lists</a></p> <hr /> <p><a href="">Favourite Song</a></p> </div> </div> </div> <ol id="queue-list-container"> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-5.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-5.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-2.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-1.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-4.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-6.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-1.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> <li> <div class="song-box"> <div class="queue-list-img-container"> <img src="assets/images/english-2.jpg" /> </div> <div class="queue-song-details"> <h6>wiggle</h6> <span>Jason Derulo</span> </div> </div> <div class="heart-icon"> <i class="fa-regular fa-heart"></i> </div> </li> </ol> </div> </aside> </main> <footer> <div id="player-bar"> <div id="player-bar-left"> <div id="current-song-box"> <div id="song-img-container"> <img src="assets/images/english-1.jpg" /> </div> <div id="current-song-details"> <h5>Imagine By John</h5> <span> John Lenon </span> </div> </div> <div id="heart-ban-container"> <span> <i class="fa-regular fa-heart"></i> </span> <i class="fa-solid fa-ban"></i> </div> </div> <div id="player-bar-center"> <div id="controllers-container"> <div id="shuffle"> <i class="fa-solid fa-shuffle"></i> </div> <div id="prev-btn"><i class="fa-solid fa-backward-step"></i></div> <div id="pause-btn"> <i class="fa-regular fa-circle-pause"></i> </div> <div id="next-btn"> <i class="fa-solid fa-forward-step"></i> </div> <div id="repeat-btn"> <i class="fa-solid fa-repeat"></i> </div> </div> <div id="progress-bar"> <div id="start-time" class="time">1:39</div> <input type="range" min="0" max="100" class="slider" id="my-range" /> <div id="start-time" class="time">4:00</div> </div> </div> <div id="player-bar-right"> <i class="fa-solid fa-computer"></i> <i class="fa-solid fa-volume-high"></i> <div> <input type="range" min="0" max="100" class="slider" id="volume-range" /> </div> <i class="fa-solid fa-up-right-and-down-left-from-center"></i> </div> </div> </footer> </body> </html>
import KanbanAPI from "./api.js"; import DropZone from "./DropZone.js"; import Item from "./Item.js"; export default class Column { /* this class is a single column from UI */ constructor(id, title) { /* From kan.js */ const topDropZone = DropZone.createDropZone(); /* from dropzone.js */ this.elements = {}; /* new object to store HTML elements */ this.elements.root = Column.createRoot(); this.elements.title = this.elements.root.querySelector( ".kanban__column-title" ); this.elements.items = this.elements.root.querySelector( ".kanban__column-items" ); this.elements.addItem = this.elements.root.querySelector(".kanban__add-item"); this.elements.root.dataset.id = id; /* column id */ this.elements.title.textContent = title; this.elements.items.appendChild(topDropZone); this.elements.addItem.addEventListener("click", () => { const newItem = KanbanAPI.insertItem(id, "", ""); /* Take input and render it */ this.renderItem(newItem); }); /* After that render every item */ /* From API.js */ KanbanAPI.getItems(id).forEach((item) => { this.renderItem(item); }); } static createRoot() { const range = document.createRange(); /* Range of elements */ range.selectNode(document.body); /* Select the entire HTML body */ return range.createContextualFragment(` <div class="kanban__column"> <div class="kanban__column-title"></div> <div class="kanban__column-items"> <button class="kanban__add-item" type="button">Add New</button> </div> `).children[0]; /* Represents the first child , that is first div here */ } renderItem(data) { const item = new Item(data.id, data.content, data.content2); this.elements.items.appendChild(item.elements.root); } }
#include <Ethernet.h> #include <TimerOne.h> #include "LPD6803.h" #include <math.h> #include "ProgressBar.h" #include <SPI.h> #include <Time.h> #define WAITTIME 2000 #define LITER_MAX 10000 #define NUM_LEDS 50 float curr_liters = 0; int knipperd = 0; int w = 1000; //wait time for debug // Choose which 2 pins you will use for output. // Can be any valid output pins. int dataPin = 2; // 'yellow' wire int clockPin = 3; // 'green' wire // Don't forget to connect 'blue' to ground and 'red' to +5V // Timer 1 is also used by the strip to send pixel clocks // Set the first variable to the NUMBER of pixels. 20 = 20 pixels in a row LPD6803 strip = LPD6803(NUM_LEDS, dataPin, clockPin); //Mac address int debug = 1; byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x78, 0x62 }; byte server[] = { 130,89,149,242}; //vestingbar.nl EthernetClient client; //dhcp renewal info int h, m,s,d; time_t t; void setup(){ //debugging Serial.begin(9600); strip.setCPUmax(50); // start with 50% CPU usage. up this if the strand flickers or is slow delay(w); strip.begin(); delay(w); strip.show(); delay(w); //Returns 1 on succesfull DHCP request, 0 on failure if(Ethernet.begin(mac) == 0){ Serial.println("Failed to configure Ethernet using DHCP"); // no point in carrying on, so do nothing forevermore: for(;;) ; } // print your local IP address: Serial.println(Ethernet.localIP()); // get info for dhcp renewal t = now(); h = hour(t); m = minute(t); s = second(t); d = day(t); delay(1000); } void debugmsg(String msg){ if(debug){ Serial.println(msg); } } void loop(){ debugmsg("DHCP Check"); dhcpCheck(); debugmsg("Getting beer info"); getBierInfo(); debugmsg("Setting new literMeter"); ProgressBar literMeter = ProgressBar(&strip, LITER_MAX); debugmsg("Fixing colour"); literMeter.setColor(31,28,0); literMeter.setProgress(curr_liters); literMeter.update(200); debugmsg("Checking if I have to blink"); if (fmod(curr_liters,200) < 40 && curr_liters > 40) { if(!knipperd){ debugmsg("Tank leeg!"); int j; for (j = 0 ; j < 10 ; j++) { literMeter.setColor(31,0,0); literMeter.update(200); literMeter.setColor(31,28,0); literMeter.update(200); } knipperd = 1; } }else{ knipperd = 0; } delay(WAITTIME); } void getBierInfo(){ //Server connection connectToVB(); int bytesAvail = client.available(); if(bytesAvail){ readPastHeader(&client); debugmsg("Read: "); String result = ""; char c = client.read(); while(c != -1){ Serial.print(c); result.concat(c); c = client.read(); } char charBuf[50]; result.toCharArray(charBuf,50); curr_liters = atof(charBuf); } } int connectToVB(){ client.stop(); delay(2000); if(client.connect(server, 80)){ debugmsg("Connected"); client.println("GET /docs/bierstanden.txt HTTP/1.0"); client.println(); delay(2000); return 1; } Serial.println("Connection failed"); return 0; } void dhcpCheck(){ time_t n = now(); if((hour(n) - h) > 23){ byte i = Ethernet.maintain(); debugmsg("Requested DHCP update, "); switch (i){ case 0: debugmsg("nothing happened"); break; case 1: debugmsg("renew failed"); break; case 2: debugmsg("renew success"); h = hour(n); break; case 3: debugmsg("rebind fail"); break; case 4: debugmsg("rebind success"); h = hour(n); break; default: Serial.println("Error getting DHCP!"); break; } } } bool readPastHeader(Client *pClient) { bool bIsBlank = true; while(true) { if (pClient->available()) { char c = pClient->read(); if(c=='\r' && bIsBlank) { // throw away the /n c = pClient->read(); return true; } if(c=='\n') bIsBlank = true; else if(c!='\r') bIsBlank = false; } } }
package Beaver::Bootstrap3::Widget::Form; use Mojo::Base 'Beaver::Bootstrap3::Widget'; use Mojo::ByteStream 'b'; use Mojo::Collection; use Mojo::Util qw(xml_escape); use List::Util qw(any); use Data::Dumper; has buttons => sub {new Mojo::Collection}; sub init { my $self = shift; $self->SUPER::init(@_); push @{ $self->buttons }, grep { ref $$_{-hide} ? $$_{-hide}->($self->c) : exists $$_{-hide} ? !$$_{-hide} : 1 } grep { ref $$_{-show} ? $$_{-show}->($self->c) : exists $$_{-show} ? $$_{-show} : 1 } grep { @{ $$_{-actions}||[] } ? any { $self->c->action eq $_ } @{ $$_{-actions}||[] } : 1 } @{ $self->props->{buttons}||[] }; $self; } sub field { my ($self, $el, $readonly) = @_; if (ref $el->[0] eq 'ARRAY') { b $self->c->widget('row', sub {return b join('', map {$self->field($_, $readonly)} @$el)}); } else { map { if (ref $_ eq 'HASH') { $_->{-readonly} = $readonly; $_->{value} = $self->props->{data}{$_->{name}}; } } @$el; b $self->c->widget(@$el); } } 1; =encoding utf8 =head1 NAME Beaver::Bootstrap3::Widget::Form - form widget =head1 SYNOPSIS <%= widget form => { -label => 'Edit record', -buttons => [ { -default => 'update', -actions => [qw(edit)] }, { -default => 'edit', -actions => [qw(item)] }, { -tag => 'a', -context => 'danger', href => sub { join '/', '', $_[0]->entity, ($_[0]->action eq 'edit' ? $_[0]->id : ()) }, -label => 'Cancel', -actions => [qw(item edit)] }, ], -fields => [ [ form-input => { name => 'label', _form => [qw(form-update)], }, ], ], } => begin %>Correct and save<% end %> =head1 DESCRIPTION L<Beaver::Bootstrap3::Widget::Form> provides pseudo-form component widget backend for L<Beaver::Plugin::Widgets>. Pseudo-form is area with title, set of buttons and set of fields. This is not real form. Submit form creates on the fly on button click events. =head1 PROPERTIES L<Beaver::Bootstrap3::Widget::Form> implements following properties. =head2 buttons <%= widget form => { -buttons => [ { predefined => 'login', }, { predefined => 'register', }, { predefined => 'remind', }, ], } => begin %>Authorization<% end %> Set of buttons which will be displayed on the top row of form. =head1 SEE ALSO L<Mojolicious>, L<Beaver::Plugin::Widgets>. =cut __DATA__ @@ widgets/form.html.ep <div class="container-fluid pt-20"> <div class="row"> <div class="col-md-4"> % if ($wg->props->{label}) { <h4><%= $wg->props->{label} %></h4> % } </div> <div class="col-md-8 text-right"> % for my $btn ($wg->buttons->each) { <%= widget button => ($btn) %> % } </div> </div> % for my $el (@{ $wg->props->{fields} || [] }) { <%= $wg->field($el, $wg->props->{readonly}) %> % } <div class="row"> <div class="col-md-12"> <%= $wg->content %> </div> </div> </div>
# Lambda-AWS Automatizar tareas utilizando AWS Lambda junto con otros servicios de AWS. Automatizaremos la copia de archivos desde un bucket de Amazon S3 a otro bucket. la función Lambda se ejecutará automáticamente y copiará ese archivo al bucket-destino. Esto automatiza la tarea de copiar archivos entre buckets de S3 cuando se producen cambios en el bucket-origen. Arquitectura: 1) Amazon S3 Buckets: Tendremos dos buckets de S3, uno llamado bucket-origen desde donde copiaremos archivos y otro llamado bucket-destino donde copiaremos los archivos. 2) AWS Lambda: Crearemos una función Lambda que se ejecutará cada vez que se cargue un archivo en el bucket-origen. Esta función copiará automáticamente el archivo al bucket-destino. Pasos para configurar la automatización: 1) Crea dos buckets de S3: bucket-origen y bucket-destino. 2) Crea una función Lambda en la consola de AWS Lambda. 3) Configura el disparador de la función Lambda para que esté vinculado al bucket-origen y se ejecute cuando se cargue un archivo en ese bucket. 4) Copia y pega el código Python de la función Lambda en el editor de código de la consola de Lambda. 5) Asegúrate de que la función Lambda tenga permisos para acceder a los buckets de S3. Puedes configurar los permisos en la pestaña "Permissions" (Permisos) de la consola de Lambda. 6) Guarda y despliega la función Lambda. Pasos para configurar la automatización: 1) Crea un bucket de Amazon S3 que contenga el archivo CSV que deseas procesar. 2) Crea una tabla en Amazon DynamoDB donde deseas cargar los datos transformados. 3) Crea una función Lambda en la consola de AWS Lambda. 4) Configura el disparador de la función Lambda para que esté vinculado al bucket de S3 y se ejecute cuando se cargue un archivo CSV en ese bucket. 5) Copia y pega el código Python de la función Lambda en el editor de código de la consola de Lambda. 6) Asegúrate de que la función Lambda tenga permisos para acceder a los buckets de S3 y a la tabla de DynamoDB. Puedes configurar los permisos en la pestaña "Permissions" (Permisos) de la consola de Lambda. 7) Guarda y despliega la función Lambda. Ahora, cada vez que se cargue un archivo CSV en el bucket de S3, la función Lambda se ejecutará automáticamente, realizará la transformación de datos y cargará los datos transformados en la tabla de DynamoDB. Esto automatiza parte del proceso ETL en AWS. Asegúrate de ajustar los nombres de los buckets y la tabla, así como de definir la transformación de datos adecuada para tu caso específico
--- title: "LiDARでスキャンしたデータをブラウザを使ってLooking Glass Portraitに表示するまで" # 記事のタイトル emoji: "📺" # アイキャッチとして使われる絵文字(1文字だけ) type: "tech" # tech: 技術記事 / idea: アイデア記事 topics: ["LiDAR", "Looking Glass"] # タグ。["markdown", "rust", "aws"]のように指定する published: true # 公開設定(falseにすると下書き) --- # はじめに Looking Glass Portrait が届いたので、LiDARでスキャンした3Dデータを、ブラウザ+WebGL(three.js)を使って表示してみました。 この記事は「[LiDARでスキャンしたデータをブラウザで表示するまで](https://zenn.dev/mganeko/articles/lidar-aframe)」の続編です。 # 準備 ## 動作環境 こちらの環境で実行しています。 - ブラウザ: Chrome 92 (arm64) - OS: macOS Big Sur (M1) ## HoloPlay Service Looking Glass Portraitを使うには、まず公式のソフトウェアをインストールし、デバイスのセットアップを済ませておきます。 - HoloPlay Service ... https://lookingglassfactory.com/software#holoplay-service ## スキャンアプリ アプリは複数ありますが、主にこちらを利用しています。 - [Polycam](https://apps.apple.com/jp/app/polycam-lidar-3d-スキャナー/id1532482376) ... データのエクスポート機能は有料 - [3d Scanner App](https://apps.apple.com/jp/app/3d-scanner-app/id1419913995) ... 無料 - [Scaniverse](https://apps.apple.com/jp/app/scaniverse-lidar-3d-scanner/id1541433223) ... Pro版の機能も2021年8月に無料に ## 3Dデータ iOSの標準ではデータ形式はUSDZですが、Webブラウザで扱いやすいように他の形式を使います。 - GLB形式(GLTF形式) スキャナプリからシェア(エクスポート)する際に、形式を選べることが多いです(形式の変換は有料のアプリもあります) ## 3D表示 ブラウザで扱うために、WebGLを使ったライブラリを活用します。今回はthree.jsをベースにした、Looking Glass公式の[holoplay.js](https://docs.lookingglassfactory.com/developer-tools/three)を利用しました。 - Holoplay.js ... https://docs.lookingglassfactory.com/developer-tools/three ### インストール方法 [こちら](https://docs.lookingglassfactory.com/developer-tools/three/setup#quick-install-with-npm)にある通り、node.js + npm の環境を用意した後に、npmでインストールすることができます。 ``` $ npm install holoplay ``` あるいは、こちにあるリンクから、ビルド済みのファイルをダウンロードできます。(zip圧縮されているので、解凍して利用してください) - First Time Usage ... https://docs.lookingglassfactory.com/developer-tools/three/setup#first-time-usage - "You can download our bundle here" ... https://s3.amazonaws.com/static-files.lookingglassfactory.com/HoloplayJS/Holoplayjs-1.0.3.zip ※ Holoplay.jsのバージョンが上がるとファイルのURLも変更になるので、最新版をご確認ください。 今回は前者(npm)でインストールした場合を記載します。npmで違う場所にインストールした場合や、直接ファイルをダウンロードをダウンロードした場合は、自分の環境に合わせてパスを変更してください。 # 実装 公式のガイド「[Creating Your First HoloPlay.js App](https://docs.lookingglassfactory.com/developer-tools/three/setup#creating-your-first-holoplay-js-app)」と、サンプル「[Load gLTF Model](https://docs.lookingglassfactory.com/developer-tools/three/examples#load-gltf-model)」のソースを参考に実装します。 ## シンプルなGLB形式の表示 ### 基本のコード例 GLB/GLTFの場合は、three/examples/js/loaders/GLTFLoader.js を使います。 ```html <!DOCTYPE HTML> <html> <body> <script src="node_modules/three/build/three.js"></script> <script src="node_modules/holoplay/dist/holoplay.js"></script> <script src="node_modules/three/examples/js/loaders/GLTFLoader.js"></script> <script> // -- カメラ、シーンを用意 -- const scene = new THREE.Scene(); const camera = new HoloPlay.Camera(); const renderer = new HoloPlay.Renderer(); document.body.appendChild(renderer.domElement); // -- 光源を用意 -- const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1); directionalLight.position.set(0, 1, 2); scene.add(directionalLight); const ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.4); scene.add(ambientLight); // -- GLB形式のモデルを読み込み -- let model = new THREE.Group(); // モデルをラップして、扱いやすくしてく const modelFile = 'path/to/your/model.glb'; // ※モデルのパス(URL)に書き換えてください new THREE.GLTFLoader().load(modelFile, (gltf) => { model.add(gltf.scene); scene.add(model); }); // -- 描画 -- function update(time) { requestAnimationFrame(update); // -- モデルを回転する -- let duration = 20000; if (model) { model.rotation.y = (Math.PI) * (time / duration); } renderer.render(scene, camera); } requestAnimationFrame(update); </script> </body> </html> ``` ### 実行 実行にはローカルにWebサーバーを立てて、ファイル一式をそこに配置します。 エディターにVS Codeを使っている場合は、[Live Server](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer)を利用すると便利です。Microsoftからも[Live Preview](https://marketplace.visualstudio.com/items?itemName=ms-vscode.live-server)のプレビュー版が公開されているので、こちらを使うのもありです(試してません) Looking Glass に表示するには次の手順を踏みます。 - 新しくブラウザのウィンドを開く - 作成したファイルのURLにアクセスする - 例えば http://localhost:5500/simple.html など - ウィンドウを Looking Glass側に移動する - ウィンドウの中身をクリックし、最大化する これでLookig Glassに表示されるハズですが、実際にはほとんどのケースでまともに表示されません。3Dモデルのスケールやセンター位置がバラバラで、表示に適切な値になっていないためです。 次のステップでは、ある程度自動的に簡易補正するコードを追加します。 ## GLB形式の簡易補正つき表示 ### 簡易補正つきコード例 ```html <!DOCTYPE HTML> <html> <body> <script src="node_modules/three/build/three.js"></script> <script src="node_modules/holoplay/dist/holoplay.js"></script> <script src="node_modules/three/examples/js/loaders/GLTFLoader.js"></script> <script> // -- カメラ、シーンを用意 -- const scene = new THREE.Scene(); const camera = new HoloPlay.Camera(); const renderer = new HoloPlay.Renderer(); document.body.appendChild(renderer.domElement); // -- 光源を用意 -- const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1); directionalLight.position.set(0, 1, 2); scene.add(directionalLight); const ambientLight = new THREE.AmbientLight(0xFFFFFF, 0.4); scene.add(ambientLight); // -- GLB形式のモデルを読み込み -- let model = new THREE.Group(); // モデルをラップして、扱いやすくしてく const modelFile = 'path/to/your/model.glb'; // ※モデルのパス(URL)に書き換えてください new THREE.GLTFLoader().load(modelFile, (gltf) => { // -- 簡易補正用 -- let desiredScale = 0.1; // 目標とするスケール let adjustOffset = new THREE.Vector3(0, 0, 0); // for Polycam //let adjustOffset = new THREE.Vector3(0, -0.15, 0); // for Scaniverse //let adjustOffset = new THREE.Vector3(0, -0.04, 0); // for 3dScanner App // -- バウンディングボックスを使ってスケール補正を計算 -- let boundigbox = new THREE.Box3().setFromObject(gltf.scene); let d = boundigbox.min.distanceTo(boundigbox.max); let scale = desiredScale * (1 / (d/2)); // -- センター位置補正を計算 -- let center = new THREE.Vector3().addVectors(boundigbox.min, boundigbox.max); let offset = center.clone(); offset.multiplyScalar(scale); offset.add(adjustOffset); //console.log("gltf distance, scale, BondingBox:", d, scale, boundigbox); //console.log("center, offset", center, offset); // -- モデルのスケール、位置を補正 -- gltf.scene.scale.setScalar(scale); gltf.scene.rotation.y = Math.PI; gltf.scene.position.add(offset); // -- シーンにモデルを追加 -- model.add(gltf.scene); model.rotation.x = Math.PI /180 * 15; // 仰角を調整 scene.add(model); }); // -- 描画 -- function update(time) { requestAnimationFrame(update); // -- モデルを回転する -- let duration = 20000; if (model) { model.rotation.y = (Math.PI) * (time / duration); } renderer.render(scene, camera); } requestAnimationFrame(update); </script> </body> </html> ``` ### スケールの補正 スケールの補正には、バウンディングボックス(モデルを囲う直方体)を取得し、その対角線を結ぶ直接の長さが程よい長さになるように補正しています。 ```js let desiredScale = 0.1; // 目標とするスケール // -- バウンディングボックスを使ってスケール補正を計算 -- let boundigbox = new THREE.Box3().setFromObject(gltf.scene); let d = boundigbox.min.distanceTo(boundigbox.max); let scale = desiredScale * (1 / (d/2)); ``` 程よい長さ(desiredScale)は、サンプル「[Load gLTF Model](https://docs.lookingglassfactory.com/developer-tools/three/examples#load-gltf-model)」に含まれるモデルの大きさを参考に決めています。 もし期待する大きさにならない場合は、desiredScaleを調整してください。 ### センター位置の補正 センター位置の補正にも、バウンディングボックスを利用しています。バウンディングボックスの中心が、ラッパーの中心に来るように offset を計算しています。 ```js // -- センター位置補正を計算 -- let center = new THREE.Vector3().addVectors(boundigbox.min, boundigbox.max); let offset = center.clone(); offset.multiplyScalar(scale); offset.add(adjustOffset); ``` 実際には、センター位置をずらす量もスケール補正をかけています。さらに、スキャンに使うアプリによってセンター位置の上下(Yの値)が異なっているように見えます。それを補正するために adjustOffset を設定しています。 これは私がスキャンした少ないサンプルで割り出した値なので、みさなんの撮影条件では異なる可能性があります。その場合は、 adjustOffset を調整して、程よい位置に表示されるようにしてください。 # まとめ Looking Glass Portraitは想像していたよりもはるかに立体感/奥行き感が感じられます。 ポートレートモードで撮影した写真を表示させるだけでも楽しいですが、LiDARで撮影した物体/風景を表示させると、よりその真価を発揮できます。 もし使える機会があったら、ぜひお試しああれ。
"use client" import * as React from "react" import { useRouter } from "next/navigation" import { zodResolver } from "@hookform/resolvers/zod" import { useForm } from "react-hook-form" import { toast } from "sonner" import type { z } from "zod" import { catchError } from "@/app/utils/utils" import { storeSchema } from "@/lib/validations/store" import { Button } from "@/components/UI/button" import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/UI/form" import { Input } from "@/components/UI/input" import { Textarea } from "@/components/UI/textarea" import { Icons } from "@/components/UI/icons" import { addStoreAction } from "@/app/_actions/store" interface AddStoreFormProps { userId: string } type Inputs = z.infer<typeof storeSchema> export function AddStoreForm({ userId }: AddStoreFormProps) { const router = useRouter() const [isPending, startTransition] = React.useTransition() // react-hook-form const form = useForm<Inputs>({ resolver: zodResolver(storeSchema), defaultValues: { name: "", description: "", }, }) function onSubmit(data: Inputs) { startTransition( () => { try { addStoreAction({ ...data, userId }) form.reset() toast.success("Store added successfully.") router.push("/dashboard/stores") router.refresh() // Workaround for the inconsistency of cache revalidation } catch (err) { catchError(err) } }) } return ( <Form {...form}> <form className="grid w-full max-w-xl gap-5" onSubmit={(...args) => void form.handleSubmit(onSubmit)(...args)} > <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input placeholder="Type store name here." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="description" render={({ field }) => ( <FormItem> <FormLabel>Description</FormLabel> <FormControl> <Textarea placeholder="Type store description here." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <Button className="w-fit" disabled={isPending}> {isPending && ( <Icons.spinner className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" /> )} Add Store <span className="sr-only">Add Store</span> </Button> </form> </Form> ) }
// ignore_for_file: overridden_fields, annotate_overrides import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; enum DeviceSize { mobile, tablet, desktop, } abstract class FlutterFlowTheme { static DeviceSize deviceSize = DeviceSize.mobile; static FlutterFlowTheme of(BuildContext context) { deviceSize = getDeviceSize(context); return LightModeTheme(); } late Color primaryColor; late Color secondaryColor; late Color tertiaryColor; late Color alternate; late Color primaryBackground; late Color secondaryBackground; late Color primaryText; late Color secondaryText; late Color lineColor; late Color customColor1; late Color customColor2; late Color customColor3; late Color fondo; String get title1Family => typography.title1Family; TextStyle get title1 => typography.title1; String get title2Family => typography.title2Family; TextStyle get title2 => typography.title2; String get title3Family => typography.title3Family; TextStyle get title3 => typography.title3; String get subtitle1Family => typography.subtitle1Family; TextStyle get subtitle1 => typography.subtitle1; String get subtitle2Family => typography.subtitle2Family; TextStyle get subtitle2 => typography.subtitle2; String get bodyText1Family => typography.bodyText1Family; TextStyle get bodyText1 => typography.bodyText1; String get bodyText2Family => typography.bodyText2Family; TextStyle get bodyText2 => typography.bodyText2; Typography get typography => { DeviceSize.mobile: MobileTypography(this), DeviceSize.tablet: TabletTypography(this), DeviceSize.desktop: DesktopTypography(this), }[deviceSize]!; } DeviceSize getDeviceSize(BuildContext context) { final width = MediaQuery.of(context).size.width; if (width < 479) { return DeviceSize.mobile; } else if (width < 991) { return DeviceSize.tablet; } else { return DeviceSize.desktop; } } class LightModeTheme extends FlutterFlowTheme { late Color primaryColor = const Color(0xFF32146D); late Color secondaryColor = const Color(0xFFFF4A4A); late Color tertiaryColor = const Color(0xFF707070); late Color alternate = const Color(0x27FF5963); late Color primaryBackground = const Color(0xFFFFFFFF); late Color secondaryBackground = const Color(0xFFFFFFFF); late Color primaryText = const Color(0xFF707070); late Color secondaryText = const Color(0xFFFFFFFF); late Color lineColor = Color(0xFFE0E3E7); late Color customColor1 = Color(0x80707070); late Color customColor2 = Color(0xFFFFF500); late Color customColor3 = Color(0x34707070); late Color fondo = Color(0x0C32146D); } abstract class Typography { String get title1Family; TextStyle get title1; String get title2Family; TextStyle get title2; String get title3Family; TextStyle get title3; String get subtitle1Family; TextStyle get subtitle1; String get subtitle2Family; TextStyle get subtitle2; String get bodyText1Family; TextStyle get bodyText1; String get bodyText2Family; TextStyle get bodyText2; } class MobileTypography extends Typography { MobileTypography(this.theme); final FlutterFlowTheme theme; String get title1Family => 'Gilory'; TextStyle get title1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w800, fontSize: 24, ); String get title2Family => 'Gilory'; TextStyle get title2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w300, fontSize: 18, ); String get title3Family => 'Gilory'; TextStyle get title3 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w600, fontSize: 20, ); String get subtitle1Family => 'Gilory'; TextStyle get subtitle1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w500, fontSize: 16, ); String get subtitle2Family => 'Gilory'; TextStyle get subtitle2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.normal, fontSize: 12, ); String get bodyText1Family => 'Gilory'; TextStyle get bodyText1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.normal, fontSize: 14, ); String get bodyText2Family => 'Gilory'; TextStyle get bodyText2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w300, fontSize: 12, ); } class TabletTypography extends Typography { TabletTypography(this.theme); final FlutterFlowTheme theme; String get title1Family => 'Gilory'; TextStyle get title1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w800, fontSize: 24, ); String get title2Family => 'Gilory'; TextStyle get title2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w300, fontSize: 18, ); String get title3Family => 'Gilory'; TextStyle get title3 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w600, fontSize: 20, ); String get subtitle1Family => 'Gilory'; TextStyle get subtitle1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w500, fontSize: 16, ); String get subtitle2Family => 'Gilory'; TextStyle get subtitle2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.normal, fontSize: 12, ); String get bodyText1Family => 'Gilory'; TextStyle get bodyText1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.normal, fontSize: 14, ); String get bodyText2Family => 'Gilory'; TextStyle get bodyText2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w300, fontSize: 12, ); } class DesktopTypography extends Typography { DesktopTypography(this.theme); final FlutterFlowTheme theme; String get title1Family => 'Gilory'; TextStyle get title1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.bold, fontSize: 60, ); String get title2Family => 'Gilory'; TextStyle get title2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w300, fontSize: 34, ); String get title3Family => 'Gilory'; TextStyle get title3 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w600, fontSize: 44, ); String get subtitle1Family => 'Gilory'; TextStyle get subtitle1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w500, fontSize: 28, ); String get subtitle2Family => 'Gilory'; TextStyle get subtitle2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.normal, fontSize: 26, ); String get bodyText1Family => 'Gilory'; TextStyle get bodyText1 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.normal, fontSize: 24, ); String get bodyText2Family => 'Gilory'; TextStyle get bodyText2 => TextStyle( fontFamily: 'Gilory', color: theme.primaryText, fontWeight: FontWeight.w300, fontSize: 22, ); } extension TextStyleHelper on TextStyle { TextStyle override({ String? fontFamily, Color? color, double? fontSize, FontWeight? fontWeight, double? letterSpacing, FontStyle? fontStyle, bool useGoogleFonts = true, TextDecoration? decoration, double? lineHeight, }) => useGoogleFonts ? GoogleFonts.getFont( fontFamily!, color: color ?? this.color, fontSize: fontSize ?? this.fontSize, letterSpacing: letterSpacing ?? this.letterSpacing, fontWeight: fontWeight ?? this.fontWeight, fontStyle: fontStyle ?? this.fontStyle, decoration: decoration, height: lineHeight, ) : copyWith( fontFamily: fontFamily, color: color, fontSize: fontSize, letterSpacing: letterSpacing, fontWeight: fontWeight, fontStyle: fontStyle, decoration: decoration, height: lineHeight, ); }
import React, { useContext } from "react"; import Modal from "../UI/Modal"; import classes from "./Cart.module.css"; import CartContext from "../../store/cart-context"; import CartItem from "./CartItem"; export default function Cart( props ) { const cartCtx = useContext( CartContext ); const totalAmount = `$${ cartCtx.totalAmount.toFixed( 2 ) }`; const hasItems = cartCtx.items.length > 0; const cartItemRemoveHandler = ( id ) => { cartCtx.removeItem( id ) }; const cartItemHandler = ( item ) => { cartCtx.addItem( { ...item, amount: 1 } ) }; const cartItems = ( <ul className={ classes[ "cart-items" ] }> { " " } { cartCtx.items.map( ( item ) => ( <CartItem key={ item.id } name={ item.name } amount={ item.amount } price={ item.price } onRemove={ cartItemRemoveHandler.bind( null, item.id ) } // this insures that the idea of the to be added or removed item is passed here to remove handler onAdd={ cartItemHandler.bind( null, item ) } /> ) ) } </ul> ); return ( <Modal onclose={ props.onHideCart }> { cartItems } <div className={ classes.total }> <span>Total Amount</span> <span>{ totalAmount }</span> </div> <div className={ classes.actions }> <button className={ classes[ "button--alt" ] } onClick={ props.onHideCart }> Close </button> { hasItems && <button className={ classes.button }>Order</button> } </div> </Modal> ); }
import React from "react"; import AppRouter from "./Router"; import { useState, useEffect } from "react"; import { authService } from "../fbase"; import { updateProfile } from "firebase/auth"; const App = () => { const [init, setInit] = useState(false); const [userObj, setUserObj] = useState(null); useEffect(() => { authService.onAuthStateChanged((user) => { if(user){ setUserObj({ uid: user.uid, displayName: user.displayName, updateProfile: (args) => user.updateProfile(args) }); } else { setUserObj(false); } setInit(true); }) }, []); const refreshUser = () => { // setUserObj(authService.currentUser); const user = authService.currentUser; setUserObj({ uid: user.uid, displayName: user.displayName, updateProfile: (args) => user.updateProfile(args), }) }; return ( <React.Fragment> { init ? <AppRouter isLoggedIn={Boolean(userObj)} userObj={userObj} refreshUser={refreshUser} /> : 'Initializing...' } {/* <footer>&copy; {new Date().getFullYear()} Twitter-2022</footer> */} </React.Fragment> ); } export default App;
/* * Copyright 2019 Hippo Seven * * 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.hippo.ehviewer.util import androidx.compose.runtime.Composable import androidx.compose.runtime.DisallowComposableCalls import androidx.compose.runtime.Stable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.lifecycle.viewModelScope import androidx.paging.compose.LazyPagingItems import com.hippo.ehviewer.EhDB import com.hippo.ehviewer.client.data.GalleryInfo import com.hippo.ehviewer.ui.tools.rememberInVM import com.hippo.ehviewer.ui.tools.rememberUpdatedStateInVM import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.transform import kotlinx.coroutines.launch object FavouriteStatusRouter { fun modifyFavourites(gid: Long, slot: Int) { _globalFlow.tryEmit(gid to slot) } private val listenerScope = CoroutineScope(Dispatchers.IO) private val _globalFlow = MutableSharedFlow<Pair<Long, Int>>(extraBufferCapacity = 1).apply { listenerScope.launch { collect { (gid, slot) -> EhDB.updateFavoriteSlot(gid, slot) } } } val globalFlow = _globalFlow.asSharedFlow() @Stable @Composable inline fun <R> collectAsState(initial: GalleryInfo, crossinline transform: @DisallowComposableCalls (Int) -> R) = remember { globalFlow.transform { (gid, slot) -> if (initial.gid == gid) emit(transform(slot)) } }.collectAsState(transform(initial.favoriteSlot)) @Composable fun observe(list: LazyPagingItems<out GalleryInfo>) { val realList by rememberUpdatedStateInVM(newValue = list.itemSnapshotList.items) rememberInVM { viewModelScope.launch { globalFlow.collect { (gid, newSlot) -> realList.forEach { info -> if (info.gid == gid) info.favoriteSlot = newSlot } } } } } }
--- title: Mastering Android Device Manager The Ultimate Guide to Unlocking Your Samsung Device date: 2024-05-19T14:17:42.325Z updated: 2024-05-20T14:17:42.325Z tags: - unlock - remove screen lock categories: - android description: This article describes Mastering Android Device Manager The Ultimate Guide to Unlocking Your Samsung Device excerpt: This article describes Mastering Android Device Manager The Ultimate Guide to Unlocking Your Samsung Device keywords: pattern lock,hack wifi password android device,unlock phone guide,Samsung Galaxy M14 4G pattern unlock without password,easy pattern lock,Samsung Galaxy M14 4G hard pattern lock thumbnail: https://www.lifewire.com/thmb/efwW06nbzdIi0kzLWEWTbso7lT8=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/best-instagram-captions-4171697-ae21b04e6866470c80a50c9bef1cc26e.png --- ## Mastering Android Device Manager: The Ultimate Guide to Unlocking Your Samsung Galaxy M14 4G Device So, what is Android Device Manager?  Android has this amazing native tool to help you locate and remote wipe your lost or stolen phone. We lock our phones via passwords or patterns or fingerprints to maintain the security but what if someone dares to meddle with your phone or unfortunately, it gets stolen? Don’t worry, all you need to do is let Android Device Manager unlock your Android phone. For this, it just needs to be enabled on your phone (before you unluckily locked yourself out of it). Android Device Manager unlocks your phone in a small amount of time, saving you from all the troubles. In addition to this, the Android Device Manager also unlocks your password/pin-encrypted phone if you have forgotten the passcode by chance. The procedure is quite simple; all you need is a Google account to set this up onyour phone and then you can make use of any other online device to track down your lost or stolen phone or to even wipe all data in it. Phew! ![how to use android device manager](https://images.wondershare.com/drfone/article/2017/10/15077981108622.jpg) _Using the Android Device Manager to track a lost phone_ ## Part 1: What is Android Device Manager lock? Android Device Manager is Google’s take on Apple’s Find My iPhone. Enabling the ADM is quite easy; just go to google.com/android/devicemanager  on your computer and search through your list of devices that are already connected to your Google account. Once you are there, you can easily send a notification to the phone you want to enable remote password application and wiping upon. ADM comes with a set of features that helps you to unlock your Android phone as well. It not only helps you to find your device, but also Ring it, lock it, and wipe and erase all the data as well, if your phone is lost or stolen. Once you’re logged into the ADM website from your computer, you can avail all these options once your phone is located. It is a wise option to get your device locked by Android Device Manager in case it is lost or stolen, so that your phone is secured. Android Device Manager can unlock your phone under a specific set of circumstances only. - • First of all, Android Device Manager needs to be enabled on your phone before it is lost, stolen, etc. - • Secondly, your phone can only be tracked by ADM if the GPS option is switched on. - • Thirdly, the Samsung Galaxy M14 4G device you are using for ADM, must be connected to Wi-Fi or internet, to login to your Google account. - • Lastly, Android Device Manager is not compatible for all Android versions. For now, it is only compatible with devices running Android 4.4 and above, so your phone must be in this category for ADM to work. ## Part 2: How to unlock Android phone with Android Device Manager? Just act according to the following steps, and the Android Device Manager will unlock your phone. 1\. On your computer or any other mobile phone, visit: google.com/android/devicemanager 2\. Then, sign in with the help of your Google login details that you had used in your locked phone as well. 3\. In the ADM interface, choose the Samsung Galaxy M14 4G device you want to unlock. Now, select “Lock”. 4\. Enter a temporary password. Now go ahead and click on “Lock” again. 5\. If the previous step was successful, you should be seeing a confirmation below the box with the buttons – Ring, Lock and Erase. 6\. Now, you should see a password field on your phone screen. Enter a temporary password to unlock your phone. 7\. Visit your phone’s lock screen settings and disable the temporary password. ![unlock with android device manager](https://images.wondershare.com/drfone/article/2017/10/15077981723179.jpg) The Android Device Manager has successfully unlocked your phone! A downside to this process, is an error message faced by some users while using ADM. Many users have reported the issue, that when they have tried using ADM to unlock their locked device, an error message has occurred, saying, “since Google has verified that a screen lock is already set”. Basically, this error message conveys that you will not be able to unlock your phone using Android Device Manager, and this is a flaw on Google’s part, not your phone’s. ## Part 3: What to do if phone is locked by Android Device Manager There are 2 situations where you would want to know how to unlock the Android Device Manager lock – one, when you have unfortunately forgotten the screen lock passcode and the other is when your phone is locked by Android Device Manager. ADM is built to completely lock your device so that unknown people cannot access it. So, if your phone is locked by Android Device Manager, you might be in a problem.While ADM is a wonderful tool to lock your phone or erase and wipe data if its stolen or lost, most of the users have reported the issue that they cannot unlock their phones that are locked by Android Device Manager. A possible solution to this is adding a temporary password via Google login and bypassing the ADM lock. Or, you can try resetting the password again by entering a new password via ADM. If that does not work, you can make use of several third-party applications which can be found in the internet, that will help to completely erase the Android Device Manager lock. So, now you know how to unlock the Android Device Manager lock. Do keep in mind, your device must be connected to internet or Wi-Fi, to login to your Google account. ## Part 4: Unlock Android devices with Dr.Fone - Screen Unlock (Android) As mentioned before, many were unable to unlock their phones with ADM. This is why we use the [Dr.Fone - Screen Unlock (Android)](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/). It is hassle-free and easy-to-use; the Dr.Fone toolkit needs to be downloaded on your computer and with a few easy steps, it erases any kind of lock-screen passcode and avoids any kind of data loss as well! ### [Dr.Fone - Android Lock Screen Removal](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) Remove 4 Types of Android Screen Lock without Data Loss - It can remove 4 screen lock types - pattern, PIN, password & fingerprints. - Only remove the lock screen, no data loss at all. - No tech knowledge asked, everybody can handle it. - Work for Samsung Galaxy S/Note/Tab series, and LG G2, G3, G4, etc. **3,224,627** people have downloaded it This tool works on removing all four types of lock-screen passcodes – PINs, Patterns, Fingerprints, and Passwords. Anyone can use this tool following these easy steps: You can also use this tool to bypass the locked screen beyond Samsung and LG.Things you should pay attention is that it will remove all the data after finishing unloking on other brand android phone. 1\. Fire up the Dr.Fone toolkit for Android on your computer and select the Screen Unlock among all the other tools. ![Dr.Fone home](https://images.wondershare.com/drfone/guide/drfone-home.png) 2\. Now, connect your Android device to the computer and select phone model in the list on the program. ![select model in the list](https://images.wondershare.com/drfone/guide/screen-unlock-any-android-device-2.png) 3\. Boot your phone into Download mode: - • Power off your Android phone. - • Press and hold the volume down+the home button + the power button at the same time. - • Press the volume up button to enter Download Mode. ![boot in download mode](https://images.wondershare.com/drfone/guide/android-screen-unlock-without-data-loss-4.png) 4\. After you get your phone into the Download mode, it will start downloading a recovery package. Wait for this to be completed. ![download recovery package](https://images.wondershare.com/drfone/guide/android-screen-unlock-without-data-loss-5.png) 5\. When the recovery package download is completed, Dr.Fone toolkit will begin removing the screen lock. This process will not cause any data loss on your Android device, so do not worry. Once the whole procedure is over, you can easily access your Android phone without entering any kind of password. Hurrah! ![unlock android phone successfully](https://images.wondershare.com/drfone/guide/screen-unlock-any-android-device-6.png) The Dr.Fone software is currently compatible with Samsung Galaxy S/Note/Tab series, and LG G2/G3/G4 series. For windows, it is compatible with 10/8.1/8/7/XP/Vista. The Android Device Manager is an excellent initiative taken by Google to give people the chance to not lose any data and regain access to their phones. This also teaches us to take precautions before such unfortunate incidents take place. Phones are probably one of the most important belongings of ours, in which we confide all our private and confidential documents that we wouldn’t want to be meddled with. So, make use of this guide and get back command over your Android phone. ## Unlock Your Samsung Galaxy M14 4G's Potential: The Top 20 Lock Screen Apps You Need to Try The stock lock screen for Android may sometime feel boring. The OS does not let us do many changes to it and we have to remain satisfied with whatever is provided. But what if someone tells you there is a way to make things more exciting? There are unique lock screen apps for android that can change the complete feel of the lock screen. You can get control over various tasks and perform actions directly from the screen. Today we will talk about the top 20 lock screen apps for android that will totally change the unlocking experience. ## 1\. AcDisplay It is a simple design android lock screen app which handles notifications in a minimalistic approach. You can access application directly from the lock screen. It has an active mode to wake your device using sensors. Compatibility – Android 4.1+ Download: [https://play.google.com/store/apps/details?id=com.achep.acdisplay](https://play.google.com/store/apps/details?id=com.achep.acdisplay) ![AcDisplay](https://images.wondershare.com/drfone/others/acdisplay.jpg) ## 2\. Hi Locker Classic, Lollipo and iOS – you get three styles of unlocking with this lock screen android app. It even features fingerprint unlocking on chosen Samsung and Marshmallow devices. You can highly customize the android lock screen and even add events or weather predictions. Compatibility – Android 4.1+ ![Hi Locker](https://images.wondershare.com/drfone/others/hi-locker.jpg) ## 3\. CM Locker It is one of the most popular lock screen apps for android. It sets new level in phone security by taking selfie of anyone who tries to enter wrong password to access the phone. Compatibility – Device dependent ![CM Locker](https://images.wondershare.com/drfone/others/cm-locker.jpg) ## 4\. LokLok This beta app to lock Android screen is more for fun with friends. You can draw on your app screen and share with friends. Friends can also modify them and share. Compatibility – Android 4.0+ ![LokLok](https://images.wondershare.com/drfone/others/loklok.jpg) ## 6\. ZUI Locker-Elegant Lock Screen With this lock screen app for Android, you can set HD wallpaper and chose different layouts and themes on an impressive and simple UI. The android lock screen wallpapers can be rendered movement by phone's gravity sensor. Compatibility – Android 4.1+ ![ZUI Locker](https://images.wondershare.com/drfone/others/zui-locker.jpg) ## 7\. Next News Lock Screen For people interested in events of the world, this lock screen android app features news stories. Breaking news from your chosen categories will be presented directly on the lock screen. Compatibility – Android 4.0+ ![Next News Lock Screen](https://images.wondershare.com/drfone/others/next-news-lock-screen.jpg) ## 8\. C-Locker Anyone looking for easy and simple unlocking experience will find C-Locker useful. It has many unlocking options to change lock screen wallpaper. Compatibility – Android 2.3.3+ ![C-Locker](https://images.wondershare.com/drfone/others/c-locker.jpg) ## 9\. Echo Notification Lockscreen One of the cool and minimalist lock screen apps for android is Echo. It provides instant detailed notifications in sorted in categories. You can snooze alerts and control music from the screen. It is also customizable with wallpapers. Compatibility – Android 4.3+ ![Echo Notification Lockscreen](https://images.wondershare.com/drfone/others/echo-notification-lockscreen.jpg) ## 10\. GO Locker It is one of the most popular and highly downloaded lock screen apps for android. Fully protection is guaranteed with lock home button feature. It presents a wide range of themes and unlocking styles and shortcuts too. Compatibility – Device dependent ![GO Locker](https://images.wondershare.com/drfone/others/go-locker.jpg) ## 11\. SlideLock Locker For iOS fanatics this app delivers the Apple way of swiping to right to unlock. Doing it the other way gives direct access to camera. You can set custom alerts for each app. Compatibility – Android 4.1+ ![SlideLock Locker](https://images.wondershare.com/drfone/others/slidelock-locker.jpg) ## 12\. Cover Lock Screen Ever heard about an app that predicts your need? Cover uses real time data to place useful apps on android lock screen when you are at work, travelling or at home. Compatibility – Android 4.1+ ![Cover Lock Screen](https://images.wondershare.com/drfone/others/cover-lock-screen.jpg) ## 13\. SnapLock Smart Lock Screen You get a smooth unlocking experience featured in an elegant design in SnapLock. The app sends editor picked wallpapers daily to make things exciting. The date and time can also be arranged in many ways. Compatibility – Android 4.1+ ![SnapLock Smart Lock Screen](https://images.wondershare.com/drfone/others/snapLock-smart-lock-screen.jpg) ## 14\. L Locker Presenting the stylish design of Lollipop and Marshmallow, this applock for android also includes fun pattern lock animations. You can quick launch apps and control music. Compatibility – Android 4.0+ ![L Locker](https://images.wondershare.com/drfone/others/l-locker.jpg) ## 16\. DashClock Widget DashClock lock screen android app lets you access weather reports, missed calls, calendar events, emails and alarms directly. It can also be used with other supported apps. Compatibility – Android 4.2+ ![DashClock Widget](https://images.wondershare.com/drfone/others/dashclock-widget.jpg) ## 18\. Locker Master You can use Lock Master's DIY editor to customize the android lock screen. Many clock designs, graphics etc can make your lock screen amazing. It delivers over 2,000 live wallpapers and themes. Compatibility – Android 4.0.3+ ![Locker Master](https://images.wondershare.com/drfone/others/locker-master.jpg) ## 20\. Dodol Locker It features best designs and themes among lock screen apps for android. You can decorate the lock screen in many ways and use powerful security features. The themes can be downloaded from Theme Shop in the app. Compatibility – Android 2.3.3+ ![Dodol Locker](https://images.wondershare.com/drfone/others/dodol-locker.jpg) These are some of the best lock screen apps for Android that you can find. You can get more security and do more with your Android apps, in an easy manner. Plus, do not forget that every phone should have an app lock for Android – it might be really risky not to. ## A Perfect Guide To Remove or Disable Google Smart Lock On Samsung Galaxy M14 4G Google services are pivotal in enhancing user experience and securing personal data. Among these services, **Google Smart Lock** stands out for its ingenious features. These are integrated into Android devices, simplifying access and bolstering security. However, there are instances where users seek to disable or remove Google Smart Lock. This article goes through the details of Google Smart Lock and its significance. It offers a solution to address unexpected screen lock scenarios on Android devices. ![disabling google smart lock feature](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-1.jpg) ## Part 1. Understanding Google Smart Lock and How It Works? Want to know **what is Google Smart Lock**? [Google Smart Lock](https://get.google.com/smartlock/) serves as a multi-purpose tool within the Google ecosystem. It is designed to streamline security measures and password management access across platforms. At its core, Google Smart Lock operates as a feature that manages passwords. Google Smart Lock aims to enhance authentication processes. Primarily, it operates across Android devices and computers. It offers a unified approach to security, ensuring you don’t have to remember all the passwords. Google Smart Lock securely stores and manages passwords for websites and apps. It enables users to access these services without repeatedly entering login details. When you visit a familiar website or app, Google Smart Lock fills in the login credentials. It automatically provides the login ID and password, maintaining effortless access. ## Part 2. Recognizing Some Top Features of Google Smart Lock Google Smart Lock’s password management has revolutionized how users handle and secure their login credentials. It remains a cornerstone when handling Android devices and computer systems. The following are several notable features that significantly enhance user convenience and security: ### 1\. Password Autofill Google Smart Lock simplifies the login process across apps and websites. It does that by automatically filling in saved credentials. This eliminates the need for users to remember and manually input passwords. ### 2\. Cross-Platform Synchronization It synchronizes saved passwords across multiple devices using the same Google account. This ensures smooth access to credentials on Android devices and computers. ### 3\. Secure Storage Passwords stored within Google Smart Lock are encrypted and securely stored in the user's Google account. This maintains confidentiality and safeguards sensitive login information. ### 4\. Effortless Password Generation It allows the creation of strong and unique passwords when signing up for new accounts. That enhances overall account security and allows users to have strong passwords. These features significantly ease the burden of password management and enhance user security. Yet, **Google Smart Lock** does have limitations that prompt some users to consider removing it. ## Part 3. Why Is It Essential To Remove Google Smart Lock? Despite its array of benefits, there are times when users consider removing or disabling Google Smart Lock. Described below are these limitations to better grasp why users might choose to **Google Smart Lock turn off**: ### 1\. Privacy Concerns Some users focus on privacy and feel uncomfortable with Google Smart Lock's access to their passwords. The reason behind this is how easily anyone can access the saved password. All they need to do is access "Manage Passwords" in Google Chrome, and all their passwords will be open. This leads them to opt for more private password management options. ### 2\. Glitches and Technical Issues Technical glitches in the functioning of Google Smart Lock can be frustrating. This is especially prominent when managing passwords with similar usernames across different websites. The same can happen when using similar passwords for different websites or apps. Users experiencing such issues can seek to remove it to restore regular operations. ### 3\. No Updates You should be aware that Google Smart Lock for Passwords has been deprecated. This indicates it no longer receives updates or support from Google. Developers are advised to opt for Google's One Tap Sign-in feature as an alternative by Google. It provides a more efficient and secure method for signing in to apps and websites. ### 4\. Preference for Third-Party Tools Certain users might have a preference for specialized third-party password management tools. They can go for solutions that offer a wider array of features. Many users might want to find options better aligned with their specific needs. This prompts them to disable Google Smart Lock. ## Part 4. Understanding Some Effective Ways To Disable or Remove Google Smart Lock If you want to disable Google Smart Lock on your devices, it is a relatively easy thing to do. Several ways are available to disable or remove Google Smart Lock from devices. These approaches cater to users' diverse needs and preferences. Here is **how to turn off Google Smart Lock**: ### Way 1. Disabling Google Smart Lock on Your Android To deactivate Google Smart Lock on your Android device, you can use Chrome. Google Chrome is the main hub for storing all your login credentials for websites and apps. This provides the quickest way to disable Google Smart Lock. To disable Google Smart Lock from the Chrome app on your Android device, follow these steps: - **Step 1.** Begin by opening the Google Chrome app on your Android device. Then, tap the “three dots” icon from the top right corner and press "Settings." ![access settings on google chrome android](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-2.jpg) - **Step 2.** Within the Settings, choose "Passwords,” and on the following screen, look for the “Save passwords” and “Auto Sign-in” options. Toggle off both options to disable the **Google Smart Lock** feature from your Android. ![toggle off save password and sign in](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-3.jpg) ### Way 2. Removing Google Smart Lock From Android Settings Google Smart Lock enables users to keep their phones unlocked under specific, pre-approved, and secure conditions. This simplifies device usage by eliminating the need to input passwords or security codes. The basic working of this aspect of Google Smart Lock, now known as “Extend Unlock,” is divided into three parts. The first one is on-body detection, which keeps the Samsung Galaxy M14 4G device unlocked when it's carried or held by the user. The other two are “Trusted Places” and “Trusted Devices.” Users can set specific locations, like home or work, as "Trusted Places." When the Samsung Galaxy M14 4G device is within these locations, it remains unlocked and accessible. Smart Lock integrates biometric authentication methods to unlock devices. As helpful as it is in managing access to your Android device, privacy concerns can cause users to disable this lock. The following are the steps you can **take to disable Google Smart Lock**/Extend Unlock via Android settings: - **Step 1.** Access “Settings” on your Android device and scroll down to tap "Passwords & security." Here, press the option labeled as "Privacy." ![navigate to android privacy settings](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-4.jpg) - **Step 2.** On the following screen, head to the "Trust agents" option and toggle off the "Smart Lock (Google)" option to disable the feature on your device. ![toggle off google smart lock](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-5.jpg) ### Way 3. Disabling Google Smart Lock From Chrome While you can manage this feature on Android devices, it is also available on Google Chrome on your computer. To disable Google Smart Lock from Google Chrome on your computer or laptop, you can follow these steps: - **Step 1.** On your computer, access Google Chrome and click the “three dots” near the top right corner. From the context menu, choose "Settings" and tap "Autofill and passwords" from the left side. ![locate autofill and password in chrome](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-6.jpg) - **Step 2.** Now, click “Google Password Manager" on the ensuing window, and choose "Settings" from the left side. Toggle off "Offer to save passwords" and "Sign in automatically" to disable Google Smart Lock. ![turn off password and sign in switch](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-7.jpg) ## Part 5. Forgot Google Smart Lock From Android Device? Recover Using Wondershare Dr.Fone Disabling the Google Smart Lock can have a side effect, which is the danger of forgetting an important password. One of these important passwords is the screen lock on your Android device. These scenarios could involve forgetting the Samsung Galaxy M14 4G device's PIN, pattern, or password. This could be essential for unlocking the phone or accessing its functionalities. It can lead to being locked out of the Samsung Galaxy M14 4G device, hindering normal operations. In such instances, regaining access becomes crucial. [Wondershare Dr.Fone](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/) offers a robust solution in these cases. This software specializes in unlocking Android devices when users forget their device passcodes. It offers a swift solution to eliminate Android lock screens within 5 minutes. If you own a Samsung or LG device, you can unlock it without data loss. ### Notable Features of Wondershare Dr.Fone 1. This tool bypasses the Android FRP lock without necessitating a PIN or Google account. 2. It broadens its ability to unlock well-known Android brands like Samsung, Huawei, and LG. 3. Additionally, its intuitive interface guarantees that no technical know-how is required. ### Step-by-Step Guide To Unlock Android Smartphone via Wondershare Dr.Fone Dr.Fone makes the process of unlocking an Android device a breeze. Here's a step-by-step guide to recover an Android device using Wondershare Dr.Fone: - **Step 1. Unlocking an Android Device Using Wondershare Dr.Fone** To begin, install the most recent edition of Wondershare Dr.Fone and connect your Android device using a USB cable. Access the "Toolbox" menu and locate the "Screen Unlock" tool upon successful connection. Once opened, choose the "Android" option when prompted. Next, select "Unlock Android Screen" from the available options. ![head to screen unlock feature](https://images.wondershare.com/drfone/guide/android-screen-unlock-3.png) - **Step 2. Device Brand Selection and Screen Unlock Initiation** Select your device brand and "100% Remove Screen Lock." Selecting the Samsung Galaxy M14 4G device brand initiates access to the designated mode. It will trigger Dr.Fone to commence unlocking the Android screen. Note that entering specific modes varies depending on the Samsung Galaxy M14 4G device brand. Upon successfully unlocking your Android device screen, tap "Done." ![choose to remove screen lock fully](https://images.wondershare.com/drfone/article/2024/01/guide-to-remove-or-disable-google-smart-lock-9.jpg) _**Tips:** Forget your device password and can't get access to it? No worries as [Dr.Fone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is here to help you. Download it and start a seamless unlock experience!_ ## Conclusion This comprehensive guide describes the significance of **Google Smart Lock**. It explains its features and various methods to disable it from Android devices and Chrome. Exploring scenarios of forgotten passcodes highlighted the critical need for a reliable solution. Wondershare Dr.Fone emerges as a savior in such situations. It offers a secure means to regain access when locked out of your device. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://android-unlock.techidaily.com/in-2024-how-to-change-oppo-a18-lock-screen-password-by-drfone-android/"><u>In 2024, How To Change Oppo A18 Lock Screen Password?</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-top-15-apps-to-hack-wifi-password-on-samsung-galaxy-f34-5g-by-drfone-android/"><u>In 2024, Top 15 Apps To Hack WiFi Password On Samsung Galaxy F34 5G</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-unlock-vivo-y100a-phone-without-pin-by-drfone-android/"><u>How to Unlock Vivo Y100A Phone without PIN</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-remove-the-lock-screen-fingerprint-of-your-oppo-reno-11-5g-by-drfone-android/"><u>In 2024, Remove the Lock Screen Fingerprint Of Your Oppo Reno 11 5G</u></a></li> <li><a href="https://android-unlock.techidaily.com/a-perfect-guide-to-remove-or-disable-google-smart-lock-on-vivo-y200-by-drfone-android/"><u>A Perfect Guide To Remove or Disable Google Smart Lock On Vivo Y200</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-can-i-bypass-a-forgotten-phone-password-of-oppo-find-n3-flip-by-drfone-android/"><u>In 2024, Can I Bypass a Forgotten Phone Password Of Oppo Find N3 Flip?</u></a></li> <li><a href="https://android-unlock.techidaily.com/the-top-5-android-apps-that-use-fingerprint-sensor-to-lock-your-apps-on-samsung-galaxy-m34-5g-by-drfone-android/"><u>The Top 5 Android Apps That Use Fingerprint Sensor to Lock Your Apps On Samsung Galaxy M34 5G</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-to-remove-or-bypass-knox-enrollment-service-on-samsung-galaxy-s23-by-drfone-android/"><u>In 2024, How To Remove or Bypass Knox Enrollment Service On Samsung Galaxy S23</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-reset-your-samsung-galaxy-xcover-7-lock-screen-password-by-drfone-android/"><u>How to Reset your Samsung Galaxy XCover 7 Lock Screen Password</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-unlock-vivo-y78t-phone-without-pin-by-drfone-android/"><u>How to Unlock Vivo Y78t Phone without PIN</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-delete-gmail-account-withwithout-password-on-vivo-y100-by-drfone-android/"><u>In 2024, Delete Gmail Account With/Without Password On Vivo Y100</u></a></li> <li><a href="https://android-unlock.techidaily.com/top-15-apps-to-hack-wifi-password-on-oppo-reno-11f-5g-by-drfone-android/"><u>Top 15 Apps To Hack WiFi Password On Oppo Reno 11F 5G</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-remove-screen-lock-pin-on-samsung-galaxy-a24-like-a-pro-5-easy-ways-by-drfone-android/"><u>How To Remove Screen Lock PIN On Samsung Galaxy A24 Like A Pro 5 Easy Ways</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-enable-usb-debugging-on-a-locked-vivo-y77t-phone-by-drfone-android/"><u>How To Enable USB Debugging on a Locked Vivo Y77t Phone</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-5-solutions-for-samsung-galaxy-m34-unlock-without-password-by-drfone-android/"><u>In 2024, 5 Solutions For Samsung Galaxy M34 Unlock Without Password</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-lock-apps-on-vivo-y36-to-protect-your-individual-information-by-drfone-android/"><u>How to Lock Apps on Vivo Y36 to Protect Your Individual Information</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-forgotten-the-voicemail-password-of-vivo-try-these-fixes-by-drfone-android/"><u>In 2024, Forgotten The Voicemail Password Of Vivo? Try These Fixes</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-to-change-samsung-galaxy-a14-4g-lock-screen-clock-in-seconds-by-drfone-android/"><u>In 2024, How To Change Samsung Galaxy A14 4G Lock Screen Clock in Seconds</u></a></li> <li><a href="https://android-unlock.techidaily.com/delete-gmail-account-withwithout-password-on-samsung-galaxy-s23-by-drfone-android/"><u>Delete Gmail Account With/Without Password On Samsung Galaxy S23</u></a></li> <li><a href="https://android-unlock.techidaily.com/a-perfect-guide-to-remove-or-disable-google-smart-lock-on-samsung-galaxy-a15-5g-by-drfone-android/"><u>A Perfect Guide To Remove or Disable Google Smart Lock On Samsung Galaxy A15 5G</u></a></li> <li><a href="https://android-unlock.techidaily.com/complete-review-and-guide-to-techeligible-frp-bypass-and-more-for-vivo-y36-by-drfone-android/"><u>Complete Review & Guide to Techeligible FRP Bypass and More For Vivo Y36</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-best-ways-on-how-to-unlockbypassswiperemove-oppo-find-n3-flip-fingerprint-lock-by-drfone-android/"><u>In 2024, Best Ways on How to Unlock/Bypass/Swipe/Remove Oppo Find N3 Flip Fingerprint Lock</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-change-samsung-galaxy-a14-4g-lock-screen-password-by-drfone-android/"><u>How To Change Samsung Galaxy A14 4G Lock Screen Password?</u></a></li> <li><a href="https://android-unlock.techidaily.com/unlocking-the-power-of-smart-lock-a-beginners-guide-for-samsung-galaxy-a24-users-by-drfone-android/"><u>Unlocking the Power of Smart Lock A Beginners Guide for Samsung Galaxy A24 Users</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-can-we-unlock-our-samsung-galaxy-f14-5g-phone-screen-by-drfone-android/"><u>In 2024, How Can We Unlock Our Samsung Galaxy F14 5G Phone Screen?</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-pattern-locks-are-unsafe-secure-your-samsung-galaxy-s23plus-phone-now-with-these-tips-by-drfone-android/"><u>In 2024, Pattern Locks Are Unsafe Secure Your Samsung Galaxy S23+ Phone Now with These Tips</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-track-imei-number-of-vivo-v27e-through-google-earth-by-drfone-android/"><u>How To Track IMEI Number Of Vivo V27e Through Google Earth?</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-full-tutorial-to-bypass-your-vivo-t2x-5g-face-lock-by-drfone-android/"><u>In 2024, Full Tutorial to Bypass Your Vivo T2x 5G Face Lock?</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-tips-and-tricks-for-setting-up-your-oppo-a2-phone-pattern-lock-by-drfone-android/"><u>In 2024, Tips and Tricks for Setting Up your Oppo A2 Phone Pattern Lock</u></a></li> <li><a href="https://android-unlock.techidaily.com/top-apps-and-online-tools-to-track-vivo-t2-pro-5g-phone-withwithout-imei-number-by-drfone-android/"><u>Top Apps and Online Tools To Track Vivo T2 Pro 5G Phone With/Without IMEI Number</u></a></li> <li><a href="https://android-unlock.techidaily.com/top-12-prominent-samsung-galaxy-a14-4g-fingerprint-not-working-solutions-by-drfone-android/"><u>Top 12 Prominent Samsung Galaxy A14 4G Fingerprint Not Working Solutions</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-lock-apps-on-vivo-x90s-to-protect-your-individual-information-by-drfone-android/"><u>How to Lock Apps on Vivo X90S to Protect Your Individual Information</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-how-to-reset-gmail-password-on-samsung-galaxy-a05-devices-by-drfone-android/"><u>In 2024, How to Reset Gmail Password on Samsung Galaxy A05 Devices</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-bypassing-google-account-with-vnrom-bypass-for-oppo-find-x7-ultra-by-drfone-android/"><u>In 2024, Bypassing Google Account With vnROM Bypass For Oppo Find X7 Ultra</u></a></li> <li><a href="https://android-unlock.techidaily.com/how-to-bypass-android-lock-screen-using-emergency-call-on-vivo-y27s-by-drfone-android/"><u>How to Bypass Android Lock Screen Using Emergency Call On Vivo Y27s?</u></a></li> <li><a href="https://android-unlock.techidaily.com/everything-you-need-to-know-about-lock-screen-settings-on-your-vivo-y78t-by-drfone-android/"><u>Everything You Need to Know about Lock Screen Settings on your Vivo Y78t</u></a></li> <li><a href="https://apple-account.techidaily.com/detailed-guide-on-removing-apple-iphone-14-pro-max-activation-lock-without-previous-owner-by-drfone-ios/"><u>Detailed Guide on Removing Apple iPhone 14 Pro Max Activation Lock without Previous Owner?</u></a></li> <li><a href="https://ai-vdieo-software.techidaily.com/new-amazon-prime-video-display-ratio/"><u>New Amazon Prime Video Display Ratio</u></a></li> <li><a href="https://apple-account.techidaily.com/top-notch-solutions-for-disabled-apple-id-from-apple-iphone-15-pro-making-it-possible-by-drfone-ios/"><u>Top-Notch Solutions for Disabled Apple ID From Apple iPhone 15 Pro Making It Possible</u></a></li> <li><a href="https://apple-account.techidaily.com/in-2024-the-easy-way-to-remove-an-apple-id-from-your-macbook-for-your-iphone-14-pro-max-by-drfone-ios/"><u>In 2024, The Easy Way to Remove an Apple ID from Your MacBook For your iPhone 14 Pro Max</u></a></li> <li><a href="https://techidaily.com/how-to-transfer-data-from-apple-iphone-6-plus-to-other-iphone-15-pro-devices-drfone-by-drfone-transfer-data-from-ios-transfer-data-from-ios/"><u>How To Transfer Data From Apple iPhone 6 Plus To Other iPhone 15 Pro devices? | Dr.fone</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-what-is-a-sim-network-unlock-pin-get-your-motorola-moto-g23-phone-network-ready-by-drfone-android/"><u>In 2024, What Is a SIM Network Unlock PIN? Get Your Motorola Moto G23 Phone Network-Ready</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/updated-descript-overdub-controlling-the-audio-in-video/"><u>Updated Descript Overdub Controlling the Audio in Video</u></a></li> <li><a href="https://ios-unlock.techidaily.com/reset-itunes-backup-password-of-apple-iphone-14-pro-max-prevention-and-solution-by-drfone-ios/"><u>Reset iTunes Backup Password Of Apple iPhone 14 Pro Max Prevention & Solution</u></a></li> <li><a href="https://review-topics.techidaily.com/how-to-transfer-data-from-iphone-xs-to-other-iphone-11-devices-drfone-by-drfone-transfer-data-from-ios-transfer-data-from-ios/"><u>How To Transfer Data From iPhone XS To Other iPhone 11 devices? | Dr.fone</u></a></li> <li><a href="https://location-social.techidaily.com/how-to-pause-life360-location-sharing-for-apple-iphone-xs-max-drfone-by-drfone-virtual-ios/"><u>How To Pause Life360 Location Sharing For Apple iPhone XS Max | Dr.fone</u></a></li> <li><a href="https://activate-lock.techidaily.com/what-you-want-to-know-about-two-factor-authentication-for-icloud-on-your-apple-iphone-11-pro-by-drfone-ios/"><u>What You Want To Know About Two-Factor Authentication for iCloud On your Apple iPhone 11 Pro</u></a></li> <li><a href="https://screen-mirror.techidaily.com/how-can-vivo-y200e-5gmirror-share-to-pc-drfone-by-drfone-android/"><u>How Can Vivo Y200e 5GMirror Share to PC? | Dr.fone</u></a></li> <li><a href="https://unlock-android.techidaily.com/how-to-unlock-a-network-locked-infinix-smart-8-pro-phone-by-drfone-android/"><u>How to Unlock a Network Locked Infinix Smart 8 Pro Phone?</u></a></li> <li><a href="https://unlock-android.techidaily.com/in-2024-still-using-pattern-locks-with-infinix-smart-8-pro-tips-tricks-and-helpful-advice-by-drfone-android/"><u>In 2024, Still Using Pattern Locks with Infinix Smart 8 Pro? Tips, Tricks and Helpful Advice</u></a></li> <li><a href="https://sim-unlock.techidaily.com/in-2024-top-11-free-apps-to-check-imei-on-samsung-galaxy-f04-phones-by-drfone-android/"><u>In 2024, Top 11 Free Apps to Check IMEI on Samsung Galaxy F04 Phones</u></a></li> <li><a href="https://change-location.techidaily.com/in-2024-can-i-use-itools-gpx-file-to-catch-the-rare-pokemon-on-samsung-galaxy-a15-5g-drfone-by-drfone-virtual-android/"><u>In 2024, Can I use iTools gpx file to catch the rare Pokemon On Samsung Galaxy A15 5G | Dr.fone</u></a></li> <li><a href="https://fix-guide.techidaily.com/play-store-stuck-on-downloading-of-poco-c51-7-ways-to-resolve-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Play Store Stuck on Downloading Of Poco C51? 7 Ways to Resolve | Dr.fone</u></a></li> <li><a href="https://review-topics.techidaily.com/how-to-transfer-whatsapp-from-iphone-x-to-other-iphone-14-devices-drfone-by-drfone-transfer-whatsapp-from-ios-transfer-whatsapp-from-ios/"><u>How To Transfer WhatsApp From iPhone X to other iPhone 14 devices? | Dr.fone</u></a></li> </ul></div>
import { useState, createContext, useContext, useEffect } from "react"; // Get window size by this context const ViewContext = createContext(undefined); export const useView = () => { const context = useContext(ViewContext); if (context === undefined) { throw new Error("useView must be used within a ViewProvider"); } return context; }; export const ViewProvider = ({ children }) => { const [width, setWidth] = useState(window.innerWidth); function handleWindowSizeChange() { setWidth(window.innerWidth); } useEffect(() => { window.addEventListener("resize", handleWindowSizeChange); return () => { window.removeEventListener("resize", handleWindowSizeChange); }; }, []); return <ViewContext.Provider value={width}>{children}</ViewContext.Provider>; };
import { PipeTransform,Pipe } from "@angular/core"; import { Student } from "./student"; @Pipe({ name:'filterStudents' }) export class FilterPipe implements PipeTransform{ transform(students:Student[],filterText:string) { if(students.length===0 || filterText===''){ return students; } else{ return students.filter((student)=>{ //loop over every student in the array and returning the array return student.gender.toLowerCase()===filterText.toLowerCase() //return the students which satisfy the condition }) } } }
<!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> body { height: 5000px; } #container { width: 1000px; height: 500px; background: pink; } #box { width: 100px; height: 100px; position: absolute; background: tomato; left: 0; top: 0; border-radius: 50%; transition: 0.5s; } p { position: fixed; background: black; width: 200px; height: 80px; right: 50px; top: 50px; color: #fff; } </style> </head> <body> <div id="container"></div> <div id="box"></div> <p></p> <script> let div = document.querySelector("#container"); let box = document.querySelector("#box"); let p = document.querySelector("p"); div.addEventListener('click', function(e){ let x = e.pageX; let y = e.pageY; box.style.left = (x -50) + "px"; box.style.top = (y -50) + "px"; console.log(`X의 좌표는 ${x}이고 Y의 좌표는 ${y}이다`); }) // document.documentElement.scrollTop; // window.scrollY; // 현재 스크롤 top 값을 지정 window.addEventListener('scroll',function(e){ let scrollT = document.documentElement.scrollTop; document.querySelector('p').innerHTML = scrollT; if(scrollT > 500) { document.body.style.background = "lightgreen"; } else { document.body.style.background = "lightblue"; } }) // p를 클릭했을 때 실행하세요 p.addEventListener('click',function(){ window.scrollTo({top: 500, behavior: 'smooth'}); }) </script> </body> </html>
import Table from "./components/table/table/table"; import Layout from "./UI/layout/layout"; import './bootstrap.css'; import SideBar from "./UI/sidebar/sidebar"; import Backdrop from "./UI/backdrop/backdrop"; import { useEffect, useState } from "react"; import useAxios from "./helpers/useAxios"; import { userType } from "./Types/types"; function App() { const [isOpen, setIsOpen] = useState(false) const { fetchData } = useAxios() const [users, SetUsers] = useState<Array<userType>>() useEffect(() => { fetchData('/users', 'get') .then(response => { SetUsers(() => response.data); }) }, []) const [currentUserPosts, setCurrentUserPosts] = useState(null) const [currentState, setCurrentState] = useState<{ id: number | null, type: string }>({ id: null, type: '' }) const [currentUser, setCurrentUser] = useState<userType>() const showPosts = (userId: number) => { if (currentState.id !== userId || !currentUserPosts) { fetchData(`/posts?userId=${userId}`, 'get') .then(response => { setCurrentUserPosts(response.data); }) } let user = users?.find(user => user.id === userId) setCurrentUser(user) setCurrentState(() => ({ id: userId, type: 'posts' })) setIsOpen(true); } const showProfile = (userId: number) => { let user = users?.find(user => user.id === userId) setCurrentUser(user) setCurrentState({ id: userId, type: 'profile' }) setIsOpen(true); } return <Layout> <Table showPosts={showPosts} showProfile={showProfile} users={users} ></Table> <Backdrop isOpen={isOpen} setIsOpen={setIsOpen} /> <SideBar showPosts={showPosts} showProfile={showProfile} isOpen={isOpen} currentState={currentState} currentUser={currentUser} currentUserPosts={currentUserPosts || []} /> </Layout> } export default App;
from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from pydantic import BaseModel fake_users_db = { "johndoe": { "username": "johndoe", "full_name": "John Doe", "email": "johndoe@example.com", "hashed_password": "fakehashedsecret", "disabled": False, }, "alice": { "username": "alice", "full_name": "Alice Wonderson", "email": "alice@example.com", "hashed_password": "fakehashedsecret2", "disabled": True, }, } router = APIRouter(tags=["auth"]) oauth2_sheme = OAuth2PasswordBearer(tokenUrl="token") def fake_hash_password(password: str): return f"fakehashed{password}" class User(BaseModel): username: str email: str | None = None full_name: str | None = None disabled: bool | None = None class UserInDB(User): hashed_password: str def get_user(db, username: str): if username in db: user_dict = db[username] return UserInDB(**user_dict) def fake_decode_user(token): user = get_user(fake_users_db, token) return user # return User( # uername=f"{token}fakedecoded", email="lNw1N@example.com", full_name="John Doe" # ) async def get_current_user(token: Annotated[str, Depends(oauth2_sheme)]): user = fake_decode_user(token) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) return user async def get_current_active_user( current_user: Annotated[User, Depends(get_current_user)], ): if current_user.disabled: raise HTTPException(status_code=400, detail="Inactive user") return current_user # выдает токен типа bearer. Вызывается при запросе /token. Тот в свою очередь вызывается при get_current_user @router.post("/token") async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]): user_dict = fake_users_db.get(form_data.username) if not user_dict: raise HTTPException(status_code=400, detail="Incorrect username or password") user = UserInDB(**user_dict) hashed_password = fake_hash_password(form_data.password) if not hashed_password == user.hashed_password: raise HTTPException(status_code=400, detail="Incorrect username or password") return {"access_token": user.username, "token_type": "dearer"} @router.get("/users/me") async def read_users_me( current_user: Annotated[User, Depends(get_current_active_user)], ): return current_user
import React, { useState } from "react"; import UserContext from "./userContext"; // this is our context provide in .jsx coz now we will wrappe the concern component // in the UserContext so they all will access the cariable of UserContext. // here we define provide as a method and pass the children like Outlet mean jo b parent // sy data aa rha hy usy as it is pass krva do this is the concept of children. const UserContextProvide = ({ children }) => { // even if u wanna call an api or Db just get the data and forward it as mention below const [user, setUser] = useState(null); return ( // now we will wrap in provide and give the access of contxt variable value to all our child or comps // pass a value in an object. you can pass any multiple value in this object value={{user, setUser}} <UserContext.Provider value={{ user, setUser }}> {/* pass the child as it is it might be card or dash board conponent */} {children} </UserContext.Provider> ); }; export default UserContextProvide;
import { Disclosure } from "@headlessui/react"; import classNames from "classnames"; import { A } from "components/A"; import { Router, withRouter } from "next/router"; import React from "react"; type NavItemProps = { name: string; href: string; icon?: React.FunctionComponent<React.ComponentProps<"svg">>; children?: NavItemProps[]; }; const NavItem = ({ router, href, icon, name, children }: NavItemProps & { router: Router }) => { const normalizedHref = `/${href[0] === "/" ? href.substring(1) : href}`; const isCurrentPath = router.pathname === normalizedHref || router.asPath === normalizedHref; const colorClass = isCurrentPath ? "text-white" : "text-neutral"; return !children ? ( <div key={name}> <A href={href} className={classNames( "group w-full flex items-center pl-2 py-2 text-sm font-medium", colorClass, "group-hover:text-primary", )} > {icon && React.createElement(icon, { className: classNames( "mr-3 flex-shrink-0 h-6 w-6 text-neutral", colorClass, "group-hover:text-primary", ), })} {name} </A> </div> ) : ( <Disclosure as="div" key={name} className="space-y-1" defaultOpen={isCurrentPath}> {({ open }) => ( <> <Disclosure.Button className={classNames( "group w-full flex items-center pl-2 pr-1 py-2 text-left text-sm font-medium focus:outline-none focus:ring-2 focus:ring-primary-500", colorClass, "group-hover:text-primary", )} > {icon && React.createElement(icon, { className: classNames("mr-3 flex-shrink-0 h-6 w-6", colorClass), })} <span className="flex-1">{name}</span> <svg className={classNames( open ? "rotate-90" : "", "text-neutral ml-3 flex-shrink-0 h-5 w-5 transform group-hover:text-primary transition-colors ease-in-out duration-150", )} viewBox="0 0 20 20" aria-hidden="true" > <path d="M6 6L14 10L6 14V6Z" fill="currentColor" /> </svg> </Disclosure.Button> <Disclosure.Panel className="space-y-1"> {children.map((subItem) => ( <Disclosure.Button key={subItem.name} as="a" href={subItem.href} className={classNames( "group w-full flex items-center pl-11 pr-2 py-2 text-sm font-medium", colorClass, "group-hover:text-primary", )} > {subItem.name} </Disclosure.Button> ))} </Disclosure.Panel> </> )} </Disclosure> ); }; export default withRouter(NavItem);
import { IZipCode, TZipCode } from "./zip-code.interface"; export class ZipCode implements IZipCode { private _zip: string; private _city: string; private _state: string; private _lastSearched: Date = new Date(Date.now()); private _searchCount: number = 1; constructor( zipCodeNumber: string, cityString: string, stateString: string ) { this._zip = zipCodeNumber; this._city = cityString; this._state = stateString; } public get zip(): string { return this._zip; } public set zip(zip: string) { this._zip = zip; } public get city(): string { return this._city; } public set city(city: string) { this._city = city; } public get state(): string { return this._state; } public set state(state: string) { this._state = state; } public get lastSearched(): Date { return this._lastSearched; } public set lastSearched(newDateTime: Date) { this._lastSearched = newDateTime; } public get searchCount(): number { return this._searchCount; } public set searchCount(searchCount: number) { this._searchCount = searchCount; } toJson(): TZipCode { const returnObj = { zip: this.zip, city: this.city, state: this.state, lastSearched: this.lastSearched, searchCount: this.searchCount, }; return returnObj; } updateSearchCount(): void { this.searchCount = this.searchCount + 1; } updateLastSearched(): void { this.lastSearched = new Date(Date.now()); } }
import { Component, OnInit } from '@angular/core'; import { AuthService } from '../auth.service'; import { FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-updateproduct', templateUrl: './updateproduct.component.html', styleUrls: ['./updateproduct.component.css'] }) export class UpdateproductComponent implements OnInit { constructor(private auth: AuthService) { } error: string; value: any; msg: string; updateProductForm = new FormGroup({ pid: new FormControl('', [Validators.required, Validators.pattern('/^-?(0|[1-9]\d*)?$/')]), name: new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z" "]+$'), Validators.maxLength(25)]), category: new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z " "]+$')]), company: new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z " "]+$')]), quantity: new FormControl('', [Validators.required, Validators.pattern('/^-?(0|[1-9]\d*)?$/')]), price: new FormControl('', [Validators.required, Validators.pattern('/^-?(0|[1-9]|[.]\d*)?$/')]) }); get pid() { return this.updateProductForm.get('pid'); } get name() { return this.updateProductForm.get('name'); } get category() { return this.updateProductForm.get('category'); } get company() { return this.updateProductForm.get('company'); } get quantity() { return this.updateProductForm.get('quantity'); } get price() { return this.updateProductForm.get('price'); } updateData(form) { console.log(form.value); this.auth.updateProduct(form.value).subscribe(data => { console.log(data); }, err => { console.log(err); }, () => { console.log('data updated successfully'); }); } ngOnInit() { } }
# BigBlueButton open source conferencing system - http://www.bigbluebutton.org/. # # Copyright (c) 2022 BigBlueButton Inc. and by respective authors (see below). # # This program is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free Software # Foundation; either version 3.0 of the License, or (at your option) any later # version. # # Greenlight is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Greenlight; if not, see <http://www.gnu.org/licenses/>. # frozen_string_literal: true require 'rails_helper' require 'bigbluebutton_api' describe RecordingCreator, type: :service do let(:room) { create(:room) } let(:bbb_recording) { single_format_recording } before { room.update(meeting_id: single_format_recording[:meetingID]) } describe '#call' do it 'creates recording if not found on GL based on BBB response' do expect do described_class.new(recording: bbb_recording).call end.to change(Recording, :count).from(0).to(1) expect(room.recordings.first.record_id).to eq(bbb_recording[:recordID]) expect(room.recordings.first.participants).to eq(bbb_recording[:participants].to_i) expect(room.recordings.first.recorded_at.to_i).to eq(bbb_recording[:startTime].to_i) end it 'updates recording data if found on GL based on BBB response' do create(:recording, room:, record_id: bbb_recording[:recordID]) expect do described_class.new(recording: bbb_recording).call end.not_to change(Recording, :count) expect(room.recordings.first.record_id).to eq(bbb_recording[:recordID]) expect(room.recordings.first.participants).to eq(bbb_recording[:participants].to_i) expect(room.recordings.first.recorded_at.to_i).to eq(bbb_recording[:startTime].to_i) end it 'does not create duplicate recordings if called more than once' do expect do described_class.new(recording: bbb_recording).call end.to change(Recording, :count).from(0).to(1) expect do described_class.new(recording: bbb_recording).call end.not_to change(Recording, :count) expect do described_class.new(recording: bbb_recording).call end.not_to change(Recording, :count) end context 'Formats' do describe 'Single format' do let(:bbb_recording) { single_format_recording } it 'creates single recording and format based on response' do expect do described_class.new(recording: bbb_recording).call end.to change(Recording, :count).from(0).to(1) expect(room.recordings.first.formats.count).to eq(1) expect(room.recordings.first.formats.first.recording_type).to eq('presentation') expect(room.recordings.first.length).to eq(bbb_recording[:playback][:format][:length]) end end describe 'Multiple formats' do let(:bbb_recording) { multiple_formats_recording } it 'creates multiple formats based on response' do expect do described_class.new(recording: bbb_recording).call end.to change(Recording, :count).from(0).to(1) expect(room.recordings.first.formats.count).to eq(2) expect(room.recordings.first.formats.first.recording_type).to eq('presentation') expect(room.recordings.first.formats.second.recording_type).to eq('podcast') expect(room.recordings.first.length).to eq(bbb_recording[:playback][:format][0][:length]) end end end context 'Meeting ID' do describe 'When meta Meeting ID is NOT returned' do let(:bbb_recording) { without_meta_meeting_id_recording(meeting_id: room.meeting_id) } it 'Finds recording room by the response meeting ID' do expect do described_class.new(recording: bbb_recording).call end.not_to raise_error expect(room.recordings.first.record_id).to eq(bbb_recording[:recordID]) expect(room.meeting_id).to eq(bbb_recording[:meetingID]) expect(room.meeting_id).not_to eq(bbb_recording[:metadata][:meetingId]) end end describe 'When meta Meeting ID is returned' do let(:bbb_recording) { with_meta_meeting_id_recording(meeting_id: room.meeting_id) } it 'Finds recording room by the response metadata meeting ID' do expect do described_class.new(recording: bbb_recording).call end.not_to raise_error expect(room.recordings.first.record_id).to eq(bbb_recording[:recordID]) expect(room.meeting_id).to eq(bbb_recording[:metadata][:meetingId]) expect(room.meeting_id).not_to eq(bbb_recording[:meetingID]) end end describe 'Inexsitent room for the given meeting ID' do let(:bbb_recording) { without_meta_meeting_id_recording(meeting_id: '404') } it 'Fails without upserting recording' do expect do described_class.new(recording: bbb_recording).call end.to raise_error(ActiveRecord::RecordNotFound) expect(room.recordings.count).to eq(0) end end end context 'Name' do describe 'When meta name is NOT returned' do let(:bbb_recording) { without_meta_name_recording } it 'sets recording name to response name' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.name).not_to eq(bbb_recording[:metadata][:name]) expect(room.recordings.first.name).to eq(bbb_recording[:name]) end end describe 'When meta name is returned' do let(:bbb_recording) { with_meta_name_recording } it 'sets recording name to response metadata name' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.name).not_to eq(bbb_recording[:name]) expect(room.recordings.first.name).to eq(bbb_recording[:metadata][:name]) end end end context 'Protectable' do describe 'When BBB server protected feature is enabled' do let(:bbb_recording) { protected_recording } it 'returns recording protectable attribute as true' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.protectable).to be(true) end end describe 'When BBB server protected feature is NOT enabled' do let(:bbb_recording) { single_format_recording } it 'returns recording protectable attribute as false if the bbb server protected feature is not enabled' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.protectable).to be(false) end end end context 'Visibility' do describe 'Published' do let(:bbb_recording) { published_recording } it 'sets a BBB published recording visibility to "Published"' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:published]) end end describe 'Protected' do let(:bbb_recording) { protected_recording } it 'sets a BBB published recording visibility to "Protected"' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:protected]) end end describe 'Unpublished' do let(:bbb_recording) { unpublished_recording } it 'sets a BBB published recording visibility to "Unpublished"' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:unpublished]) end end describe 'Public' do let(:bbb_recording) { public_recording } it 'sets a BBB public recording visibility to "Public"' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:public]) end end describe 'Public/Protected' do let(:bbb_recording) { public_protected_recording } it 'sets a BBB Public/Protected recording visibility to "Public/Protected"' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:public_protected]) end end describe 'Unknown cases' do let(:bbb_recording) { unkown_visibility_recording } it 'sets a BBB with unkown recording visibility to "Unpublished"' do described_class.new(recording: bbb_recording).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:unpublished]) end end describe 'DefaultRecordingVisibility' do let(:bbb_recording) { public_recording } before do allow_any_instance_of(BigBlueButtonApi).to receive(:update_recording_visibility) create(:site_setting, setting: create(:setting, name: 'DefaultRecordingVisibility'), value: 'Unpublished') end it 'sets a BBB public recording visibility to the DefaultRecordingVisibility' do expect_any_instance_of(BigBlueButtonApi).to receive(:update_recording_visibility) described_class.new(recording: bbb_recording, first_creation: true).call expect(room.recordings.first.visibility).to eq(Recording::VISIBILITIES[:unpublished]) end end end end private def dummy_recording(**args) { recordID: 'f0e2be4518868febb0f381ebe7d46ae61364ef1e-1652287428125', meetingID: 'random-1291479', internalMeetingID: 'f0e2be4518868febb0f381ebe7d46ae61364ef1e-1652287428125', name: 'random-1291479', isBreakout: 'false', published: true, state: 'published', startTime: Faker::Time.between(from: 2.days.ago, to: Time.zone.now).to_datetime, endTime: Faker::Time.between(from: 2.days.ago, to: Time.zone.now).to_datetime, participants: Faker::Number.within(range: 1..100).to_s, rawSize: '977816', metadata: { isBreakout: 'false' }, size: '305475', playback: { format: { type: 'presentation', url: 'https://test24.bigbluebutton.org/playback/presentation/2.3/f0e2be4518868febb0f381ebe7d46ae61364ef1e-1652287428125', processingTime: '6386', length: Faker::Number.within(range: 1..60), size: '305475' } }, data: {} }.merge(args) end def single_format_recording dummy_recording end def multiple_formats_recording dummy_recording playback: { format: [{ type: 'presentation', url: 'https://test24.bigbluebutton.org/playback/presentation/2.3/955458f326d02d78ef8d27f4fbf5fafb7c2f666a-1652296432321', processingTime: '5780', length: 0, size: '211880' }, { type: 'podcast', url: 'https://test24.bigbluebutton.org/podcast/955458f326d02d78ef8d27f4fbf5fafb7c2f666a-1652296432321/audio.ogg', processingTime: '0', length: 0, size: '61117' }] } end def without_meta_meeting_id_recording(meeting_id:) dummy_recording meetingID: meeting_id end def with_meta_meeting_id_recording(meeting_id:) dummy_recording meetingID: "NOT_#{meeting_id}", metadata: { isBreakout: 'false', meetingId: meeting_id } end def without_meta_name_recording name = Faker::Name.name dummy_recording name:, metadata: { isBreakout: 'false' } end def with_meta_name_recording name = Faker::Name.name dummy_recording name: "WRONG_#{name}", metadata: { isBreakout: 'false', name: } end def protected_recording dummy_recording published: true, protected: true, metadata: { isBreakout: 'false', 'gl-listed': [false, nil].sample } end def published_recording dummy_recording published: true, protected: false, metadata: { isBreakout: 'false', 'gl-listed': [false, nil].sample } end def unpublished_recording dummy_recording published: false, protected: false, metadata: { isBreakout: 'false', 'gl-listed': [false, nil].sample } end def public_recording dummy_recording published: true, protected: false, metadata: { isBreakout: 'false', 'gl-listed': true } end def public_protected_recording dummy_recording published: true, protected: true, metadata: { isBreakout: 'false', 'gl-listed': true } end def unkown_visibility_recording dummy_recording published: false, protected: [true, false].sample, metadata: { isBreakout: 'false', 'gl-listed': [true, false].sample } end end
<!-- * @Author: zhengjiefeng zhengjiefeng * @Date: 2023-08-31 11:13:16 * @LastEditors: zhengjiefeng zhengjiefeng * @LastEditTime: 2023-11-17 10:15:52 * @FilePath: \vite-vue3-temp\src\views\components\Layout\SysMenu.vue * @Description: * --> <template> <div class="menu-box" :style="{ width: isCollapse ? '60px' : '220px' }"> <div class="menu-title"> <span>管理后台</span> <span class="icon" @click="toggleFun"> <el-icon v-if="isCollapse"><Expand /></el-icon> <el-icon v-else><Fold /></el-icon> </span> </div> <el-menu :collapse="isCollapse" :default-active="activeMenuKey" class="menu-content" @open="handleOpen" @close="handleClose" @select="headerMenuSelect" > <template v-for="item in menuList" :key="item.key"> <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.key"> <template #title> <el-icon> <component :is="item.icon"></component> </el-icon> <span>{{ item.name }}</span> </template> <el-menu-item :index="sub.key" v-for="sub in item.children" :key="sub.key" @click="goPage(sub.path)" >{{ sub.name }}</el-menu-item > </el-sub-menu> <el-menu-item :index="item.key" @click="goPage(sub.path)" v-else> {{ item.name }} </el-menu-item> </template> <!-- <el-sub-menu index="1"> <template #title> <el-icon><location /></el-icon> <span>Navigator One</span> </template> <el-menu-item-group title="Group One"> <el-menu-item index="1-1">item one</el-menu-item> <el-menu-item index="1-2">item two</el-menu-item> </el-menu-item-group> <el-menu-item-group title="Group Two"> <el-menu-item index="1-3">item three</el-menu-item> </el-menu-item-group> <el-sub-menu index="1-4"> <template #title>item four</template> <el-menu-item index="1-4-1">item one</el-menu-item> </el-sub-menu> </el-sub-menu> <el-menu-item index="2"> <el-icon><icon-menu /></el-icon> <span>Navigator Two</span> </el-menu-item> <el-menu-item index="3" disabled> <el-icon><document /></el-icon> <span>Navigator Three</span> </el-menu-item> <el-menu-item index="4"> <el-icon><setting /></el-icon> <span>Navigator Four</span> </el-menu-item> --> </el-menu> </div> </template> <script setup lang="ts"> import { useRouter, useRoute } from 'vue-router' import menuList from '@/utils/menuList.ts' const router = useRouter() const route = useRoute() const isCollapse = ref() onMounted(() => { console.log(1231) }) const activeMenuKey = computed(() => { return router.currentRoute.value.name }) const handleOpen = (key: string, keyPath: string[]) => { console.log(key, keyPath) } const handleClose = (key: string, keyPath: string[]) => { console.log(key, keyPath) } const headerMenuSelect = (key: string, keyPath: string[]) => { console.log(key, keyPath) } const goPage = (path: string) => { router.push({ path: path }) } const toggleFun = () => { isCollapse.value = !isCollapse.value } </script> <style lang="less" scoped> .menu-box { width: 220px; .menu-title { font-size: 16px; padding: 0px 15px; height: 60px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #eee; .icon { cursor: pointer; } } .menu-content { border-right: none; } } </style>
/** * COPYRIGHT(c) 2014 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "uart.h" /** * @brief Send a text string via USART. * @param huart pointer to a UART_HandleTypeDef structure that contains * the configuration information for the specified UART module. * @param TextString The text string to be sent. * @note It use the HAL_UART_Transmit function. */ void USART_Transmit(UART_HandleTypeDef* huart, uint8_t* TextString) { uint8_t TextStringLength; /* Calculate the length of the text string to be sent */ TextStringLength = 0; while (TextString[TextStringLength++] != '\0') ; TextStringLength--; /* Use the HAL function to send the text string via USART */ HAL_UART_Transmit(huart, TextString, TextStringLength, 10); } /** * @brief Convert a number nbr into a string str with 7 characters. * @param nbr The number to be converted. * @param str The container of the converted number into a text in decimal * format. * @note The decimal digits of the number must be maximum 7 so str has to be * able to store at least 7 characters plus '\0'. */ void num2str(uint32_t nbr, uint8_t *str) { uint8_t k; uint8_t *pstrbuff; uint32_t divisor; pstrbuff = str; /* Reset the text string */ for (k = 0; k < 7; k++) *(pstrbuff + k) = '\0'; divisor = 1000000; if (nbr) // if nbr is different from zero then it is processed { while (!(nbr / divisor)) { divisor /= 10; } while (divisor >= 10) { k = nbr / divisor; *pstrbuff++ = '0' + k; nbr = nbr - (k * divisor); divisor /= 10; } } *pstrbuff++ = '0' + nbr; *pstrbuff++ = '\0'; } /** * @brief Convert an integer number into hexadecimal format. * * @param num The integer number to convert. * @param HexFormat The output format about hexadecimal number. * * @retval uint8_t* The address of the string text for the converted hexadecimal number. */ uint8_t* num2hex(uint32_t num, eHexFormat HexFormat) { static uint8_t HexValue[8 + 1]; uint8_t i; uint8_t dummy; uint8_t HexDigits = 0; switch (HexFormat) { case HALFBYTE_F: HexDigits = 1; break; case BYTE_F: HexDigits = 2; break; case WORD_F: HexDigits = 4; break; case DOUBLEWORD_F: HexDigits = 8; break; } for (i = 0; i < HexDigits; i++) { HexValue[i] = '\0'; dummy = (num & (0x0F << (((HexDigits - 1) - i) * 4))) >> (((HexDigits - 1) - i) * 4); if (dummy < 0x0A) { HexValue[i] = dummy + '0'; } else { HexValue[i] = (dummy - 0x0A) + 'A'; } } HexValue[i] = '\0'; return HexValue; }
package com.example.bookapp.Database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.bookapp.Database.entities.Book import com.example.bookapp.Database.entities.Category import com.example.bookapp.Database.entities.User @Database( entities = [ Book::class, Category::class, User::class, ], version = 2 ) abstract class BookDatabase : RoomDatabase() { abstract fun bookDao(): BookDao companion object { @Volatile private var INSTANCE: BookDatabase? = null fun getDatabase(context: Context): BookDatabase { val tempInstance = INSTANCE if (tempInstance != null) { return tempInstance } synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, BookDatabase::class.java, "book.db" ).fallbackToDestructiveMigration().build()// today INSTANCE =instance return instance } } } }
import * as React from 'react'; import Menu from '@mui/material/Menu'; import MenuItem from '@mui/material/MenuItem'; import { signIn, signOut, useSession } from 'next-auth/react'; import { Avatar, Box, Divider, IconButton, ListItemIcon } from '@mui/material'; import { useColorScheme } from "@mui/material/styles"; import { Login, Logout, Settings } from '@mui/icons-material'; import Brightness4Icon from '@mui/icons-material/Brightness4'; import Brightness7Icon from '@mui/icons-material/Brightness7'; import { UserRole } from '@prisma/client'; import { MenuInfo } from './Menu'; import { App } from '../context/AppContext'; import Link from 'next/link'; import { useRouter } from 'next/router'; export const adminMenu: Array<MenuInfo> = [ { text: 'Taxes', href: '/admin/taxes', icon: App.Icons.Tax }, { text: 'Bank Accounts', href: '/admin/bankaccounts', icon: App.Icons.BankAccount }, { text: 'Customers', href: '/admin/customers', icon: App.Icons.Customer }, { text: 'Contacts', href: '/admin/contacts', icon: App.Icons.Contact }, { text: 'Company Info', href: '/admin/companyinfo', icon: <Settings /> }, ]; export default function ProfileButton() { const router = useRouter() const [anchorElUser, setAnchorElUser] = React.useState<null | HTMLElement>(null); const [hydrated, setHydrated] = React.useState(false); const { data: session } = useSession(); const { mode, setMode } = useColorScheme(); React.useEffect(() => { setHydrated(true); }, []) const handleOpenUserMenu = (event: React.MouseEvent<HTMLButtonElement>) => { if (anchorElUser) setAnchorElUser(null) else setAnchorElUser(event.currentTarget); }; const handleCloseUserMenu = () => { setAnchorElUser(null) }; return ( <React.Fragment> <Box sx={{ mr: 2 }}> {session?.user?.email} </Box> <Box sx={{ flexGrow: 0 }}> <IconButton onClick={handleOpenUserMenu}> <Avatar alt={session?.user?.email ?? undefined} src={session?.user?.image ?? undefined}></Avatar> </IconButton> <Menu sx={{ mt: '50px', transform: 'translateX(21px)', }} id="menu-appbar" anchorEl={anchorElUser} anchorOrigin={{ vertical: 'top', horizontal: 'right', }} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right', }} open={Boolean(anchorElUser)} onClose={handleCloseUserMenu} > {hydrated && <MenuItem onClick={() => { setMode(mode === 'light' ? 'dark' : 'light'); }} color="inherit"> <ListItemIcon> {mode === 'dark' ? <Brightness7Icon /> : <Brightness4Icon />} </ListItemIcon> {mode === 'dark' ? 'Light' : 'Dark'} Mode </MenuItem> } {session?.role == UserRole.ADMIN && <Divider />} {session?.role == UserRole.ADMIN && adminMenu.map(item => (item.text && item.href) ? ( <MenuItem key={item.href} href={item.href} component={Link} onClick={() => handleCloseUserMenu()} > <ListItemIcon> {item.icon} </ListItemIcon> {item.text} </MenuItem> ) : <Divider />) } <Divider /> {!session && <MenuItem href='auth/signin' onClick={() => { signIn(); handleCloseUserMenu(); }}> <ListItemIcon> <Login fontSize="small" /> </ListItemIcon> Login </MenuItem> } {session && <MenuItem onClick={() => { signOut({redirect: true, callbackUrl: '/'}); handleCloseUserMenu(); }}> <ListItemIcon> <Logout fontSize="small" /> </ListItemIcon> Logout </MenuItem> } </Menu> </Box> </React.Fragment > ); }
<!DOCTYPE html> <html lang="pt-br"> <head> <title>Projeto Strata</title> <meta charset="utf-8"> <meta name="author"content="Gabriel"> <meta name="description" content="#"> <meta name="keywords" content="#"> <script src="https://kit.fontawesome.com/7d593ee37c.js" crossorigin="anonymous"></script> <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=Open+Sans:wght@300&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/normalize.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <header class="main-header"> <a href="index.html" class="main-header-link imagem-link"> <img src="imagens/avatar.jpg" alt="logo"> </a> <h1 class="main-header-title"> Trabalhos e groselhas de <br> <strong>Gabriel Barros Apolinário</strong>, <br> um zé ninguem qualquer </h1> <p class="p-header">Retirado de <a href="htttp://html5up.net" class="main-header-link">html5up.net</a></p> </header> <main class="main-content"> <section class="main-content-section"> <h2>Quando o header é aside e o aside é no header</h2> <p>Accumsan orci faucibus id eu lorem semper. Eu ac iaculis ac nunc nisi lorem vulputate<br> lorem neque cubilia ac in adipiscing in curae lobortis tortor primis integer massa adipiscing<br> id nisi accumsan pellentesque commodo blandit enim arcu non at amet id arcu magna. Accumsan<br> orci faucibus id eu lorem semper nunc nisi lorem vulputate lorem neque cubilia. </p> <a href="#" title="Saiba mais" class="button-default button-default-stroke">Saiba mais</a> </section> <section class="main-content-section"> <br> <hr> <h2>Recent Works</h2> <div class="row"> <div class="col-2"> <article class="recent-works-card"> <a class="imagem-link" href="imagens/fulls/01.jpg"> <img src="imagens/thumbs/01.jpg" alt="Imagem do card"> </a> <p>Magna sed consequat tempus</p> <p>Lorem ipsum dolor sit amet nisl sed nullam feugiat.</p> </article> <article class="recent-works-card"> <a class="imagem-link" href="imagens/fulls/02.jpg"> <img src="imagens/thumbs/02.jpg" alt="Imagem do card"> </a> <p>Ultricies lacinia interdum</p> <p>Lorem ipsum dolor sit amet nisl sed nullam feugiat.</p> </article> <article class="recent-works-card"> <a class="imagem-link" href="imagens/fulls/03.jpg"> <img src="imagens/thumbs/03.jpg" alt="Imagem do card"> </a> <p>Tortor metus commodo</p> <p>Lorem ipsum dolor sit amet nisl sed nullam feugiat.</p> </article> </div> <div class="col-2"> <article class="recent-works-card"> <a class="imagem-link" href="imagens/fulls/04.jpg"> <img src="imagens/thumbs/04.jpg" alt="Imagem do card"> </a> <p>Ultricies lacinia interdum</p> <p>Lorem ipsum dolor sit amet nisl sed nullam feugiat.</p> </article> <article class="recent-works-card"> <a class="imagem-link" href="imagens/fulls/05.jpg"> <img src="imagens/thumbs/05.jpg" alt="Imagem do card"> </a> <p>Quam neque phasellus</p> <p>Lorem ipsum dolor sit amet nisl sed nullam feugiat.</p> </article> <article class="recent-works-card"> <a class="imagem-link" href="imagens/fulls/06.jpg"> <img src="imagens/thumbs/06.jpg" alt="Imagem do card"> </a> <p>Nunc enim commodo aliquet</p> <p>Lorem ipsum dolor sit amet nisl sed nullam feugiat.</p> </article> </div> </div> <a href="#" title="Veja o Portifólio completo" class="button-default">Veja o Portifólio completo</a> </section> <section class="main-content-section"> <hr> <br> <h2>Get In Touch</h2> <p>Accumsan pellentesque commodo blandit enim arcu non at amet id arcu magna. Accumsan orci<br> faucibus id eu lorem semper nunc nisi lorem vulputate lorem neque lorem ipsum dolor. </p> <div class="row"> <div class="col-2-3"> <form action="#" method="post"> <div class="row"> <div class="col-2"> <label for="nome">Nome</label> <input placeholder="Nome completo" type="text" name="nome" required id="nome"> </div> <div class="col-2"> <label for="email">Email</label> <input placeholder="Email" type="email"name="email" required id="email"> </div> </div> <label for="message">Message</label> <textarea placeholder="Digite aqui" required id="message"></textarea> <input type="submit" value="Send Message" name="msg" class="button-default button-default-stroke button-default-big"> </form> </div> <div class="col-1-3"> <address> <p> <span>Endereço: </span> 1234 Somewhere Rd. Nashville, TN 00000 United States </p> <p> <span>Telefone: </span> 000-000-0000 </p> <p> <span>E-mail: </span> email@server.com </p> </address> </div> </div> <!--row--> </section> <section class="main-content-section"> <hr> <br> <h2>Elements</h2> <h3>Text</h3> <p>This is <b>bold</b> and this is <strong>strong</strong>. This is <i>italic</i> and this is <em>emphasized</em>. This is <sup>superscript</sup> text and this is <sub>subscript</sub> text.<br> This is <u>underlined</u> and this is code: <code>for (;;) { ... }</code>. Finally, <a href="#">is a link</a>. </p> <h1>Titulo h1</h1> <h2>Titulo h2</h2> <h3>Titulo h3</h3> <h4>Titulo h4</h4> <h5>Titulo h5</h5> <h6>Titulo h6</h6> <h3>Blockquote</h3> <blockquote cite="http://developer.mozilla.org"> <p>Esta é uma citação tirada da Mozilla Developer Center.</p> </blockquote> <p> <q cite="http://developer.mozilla.org"> Esta é uma citação tirada da Mozilla Developer Center.</q> </p> <h4>Preformatado</h4> <pre><code> &lt;script&gt; alert('oi'); &lt;/script&gt; </code></pre> <h3>Listas</h3> <div class="row"> <div class="col-2"> <h4>Não ordenada</h4> <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> <h4>Ordenada</h4> <ol> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ol> </div> <div class="col-2"> <h4>Alternate</h4> <ul class="ul-alternate"> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> <h4>Icons</h4> <ul class="ul-icons"> <li><span class="hidden">Cubo</span><i class="fa-solid fa-cube"></i></li> <li><span class="hidden">Android</span><i class="fa-brands fa-android"></i></li> <li><span class="hidden">Apple</span><i class="fa-brands fa-apple"></i></li> </ul> </div> </div> <h3>Actions</h3> <div class="row"> <div class="col-2"> <p> <a href="#" class="button-default">Default</a> <a href="#" class="button-default button-default-stroke">Default</a> </p> <p> <a href="#" class="button-default button-default-small">Default</a> <a href="#" class="button-default button-default-small button-default-stroke">Default</a> </p> </div> <div class="col-2"> <p> <a href="#" class="button-default button-default-full">Default</a> <a href="#" class="button-default button-default-full button-default-stroke">Default</a> </p> <p> <a href="#" class="button-default button-default-small button-default-full">Default</a> <a href="#" class="button-default button-default-small button-default-full button-default-stroke">Default</a> </p> </div> </div> <!--row--> <h3>Table</h3> <table class="table"> <caption>Default</caption> <thead> <tr> <th>Name</th> <th>Description</th> <th>Price</th> </tr> </thead> <tfoot> <tr> <td colspan="2"></td> <td>100.00</td> </tr> </tfoot> <tbody> <tr> <td>Item One</td> <td>Ante turpis integer aliquet porttitor.</td> <td>29.99</td> </tr> <tr> <td>Item Two</td> <td>Vis ac commodo adipiscing arcu aliquet.</td> <td>19.99</td> </tr> <tr> <td>Item Three</td> <td>Morbi faucibus arcu accumsan lorem.</td> <td>29.99</td> </tr> <tr> <td>Item Four</td> <td>Vitae integer tempus condimentum.</td> <td>19.99</td> </tr> <tr> <td>Item Five</td> <td>Ante turpis integer aliquet porttitor.</td> <td>29.99</td> </tr> </tbody> </table> <table class="table table-alternative"> <caption>Alternative</caption> <thead> <tr> <th>Name</th> <th>Description</th> <th>Price</th> </tr> </thead> <tfoot> <tr> <td colspan="2"></td> <td>100.00</td> </tr> </tfoot> <tbody> <tr> <td>Item One</td> <td>Ante turpis integer aliquet porttitor.</td> <td>29.99</td> </tr> <tr> <td>Item Two</td> <td>Vis ac commodo adipiscing arcu aliquet.</td> <td>19.99</td> </tr> <tr> <td>Item Three</td> <td>Morbi faucibus arcu accumsan lorem.</td> <td>29.99</td> </tr> <tr> <td>Item Four</td> <td>Vitae integer tempus condimentum.</td> <td>19.99</td> </tr> <tr> <td>Item Five</td> <td>Ante turpis integer aliquet porttitor.</td> <td>29.99</td> </tr> </tbody> </table> <h3>Buttons</h3> <p> <button class="button-default">Default</button> <button class="button-default button-default-stroke">Default</button> </p> <p> <button class="button-default button-default-small">Default</button> <button class="button-default button-default-small button-default-stroke">Default</button> </p> <p> <button class="button-default button-default-full">Default</button> <button class="button-default button-default-full button-default-stroke">Default</button> </p> <p> <button class="button-default button-default-small button-default-full">Default</button> <button class="button-default button-default-small button-default-full button-default-stroke">Default</button> </p> <h3>Forms</h3> <form action="#" method="post"> <label for="name">Nome</label> <input type="text" name="name"id="name" required> <label for="email">Email</label> <input type="email" name="name"id="email" required> <br> <select> <option value="0">Selecione...</option> <option value="1">HTML</option> <option value="2">CSS</option> <option value="3">Javascript</option> </select> <br> <label><input type="radio" value="Baixa" name="prioridade">Baixa Prioridade</label> <label><input type="radio" value="Media" name="prioridade">Média Prioridade</label> <label><input type="radio" value="Alta" name="prioridade">Alta Prioridade</label> <br> <label><input type="checkbox" value="email-copy" name="email-copy">Email me a copy of this message</label> <label><input type="checkbox" value="robot" name="robot">I'm a human and not a robot</label> <br> <label for="msg-form">Mensagem:</label> <textarea required placeholder="digite uma mensagem" id="msg-form"></textarea> <input type="submit" class="button-default button-default-big" value="Enviar"> <input type="reset" class="button-default button-default-stroke button-default-big" value="Limpar"> </form> </section> <section class="main-content-section"> <hr> <h2>Imagens</h2> <div class="gallery-img"> <img src="/ProjetoStrata/imagens/fulls/01.jpg"> </div> <div class="gallery-thumb row"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/01.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/02.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/03.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/04.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/05.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/06.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/03.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/02.jpg"> <img class="col-1-3" src="/ProjetoStrata/imagens/thumbs/01.jpg"> </div> <br> <h3>Left &amp; Right</h3> <p><img src="imagens/avatar.jpg" class="img-text-left" alt="">Fringilla nisl. Donec accumsan interdum nisi, quis tincidunt felis sagittis eget.<br> tempus euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus.<br> Integer ac pellentesque praesent tincidunt felis sagittis eget. tempus euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis<br> iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent. Donec accumsan interdum nisi, quis tincidunt felis sagittis eget. tempus euismod.<br> Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent<br> tincidunt felis sagittis eget. tempus euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus.<br> Integer ac pellentesque praesent. </p> <p><img src="imagens/avatar.jpg" class="img-text-right" alt="">Fringilla nisl. Donec accumsan interdum nisi, quis tincidunt felis sagittis eget.<br> tempus euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus.<br> Integer ac pellentesque praesent tincidunt felis sagittis eget. tempus euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis<br> iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent. Donec accumsan interdum nisi, quis tincidunt felis sagittis eget. tempus euismod.<br> Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus. Integer ac pellentesque praesent<br> tincidunt felis sagittis eget. tempus euismod. Vestibulum ante ipsum primis in faucibus vestibulum. Blandit adipiscing eu felis iaculis volutpat ac adipiscing accumsan eu faucibus.<br> Integer ac pellentesque praesent. </p> <br> <br> </section> </main> <footer class="main-footer"> <ul> <li class="logo-footer"><a href="#"><span class="hidden">Apple</span><i class="fa-brands fa-apple"></i></a></li> <li class="logo-footer"><a href="#"><span class="hidden">Android</span><i class="fa-brands fa-android"></i></a></li> <li class="logo-footer"><a href="#"><span class="hidden">Linkedin</span><i class="fa-brands fa-linkedin"></i></a></li> <li class="logo-footer"><a href="#"><span class="hidden">Facebook</span><i class="fa-brands fa-facebook"></i></a></li> <li class="text-footer">&copy; Untitled | Design: <a href="#">HTML5 UP</a></li> </ul> </footer> </body> </html>
package com.riwi.performance_test.api.controllers; import java.util.Objects; import org.springframework.data.domain.Page; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.riwi.performance_test.api.dtos.request.ClassRequest; import com.riwi.performance_test.api.dtos.response.ClassResponse; import com.riwi.performance_test.infraestructure.abstract_services.IClassService; import com.riwi.performance_test.utils.enums.SortType; import io.swagger.v3.oas.annotations.Operation; import lombok.AllArgsConstructor; @RestController @RequestMapping(path = "/class") @AllArgsConstructor public class ClassController { private final IClassService service; @Operation(summary = "Create a new class", description = "The body of the ClassRequest in Json format is needed for the operation of creating a new class. ") @PostMapping public ResponseEntity<ClassResponse> insert( @Validated @RequestBody ClassRequest request ){ return ResponseEntity.ok(this.service.create(request)); } @Operation(summary = "Search a class by Id", description = "The id of the class to be searched for is needed to perform the search for it ") @GetMapping(path = "/{id}") public ResponseEntity<ClassResponse> get(@PathVariable Long id) { return ResponseEntity.ok(this.service.get(id)); } @Operation(summary = "Get all Classes", description = "Brings all currently active classes") @GetMapping public ResponseEntity<Page<ClassResponse>> getAll( @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size, @RequestHeader(required = false) SortType sortType ){ if (Objects.isNull(sortType)) sortType = SortType.NONE; return ResponseEntity.ok(this.service.getAll(page -1, size, sortType)); } }
import { useMutation } from "@apollo/client"; import dynamic from "next/dynamic"; import "react-quill/dist/quill.snow.css"; import { useForm } from "react-hook-form"; import { useRouter } from "next/router"; import { CREATE_USED_ITEM_QUESTION_ANSWER, UPDATE_USED_ITEM_QUESTION_ANSWER, } from "./answerNew.query"; import { FETCH_USED_ITEM_QUESTION_ANSWERS } from "../answernewlist/answerNewList.query"; import { Modal } from "antd"; import * as S from "./answerNew.styles"; import { useEffect } from "react"; import { useRecoilState } from "recoil"; import { QuestionIdState } from "../../../../../commons/store"; const ReactQuill = dynamic(() => import("react-quill"), { ssr: false }); export default function AnswerNew(props) { const router = useRouter(); const [createAnswergql] = useMutation(CREATE_USED_ITEM_QUESTION_ANSWER); const { handleSubmit, setValue, trigger, reset } = useForm(); const [questionId, setQuestionId] = useRecoilState(QuestionIdState); const [updateAnswergql] = useMutation(UPDATE_USED_ITEM_QUESTION_ANSWER); const onChangeText = (value) => { setValue("contents", value === "<p><br></p>" ? "" : value); trigger("contents"); }; const onSubmitCreateAnswer = async (data) => { try { await createAnswergql({ variables: { createUseditemQuestionAnswerInput: { contents: data.contents, }, useditemQuestionId: props.useditemQuestionId, }, update(cache, { data }) { cache.modify({ fields: { fetchUseditemQuestionAnswers: (prev) => { return [data.createUseditemQuestionAnswer, ...prev]; }, }, }); }, }); setQuestionId(props.useditemQuestionId); props.setOpen(false); } catch (error) { Modal.error({ content: error.message }); } }; const onSubmitUpdateAnswer = async (data) => { const updateUseditemQuestionAnswerInput = {}; if (data.contents) updateUseditemQuestionAnswerInput.contents = data.contents; try { await updateAnswergql({ variables: { updateUseditemQuestionAnswerInput, useditemQuestionAnswerId: props.useditemQuestionAnswerId, }, refetchQueries: [ { query: FETCH_USED_ITEM_QUESTION_ANSWERS, variables: { useditemQuestionId: props.useditemQuestionId, }, }, ], // update(cache, { data }) { // cache.modify({ // fields: { // fetchUseditemQuestionAnswers: (prev) => { // return [data.updateUseditemQuestionAnswer, ...prev]; // }, // }, // }); // }, }); props.setIsEdit(false); } catch (error) { Modal.error({ content: error.message }); } }; useEffect(() => { reset({ contents: props.prevValue?.contents, }); }, [props.prevValue?.contents]); return ( <> {props.isEdit && ( <S.Wrapper> <S.Form onSubmit={ props.isEdit ? handleSubmit(onSubmitUpdateAnswer) : handleSubmit(onSubmitCreateAnswer) } > <S.Divider></S.Divider> <S.LogoBox> <S.QuestionLogo /> <S.Questionary>ANSWER</S.Questionary> </S.LogoBox> <ReactQuill onChange={onChangeText} defaultValue={props.prevValue?.contents} /> <S.TextBox> <S.TextCount>/100</S.TextCount> <S.Btn>{props.isEdit ? "수정하기" : "Answer"}</S.Btn> </S.TextBox> </S.Form> </S.Wrapper> )} {props.open && ( <S.Wrapper> <S.Form onSubmit={handleSubmit(onSubmitCreateAnswer)}> <S.Divider></S.Divider> <S.LogoBox> <S.QuestionLogo /> <S.Questionary>ANSWER</S.Questionary> </S.LogoBox> <ReactQuill onChange={onChangeText} /> <S.TextBox> <S.TextCount>/100</S.TextCount> <S.Btn>Answer</S.Btn> </S.TextBox> </S.Form> </S.Wrapper> )} </> ); }
import React, { useState, useEffect } from 'react'; import fakeData from '../../fakeData'; import { addToDatabaseCart, getDatabaseCart } from '../../utilities/databaseManager'; import Cart from '../Cart/Cart'; import Product from '../Product/Product'; import './Shop.css'; import { Link } from 'react-router-dom'; const Shop = () => { const first10 = fakeData.slice(0,10); const[products, setProducts] = useState(first10); const [cart, setCart] = useState([]); useEffect(() => { const savedCart = getDatabaseCart(); const productKeys = Object.keys(savedCart); const previousCart = productKeys.map(existingKey => { const product = fakeData.find(pd => pd.key === existingKey); product.quantity =savedCart[existingKey]; console.log(existingKey, savedCart[existingKey]); return product; }) setCart(previousCart); }, []) const handleAddProduct = (product) =>{ const toBeAddedKey = product.key; const sameProduct = cart.find(pd => pd.key === toBeAddedKey); let count = 1; let newCart; if(sameProduct){ count = sameProduct.quantity + 1; sameProduct.quantity = count; const others = cart.filter(pd => pd.key !== toBeAddedKey); newCart = [...others, sameProduct]; } else{ product.quantity = 1; newCart = [...cart, product]; } //const newCart = [...cart, product]; //ager cart gulore array er moddhe copy korte hole 3 dot use hoy setCart(newCart); addToDatabaseCart(product.key, count); } return ( <div className = 'twin-container'> <div className="product-container"> { products.map(pd => <Product key = {pd.key} handleAddProduct = {handleAddProduct} product = {pd} ></Product>) } </div> <div className="cart-container"> <Cart cart = {cart}> <Link to = '/review'> <button className = 'main-button'>Review order</button> </Link> </Cart> </div> </div> ); }; export default Shop; //parallel vabe props use kora jay naa...props ta child er khetre hye thakee //parallel vabe pathate hole database(local storage) e pathate hoy or rout parameter hisebe kintu seta recommended naa... //ejonno use kora hoy context api jeta provider diye kaj kore //ektu advance hole redux diye korle valo hoy //ei project e local storage diye kora hoise
package Homeworks.L121314_HW_Java_Collections; public class TrafficLightDemo { public static void main(String[] args) { TrafficLightSimulator tl = new TrafficLightSimulator(TrafficLightColor.GREEN); for (int i = 0; i < 9; i++){ System.out.println(tl.getColor()); tl.waitForChange(); } tl.cancel(); } } enum TrafficLightColor{ RED, GREEN, YELLOW } class TrafficLightSimulator implements Runnable{ private Thread thrd; private TrafficLightColor tlc; boolean stop = false; boolean changed = false; TrafficLightSimulator(TrafficLightColor init){ tlc = init; thrd = new Thread(this); thrd.start(); } TrafficLightSimulator(){ tlc = TrafficLightColor.RED; thrd = new Thread(this); thrd.start(); } public void run(){ while (!stop){ try { switch (tlc){ case GREEN: Thread.sleep(10000); break; case YELLOW: Thread.sleep(2000); break; case RED: Thread.sleep(12000); break; } }catch (InterruptedException exc){ System.out.println(exc); } changeColor(); } } synchronized void changeColor(){ switch (tlc){ case RED: tlc = TrafficLightColor.GREEN; break; case YELLOW: tlc = TrafficLightColor.RED; break; case GREEN: tlc = TrafficLightColor.YELLOW; break; } changed = true; notify(); } synchronized void waitForChange(){ try { while (!changed) wait(); changed = false; }catch (InterruptedException exc){ System.out.println(exc); } } TrafficLightColor getColor(){ return tlc; } void cancel(){ stop = true; } }