text
stringlengths
184
4.48M
package service import ( "fmt" "mime/multipart" awsDownload "rojgaarkaro-backend/aws/download" awsUpload "rojgaarkaro-backend/aws/upload" errorWithDetails "rojgaarkaro-backend/baseThing" userModel "rojgaarkaro-backend/user/model" userRepo "rojgaarkaro-backend/user/repository" "gorm.io/gorm" ) type Service struct { Db *gorm.DB User *userModel.User } func NewService(db *gorm.DB, user *userModel.User) *Service { return &Service{ Db: db, User: user, } } type ServiceMethod interface { GetAllUsers() (*[]userModel.User, errorWithDetails.ErrorWithDetails) GetUser() (*userModel.User, errorWithDetails.ErrorWithDetails) CreateUser() errorWithDetails.ErrorWithDetails DeleteUser() errorWithDetails.ErrorWithDetails UpdateUser() errorWithDetails.ErrorWithDetails GetUserByEmail() (*userModel.User, errorWithDetails.ErrorWithDetails) UploadFile(*multipart.FileHeader) errorWithDetails.ErrorWithDetails DownloadFile() errorWithDetails.ErrorWithDetails } func (service *Service) UploadFile(fileheader *multipart.FileHeader) errorWithDetails.ErrorWithDetails { location, err := awsUpload.Upload(fileheader, service.User.ID) if err != nil { return errorWithDetails.ErrorWithDetails{Status: 10011010, Detail: "aws upload file error"} } fmt.Println("2") // first we will get the user service.User.Image = location service.UpdateUser() repository := userRepo.NewRepository(service.Db, service.User) err1 := repository.UpdateUser() if err1.Detail != "" { return err1 } return errorWithDetails.ErrorWithDetails{} } func (service *Service) DownloadFile() errorWithDetails.ErrorWithDetails { user, err := service.GetUser() if err.Detail != "" { return err } awsDownload.Download(user.Image) return errorWithDetails.ErrorWithDetails{} } func (service *Service) GetAllUsers() (*[]userModel.User, errorWithDetails.ErrorWithDetails) { // var result *[]userModel.User repository := userRepo.NewRepository(service.Db, service.User) result, err := repository.GetAllUsers() return result, err } func (service *Service) GetUser() (*userModel.User, errorWithDetails.ErrorWithDetails) { repository := userRepo.NewRepository(service.Db, service.User) result, err := repository.GetUser() return result, err } func (service *Service) GetUserByEmail() (*userModel.User, errorWithDetails.ErrorWithDetails) { repository := userRepo.NewRepository(service.Db, service.User) result, err := repository.GetUserByEmail() return result, err } func (service *Service) CreateUser() errorWithDetails.ErrorWithDetails { repository := userRepo.NewRepository(service.Db, service.User) // first we will checck whether gmail exist or not _, err := service.GetUserByEmail() if err.Detail != "" { if err.Status == 404 { err = repository.CreateUser() return err } return err } return errorWithDetails.ErrorWithDetails{Status: 409, Detail: "email already exist"} } func (service *Service) DeleteUser() errorWithDetails.ErrorWithDetails { repository := userRepo.NewRepository(service.Db, service.User) err := repository.DeleteUser() return err } func (service *Service) UpdateUser() errorWithDetails.ErrorWithDetails { user, err := service.GetUser() if err.Detail != "" { return err } updatedUser := service.User if updatedUser.FirstName != "" { user.FirstName = updatedUser.FirstName } if updatedUser.LastName != "" { user.LastName = updatedUser.LastName } if updatedUser.Contact != "" { user.Contact = updatedUser.Contact } if updatedUser.Email != "" { user.Email = updatedUser.Email } if updatedUser.Password != "" { user.Password = updatedUser.Password } if updatedUser.Image != "" { user.Image = updatedUser.Image } user.UpdatedAt = updatedUser.UpdatedAt repository := userRepo.NewRepository(service.Db, user) err = repository.UpdateUser() if err.Detail != "" { return err } return errorWithDetails.ErrorWithDetails{} // we will update all the fields which are not null // types := values.Type() // for i := 0; i < values.NumField(); i++ { // fmt.Println(types.Field(i)) // } // for i := 0; i < values.NumField(); i++ { // fmt.Println(types.Field(i).Name) // } // for i := 0; i < values.NumField(); i++ { // fmt.Println(values.Field(i).Type()) // } // for i := 0; i < values.NumField(); i++ { // fmt.Println(values.Field(i)) // } // valuesForUpdation := reflect.ValueOf(updatedUser) // types := valuesForUpdation.Type() // valueUser := reflect.ValueOf(user) // for i := 0; i < valuesForUpdation.NumField(); i++ { // // if values.Field(i).Type().String() == "int" { // // } // switch valuesForUpdation.Field(i).Type().String() { // case "int": // // we will edit this later // case "float": // // we will edit this later // case "bool": // // we will edit this later // case "string": // fieldName := types.Field(i).Name // fmt.Println(fieldName, valuesForUpdation.Field(i)) // valueUser = valuesForUpdation.Field(i) // } // } }
/* -*-c++-*- */ /* * osgEarth 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 2 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef QGSGLOBEFEATUREOPTIONS_H #define QGSGLOBEFEATUREOPTIONS_H #include <osgEarth/Common> #include <osgEarthFeatures/FeatureSource> class QgsVectorLayer; class QgsGlobeFeatureOptions : public osgEarth::Features::FeatureSourceOptions // NO EXPORT; header only { private: template <class T> class RefPtr : public osg::Referenced { public: RefPtr( T* ptr ) : mPtr( ptr ) {} T* ptr() { return mPtr; } private: T* mPtr; }; public: QgsGlobeFeatureOptions( const ConfigOptions& opt = ConfigOptions() ) : osgEarth::Features::FeatureSourceOptions( opt ) { // Call the driver declared as "osgearth_feature_qgis" setDriver( "qgis" ); fromConfig( _conf ); } osgEarth::Config getConfig() const override { osgEarth::Config conf = osgEarth::Features::FeatureSourceOptions::getConfig(); conf.updateIfSet( "layerId", mLayerId ); conf.updateNonSerializable( "layer", new RefPtr< QgsVectorLayer >( mLayer ) ); return conf; } osgEarth::optional<std::string>& layerId() { return mLayerId; } const osgEarth::optional<std::string>& layerId() const { return mLayerId; } QgsVectorLayer* layer() const { return mLayer; } void setLayer( QgsVectorLayer* layer ) { mLayer = layer; } protected: void mergeConfig( const osgEarth::Config& conf ) override { osgEarth::Features::FeatureSourceOptions::mergeConfig( conf ); fromConfig( conf ); } private: void fromConfig( const osgEarth::Config& conf ) { conf.getIfSet( "layerId", mLayerId ); RefPtr< QgsVectorLayer > *layer_ptr = conf.getNonSerializable< RefPtr< QgsVectorLayer > >( "layer" ); mLayer = layer_ptr ? layer_ptr->ptr() : 0; } osgEarth::optional<std::string> mLayerId; QgsVectorLayer* mLayer; }; #endif // QGSGLOBEFEATUREOPTIONS_H
<?php declare(strict_types=1); namespace App\Model\Table; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * Reply Model * * @property \App\Model\Table\TicketsTable&\Cake\ORM\Association\BelongsTo $Tickets * @property \App\Model\Table\StaffsTable&\Cake\ORM\Association\BelongsTo $Staffs * * @method \App\Model\Entity\Reply newEmptyEntity() * @method \App\Model\Entity\Reply newEntity(array $data, array $options = []) * @method \App\Model\Entity\Reply[] newEntities(array $data, array $options = []) * @method \App\Model\Entity\Reply get($primaryKey, $options = []) * @method \App\Model\Entity\Reply findOrCreate($search, ?callable $callback = null, $options = []) * @method \App\Model\Entity\Reply patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = []) * @method \App\Model\Entity\Reply[] patchEntities(iterable $entities, array $data, array $options = []) * @method \App\Model\Entity\Reply|false save(\Cake\Datasource\EntityInterface $entity, $options = []) * @method \App\Model\Entity\Reply saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = []) * @method \App\Model\Entity\Reply[]|\Cake\Datasource\ResultSetInterface|false saveMany(iterable $entities, $options = []) * @method \App\Model\Entity\Reply[]|\Cake\Datasource\ResultSetInterface saveManyOrFail(iterable $entities, $options = []) * @method \App\Model\Entity\Reply[]|\Cake\Datasource\ResultSetInterface|false deleteMany(iterable $entities, $options = []) * @method \App\Model\Entity\Reply[]|\Cake\Datasource\ResultSetInterface deleteManyOrFail(iterable $entities, $options = []) * * @mixin \Cake\ORM\Behavior\TimestampBehavior */ class ReplyTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config): void { parent::initialize($config); $this->setTable('reply'); $this->setDisplayField('id'); $this->setPrimaryKey('id'); $this->addBehavior('Timestamp'); $this->belongsTo('Tickets', [ 'foreignKey' => 'ticket_id', 'joinType' => 'INNER', ]); $this->belongsTo('Staffs', [ 'foreignKey' => 'Staff_id', 'joinType' => 'INNER', ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator): Validator { $validator ->scalar('message') ->maxLength('message', 255) ->requirePresence('message', 'create') ->notEmptyString('message'); $validator ->integer('ticket_id') ->notEmptyString('ticket_id'); $validator ->integer('Staff_id') ->notEmptyString('Staff_id'); $validator ->integer('Reply_id') ->requirePresence('Reply_id', 'create') ->notEmptyString('Reply_id'); return $validator; } /** * Returns a rules checker object that will be used for validating * application integrity. * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules): RulesChecker { $rules->add($rules->existsIn('ticket_id', 'Tickets'), ['errorField' => 'ticket_id']); $rules->add($rules->existsIn('Staff_id', 'Staffs'), ['errorField' => 'Staff_id']); return $rules; } }
// // HTTPClient.swift // MoviesApp // // Created by Vedran Novak on 13.08.2023.. // import Foundation enum NetworkError: Error { case badURL case noData case decodingError } class HTTPClient { func getMoviesBy(search: String, completion: @escaping (Result<[Movie]?, NetworkError>) -> Void) { guard let url = URL.forMoviesBySearch(search) else { return completion(.failure(.badURL)) } URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, error == nil else { return completion(.failure(.noData)) } guard let moviesResponse = try? JSONDecoder().decode(MovieResponse.self, from: data) else { return completion(.failure(.decodingError)) } completion(.success(moviesResponse.movies)) }.resume() } func getMovieDetalisBy(movieID: String, completion: @escaping (Result<MovieDetail?, NetworkError>) -> Void) { guard let url = URL.forMovieDetailsByMovieId(movieID) else { return completion(.failure(.badURL)) } URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, error == nil else { return completion(.failure(.noData)) } guard let movieDetailsResponse = try? JSONDecoder().decode(MovieDetail.self, from: data) else { return completion(.failure(.decodingError)) } completion(.success(movieDetailsResponse)) }.resume() } }
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ import { render } from '@testing-library/react'; import { renderHook } from '@testing-library/react-hooks'; import { createMemoryHistory } from 'history'; import React from 'react'; import { Router } from 'react-router-dom'; import { MockApmPluginContextWrapper } from '../../../../context/apm_plugin/mock_apm_plugin_context'; import { MockUrlParamsContextProvider } from '../../../../context/url_params_context/mock_url_params_context_provider'; import { TransactionOverviewLink, useTransactionsOverviewHref, } from './transaction_overview_link'; const history = createMemoryHistory(); function Wrapper({ children }: { children: React.ReactElement }) { return ( <MockApmPluginContextWrapper> <Router history={history}> <MockUrlParamsContextProvider>{children}</MockUrlParamsContextProvider> </Router> </MockApmPluginContextWrapper> ); } describe('Transactions overview link', () => { describe('useTransactionsOverviewHref', () => { it('returns transaction link', () => { const { result } = renderHook( () => useTransactionsOverviewHref({ serviceName: 'foo' }), { wrapper: Wrapper } ); expect(result.current).toEqual( '/basepath/app/apm/services/foo/transactions' ); }); it('returns transaction link with persisted query items', () => { const { result } = renderHook( () => useTransactionsOverviewHref({ serviceName: 'foo', latencyAggregationType: 'avg', }), { wrapper: Wrapper } ); expect(result.current).toEqual( '/basepath/app/apm/services/foo/transactions?latencyAggregationType=avg' ); }); }); describe('TransactionOverviewLink', () => { function getHref(container: HTMLElement) { return ((container as HTMLDivElement).children[0] as HTMLAnchorElement) .href; } it('returns transaction link', () => { const { container } = render( <Wrapper> <TransactionOverviewLink serviceName="foo"> Service name </TransactionOverviewLink> </Wrapper> ); expect(getHref(container)).toEqual( 'http://localhost/basepath/app/apm/services/foo/transactions' ); }); it('returns transaction link with persisted query items', () => { const { container } = render( <Wrapper> <TransactionOverviewLink serviceName="foo" latencyAggregationType="avg" > Service name </TransactionOverviewLink> </Wrapper> ); expect(getHref(container)).toEqual( 'http://localhost/basepath/app/apm/services/foo/transactions?latencyAggregationType=avg' ); }); }); });
import React, { createContext, useContext } from "react"; import { Blog } from "types/src/Blog"; import { Post } from "types/src/Post"; import { Media } from "types/src/Media"; import { fetchBlog, editBlog as editBlogService, FETCH_BLOG_DENY } from "../services/blogs"; import { fetchMedia, deleteMedia as deleteMediaService, putMedia as putMediaService } from "../services/media"; import { fetchPosts, deletePost as deletePostService, editPost as editPostService } from "../services/posts"; import { AppError, declareError } from "./AppError"; import { changePassword as changePasswordService } from "../services/settings"; import { createClient, Webdav } from "../services/webdav"; import { buildUrl } from "../helpers/buildUrl"; interface IAppContext { client: Webdav | undefined, blog: Blog; posts: Post[]; media: Media[]; online: boolean, actions: { refresh: (c?: Webdav) => Promise<unknown> login: (u: string, p: string, t?: boolean) => Promise<Webdav>, logout: () => void, editBlog: (b: Blog) => Promise<boolean>, editPost: (p: Post) => Promise<boolean>, deletePost: (p: Post) => Promise<void>, deleteMedia: (m: Media) => Promise<void>, putMedia: (m: Media) => Promise<boolean>, loadMedia: () => Promise<void> changePassword: (s: string) => Promise<void>, } } function save(context: Partial<IAppContext>) { // I know this is not that call to store that in sessionStorage, however given that webdav lib design, I don't know how I can do that in a better way // TODO: use oauth and only store token // https://security.stackexchange.com/questions/36958/is-it-safe-to-store-password-in-html5-sessionstorage sessionStorage.setItem("context", JSON.stringify({ client: context.client ? { username: context.client.username, password: context.client.password } : undefined, actions: undefined })); } function load(): Partial<IAppContext> { const context = JSON.parse(sessionStorage.getItem("context") || "{}") as Partial<IAppContext> return { ...context, // we init a new client here, restoring auth state is done via the ServiceWorker // it keep in memory the last auth header used client: context.client ? createClient(import.meta.env.VITE_SERVER, { username: context.client.username, password: context.client.password }) : undefined, } } const AppContext = createContext<IAppContext>({} as IAppContext); export const LOGIN_FAIL = declareError('Unable to log you in with these credentials, please check your inputs and retry.'); export const AppContextProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [online, setOnline] = React.useState(navigator.onLine); const savedData = React.useRef(load()); const [client, setClient] = React.useState<undefined | Webdav>(savedData.current.client as Webdav); const [blog, setBlog] = React.useState<Blog | undefined>(savedData.current.blog); const [posts, setPosts] = React.useState<Post[] | undefined>(savedData.current.posts); const [media, setMedia] = React.useState<Media[] | undefined>(savedData.current.media); React.useEffect(() => { const ctx = { client }; save(ctx) }, [client]); const onOnline = React.useCallback(() => { setOnline(true); }, []); const onOffline = React.useCallback(() => { setOnline(false); }, []); React.useEffect(() => { window.addEventListener("online", onOnline); window.addEventListener("offline", onOffline); return () => { window.removeEventListener("online", onOnline); window.removeEventListener("offline", onOffline); } }, [onOnline, onOffline]); const loadBlog = React.useCallback(async (fclient: Webdav | undefined = undefined) => { const blog = await fetchBlog(fclient || client as Webdav); setBlog(blog); }, [client]); const loadPosts = React.useCallback(async (fclient: Webdav | undefined = undefined) => { const posts = await fetchPosts(fclient || client as Webdav); setPosts(posts); }, [client]); const loadMedia = React.useCallback(async (fclient: Webdav | undefined = undefined) => { const media = await fetchMedia(fclient || client as Webdav); setMedia(media); }, [client]); const refresh = React.useCallback((fclient: Webdav | undefined = undefined) => { return Promise.all([loadBlog(fclient), loadPosts(fclient), loadMedia(fclient)]); }, [loadBlog, loadMedia, loadPosts]); // login const login = React.useCallback(async (username: string, password: string, temp: boolean = false) => { const c = createClient(import.meta.env.VITE_SERVER, { username, password }); try { await fetchBlog(c); } catch (e) { const error = e as Error; if((error as AppError).code == FETCH_BLOG_DENY) { throw new AppError(LOGIN_FAIL, error.message); } else throw e; } if(!temp) setClient(c); return c; }, []); const logout = React.useCallback(() => setClient(undefined), []); // blog const editBlog = React.useCallback(async (blog: Blog) => { const result = await editBlogService(client as Webdav, blog); setBlog(blog); return result; }, [client]); // posts const editPost = React.useCallback(async (post: Post) => { const result = await editPostService(client as Webdav, post); const index = posts?.findIndex((p) => p.file === post.file); if(index === -1) { setPosts([...(posts as Post[]), post]); } else { setPosts(posts?.map((p) => p.file === post.file ? post : p)); } return result; }, [client, posts]); const deletePost = React.useCallback(async (post: Post) => { const result = await deletePostService(client as Webdav, post); setPosts(posts?.map((p) => p.file === post.file ? null : p).filter((p) => !!p) as Post[]); return result; }, [client, posts]); // media const putMedia = React.useCallback(async (_media: Media) => { const result = await putMediaService(client as Webdav, _media); const m = { ..._media, url: buildUrl(`/${import.meta.env.VITE_BLOGS_PATH}/${(client as Webdav).username}/ressources/${_media.file}`) }; setMedia([...(media as Media[]), m]); return result; }, [client, media]); const deleteMedia = React.useCallback(async (cmedia: Media) => { await deleteMediaService(client as Webdav, cmedia); setMedia(media?.map((p) => p.file === cmedia.file ? null : p).filter((p) => !!p) as Media[]); }, [client, media]); // settings const changePassword = React.useCallback((password: string) => changePasswordService(client as Webdav, password), [client]); React.useEffect(() => { if(client) { if(!blog) loadBlog(); if(!posts) loadPosts(); if(!media) loadMedia(); } }, [client, blog, posts, media, loadBlog, loadPosts, loadMedia]) const value = React.useMemo(() => ({ client, blog: blog as Blog, posts: posts as Post[], media: media as Media[], online, actions: { refresh, login, editBlog, editPost, deletePost, putMedia, deleteMedia, logout, loadMedia, changePassword, } }), [client, blog, posts, media, online, refresh, login, editBlog, editPost, deletePost, putMedia, deleteMedia, logout, loadMedia, changePassword]); return ( <AppContext.Provider value={value}> {children} </AppContext.Provider> ); }; // eslint-disable-next-line react-refresh/only-export-components export const useAppContext = () => { const context = useContext(AppContext); if (!context) { throw new Error('useAppContext must be used within an AppContextProvider'); } return context; };
import React, { useState } from "react"; import Photo1 from "../assets/Photo1.webp"; import Photo2 from "../assets/Photo2.jpeg"; import Photo3 from "../assets/Photo3.jpeg"; import Photo4 from "../assets/Photo4.webp"; import { motion, AnimatePresence } from "framer-motion"; const arrOfPhotos = [Photo1, Photo2, Photo3, Photo4]; function Gallery() { const [currActivePhoto, setCurrActivePhoto] = useState(0); const [direction, setDirection] = useState(0); const handlePrev = () => { if (currActivePhoto > 0) { setCurrActivePhoto(currActivePhoto - 1); } setDirection(+1); }; const handleForward = () => { if (currActivePhoto < arrOfPhotos.length - 1) { setCurrActivePhoto(currActivePhoto + 1); } setDirection(-1); }; const variants = { enter: (direction) => { return { x: direction > 0 ? 200 : -200, opacity: 1, }; }, center: { x: 0, opacity: 1, }, exit: { x: direction < 0 ? 200 : -200, display: "none", }, }; return ( <div className="flex space-x-4 w-full h-[600px] p-10"> <div className="flex flex-col justify-center cursor-pointer text-white" onClick={handlePrev} > {"<"} </div> <div className="grow"> {/* <AnimatePresence> */} <motion.img key={currActivePhoto} src={arrOfPhotos[currActivePhoto]} className="w-full h-full object-cover object-bottom rounded" initial="enter" animate="center" exit="exit" variants={variants} /> {/* </AnimatePresence> */} </div> <div className="flex flex-col justify-center cursor-pointer text-white" onClick={handleForward} > {">"} </div> </div> ); } export default Gallery;
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Checks if two Rectangles intersect. * * A Rectangle intersects another Rectangle if any part of its bounds is within the other Rectangle's bounds. * As such, the two Rectangles are considered "solid". * A Rectangle with no width or no height will never intersect another Rectangle. * * @function Phaser.Geom.Intersects.RectangleToRectangle * @since 3.0.0 * * @param {Phaser.Geom.Rectangle} rectA - The first Rectangle to check for intersection. * @param {Phaser.Geom.Rectangle} rectB - The second Rectangle to check for intersection. * * @return {boolean} `true` if the two Rectangles intersect, otherwise `false`. */ var RectangleToRectangle = function (rectA, rectB) { if (rectA.width <= 0 || rectA.height <= 0 || rectB.width <= 0 || rectB.height <= 0) { return false; } return !(rectA.right < rectB.x || rectA.bottom < rectB.y || rectA.x > rectB.right || rectA.y > rectB.bottom); }; module.exports = RectangleToRectangle;
-- Aula (11/09/2021) CREATE DATABASE "ADS_NOTURNO" -- Identificador do BD TEMPLATE = template0 -- Aplicação de herança de modelo pré-existente ENCODING 'UTF-8' -- Codificação suportada pelo BD (acentuações/moeda) CONNECTION LIMIT 100; -- Número de conexões simultâneas suportadas -- Criando a tb_empregados CREATE TABLE tb_empregados( rg VARCHAR(11), nome VARCHAR(60), idade INTEGER, CONSTRAINT pk_tb_empregados_rg PRIMARY KEY(rg) ); CREATE TABLE tb_pedidos( numero INTEGER, ds_pedido VARCHAR(40), dt_pedido TIMESTAMP, CONSTRAINT pk_tb_pedidos_nr PRIMARY KEY(numero) ); CREATE TABLE tb_itens( NroPedido INTEGER, NroItem INTEGER, produto VARCHAR(60), quantidade INTEGER, CONSTRAINT pk_tb_itens_NroPedido_NrItem PRIMARY KEY(NroPedido, NroItem), CONSTRAINT fk_tb_itens_NroPedido FOREIGN KEY(NroPedido) REFERENCES tb_pedidos(numero) ); -- Instrução DDL para eliminar o objeto (table) DROP TABLE tb_empregados; CREATE TABLE tb_empregados( rg VARCHAR(11), nm_empregado VARCHAR(60), idade INTEGER, plano_saude VARCHAR(20), rua VARCHAR(60), numero VARCHAR(5), cidade VARCHAR(60), CONSTRAINT pk_tb_empregados_rg PRIMARY KEY(rg) ); CREATE TABLE tb_telefones( rg VARCHAR(11), numero VARCHAR(11), CONSTRAINT pk_tb_telefones_rg_nr PRIMARY KEY(rg, numero), CONSTRAINT fk_tb_telefones_rg FOREIGN KEY(rg) REFERENCES tb_empregados(rg) ); SELECT * FROM tb_empregados; INSERT INTO tb_empregados VALUES ('123', 'Luis Felipe', 20, 'Unimed', 'Rua X', 'Nr Y', 'Ribeirão Preto'), ('456', 'Caio Henrique', 21, 'São Francisco', 'Rua W', 'Nr Z', 'São Carlos'), ('789', 'Erika Carvalho', 22, 'Unimed', 'Rua A', 'Nr B', 'Franca'), ('012', 'Jessica Caroline', 23, 'Não têm', 'Rua C', 'Nr D', 'Ribeirão Preto'), ('345', 'Camila Batista', 24, 'Não têm', 'Rua D', 'Nr E', 'Sertãozinho'); SELECT * FROM tb_telefones; INSERT INTO tb_telefones VALUES ('123', '3512 1111'), ('123', '9133 5566'), ('789', '9813 8877'), ('345', '3635 1010'), ('345', '3578 9887'), ('345', '9185 0022'); -- Gerando um relatório simples SELECT e.nm_empregado, t.numero FROM tb_empregados e INNER JOIN tb_telefones t ON(t.rg = e.rg) ORDER BY e.nm_empregado; CREATE TABLE tb_servidores( cpf VARCHAR(11), nm_servidor VARCHAR(60), CONSTRAINT pk_tb_servidores_cpf PRIMARY KEY(cpf) ); CREATE TABLE tb_funcionarios( cpf VARCHAR(11), ds_funcao VARCHAR(25), CONSTRAINT pk_tb_funcionarios_cpf PRIMARY KEY(cpf), CONSTRAINT fk_tb_funcionarios_cpf FOREIGN KEY(cpf) REFERENCES tb_servidores(cpf) ); CREATE TABLE tb_professores( cpf VARCHAR(11), titulacao VARCHAR(20), categoria VARCHAR(10), CONSTRAINT pk_tb_professores_cpf PRIMARY KEY(cpf), CONSTRAINT fk_tb_professores_cpf FOREIGN KEY(cpf) REFERENCES tb_servidores(cpf) ); CREATE TABLE tb_pessoas( codigo INTEGER, nm_pessoa VARCHAR(60), CONSTRAINT pk_tb_pessoas_codigo PRIMARY KEY(codigo) ); CREATE TABLE tb_cnh( nr_cnh INTEGER, dt_expedicao DATE, validade DATE, categoria VARCHAR(3), codigo INTEGER CONSTRAINT uq_tb_cnh_codigo UNIQUE, dt_retirada DATE, CONSTRAINT pk_tb_cnh_nr PRIMARY KEY(nr_cnh), CONSTRAINT fk_tb_cnh_codigo FOREIGN KEY(codigo) REFERENCES tb_pessoas(codigo) ); SELECT * FROM tb_pessoas; INSERT INTO tb_pessoas VALUES (10, 'Paulo Antonio'), (11, 'Alexandre Marques'), (12, 'Caio Andrade'), (13, 'Soninho Gameplay'), (14, 'Cleber Genrique'), (15, 'Tokio drift'), (16, 'Douglas Samuel'), (17, 'Jefford Paulo'); SELECT * FROM tb_cnh; INSERT INTO tb_cnh VALUES (100, '11/09/2021', '11/09/2026', 'AB',10,'13/09/2021'); INSERT INTO tb_cnh VALUES (101, '11/09/2021', '11/09/2026', 'C',16,'13/09/2021'); CREATE TABLE tb_homens( rg VARCHAR(11), nm_homem VARCHAR(60), CONSTRAINT pk_tb_homens_rg PRIMARY KEY(rg) ); CREATE TABLE tb_mulheres( rg VARCHAR(11), nm_mulher VARCHAR(60), CONSTRAINT pk_tb_mulheres_rg PRIMARY KEY (rg) ); CREATE TABLE tb_casamentos( rg_homem VARCHAR(11), rg_mulher VARCHAR(11) CONSTRAINT uq_tb_casamentos_rg_mulher UNIQUE, dt_casamento DATE, CONSTRAINT pk_tb_casamentos_rg_homem PRIMARY KEY(rg_homem), CONSTRAINT fk_tb_casamentos_rg_homem FOREIGN KEY(rg_homem) REFERENCES tb_homens(rg), CONSTRAINT fk_tb_casamentos_rg_mulher FOREIGN KEY(rg_mulher) REFERENCES tb_mulheres(rg) ); DROP TABLE tb_empregados CASCADE; CREATE TABLE tb_departamentos( cod_dpto INTEGER, nm_dpto VARCHAR(40), CONSTRAINT pk_tb_empregados_cod_dpto PRIMARY KEY (cod_dpto) ); CREATE TABLE tb_empregados( cpf VARCHAR(11), nm_emp VARCHAR(60), cod_dpto INTEGER CONSTRAINT nn_tb_empregados_cod_dpto NOT NULL, dt_lotacao DATE, CONSTRAINT pk_tb_empregados_cpf PRIMARY KEY(cpf), CONSTRAINT fk_tb_empregados_cod_dpto FOREIGN KEY (cod_dpto) REFERENCES tb_departamentos(cod_dpto) ); DROP TABLE tb_pessoas CASCADE; CREATE TABLE tb_pessoas( rg VARCHAR(11), nm_pessoa VARCHAR(60), CONSTRAINT pk_tb_pessoas_rg PRIMARY KEY(rg) ); CREATE TABLE tb_automoveis( chassi VARCHAR(17), modelo VARCHAR(25), ano INTEGER, CONSTRAINT pk_tb_automoveis_chassi PRIMARY KEY(chassi) ); CREATE TABLE tb_posses( rg VARCHAR(11), chassi VARCHAR(17), dt_compra DATE, CONSTRAINT pk_tb_posses_chassi PRIMARY KEY(chassi), CONSTRAINT fk_tb_posses_rg FOREIGN KEY (rg) REFERENCES tb_pessoas(rg), CONSTRAINT fk_tb_posses_chassi FOREIGN KEY (chassi) REFERENCES tb_automoveis(chassi) ); CREATE TABLE tb_empregados( rg VARCHAR(11), nm_empregado VARCHAR(60), CONSTRAINT pk_tb_empregados_rg PRIMARY KEY(rg) ); CREATE TABLE tb_projetos( cod_projeto INTEGER, nm_projeto VARCHAR(60), CONSTRAINT pk_tb_projetos_cod_proj PRIMARY KEY(cod_projeto) ); CREATE TABLE tb_participacoes( rg VARCHAR(11), cod_projeto INTEGER, dt_inicio DATE, CONSTRAINT pk_tb_participacoes_rg_cod PRIMARY KEY(rg, cod_projeto), CONSTRAINT fk_tb_participacoes_rg FOREIGN KEY(rg) REFERENCES tb_empregados, CONSTRAINT fk_tb_participacoes_cod_proj FOREIGN KEY (cod_projeto) REFERENCES tb_projetos(cod_projeto) );
<template> <div> <div class="box"> <div class="header"> <span class="login is-active">登录</span> <span class="register">注册</span> </div> <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" > <el-form-item label="账号" prop="username"> <el-input type="text" v-model="ruleForm.username" autocomplete="off" ></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="ruleForm.password" autocomplete="off" ></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm('ruleForm')" >提交</el-button > <el-button @click="resetForm('ruleForm')">重置</el-button> </el-form-item> </el-form> </div> </div> </template> <script> import jwt from "jwt-decode"; export default { data() { var validateUser = (rule, value, callback) => { if (value === "") { callback(new Error("请输入账号")); } else { callback(); } }; var validatePwd = (rule, value, callback) => { if (value === "") { callback(new Error("请输入密码")); } else { callback(); } }; return { ruleForm: { username: "", password: "", }, rules: { username: [ { required: true, validator: validateUser, trigger: "blur" }, ], password: [{ required: true, validator: validatePwd, trigger: "blur" }], }, }; }, methods: { submitForm(formName) { this.$refs[formName].validate((valid) => { if (valid) { console.log("校验通过", this.ruleForm); // 请求登录接口 let { username, password } = this.ruleForm; this.$api.login({ username, password }).then((res) => { // 登录成功后,存储登录信息 // console.log("jwt(res.data.data)", jwt(res.data.data)); if (res.data.status == 200) { let obj = { username: jwt(res.data.data).username, token: res.data.data, }; this.$store.commit("userModule/changeUser", obj); localStorage.setItem('userInfo',JSON.stringify(obj)); this.$router.push('/'); } }); } else { console.log("error submit!!"); return false; } }); }, resetForm(formName) { this.$refs[formName].resetFields(); }, }, }; </script> <style lang="less" scoped> div { background-color: #fff; } .box { width: 600px; border: 1px solid #ccc; background-color: #fff; margin: 150px auto; box-shadow: -1px 1px 2px 2px #eee; .el-form { margin-right: 20px; } } .header { height: 46px; background-color: #eee; line-height: 46px; text-align: left; margin-bottom: 30px; border-bottom: 1px solid #ccc; span { color: #666; padding: 13px 30px; font-size: 14px; } .is-active { color: rgb(73, 137, 255); background-color: #fff; // border: 1px solid #ccc; border-bottom: 1px solid #fff; } } </style>
import { useState,useContext } from "react"; import { createUserWithEmailAndPasswordCustom, createUserDocumentFromAuth} from '../../utils/firebase/firebase.utils' import FormInput from "../form-input/form-input.component"; import './sign-up-form.styles.scss' import Button from "../button/button.component"; const formDefaultValues = { displayName:'', email:'', password:'', confirmPassword:'' } const SignUpForm = () =>{ const [formFields,setFormFields] = useState(formDefaultValues); const {displayName,email,password,confirmPassword}=formFields; const handleEvent =(event) =>{ const {name,value} = event.target setFormFields({...formFields,[name]:value}) } const handleSubmit = async (event)=>{ event.preventDefault() if(password !== confirmPassword){ alert('password does not match') return; } try{ const {user} = await createUserWithEmailAndPasswordCustom(email,password) const userData = await createUserDocumentFromAuth(user,{displayName}) setFormFields(formDefaultValues); }catch(error){ console.log('error while creating user',error) } } return( <div className="sign-up-container"> <h2>Don't have an account?</h2> <span>Sign Up with your Email and Password</span> <form onSubmit={handleSubmit}> <FormInput label="Display Name" name="displayName" onChange={handleEvent} value={displayName} required /> <FormInput label ="Email" type='email' name="email" onChange={handleEvent} value={email} required/> <FormInput label ="Password" type='password' name="password" onChange={handleEvent} value={password} required/> <FormInput label ="Confirm Password" type='password' name="confirmPassword" onChange={handleEvent} value={confirmPassword} required/> <Button type='submit' >Sign Up</Button> </form> </div> ) } export default SignUpForm;
// // APIMovie.swift // CoreDataFavoriteMovies // // Created by Parker Rushton on 11/5/22. // import Foundation struct APIMovie: Codable, Identifiable, Hashable { let title: String let year: String let imdbID: String let posterURL: URL? var id: String { imdbID } enum CodingKeys: String, CodingKey { case title = "Title" case year = "Year" case imdbID case posterURL = "Poster" } } extension Movie { var posterURL: URL? { URL(string: self.posterURLString!) } } struct SearchResponse: Decodable { let movies: [APIMovie] enum CodingKeys: String, CodingKey { case movies = "Search" } }
import { useContext, useEffect, useLayoutEffect, useRef, useState, } from "react"; import Frame from "../Frame"; import { DragContext } from "../SplitPane"; /** * A wrapper around an iframe that loads any changes to the src in the background, * keeping around the current content in the meantime. It does this by listening * to the "load" event and swapping between two underlying iframe elements */ export function useRefreshableIframe( src: string | undefined, onLoad: (frame: HTMLIFrameElement) => void ) { const isPaneDragging = useContext(DragContext); const refs = [ useRef<HTMLIFrameElement>(null), useRef<HTMLIFrameElement>(null), ]; const [index, setIndex] = useState(0); const [isLoadingContent, setIsLoadingContent] = useState(false); const [firstLoad, setFirstLoad] = useState(false); useEffect(() => { function onLoadEvent(this: HTMLIFrameElement) { onLoad(this); } const first = refs[0].current; const second = refs[1].current; if (first && second) { first.addEventListener("load", onLoadEvent); second.addEventListener("load", onLoadEvent); return () => { first.removeEventListener("load", onLoadEvent); second.removeEventListener("load", onLoadEvent); }; } }, [onLoad]); function listen() { !firstLoad && setFirstLoad(true); requestAnimationFrame(() => { setIndex(index === 0 ? 1 : 0); setIsLoadingContent(false); }); } function setUrl(url: string) { setIsLoadingContent(true); const nextIndex = index === 0 ? 1 : 0; const nextRef = refs[nextIndex].current; if (nextRef) { if (isLoadingContent) { nextRef.removeEventListener("load", listen); } nextRef.addEventListener("load", listen, { once: true, }); nextRef.src = url; } } useLayoutEffect(() => { if (src) { setUrl(src); } }, [src]); const isLoading = isLoadingContent; return { firstLoad, isLoading, refresh() { if (src) { setUrl(src); } }, frame: ( <> <Frame innerRef={refs[0]} style={{ opacity: index === 0 ? 1 : 0, zIndex: index === 0 ? 10 : 5, pointerEvents: isLoading || isPaneDragging ? "none" : "auto", }} sandbox="allow-forms allow-modals allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox" /> <Frame innerRef={refs[1]} style={{ opacity: index === 1 ? 1 : 0, zIndex: index === 1 ? 10 : 5, pointerEvents: isLoading || isPaneDragging ? "none" : "auto", }} sandbox="allow-forms allow-modals allow-same-origin allow-scripts allow-popups allow-popups-to-escape-sandbox" /> </> ), }; }
import 'dart:convert'; import 'package:erp_management/model/fees_model.dart'; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'package:path_provider/path_provider.dart'; import 'package:path/path.dart' as path; import 'package:erp_management/extra/constants.dart' as constants; import 'package:http/http.dart' as http; class FeesDatabaseHelper { FeesDatabaseHelper._() { initializeFeesDatabase(); } static final FeesDatabaseHelper _instance = FeesDatabaseHelper._(); factory FeesDatabaseHelper() { return _instance; } static Database? _database; Future<void> initializeFeesDatabase() async { if (_database == null) { sqfliteFfiInit(); final dbFactory = databaseFactoryFfi; final documentsDir = await getApplicationDocumentsDirectory(); final dbPath = path.join(documentsDir.path, 'fees.db'); _database = await dbFactory.openDatabase(dbPath); await _database?.execute( "CREATE TABLE IF NOT EXISTS fees (id INTEGER PRIMARY KEY AUTOINCREMENT," "uid TEXT NOT NULL," "amount INTEGER NOT NULL," "slipNumber TEXT NOT NULL," "date DATE NOT NULL)"); } } Future<void> addFeesDetails(FeesModel feesModel) async { await _database?.insert("fees", feesModel.toJson()); var url = Uri.parse(constants.addFeesDetails); await http.post(url, headers: {"Content-Type": "application/json"}, body: jsonEncode(feesModel.toJson())); } }
import React, { useState, useEffect } from "react"; import ConnectionsSearchbar from "../components/ConnectionsSearchbar"; import ConnectionCard from '../components/ConnectionCard'; import ConnectionSendModalContent from '../components/ConnectionSendModalContent'; import { makeRequest } from "../helpers"; import './Connections.css' import { Modal } from '@mui/material'; const Connections = ({ firebaseApp }) => { const [isLoading, setIsLoading] = useState('Loading...'); const [connections, setConnections] = useState(); const [currConnections, setCurrConnections] = useState(null); const [openConnectionSend, setOpenConnectionSend] = useState(false); const handleOpenConnectionSend = () => { setOpenConnectionSend(true) }; const handleCloseConnectionSend = () => { setOpenConnectionSend(false) }; const currentUser = firebaseApp.auth().currentUser; useEffect(async () => { const data = await makeRequest('/connections/get_connected_taskmasters', 'GET', null, currentUser.uid); if (data.error) alert(data.error); else { setConnections(data); setIsLoading(false); } }, []); return ( <> <div id="connections-container"> <div id="connections-header"> <h3 id="connections-title">{currentUser.displayName}'s Connections</h3> <button onClick={handleOpenConnectionSend}>Send Connection Request</button> <Modal open={openConnectionSend} onClose={handleCloseConnectionSend}> <ConnectionSendModalContent handleClose={handleCloseConnectionSend} uid={currentUser.uid} /> </Modal> <ConnectionsSearchbar connections={connections} setConnections={setCurrConnections} /> </div> {isLoading || ( <div id="connections-card-container"> {currConnections === null ? connections.map((connection, idx) => { return <ConnectionCard key={idx} photo={connection.photo_url} displayName={connection.display_name} role={connection.role} uid={connection.uid}/> }) : currConnections.map((connection, idx) => { return <ConnectionCard key={idx} photo={connection.photo_url} displayName={connection.display_name} role={connection.role} uid={connection.uid}/> })} </div> )} </div> </> ) } export default Connections;
<template> <q-dialog v-model="dialog" persistent> <q-card style="width: 700px; max-width: 80vw"> <q-toolbar> <q-toolbar-title class="text-h6 text-weight-medium"> Presupuestos </q-toolbar-title> <q-btn flat round dense icon="close" @click="$emit('closeModal')" /> </q-toolbar> <q-card-section class="q-px-lg q-pb-none items-center"> <div class="row"> <div class="col-md-12 col-xs-12"> <div class="row bg-orange-2 q-py-md"> <div class="col-xs-12 q-px-md"> <span class="text-subtitle1 text-weight-bold text-primary"> Información de Presupuesto de la Operación {{ model.codigo }}</span> </div> <q-item class="col-xs-4 col-md-4 col-lg-4"> <q-item-section > <q-item-label caption><b>Monto Presupuestado en la Institucion:</b></q-item-label> <q-item-label >Bs. {{montoInstitucion}}</q-item-label> </q-item-section> </q-item> <q-item class="col-xs-4 col-md-4 col-lg-4"> <q-item-section > <q-item-label caption><b>Monto Presupuestado en la Operación:</b></q-item-label> <q-item-label >Bs. {{montoOperacion}}</q-item-label> </q-item-section> </q-item> <q-item class="col-xs-4 col-md-4 col-lg-4"> <q-item-section > <q-item-label caption><b>Monto Ejecutado de la Operación:</b></q-item-label> <q-item-label >Bs. {{montoOperacionEjecutado}}</q-item-label> </q-item-section> </q-item> </div> </div> </div> </q-card-section> <q-card-section class="q-gutter-md"> <div class="text-center text-grey" > <q-btn class="q-mt-md full-width" push outline color="primary" icon="add" label="AGREGAR PRESUPUESTO" @click="openModal()" /> </div> <q-table class="my-sticky-header-table" :rows="presupuestos" :columns="columns" row-key="partida" :pagination="pagination" hide-pagination :rows-per-page-options="[0]" separator="vertical"> <template v-slot:body="props"> <q-tr> <q-td> <q-btn class="q-pa-xs" flat round icon="edit" @click="openModal(row)" /> <q-btn class="q-pa-xs" flat round color="negative" icon="delete" @click="eliminar({ url: `${url}/${row.id}` })" /> </q-td> <q-td>{{ props.row.descripcion }}</q-td> <q-td>{{ props.row.organismoFinanciador.nombre }}</q-td> <q-td>{{ props.row.partidaPresupuestaria.codigo }}</q-td> <q-td>{{ props.row.montoInicial }}</q-td> <q-td>{{ props.row.montoOficial }}</q-td> <q-td>{{ props.row.saldo }}</q-td> </q-tr> </template> </q-table> </q-card-section> </q-card> </q-dialog> <ItemPresupuesto v-if="dialogItem" :open="dialogItem" :value="selected" @closeModal="closeItem" @guardar="guardar" /> </template> <script> import ItemPresupuesto from '@components/Financiera/ItemPresupuesto' import validaciones from '@common/validations' import { useVModel } from 'src/composables/useVModel' import { inject, ref, onMounted } from 'vue' import { useQuasar } from 'quasar' const rules = { requerido: [validaciones.requerido] } const columns = [ { name: 'accion', label: 'Acción', align: 'center' }, { name: 'descripcion', label: 'Descripción', align: 'center' }, { name: 'organismo', label: 'Organismo Financiador', align: 'center' }, { name: 'partida', label: 'Partida Presupuestaria', align: 'center' }, { name: 'montoInicial', label: 'Monto Inicial', align: 'center' }, { name: 'montoOficial', label: 'Monto Oficial', align: 'center' }, { name: 'saldo', label: 'Saldo', align: 'center' } ] export default { emits: ['closeModal'], components: { ItemPresupuesto }, props: { value: { type: Object, defaultValue: () => {} }, open: { type: Boolean, defaultValue: false }, entidad: { type: Object, defaultValue: () => {} } }, setup (props) { const model = useVModel(props, 'value') const dialog = useVModel(props, 'open') const dialogItem = ref(false) const _http = inject('http') const url = ref('financiera/presupuesto') const presupuestos = ref([]) const selected = ref({}) const montoInstitucion = ref(0) const montoOperacion = ref(0) const $q = useQuasar() const montoOperacionEjecutado = ref(0) onMounted(async () => { await refresh() }) const refresh = async () => { let montoOpe = 0 let montoIns = 0 let montoOpeEj = 0 const tmpPresupuesto = [] const presupuesto = await getPresupuesto() for (const item of presupuesto) { if (item.idOperacion === model.value.id) { montoOpe += parseFloat(item.montoOficial) montoOpeEj += parseFloat(item.montoEjecutado) tmpPresupuesto.push(item) } montoIns += parseFloat(item.montoOficial) } montoInstitucion.value = montoIns montoOperacion.value = montoOpe montoOperacionEjecutado.value = montoOpeEj presupuestos.value = tmpPresupuesto } const openModal = (row) => { if (row) selected.value = row else selected.value = { idOperacion: model.value.id } console.log(selected.value) dialogItem.value = true } const eliminar = async (row) => { $q.dialog({ title: 'Confirmacion', message: '¿Esta seguro de eliminar el presupuesto?', persistent: true, ok: { color: 'primary', label: 'Aceptar' }, cancel: { color: 'white', 'text-color': 'black', label: 'Cancelar' } }).onOk(async () => { await _http.delete(row.url) await refresh() }).onCancel(async () => {}) } const closeItem = () => { selected.value = {} dialogItem.value = false } const getPresupuesto = async () => { const { rows } = await _http.get(_http.convertQuery(url.value, { idEntidad: props.entidad.id })) return rows } const guardar = async (row) => { console.log(row) if (row.id) await _http.put(`${url.value}/${row.id}`, row) else await _http.post(url.value, row) refresh() closeItem() } return { rules, model, dialog, openModal, montoInstitucion, montoOperacion, montoOperacionEjecutado, presupuestos, columns, pagination: { rowsPerPage: 0 }, dialogItem, selected, closeItem, guardar, eliminar, url } } } </script> <style lang="sass"> .my-sticky-header-table .q-table__top, tr th font-weight: 700 background-color: #ce93d8 </style>
#include "stdafx.h" #include "Rect.h" #define LT 0 #define RT 1 #define RB 2 #define LB 3 Rect::Rect(const float& left, const float& top, const float& right, const float& bottom) : Shape(4) { m_vertices[LT] = { left, top }; m_vertices[RT] = { right, top }; m_vertices[RB] = { right, bottom }; m_vertices[LB] = { left, bottom }; Init(); } Rect::Rect(const Vector2& leftTop, const Vector2& rightBottom) : Shape(4) { m_vertices[LT] = leftTop; m_vertices[RT] = { rightBottom.x, leftTop.y }; m_vertices[RB] = rightBottom; m_vertices[LB] = { leftTop.x, rightBottom.y }; Init(); } Rect::Rect(const Vector2& leftTop, const Vector2& rightTop, const float& height) : Shape(4) { m_vertices[LT] = leftTop; m_vertices[RT] = rightTop; Vector2 rel = leftTop - rightTop; Vector2 dir = rel.normalized(); Vector2 nor = dir.normal(); m_vertices[LB] = leftTop + nor * height; m_vertices[RB] = rightTop + nor * height; Init(); } Rect::Rect(const float& width, const Vector2& leftTop, const Vector2& leftBottom) : Shape(4) { m_vertices[LT] = leftTop; m_vertices[LB] = leftBottom; Vector2 rel = leftBottom - leftTop; Vector2 dir = rel.normalized(); Vector2 nor = dir.normal(); m_vertices[RT] = leftTop + nor * width; m_vertices[RB] = leftBottom + nor * width; Init(); } Rect::~Rect() { } const Vector2& Rect::position() const { return m_position; } void Rect::setPosition(const Vector2& position) { m_position = position; UpdateVertices(); } const float& Rect::angle() const { return m_angle; } void Rect::setAngle(const float& radian) { m_angle = radian; UpdateVertices(); } float Rect::width() const { return (m_vertices[RT] - m_vertices[LT]).magnitude(); } float Rect::height() const { return (m_vertices[LT] - m_vertices[LB]).magnitude(); } Vector2 Rect::horizontalDirection() const { return (m_vertices[RT] - m_vertices[LT]).normalized(); } Vector2 Rect::verticalDirection() const { return (m_vertices[LT] - m_vertices[LB]).normalized(); } void Rect::Init() { m_position = (m_vertices[LT] + m_vertices[RB]) * 0.5f; m_originalVertices[LT] = m_vertices[LT] - m_position; m_originalVertices[RT] = m_vertices[RT] - m_position; m_originalVertices[RB] = m_vertices[RB] - m_position; m_originalVertices[LB] = m_vertices[LB] - m_position; } void Rect::UpdateVertices() { Matrix3x3 R = Matrix3x3::Rotate(m_angle); Matrix3x3 T = Matrix3x3::Translate(+m_position.x, +m_position.y); Matrix3x3 M = T * R; for (size_t i = 0; i < m_vertexCount; ++i) { m_vertices[i] = M * m_originalVertices[i]; } }
/** * Definitions for all event types fired by the Model. * * Import this class into your project/plugin for strong-typed api references. **/ package com.jeroenwijering.events { import flash.events.Event; public class ModelEvent extends Event { /** Definitions for all event types. **/ public static var BUFFER : String = "BUFFER"; public static var ERROR : String = "ERROR"; public static var LOADED : String = "LOADED"; public static var META : String = "META"; public static var STATE : String = "STATE"; public static var TIME : String = "TIME"; /** The data associated with the event. **/ private var _data : Object; /** * Constructor; sets the event type and inserts the new value. * * @param typ The type of event. * @param dat An object with all associated data. **/ public function ModelEvent(typ : String, dat : Object = undefined, bbl : Boolean = false, ccb : Boolean = false) : void { super(typ, bbl, ccb); _data = dat; }; /** Returns the data associated with the event. **/ public function get data() : Object { return _data; }; } }
# Name: ADCM # # Label: Concomitant Medications Analysis Dataset # # Input: cm, adsl library(admiral) library(pharmaversesdtm) # Contains example datasets from the CDISC pilot project library(dplyr) library(lubridate) # Load source datasets ---- # Use e.g. haven::read_sas to read in .sas7bdat, or other suitable functions # as needed and assign to the variables below. # For illustration purposes read in admiral test data data("cm") data("admiral_adsl") adsl <- admiral_adsl # When SAS datasets are imported into R using haven::read_sas(), missing # character values from SAS appear as "" characters in R, instead of appearing # as NA values. Further details can be obtained via the following link: # https://pharmaverse.github.io/admiral/cran-release/articles/admiral.html#handling-of-missing-values # nolint cm <- convert_blanks_to_na(cm) # Derivations ---- # Get list of ADSL vars required for derivations adsl_vars <- exprs(TRTSDT, TRTEDT, DTHDT, EOSDT, TRT01P, TRT01A) adcm <- cm %>% # Join ADSL with CM (only ADSL vars required for derivations) derive_vars_merged( dataset_add = adsl, new_vars = adsl_vars, by = exprs(STUDYID, USUBJID) ) %>% ## Derive analysis start time ---- derive_vars_dtm( dtc = CMSTDTC, new_vars_prefix = "AST", highest_imputation = "M", min_dates = exprs(TRTSDT) ) %>% ## Derive analysis end time ---- derive_vars_dtm( dtc = CMENDTC, new_vars_prefix = "AEN", highest_imputation = "M", date_imputation = "last", time_imputation = "last", max_dates = exprs(DTHDT, EOSDT) ) %>% ## Derive analysis end/start date ----- derive_vars_dtm_to_dt(exprs(ASTDTM, AENDTM)) %>% ## Derive analysis start relative day and analysis end relative day ---- derive_vars_dy( reference_date = TRTSDT, source_vars = exprs(ASTDT, AENDT) ) %>% ## Derive analysis duration (value and unit) ---- derive_vars_duration( new_var = ADURN, new_var_unit = ADURU, start_date = ASTDT, end_date = AENDT, in_unit = "days", out_unit = "days", add_one = TRUE, trunc_out = FALSE ) ## Derive flags ---- adcm <- adcm %>% # Derive On-Treatment flag # Set `span_period = TRUE` if you want occurrences that started prior to drug # intake and ongoing or ended after this time to be considered as on-treatment. derive_var_ontrtfl( start_date = ASTDT, end_date = AENDT, ref_start_date = TRTSDT, ref_end_date = TRTEDT ) %>% # Derive Pre-Treatment flag mutate(PREFL = if_else(ASTDT < TRTSDT, "Y", NA_character_)) %>% # Derive Follow-Up flag mutate(FUPFL = if_else(ASTDT > TRTEDT, "Y", NA_character_)) %>% # Derive ANL01FL # This variable is sponsor specific and may be used to indicate particular # records to be used in subsequent derivations or analysis. mutate(ANL01FL = if_else(ONTRTFL == "Y", "Y", NA_character_)) %>% # Derive 1st Occurrence of Preferred Term Flag restrict_derivation( derivation = derive_var_extreme_flag, args = params( new_var = AOCCPFL, by_vars = exprs(USUBJID, CMDECOD), order = exprs(ASTDTM, CMSEQ), mode = "first" ), filter = ANL01FL == "Y" ) ## Derive APHASE and APHASEN Variable ---- # Other timing variable can be derived similarly. # See also the "Visit and Period Variables" vignette # (https://pharmaverse.github.io/admiral/cran-release/articles/visits_periods.html) adcm <- adcm %>% mutate( APHASE = case_when( PREFL == "Y" ~ "Pre-Treatment", ONTRTFL == "Y" ~ "On-Treatment", FUPFL == "Y" ~ "Follow-Up" ), APHASEN = case_when( PREFL == "Y" ~ 1, ONTRTFL == "Y" ~ 2, FUPFL == "Y" ~ 3 ) ) %>% # Assign TRTP/TRTA mutate( TRTP = TRT01P, TRTA = TRT01A ) # Join all ADSL with CM adcm <- adcm %>% derive_vars_merged( dataset_add = select(adsl, !!!negate_vars(adsl_vars)), by_vars = exprs(STUDYID, USUBJID) ) # Save output ---- dir <- tempdir() # Change to whichever directory you want to save the dataset in saveRDS(adcm, file = file.path(dir, "adcm.rds"), compress = "bzip2")
use clap::{Command, Arg, ArgAction}; use regex::{Regex, RegexBuilder}; use std::error::Error; use std::fs::{self, File}; use std::io::{BufRead, BufReader}; use walkdir::WalkDir; type MyResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug)] pub struct Config { pattern: Regex, files: Vec<MyResult<String>>, count: bool, recursive: bool, invert_match: bool, } pub fn get_args() -> MyResult<Config> { let cmd = Command::new("grepr") .author("locnguyenvu") .version("0.0.1") .arg( Arg::new("pattern") .value_name("PATTERN") .action(ArgAction::Set) .required(true) ) .arg( Arg::new("files") .value_name("FILE") .action(ArgAction::Append) .default_value("-") ) .arg( Arg::new("insensitive") .short('i') .long("insensitive") .action(ArgAction::SetTrue) ) .arg( Arg::new("recursive") .short('r') .long("recursive") .action(ArgAction::SetTrue) ) .arg( Arg::new("count") .short('c') .long("count") .action(ArgAction::SetTrue) ) .arg( Arg::new("invert_match") .short('v') .long("invert-match") .action(ArgAction::SetTrue) ).get_matches(); let count = cmd.get_flag("count"); let recursive = cmd.get_flag("recursive"); let invert_match = cmd.get_flag("invert_match"); let insensitive = cmd.get_flag("insensitive"); let pattern_str = cmd.get_one::<String>("pattern").unwrap(); let pattern = RegexBuilder::new(pattern_str) .case_insensitive(insensitive) .build() .map_err(|_| format!("Invalid pattern \"{}\"", pattern_str))?; let files: Vec<String> = cmd.get_many::<String>("files").unwrap().map(|e| e.to_owned()).collect(); Ok(Config{ files: find_files(&files, recursive), pattern, recursive, count, invert_match, }) } pub fn run(config: Config) -> MyResult<()>{ for filename in &config.files { match filename { Ok(filename) => match open(filename) { Err(e) => { eprintln!("Failed to open {}: {}", filename, e) } Ok(f) => { let printmatch = |text: &String| { if config.recursive || config.files.len() > 1 { println!("{}:{}", filename, text); } else { println!("{}", text); } }; match find_lines(f, &config.pattern, config.invert_match) { Ok(lines) => { if config.count { printmatch(&lines.len().to_string()); } else { lines.iter().for_each(printmatch); } }, Err(e) => { return Err(From::from(format!("{}", e))); } } } }, Err(e) => { eprintln!("{}", e); } } } Ok(()) } fn open(filename: &str) -> MyResult<Box<dyn BufRead>> { match filename { "-" => { Ok(Box::new(BufReader::new(std::io::stdin()))) } _ => { Ok(Box::new(BufReader::new(File::open(filename)?))) } } } fn find_files(paths: &[String], recursive: bool) -> Vec<MyResult<String>> { let mut result: Vec<_> = vec![]; for path in paths { match path.as_str() { "-" => result.push(Ok(path.to_string())), _ => match fs::metadata(path) { Ok(metadata) => { if metadata.is_dir() { if recursive { for entry in WalkDir::new(path) .into_iter() .flatten() .filter(|e| !e.file_type().is_dir()) { result.push(Ok(entry .path() .display() .to_string())); } } else { result.push(Err(From::from(format!( "{}: Is a directory", path )))); } } else if metadata.is_file() { result.push(Ok(path.to_string())); } } Err(e) => { result.push(Err(From::from(format!("{}: {}", path, e)))) } } } } result } fn find_lines<T: BufRead>( file: T, pattern: &Regex, invert_match: bool, ) -> MyResult<Vec<String>> { let mut result: Vec<String> = vec![]; for line in file.lines() { let line = &line.unwrap(); if pattern.is_match(line) { if !invert_match { result.push(line.to_string()); } } else { if invert_match { result.push(line.to_string()); } } } Ok(result) } #[cfg(test)] mod tests { use super::{find_files, find_lines}; use rand::{distributions::Alphanumeric, Rng}; use regex::{Regex, RegexBuilder}; use std::io::Cursor; #[test] fn test_find_lines() { let text = b"Lorem\nIpsum\r\nDOLOR"; // The pattern _or_ should match the one line, "Lorem" let re1 = Regex::new("or").unwrap(); let matches = find_lines(Cursor::new(&text), &re1, false); assert!(matches.is_ok()); assert_eq!(matches.unwrap().len(), 1); // When inverted, the function should match the other two lines let matches = find_lines(Cursor::new(&text), &re1, true); assert!(matches.is_ok()); assert_eq!(matches.unwrap().len(), 2); // This regex will be case-insensitive let re2 = RegexBuilder::new("or") .case_insensitive(true) .build() .unwrap(); // The two lines "Lorem" and "DOLOR" should match let matches = find_lines(Cursor::new(&text), &re2, false); assert!(matches.is_ok()); assert_eq!(matches.unwrap().len(), 2); // When inverted, the one remaining line should match let matches = find_lines(Cursor::new(&text), &re2, true); assert!(matches.is_ok()); assert_eq!(matches.unwrap().len(), 1); } #[test] fn test_find_files() { // Verify that the function finds a file known to exist let files = find_files(&["./tests/inputs/fox.txt".to_string()], false); assert_eq!(files.len(), 1); assert_eq!(files[0].as_ref().unwrap(), "./tests/inputs/fox.txt"); // The function should reject a directory without the recursive option let files = find_files(&["./tests/inputs".to_string()], false); assert_eq!(files.len(), 1); if let Err(e) = &files[0] { assert_eq!(e.to_string(), "./tests/inputs: Is a directory"); } // Verify the function recurses to find four files in the directory let res = find_files(&["./tests/inputs".to_string()], true); let mut files: Vec<String> = res .iter() .map(|r| r.as_ref().unwrap().replace("\\", "/")) .collect(); files.sort(); println!("{:?}", &files); assert_eq!(files.len(), 4); assert_eq!( files, vec![ "./tests/inputs/bustle.txt", "./tests/inputs/empty.txt", "./tests/inputs/fox.txt", "./tests/inputs/nobody.txt", ] ); // Generate a random string to represent a nonexistent file let bad: String = rand::thread_rng() .sample_iter(&Alphanumeric) .take(7) .map(char::from) .collect(); // Verify that the function returns the bad file as an error let files = find_files(&[bad], false); assert_eq!(files.len(), 1); assert!(files[0].is_err()); } }
/* Copyright (C) 2006-2020 GSI Helmholtzzentrum fuer Schwerionenforschung, Darmstadt SPDX-License-Identifier: GPL-3.0-only Authors: Volker Friese, Denis Bertini [committer] */ /** @file CbmTofPoint.cxx ** @author Volker Friese <v.friese@gsi.de> ** @author Christian Simon <c.simon@physi.uni-heidelberg.de> ** @since 16.06.2014 ** @date 11.04.2017 **/ #include "CbmTofPoint.h" #include <FairMCPoint.h> // for FairMCPoint #include <TVector3.h> // for TVector3 #include <bitset> // for bitset #include <cassert> // for assert #include <limits> // for numeric_limits, numeric_limits<>::digits #include <sstream> // for operator<<, basic_ostream, stringstream #include <string> // for char_traits using std::endl; using std::string; using std::stringstream; // ----- Default constructor ------------------------------------------- CbmTofPoint::CbmTofPoint() : FairMCPoint(), fNofCells(0), fGapMask(0) {} // ------------------------------------------------------------------------- // ----- Standard constructor ------------------------------------------ CbmTofPoint::CbmTofPoint(int32_t trackID, int32_t detID, TVector3 pos, TVector3 mom, double tof, double length, double eLoss) : FairMCPoint(trackID, detID, pos, mom, tof, length, eLoss) , fNofCells(0) , fGapMask(0) { } // ------------------------------------------------------------------------- // ----- Destructor ---------------------------------------------------- CbmTofPoint::~CbmTofPoint() {} // ------------------------------------------------------------------------- // ----- Get the number of gaps ---------------------------------------- int32_t CbmTofPoint::GetNGaps() const { int32_t iNGaps(0); for (int32_t iGapBit = 0; iGapBit < std::numeric_limits<uint16_t>::digits; iGapBit++) { if (fGapMask & (0x1 << iGapBit)) { iNGaps++; } } return iNGaps; } // ------------------------------------------------------------------------- // ----- Get the index of the first gap -------------------------------- int32_t CbmTofPoint::GetFirstGap() const { for (int32_t iGapBit = 0; iGapBit < std::numeric_limits<uint16_t>::digits; iGapBit++) { if (fGapMask & (0x1 << iGapBit)) { return iGapBit; } } return -1; } // ------------------------------------------------------------------------- // ----- Get the index of the last gap --------------------------------- int32_t CbmTofPoint::GetLastGap() const { int32_t iLastGap(-1); for (int32_t iGapBit = 0; iGapBit < std::numeric_limits<uint16_t>::digits; iGapBit++) { if (fGapMask & (0x1 << iGapBit)) { iLastGap = iGapBit; } } return iLastGap; } // ------------------------------------------------------------------------- // ----- Add one gap to the gap mask ----------------------------------- void CbmTofPoint::SetGap(int32_t iGap) { assert(0 <= iGap && std::numeric_limits<uint16_t>::digits > iGap); fGapMask |= 0x1 << iGap; } // ------------------------------------------------------------------------- // ----- String output ------------------------------------------------- string CbmTofPoint::ToString() const { stringstream ss; ss << "STofPoint: track ID " << fTrackID << ", detector ID " << fDetectorID << "\n"; ss << " Position (" << fX << ", " << fY << ", " << fZ << ") cm \n"; ss << " Momentum (" << fPx << ", " << fPy << ", " << fPz << ") GeV \n"; ss << " Time " << fTime << " ns, Length " << fLength << " cm, Energy loss " << fELoss * 1.0e06 << " keV \n"; ss << " Number of cells " << fNofCells << ", gap mask " << std::bitset<std::numeric_limits<uint16_t>::digits>(fGapMask) << endl; return ss.str(); } // ------------------------------------------------------------------------- ClassImp(CbmTofPoint)
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_copy_strv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: akeryan <akeryan@student.42abudhabi.ae> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/02/13 14:28:26 by dabdygal #+# #+# */ /* Updated: 2024/03/02 14:33:09 by akeryan ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" static size_t strv_size(const char **strv) { size_t i; if (!strv) return (0); i = 0; while (strv[i]) i++; return (i); } static void free_strv(char **strv) { while (*strv) { free(*strv); *strv = NULL; strv++; } } char **ft_copy_strv(const char **strv) { int size; char **envp; int i; if (strv == NULL) return (NULL); size = strv_size((const char **)strv); envp = (char **)malloc(sizeof(char *) * (size + 1)); if (!envp) return (NULL); i = 0; while (i < size) { envp[i] = ft_strdup(strv[i]); if (envp[i] == NULL) { free_strv(envp + size + 1); return (NULL); } i++; } envp[i] = NULL; return (envp); }
package io.github.kangjinghang.chapter1_3.exercise; import io.github.kangjinghang.chapter1_3.Node; /** * 编写一个方法 delete(),接受一个 int 参数 k,删除链表的第 k 个元素(如果它存在的话)。 */ public class Ex20<T> { Node<T> first; public Ex20(Node<T> first) { this.first = first; } public void delete(int k) { // deal with k <= 0, list is empty if (k <= 0 || first == null) { return; } // deal with first node if (k == 1) { first = first.next; return; } Node<T> current = first; // 0 int i = 1; while (i < k - 1) { // k =3; // k - 1 = 2 // 0 1 // i = 1 current = current.next; // 1 i++; } Node<T> next = current.next; current.next = next.next; } public void display() { Node<T> current = first; while (current != null) { System.out.print(current.item + " -> "); current = current.next; } System.out.println("null"); } public static void main(String[] args) { Node<String> first = new Node<>(); Node<String> second = new Node<>(); Node<String> third = new Node<>(); Node<String> forth = new Node<>(); Node<String> fifth = new Node<>(); first.item = "first"; first.next = second; second.item = "second"; second.next = third; third.item = "third"; third.next = forth; forth.item = "forth"; forth.next = fifth; fifth.item = "fifth"; fifth.next = null; Ex20<String> ex = new Ex20<>(first); // 删除尾节点之前 System.out.println("原链表:"); ex.display(); ex.delete(4); System.out.println("删除成功"); System.out.println("新链表:"); ex.display(); } }
import "./navbar.css" import { Link } from "react-router-dom"; import { useContext } from "react"; import DataContext from "../store/dataContext"; import ReactDOM from 'react-dom' function Navbar(){ const cart = useContext(DataContext).cart return ( <nav className="navbar navbar-expand-lg bg-body-tertiary"> <div className="container-fluid"> <Link className="navbar-brand" to="#">Fish Fillet</Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link className="nav-link active" aria-current="page" to="/home">Home</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/catalog">Catalog</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/admin">Admin</Link> </li> </ul> <form className="d-flex" role="search"> <Link to = "/cart" className="btn btn-outline-info"><span className="badge text-bg-light">{cart.length} </span> View Cart</Link> </form> </div> </div> </nav> ); } export default Navbar;
package com.example.navigationinjetpackcompose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.navigationinjetpackcompose.ui.theme.NavigationInJetpackComposeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { Navigation() } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { NavigationInJetpackComposeTheme { Greeting("Android") } }
const express = require('express'); const cors = require('cors'); const connection = require('./connection'); const session = require('express-session'); const app = express(); app.use(cors()); app.use(express.json()); app.use( session({ secret: "some secret", // cookie: { maxAge: 30000 }, saveUninitialized: false, resave: true }) ); app.post('/reminderToDb' , (req,res)=>{ const { inquiryId, Date, nextDate } = req.body; // Insert data into the 'reminder' table const insertQuery = `INSERT INTO reminder (inquiryId, reminderDate, nextReminderDate) VALUES (?, ?, ?)`; connection.query(insertQuery, [inquiryId, Date, nextDate], (err, result) => { if (err) { console.error('Error saving reminder:', err); res.status(500).json({ error: 'Failed to save reminder.' }); } else { console.log('Reminder saved with ID:', result.insertId); res.json({ id: result.insertId }); // Sending the auto-generated ID back to React } }); }); app.post('/torToDatabase' , (req,res)=>{ const inquiryId = req.body.inquiryId; console.log( "inquiury id " + inquiryId); const tors = req.body.data; console.log(tors); tors.forEach((item) => { const { title, findings } = item; const insertQuery = `INSERT INTO tors (inquiryId, title, findings) VALUES (?, ?, ?)`; const values = [inquiryId, title, findings]; connection.query(insertQuery, values, (error, result) => { if (error) { console.error('Error inserting data into database:', error); } else { console.log('Data inserted successfully:', result); // res.send('Data inserted into database successfully'); } }); }); res.send('Data received successfully'); }); app.post('/r', (req, res) => { console.log(req.body.username); console.log(req.body.password); console.log(req.body.designation); const username = req.body.username; const password = req.body.password; const designation = req.body.designation; const status = "pending"; // console.log(connection); res.json({ message: 'server : Rcvd Input ' }); const dataToInsert = { userName: username, password: password, designation: designation, status : status }; const sql = 'INSERT INTO user (userName, password,designation,status) VALUES (?, ?, ?,?)'; connection.query(sql, [dataToInsert.userName, dataToInsert.password,dataToInsert.designation,dataToInsert.status], (err, result) => { if (err) { console.error('Error inserting data:', err); return; } console.log('Data inserted successfully:', result); }); }); app.get('/authorize', (req, res) => { const queryStr = "select * from user where status='pending'"; connection.query(queryStr, (error, results) => { if (error) { console.error('Error fetching data:', error); res.status(500).json({ error: 'Server error' }); } else { res.json(results); } }); }); app.get('/inquiryId' , (req,res)=>{ const u = "SELECT * from inquiry ORDER BY inquiryId DESC LIMIT 1;"; connection.query(u, (error, results) => { if (error) { console.error('Error fetching data:', error); res.status(500).json({ error: 'Server error' }); } else { res.json(results); } }); }); app.get('/employee-data' ,(req,res)=>{ const qu = "select * from employee"; connection.query(qu, (error, results) => { if (error) { console.error('Error fetching data:', error); res.status(500).json({ error: 'Server error' }); } else { res.json(results); } }); }); app.post('/login', (req, res) => { console.log(req.body.username); console.log(req.body.password); // res.json({ message: 'server : Rcvd Login information' }); const username = req.body.username; const password = req.body.password; const sql = 'SELECT id,userName,designation,status FROM user WHERE userName = ? AND password = ?'; connection.query(sql, [username, password], (err, result) => { if (err) { console.error('Error querying database:', err); res.json({ message: 'ServerError' }); return; } if (result.length === 0) { // User not found or invalid credentials res.json({ message: 'InvalidCredentials' }); } else { console.log(result[0].id); // login -> maintaining sessions const userId = result[0].id; req.session.userId = {userId}; console.log(req.session.userId); const userName = result[0].userName ; const designation = result[0].designation; const status = result[0].status; if ( status == "accepted"){ res.status(200).json({ message: 'AuthenticationSuccessful', userId ,userName,designation}); } else{ res.json({ message: 'UserNotApprovedYet' }); } } }); }); app.post('/authorize/accept', (req,res)=>{ console.log(req.body.id); const q = 'update user set status = ? where id = ?'; connection.query(q, ["accepted", req.body.id], (err, result) => { if (err) { console.error('Error querying database:', err); res.json({ message: 'ServerError' }); return; } if (result.length === 0) { res.json({ message: 'UpdateNotPossible' }); } else { const id=req.body.id ; res.status(200).json({message: 'UserAuthorized' , id }); } }); }); app.post('/authorize/decline', (req,res)=>{ const q2 = 'delete from user where id = ?'; connection.query(q2, [ req.body.id], (err, result) => { if (err) { console.error('Error querying database:', err); res.json({ message: 'ServerError' }); return; } if (result.length === 0) { res.json({ message: 'UpdateNotPossible' }); } else{ const id = req.body.id ; res.json({message: 'UserDeleted' , id}); } }); }); app.post('/logout', (req,res)=>{ console.log(req.session); if (req.session.id) { // Destroy the user's session (including userId) req.session.destroy((err) => { console.log("logout clicked "); if (err) { console.error('Error destroying session:', err); res.status(500).json({ message: 'LogoutFailed' }); } else { // Session destroyed successfully res.json({ message: 'logoutSuccess' }); } }); } }); process.on('exit', () => { closeDatabaseConnection(); }); // Or, if you are using Express, you can close the connection when the server is shutting down: app.on('close', () => { closeDatabaseConnection(); }); app.listen(8000, () => { console.log(`Server is running on port 8000.`); });
#include "header.h" /* quicksort: sort v[left]...v[right] into increasing order */ void quicksort(int v[], int left, int right) { int i, last; extern void swap(int v[], int i, int j); if (left >= right) /* do nothing if array contains fewer than two elements */ return; swap(v, left, (left + right) / 2); /* move partition element */ last = left; for (i = left + 1; i <= right; i++) /* partition */ if (v[i] < v[left]) swap(v, ++last, i); swap(v, left, last); /* restore partition item */ quicksort(v, left, last - 1); quicksort(v, last + 1, right); }
import { useNavigate } from "react-router-dom"; import SideBar from "../components/sideBar/sideBar"; import Navbar from "../components/navbar"; import { userContext } from "../context/userContext"; import { useContext, useState } from "react"; import AddNew from "../components/add-new"; export function Assignments() { const { user, assignments } = useContext(userContext); const navigate = useNavigate(); const [isAddNew, setIsAddNew] = useState(false); function addNewToggler() { setIsAddNew((prev) => !prev); } return ( <div className="d-flex main_container"> <SideBar /> <div className="main_body"> <Navbar /> <div className="assignment__container d-flex justify-content-center px-4"> <div className="col-12"> <h1 className="py-4">Assignments</h1> <div className="d-flex align-items-center justify-content-between"> <h3 className="my-2">List</h3> {user?.role.toLowerCase() === "lecturer" && ( <button className="add_new btn" onClick={addNewToggler}> Add new + </button> )} </div> <div className="sm-card m-auto w-100 mt-4"> <table class="table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Content</th> <th scope="col">Year</th> <th scope="col">Total Content</th> </tr> </thead> <tbody> {assignments.map((value, index) => ( <tr onClick={() => navigate(`/assignment?id=${value._id}`)} key={index} > <th>{value.title}</th> <td>{value.description.slice(0, 20)}...</td> <td>{value.year}</td> <td>{value.description.length} Contents</td> </tr> ))} </tbody> </table> </div> </div> </div> </div> {isAddNew && <AddNew addNewToggler={addNewToggler} />} </div> ); }
// // LLJAboutSwiftController.swift // Dandelion-swift // // Created by 刘帅 on 2021/5/21. // import UIKit //MARK: - extension - extension LLJAboutSwiftController { /* * 1. extension 不是创建属性,属性只能在class里创建。可以使用计算属性来关联属性(类似oc动态添加属性) */ } class LLJAboutSwiftController: LLJFViewController { //MARK: - 闭包 - //创建别名闭包 typealias supBlock = ((String, String) -> Void) //属性闭包 var subBlock: supBlock? //给当前类声明一个闭包变量supBlock,将subBlock函数内的闭包参数赋值给这个变量,此时这个闭包就可以在函数执行结束后或其他时候被调用。 //上述闭包即为逃逸闭包要用 @escaping 修饰 func subBlock(block: @escaping supBlock) { self.subBlock = block } //给函数subBlock1传递一个闭包参数block。 func subBlock1(block: (String, String) -> Void) { //此时闭包block调用只能在函数作执行结束前被当做函数内的任务依次被执行,这种情况下的闭包就是非逃逸闭包。 block("str1","str2") } typealias boclk = ((String, String) -> Void) //MARK: - 属性 - //存储属性 var name: String? var _age: String = "age" //计算属性 //get var name1: String { get { return "str1" } } //get set //通常使用计算属性给存储属性赋值(类似oc重写属性get set方法) var age: String { set { _age = newValue } get { return _age } } override func viewDidLoad() { super.viewDidLoad() //闭包相关 block() //NSString 类簇 及 深拷贝浅拷贝 stringAndCopy() } } //MARK - 闭包相关 - extension LLJAboutSwiftController { func block() { self.view.backgroundColor = LLJWhiteColor() self.subBlock = {(str1, str2) in LLJLog(str1 + " 1 " + str2) } if self.subBlock != nil { self.subBlock!("str1","str2") } self.subBlock { (str1, str2) in LLJLog(str1 + " 2 " + str2) } if self.subBlock != nil { self.subBlock!("str1","str2") } self.subBlock1 { (str1, str2) in LLJLog(str1 + " 3 " + str2) } } } //MARK - NSString 类簇 及 深拷贝浅拷贝 - extension LLJAboutSwiftController { func stringAndCopy() { self.view.backgroundColor = LLJWhiteColor() } } //MARK - guard判断语句 不符合条件执行else 符合条件继续执行 - extension LLJAboutSwiftController { func showName(name: String?) { guard let name = name else { print("name==nil") return } print("my name is \(name)") } } //MARK - swift 关键字 - extension LLJAboutSwiftController { //let:声明静态变量,类似于const,用let声明的变量不可以再赋值,不然会报错 //var:声明变量,是可以改变值 //class:用来声明一个类 //enum:用来声明一个枚举 //func:用来定义函数 //init:相对于类的构造方法的修饰 //deinit:属于析构函数。析构函数(destructor) 与构造函数相反,当对象结束其生命周期时(例如对象所在的函数已调用完毕),系统自动执行析构函数 //fileprivate: 权限在本文件可访问,一个文件可以定义多个类或结构体 //private: 权限在该类或结构体可访问 //guard: 判断语句 符合条件继续往下执行 不符合条件执行else 通常是return //where:用于条件判断,和数据库查询时的where 'id > 10'这样功能. swift语言的特性.OC中并没有 //mutating:写在func前面,以便于让func可以修改struct和protocol的extension中的成员的值。 如果func前面不加mutating,struct和protocol的extension中的成员的值便被保护起来,不能修改 //is:is一般用于对一些变量的类型做判断.类似于OC中的isKindClass. as 与强制转换含义雷同 //as:keyword:Guaranteed conversion、 Upcasting 理解:字面理解就是有保证的转换,从派生类转换为基类的向上转型 //as?: keyword:** Optional、 Nil*** Swfit代码写一段时间后会发现到处都是 ?,这预示着如果转换不成功的时候便会返回一个 nil 对象,成功的话返回可选类型值(optional)。 //extension:扩展,类似于OC的categories,Swift 中的可以扩展以下几个: /* 添加计算型属性和计算静态属性 定义实例方法和类型方法 提供新的构造器 定义下标 定义和使用新的嵌套类型 使一个已有类型符合某个接口 */ //typealias:为此类型声明一个别名.和 typedef类似. //override:如果我们要重写某个方法, 或者某个属性的话, 我们需要在重写的变量前增加一个override关键字 //subscript:下标索引修饰.可以让class、struct、以及enum使用下标访问内部的值 //final:Swift中,final关键字可以在class、func和var前修饰。表示 不可重写,可以将类或者类中的部分实现保护起来,从而避免子类破坏 //break:跳出循环.一般在控制流中使用,比如 for . while switch等语句 //case:switch的选择分支. //continue: 跳过本次循环,继续执行后面的循环. //in:范围或集合操作,多用于遍历. //fallthrough: //swift语言特性switch语句的break可以忽略不写,满足条件时直接跳出循环 //.fallthrough的作用就是执行完当前case,继续执行下面的case //.类似于其它语言中省去break里,会继续往后一个case跑,直到碰到break或default才完成的效果 //dynamicType : 获取对象的动态类型,即运行时的实际类型,而非代码指定或编译器看到的类型 //#column: 列号, //#file:路径, //#function: 函数, //#line : 行号 //print("COLUMN = (#column) \n FILE = (#file) \n FUNCTION = (#function) \n LINE = (#line)") //convenience:convenience用来进行方便的初始化,就相当于构造函数重载。 /* convenience init(name:String!,nikname:String!) { self.init() self.name = name self.nikname = nikname } */ } //MARK - forEach 简化版for循环 - extension LLJAboutSwiftController { func forEach1() { for view in self.view.subviews { if view is UIButton { let _: UIButton = view as! UIButton } } } func forEach2() { self.view.subviews.forEach { (view) in let _: UIButton = view as! UIButton } } } //MARK - //swift自动为闭包提供参数名缩写功能,可以直接通过$0和$1等来表示闭包中的第一个第二个参数 - extension LLJAboutSwiftController { //删除所有子视图 func removeSubView() { self.view.subviews.forEach {$0.removeFromSuperview()} } } /* Swift中struct和class有什么不一样的地方?首先要先和大家提到一个观念,值类型ValueType和引用类型ReferenceType。其中 struct是ValueType而class是ReferenceType。 值类型的变量直接包含他们的数据,而引用类型的变量存储对他们的数据引用,因此后者称为对象,因此对一个变量操作可能影响另一个变量所引用的对象。对于值类型都有他们自己的数据副本,因此对一个变量操作不可能影响另一个变量。 定义一个struct struct SRectangle { var width = 200 } 定义一个class class CRectangle { var width = 200 } 1. 成员变量 struct SRectangle { var width = 200 var height: Int } class CRectangle { var width = 200 var height: Int // 报错 } 解释: struct定义结构体类型时其成员可以没有初始值,如果使用这种格式定义一个类,编译器是会报错的,他会提醒你这个类没有被初始化。 2. 构造器 var sRect = SRectangle(width: 300) sRect.width // 结果是300 var cRect = CRectangle() // 不能直接用CRectangle(width: 300),需要构造方法 cRect.width // 结果是200 解释: 所有的struct都有一个自动生成的成员构造器,而class需要自己生成。 3. 指定给另一个变量的行为不同 var sRect2 = sRect sRect2.width = 500 sRect.width // 结果是300 var cRect2 = cRect cRect2.width = 500 cRect.width // 结果是500 解释: ValueType每一个实例都有一份属于自己的数据,在复制时修改一个实例的数据并不影响副本的数据。而ReferenceType被复制的时候其实复制的是一份引用,两份引用指向同一个对象,所以在修改一个实例的数据时副本的数据也被修改了。 4. 不可变实例的不同 let sRect3 = SRectangle(width: 300); sRect3.width = 500 // 报错 let cRect3 = CRectangle() cRect3.width = 500 解释: struct对于let声明的实例不能对变量进行赋值,class预设值是可以赋值let实例的。注意Swift中常用的String、Array、 Dictionary都是struct。 方法 struct SRectangle { var width = 200 mutating func changeWidth(width: Int) { self.width = width } } class CRectangle { var width = 200 func changeWidth(width: Int) { self.width = width } } 解释: struct的方法要去修改property的值,要加上mutating,class则不需要。 继承 struct不能继承,class可以继承 */
/* * Copyright (c) 2022 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * This project and source code may use libraries or frameworks that are * released under various Open-Source licenses. Use of those libraries and * frameworks are governed by their own individual licenses. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.raywenderlich.learn.presentation import com.raywenderlich.learn.data.model.RWContent import com.raywenderlich.learn.data.model.RWEntry import com.raywenderlich.learn.domain.GetFeedData import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json private const val TAG = "FeedPresenter" private const val RW_CONTENT = "[" + "{\"platform\":\"all\", \"url\":\"https://www.raywenderlich.com/feed.xml\", \"image\":\"https://assets.carolus.raywenderlich.com/assets/razeware_460-308933a0bda63e3e327123cab8002c0383a714cd35a10ade9bae9ca20b1f438b.png\"}," + "{\"platform\":\"android\", \"url\":\"https://raywenderlich.com/android/feed\", \"image\":\"https://koenig-media.raywenderlich.com/uploads/2017/11/android-love-1-1.png\"}," + "{\"platform\":\"ios\", \"url\":\"https://raywenderlich.com/ios/feed\", \"image\":\"https://koenig-media.raywenderlich.com/uploads/2018/09/iOS12_LaunchParty-feature.png\"}," + "{\"platform\":\"unity\", \"url\":\"https://raywenderlich.com/gametech/feed\", \"image\":\"https://koenig-media.raywenderlich.com/uploads/2021/03/Unity2D-feature.png\"}," + "{\"platform\":\"flutter\", \"url\":\"https://raywenderlich.com/flutter/feed\", \"image\":\"https://koenig-media.raywenderlich.com/uploads/2018/11/OpenCall-Android-Flutter-Book-feature.png\"}" + "]" private const val RW_ALL_FEED = """ [ { "id": "https://www.raywenderlich.com/26244793-building-a-camera-app-with-swiftui-and-combine", "link": "https://www.raywenderlich.com/26244793-building-a-camera-app-with-swiftui-and-combine", "summary":"Learn to natively build your own SwiftUI camera app using Combine and create fun filters using the power of Core Image.", "title": "Building a Camera App With SwiftUI and Combine [FREE]", "updated": "2021-11-10T13:59:59Z" }, { "id": "https://www.raywenderlich.com/29045204-announcing-swiftui-by-tutorials-fourth-edition", "link": "https://www.raywenderlich.com/29045204-announcing-swiftui-by-tutorials-fourth-edition", "summary":"Build apps more efficiently with SwiftUI’s declarative approach and leave the old ways of imperative coding in the dust, with this freshly-updated book.", "title": "Announcing SwiftUI by Tutorials, Fourth Edition! [FREE]", "updated": "2021-11-10T13:44:43Z" }, { "id": "https://www.raywenderlich.com/books/swiftui-by-tutorialse", "link": "https://www.raywenderlich.com/books/swiftui-by-tutorials", "summary":"Build fluid and engaging declarative UI for your apps — using less code — with SwiftUI!</h2> <p>SwiftUI by Tutorials is designed to help you learn how to transition from the “old way” of building your app UI with UIKit, to the “new way” of building responsive UI with modern declarative syntax with SwiftUI. This book is for readers who are comfortable building Swift apps, and want to make the exciting leap into building their app UI with modern, declarative code.</p> <h3>What is SwiftUI?</h3> <p>SwiftUI lets you build better apps, faster, and with less code. It’s a developer’s dream come true! With SwiftUI, you can design your user interfaces in a declarative way; instead of developing app interfaces in an imperative way, by coding all of the application state logic before time, you can instead define what your app’s UI <em>should</em> do in a particular state and let the underlying OS figure out <em>how</em> to do it. What’s more is that SwiftUI lets you build modern, responsive UI and animations for <em>all</em> Apple devices — not just iOS. So whether you’re building apps for iOS, watchOS, tvOS or any other Apple platform, you can use the same concise, natural language to describe your UI and have it look stunning — no matter where your code runs. In addition, SwiftUI’s built-in automatic support for things such as dark mode, localization and accessibility, along with Xcode 11 support for drag-and-drop design and instant preview makes it easier to build apps than ever before.</p> <h3>How is this book different than SwiftUI Apprentice?</h3> <p>Our other book on getting started with SwiftUI, <a href=\"https://www.raywenderlich.com/books/swiftui-apprentice/\">SwiftUI Apprentice</a>, is designed to teach new developers how to build iOS apps, using a SwiftUI-first approach. The goal of that book is to teach you fundamental development practices as you build out some fully-functional and great-looking apps! This book, <em>SwiftUI by Tutorials</em>, is designed for developers who have a solid background in iOS development, and are looking to make the leap from building apps with UIKit, to building apps with SwiftUI.", "title": "SwiftUI by Tutorials [SUBSCRIBER]", "updated": "2021-11-10T00:00:00Z" }, { "id": "https://www.raywenderlich.com/26933987-flutter-ui-widgets", "link": "https://www.raywenderlich.com/26933987-flutter-ui-widgets", "summary":"Explore commonly used UI widgets in Flutter and see how they relate to their native iOS and Android counterparts.", "title": "Flutter UI Widgets [SUBSCRIBER]", "updated": "2021-11-09T00:00:00Z" }, { "id": "https://www.raywenderlich.com/26236685-shazamkit-tutorial-for-ios-getting-started", "link": "https://www.raywenderlich.com/26236685-shazamkit-tutorial-for-ios-getting-started", "summary":"Learn how to use ShazamKit to find information about specific audio recordings by matching a segment of that audio against a reference catalog of audio signatures.", "title": "ShazamKit Tutorial for iOS: Getting Started [FREE]", "updated": "2021-11-08T13:59:30Z" } ] """ class FeedPresenter(private val feed: GetFeedData) { private val json = Json { ignoreUnknownKeys = true } val content: List<RWContent> by lazy { json.decodeFromString(RW_CONTENT) } val allFeeds: List<RWEntry> by lazy { json.decodeFromString(RW_ALL_FEED) } }
import searchIcon from "../../assets/icons/search.svg"; import { CustomerRow } from "../CustomerRow"; import { Pagination } from "../Pagination"; import "./CustomersList.scss"; const customersList = [ { name: "Jane Cooper", company: "Microsoft", phone: "(225) 555-0118", email: "jane@microsoft.com", country: "United States", status: "active", }, { name: "Floyd Miles", company: "Yahoo", phone: "(205) 555-0100", email: "floyd@yahoo.com", country: "Kiribati", status: "inactive", }, { name: "Ronald Richards", company: "Adobe", phone: "(302) 555-0107", email: "ronald@adobe.com", country: "Israel", status: "inactive", }, { name: "Marvin McKinney", company: "Tesla", phone: "(252) 555-0126", email: "marvin@tesla.com", country: "Iran", status: "active", }, { name: "Jerome Bell", company: "Google", phone: "(629) 555-0129", email: "jerome@google.com", country: "Réunion", status: "active", }, { name: "Kathryn Murphy", company: "Microsoft", phone: "(406) 555-0120", email: "kathryn@microsoft.com", country: "Curaçao", status: "active", }, { name: "Jacob Jones", company: "Yahoo", phone: "(208) 555-0112", email: "jacob@yahoo.com", country: "Brazil", status: "active", }, { name: "Kristin Watson", company: "Facebook", phone: "(704) 555-0127", email: "kristin@facebook.com", country: "Åland Islands", status: "inactive", }, ]; export const CustomersList = () => { return ( <div className="customers-list"> <div className="customers-list__header"> <div className="customers-list__header-title"> <h3 className="customers-list__header-title-content"> All Customers </h3> <p className="customers-list__header-title-hint">Active Members</p> </div> <div className="customers-list__header-search"> <input className="customers-list__header-search-input" type="text" placeholder="Search" /> <img className="customers-list__header-search-img" src={searchIcon} alt="Q" /> </div> </div> <div className="customers-list__table"> <ul className="customers-list__table-list"> <li className="customers-list__table-header"> <div className="customers-list__table-cell-name">Customer Name</div> <div className="customers-list__table-cell-company">Company</div> <div className="customers-list__table-cell-phone">Phone Number</div> <div className="customers-list__table-cell-email">Email</div> <div className="customers-list__table-cell-country">Country</div> <div className="customers-list__table-cell-status">Status</div> </li> {customersList.map((customer) => { return ( <li key={customer.name} className="customers-list__table-row"> <CustomerRow {...customer} /> </li> ); })} </ul> </div> <div className="customers-list__info"> <p className="customers-list__info-data"> Showing data 1 to 8 of 256K entries </p> <div className="customers-list__info-pagination"> <Pagination/> </div> </div> </div> ); };
<!DOCTYPE html> <html lang="ru" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/> <title>Редактировать профиль</title> <div th:insert="blocks/webjars :: webjars"></div> <link rel="stylesheet" th:href="@{/css/profileStyle.css}"> <link rel="stylesheet" th:href="@{/css/datepickerStyle.css}"> <script type="text/javascript" th:src="@{/js/phoneForm.js}"></script> <script type="text/javascript" th:src="@{/js/deleteConfirmation.js}"></script> <script type="text/javascript" th:src="@{/js/newPasswordModals.js}"></script> <script type="text/javascript" th:src="@{/js/photoPreview.js}"></script> <script type="text/javascript" th:src="@{/js/passwordMatch.js}"></script> <script type="text/javascript" th:src="@{/js/showHidePassword.js}"></script> <script type="text/javascript" th:src="@{/js/setDatepicker.js}"></script> </head> <script> $(document).ready(function() { setDatepicker($("#inputBirthDate"), $("#editSubmit")); }); </script> <body> <div class="wrapper"> <div class="content"> <header th:insert="blocks/header :: header"></header> <div class="container-fluid" style="padding-left: 85px"> <div class="row"> <!--Профиль--> <div class="leftC col-md-5"> <form th:method="PUT" th:action="@{/patients/{id}(id=${patient.getId()})}" th:object="${patient}" enctype="multipart/form-data"> <h3 class="top mt-4">Профиль</h3> <!--Фото профиля--> <div> <label for="file-input" class="photoFrame"> <img class="mainPhotoInput" id="profileImage" th:if="${patient.getImage() != null && !patient.getImage().isEmpty()}" th:src="@{/applicationFiles/patients/{id}/{image}(id=${patient.getId()}, image=${patient.getImage()})}"> <div th:if="${patient.getImage() == null || patient.getImage().isEmpty()}"> <img class="mainPhotoInput" th:if="${patient.getSex() == 1}" th:src="@{/applicationFiles/usersFiles/manProfile.jpg}"> <img class="mainPhotoInput" th:if="${patient.getSex() == 2}" th:src="@{/applicationFiles/usersFiles/womenProfile.png}"> </div> <!--Icon--> <div class="iconInput"> <i class="las la-portrait la-5x"></i> </div> </label> <input id="file-input" type="file" style="display: none;" accept="image/png, image/jpeg, image/jpg" th:name="profileImage"/> </div> <!--Данные пользователя--> <div class="container headlines"> <!--Ряд имени и фамилии--> <div class="row d-flex justify-content-center mt-1"> <input class="attrBlock col-5" id="inputName" type="text" th:field="*{name}" th:value="${patient.getName()}"> <div class="col-1"></div> <input class="attrBlock col-5" id="inputSurname" type="text" th:field="*{surname}" th:value="${patient.getSurname()}"> </div> <div class="row d-flex justify-content-center mt-1" th:if="${#fields.hasErrors('name') || #fields.hasErrors('surname')}"> <div class="col-5 messageAlert" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></div> <div class="col-1"></div> <div class="col-5 messageAlert" th:if="${#fields.hasErrors('surname')}" th:errors="*{surname}"></div> </div> <!--Ряд пола и даты пождения--> <div class="row d-flex justify-content-center mt-4"> <select class="col-5 attrBlock" id="sexInput" th:field="*{sex}" th:selected="${patient.getSex()}"> <option value="0" disabled>Не выбрано</option> <option value="1">Мужчина</option> <option value="2">Женщина</option> </select> <div class="col-1"></div> <input class="col-5 attrBlock" id="inputBirthDate" type="text" th:value="${T(org.apache.commons.lang3.time.DateFormatUtils).format(patient.getBirthDate(), 'dd-MM-yyyy')}"> </div> <div class="row d-flex justify-content-center mt-1" th:if="${#fields.hasErrors('sex') || #fields.hasErrors('birthDate')}"> <div class="col-5 messageAlert" th:if="${#fields.hasErrors('sex')}" th:errors="*{sex}"></div> <div class="col-1"></div> <div class="col-5 messageAlert" th:if="${#fields.hasErrors('birthDate')}" th:errors="*{birthDate}"></div> </div> <!--Ряд телефона и email-а--> <div class="row d-flex justify-content-center mt-4"> <input class="col-5 attrBlock" data-tel-input type="tel" id="inputPhone" th:field="*{telephone}" th:value="${patient.getTelephone()}"> <div class="col-1"></div> <input class="col-5 attrBlock" id="inputEmail" type="email" th:value="${patient.getEmail()}" disabled> </div> <!--Ряд подтверждения почты--> <div class="row d-flex justify-content-center"> <div class="col-5 messageAlert" th:if="${#fields.hasErrors('telephone')}" th:errors="*{telephone}"></div> <div class="col-5" th:unless="${#fields.hasErrors('telephone')}"></div> <div class="col-1"></div> <!--Подтверждена--> <h5 class="col-5 buttonFont aStyleText" th:if="${patient.isConfirmed() == true}">Почта подтверждена</h5> <!--Не Подтверждена--> <h5 class="btn col-5 btn-link buttonFont aStyleButton" th:if="${patient.isConfirmed() == false}">Подтвердить почту</h5> </div> <!--Спрятанные поля--> <div> <input id="inputId" th:value="${patient.getId()}" hidden> <input id="hiddenBirthDate" type="date" th:field="*{birthDate}" hidden> <input th:field="*{email}" hidden> <input th:field="*{password}" th:value="${'Password915#'}" hidden> </div> </div> <!--Кнопка--> <div class="mt-4"> <!--Подтвердить--> <div class="d-flex justify-content-center align-items-center"> <input class="btn btn-primary button mt-5 mb-3 px-4" id="editSubmit" type="submit" value="Подтвердить"/> </div> <!--Изменить пароль--> <div class="mt-5 pt-2"> <a class="mutedButton" id="changePasswordButton" data-bs-toggle="modal" data-bs-target="#checkPasswordModal"> Изменить пароль </a> </div> <!--Удалить аккаунт--> <div class="mt-1 pt-2"> <a class="mutedButton" id="deleteButton" data-bs-toggle="modal" data-bs-target="#warningDeleteModal"> Удалить аккаунт </a> </div> </div> </form> </div> <!--Разделитель--> <div class="col-1"> <div class="greenLine"></div> </div> <!--Приёмы--> <div class="rightC col" aria-disabled="true"> <h3 class="mt-4 top">Мои Приёмы</h3> <div class="overflow-auto" style=" max-height: 550px; overflow: auto"> <!--Нет приемов --> <div class="doctorBody mt-4" style="width: 520px" th:if="${patient.getAppointments().size() == 0}"> <!--Центрируем данные--> <!--Плажка зеленая--> <div class="greenDoctorHeader d-flex align-items-center justify-content-center"></div> <div class="container-fluid d-flex align-items-center justify-content-center mt-3" style=" margin-left: auto;"> <div> <h4 class="themes">У вас еще нет приемов</h4> <h5 class="headlines"> Запишитесь к нашим специалистам</h5> <i class="las la-heartbeat la-4x" style="color:#243528 "></i> </div> </div> </div> <!--Список приёмов--> <ul th:if="${patient.getAppointments().size() != 0}"> <li th:each="appointment : ${patient.getAppointments()}"> <!--Карточка--> <div class="doctorBody mt-4"> <!--Плажка зеленая--> <div class=" green d-flex align-items-center justify-content-center"></div> <div class="container-fluid"> <!--Доктор--> <div class="row mt-2"> <!--Фото--> <div class="col-2"> <img class="doctorPhoto float-start" alt="" th:src="@{/applicationFiles/doctors/{id}/{image}(id=${appointment.getDoctor().getId()}, image=${appointment.getDoctor().getImage()})}"> </div> <!--Личные данные--> <div class="col text-start"> <!--ФИО--> <h4 class="themes mt-1" th:text="${appointment.getDoctor().getSurname() + ' ' + appointment.getDoctor().getName() + ' ' + appointment.getDoctor().getPatronymic()}"></h4> <!--Описание специалиста--> <h5 class="headlines" th:text="${#strings.setJoin(appointment.getDoctor().getSpecialities(), ', ') + ', ' + appointment.getDoctor().getCategory() + ', Стаж ' + appointment.getDoctor().getExperienceWithPrefix()}"></h5> </div> </div> <!--Данные приема и кнопка--> <div class="row"> <!--Дата, время, кабинет--> <div class="col-8 row gx-1 headlines"> <div class="col text-start mx-2"> <h5>Дата:</h5> <span class="spanStyle" th:text="${appointment.getDate() + ' ' + #dates.dayOfWeekName(appointment.getDate())}"></span> </div> <div class="col-1"></div> <div class="col text-start"> <h5>Время:</h5><span class="p-1 spanStyle" th:text="${appointment.getTime()}"></span> </div> <div class="col text-start"> <h5>Кабинет:</h5><span class="p-1 spanStyle" th:text="${appointment.getDoctor().getCabinet() + ' каб'}"></span> </div> </div> <!--Подробнее кнопка--> <div class="col "> <button class="btn btn-primary button float-end mt-2 mb-3 px-4"> Подробнее </button> </div> </div> </div> </div> </li> </ul> </div> </div> </div> </div> </div> <footer th:insert="blocks/footer :: footer"></footer> </div> <!--Модальные окна--> <div class="container"> <!-- Окно удаления --> <div class="modal fade" id="warningDeleteModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content doctorBody mt-4 "> <div class="greenDoctorHeader d-flex align-items-center justify-content-end" > <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="margin: 4rem 1rem 0 0; position: absolute;"></button> </div> <div class="container-fluid mt-3" style=" margin-left: auto;"> <div> <h5 class="headlines d-flex align-items-center justify-content-center">Удаление аккаунта</h5> <p class="buttonFont"> При удалении аккаунта связанные с ним данные будут удалены без возможности восстановления. Это действие нельзя будет отменить, вы абсолютно уверены? </p> </div> <div class="d-flex align-items-center justify-content-center mb-3"> <button type="button" class="btn buttonFont" data-bs-dismiss="modal">Закрыть</button> <button type="button" id="warningDeleteButton" class="btn btn-primary button" data-bs-toggle="modal" data-bs-target="#confirmDeleteModal">Подтвердить </button> </div> </div> </div> </div> </div> <!-- Окно подтверждения удаления --> <div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content doctorBody"> <!--Плажка зеленая--> <div class="greenDoctorHeader d-flex align-items-center justify-content-end"> <button id="closeConfirmDeleteModal" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="margin: 4rem 1rem 0 0; position: absolute;"></button> </div> <div class="container-fluid mt-3" style=" margin-left: auto;"> <div id="confirmDeleteModalBody"> <h5 class="headlines d-flex align-items-center justify-content-center">Удаление аккаунта</h5> <p class="buttonFont"> На вашу почту было отправлено письмо с кодом подтверждения. Для подтверждения удаления введите код в форму ниже: </p> <form id="confirmDeleteForm" class="d-flex align-items-center justify-content-center mb-1"> <input name='code' class='code-input form-control squareInput'/> <input name='code' class='code-input form-control squareInput'/> <input name='code' class='code-input form-control squareInput'/> <span>-</span> <input name='code' class='code-input form-control squareInput'/> <input name='code' class='code-input form-control squareInput'/> <input name='code' class='code-input form-control squareInput'/> <br> </form> <div class="d-flex align-items-center justify-content-center mb-3"> <div style="width: 360px;" id="incorrectCode"></div> </div> </div> <div class="d-flex align-items-center justify-content-center mb-3" id="confirmDeleteModalFooter"> <button type="button" class="btn buttonFont" data-bs-dismiss="modal">Закрыть</button> <button type="button" id="confirmDeleteButton" class="btn btn-primary button">Подтвердить</button> </div> </div> </div> </div> </div> <!-- Окно ввода текущего пароля --> <div class="modal fade" id="checkPasswordModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content doctorBody"> <div class="greenDoctorHeader d-flex align-items-center justify-content-end"> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="margin: 4rem 1rem 0 0; position: absolute;"></button> </div> <div class="container-fluid mt-3" style=" margin-left: auto;"> <div> <h5 class="headlines d-flex align-items-center justify-content-center">Изменение пароля</h5> <p class="buttonFont d-flex justify-content-center"> Введите свой текущий пароль: </p> <!--Форма--> <div class="input-group mb-3 ms-4" style="width: 400px"> <input class="form-control border-end-0 inputPasswordClass" type="password" id="checkActualPassword" value="" aria-describedby="basic-addon1"> <div class="input-group-addon"> <span class="input-group-text rounded-start-0 textarea-addon" id="basic-addon1"> <i class="bi bi-eye-slash togglePasswordClass"></i> </span> </div> </div> <div class="ms-4" style="width: 400px" id="incorrectPassword"></div> </div> <div class="d-flex align-items-center justify-content-center mb-3"> <button type="button" class="btn buttonFont" data-bs-dismiss="modal">Закрыть</button> <button type="button" id="submitCheckPassword" class="btn btn-primary button">Подтвердить </button> </div> </div> </div> </div> </div> <!-- Окно ввода нового пароля --> <div class="modal fade " id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePasswordModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content doctorBody"> <div class="greenDoctorHeader d-flex align-items-center justify-content-end"> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="margin: 4rem 1rem 0 0; position: absolute;"></button> </div> <div id="changePasswordModalBody"> <h5 class="headlines d-flex align-items-center justify-content-center mt-3">Изменение пароля</h5> <div class="container-fluid" style=" margin-left: auto;"> <p class="buttonFont d-flex justify-content-center">Введите новый пароль:</p> <div class="input-group mb-3 ms-4" style="width: 400px"> <input class="form-control border-end-0 inputPasswordClass" type="password" id="inputPassword" value="" onkeyup='check($("#submitChangePassword"));' aria-describedby="basic-addon2"> <div class="input-group-addon"> <span class="input-group-text rounded-start-0 textarea-addon" id="basic-addon2"> <i class="bi bi-eye-slash togglePasswordClass"></i> </span> </div> </div> <p class="buttonFont d-flex justify-content-center">Подтвердите новый пароль:</p> <input class="form-control inputPasswordClass ms-4" type="password" id="inputConfirmPassword" onkeyup='check($("#submitChangePassword"));' value="" style="width: 400px"> <!--Matching--> <div class="ms-4"> <span id="passwordMessage"></span> </div> </div> <div class="d-flex align-items-center justify-content-center mb-3 mt-3"> <button type="button" class="btn buttonFont" data-bs-dismiss="modal">Закрыть</button> <button type="button" id="submitChangePassword" class="btn btn-primary">Подтвердить </button> </div> <!--Ошибки--> <div class="mx-5"> <ul class="p-0" id="errorsPassword"> </ul> </div> </div> </div> </div> </div> </div> </div> </body> </html>
import { Form, json, useNavigation, useSearchParams, Link, useActionData } from "react-router-dom"; import classes from './AuthForm.module.css' const AuthForm = () => { const navigation = useNavigation(); const data = useActionData(); const [serchParams] = useSearchParams(); const isLogin = serchParams.get('mode') === 'login'; const isSubmitting = navigation.state === 'submitting'; return ( <Form className={classes.form} method="post"> <h1>{isLogin ? 'Login' : 'Create new user'}</h1> { data && data.error && ( <ul className={classes.errors}> {Object.values(data.error).map((err) => ( <li key={err} >{err}</li>))} </ul> ) } {!isLogin && <p> <label htmlFor="name" >Name</label> <input type="text" name="name" id="name" required /> </p>} <p> <label htmlFor="email" >Email</label> <input type="text" name="email" id="email" required /> </p> <p> <label htmlFor="password" >Password</label> <input type="password" name="password" id="password" required /> </p> <div className={classes.actions}> <Link to={`?mode=${isLogin ? 'signup' : 'login'}`}> {isLogin ? 'Create new user' : 'Login'} </Link> <button type='submit'>{isSubmitting ? 'Submitting...' : 'Save'}</button> </div> </Form> ) } export default AuthForm;
# Start time: 2024-04-10 14:59:27.347537 ''' Prompt: The prompt describes the relationship between the inputs and outputs. Given that the prompt is: Summary for Input Column Data: - The input column data consists of URLs in the format of protocol=//domain/path. - Each URL in the input column data follows a similar structure with variations in the domain and path. Summary for Output Column Data: - The output column data consists of URLs with the protocol and domain extracted from the corresponding input URLs. - The output URLs retain the protocol and domain from the input URLs while removing the path component. Relationship between Input and Output: - The relationship between the input and output is that the output URLs are derived from the input URLs by extracting the protocol and domain components while excluding the path component. - The output URLs serve as a simplified version of the input URLs, focusing on the essential protocol and domain information. - This process of extracting and simplifying the URLs helps in creating a more concise and structured representation of the original URLs., and input as ['https=//abc.com/def'] output is https=//abc.com/, input as ['http=//www.abc.com/def/cef'] output is http=//www.abc.com, input as ['http=//chandoo.org/wp/def-def'] output is http=//chandoo.org/, , generate a python function that matches the given input and output above, treating the input and output as strings, not lists. If the input has multiple list elements, that means there are separate inputs that should be passed as separate arguments to the python function. Include the above input in test cases. Do not include the output of the test code in the python program. The generated python code should have only executable statements and comments. The function should return the output, not print it. Do not include assert statements. Name the generated python function as generated_function. Make sure to generate a python function as defined above. ''' def generated_function(input_str): # Split the input string into protocol, domain, and path components protocol, domain_path = input_str.split('=') domain, path = domain_path.split('/', 1) # Construct the output URL with protocol and domain only output_str = f"{protocol}={domain}/" return output_str # Test cases print(generated_function('https=//abc.com/def')) # Output: https=//abc.com/ print(generated_function('http=//www.abc.com/def/cef')) # Output: http=//www.abc.com print(generated_function('http=//chandoo.org/wp/def-def')) # Output: http=//chandoo.org/ print(generated_function("https=//abc.com/def")) ## Output: https=//abc.com/ print(generated_function("http=//www.abc.com/def/cef")) ## Output: http=//www.abc.com print(generated_function("http=//chandoo.org/wp/def-def")) ## Output: http=//chandoo.org/ # End time: 2024-04-10 14:59:29.658058 # Elapsed time in seconds: 2.310453730000063 # APPEND TEST SCRIPTS... print(generated_function("https=//abc.com/def")) ## Output: https=//abc.com/ print(generated_function("http=//www.abc.com/def/cef")) ## Output: http=//www.abc.com print(generated_function("http=//chandoo.org/wp/def-def")) ## Output: http=//chandoo.org/ print(generated_function("https=//abc.com/home")) ### Output: https=//abc.com/ print(generated_function("http=//www.abc.com/home/category")) ### Output: http=//www.abc.com print(generated_function("http=//chandoo.org/wp/home-home")) ### Output: http=//chandoo.org/ # TEST SCRIPTS APPENDED!
using Abp.Dependency; using Castle.MicroKernel.Registration; using Castle.Windsor.MsDependencyInjection; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using FintrakERPIMSDemo.EntityFrameworkCore; using FintrakERPIMSDemo.Identity; namespace FintrakERPIMSDemo.Test.Base.DependencyInjection { public static class ServiceCollectionRegistrar { public static void Register(IIocManager iocManager) { RegisterIdentity(iocManager); var builder = new DbContextOptionsBuilder<FintrakERPIMSDemoDbContext>(); var inMemorySqlite = new SqliteConnection("Data Source=:memory:"); builder.UseSqlite(inMemorySqlite); iocManager.IocContainer.Register( Component .For<DbContextOptions<FintrakERPIMSDemoDbContext>>() .Instance(builder.Options) .LifestyleSingleton() ); inMemorySqlite.Open(); new FintrakERPIMSDemoDbContext(builder.Options).Database.EnsureCreated(); } private static void RegisterIdentity(IIocManager iocManager) { var services = new ServiceCollection(); IdentityRegistrar.Register(services); WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services); } } }
import React, { Fragment } from 'react'; import '../../../components/styles/Demo.css'; import Tabs from '../../../tabs/Tabs.js'; import {Link} from 'react-router-dom'; import Fade from 'react-reveal/Fade'; import Quiz from '../../../components/quiz/Quiz.js'; import fire from '../../../config/Fire'; import Login from '../../../components/Login.js'; class Unit6Lesson6 extends React.Component { constructor(props) { super(props); this.logout = this.logout.bind(this); this.state = ({ user: null, }); this.authListener = this.authListener.bind(this); } logout(){ fire.auth().signOut(); } componentDidMount(){ this.authListener(); } authListener() { fire.auth().onAuthStateChanged((user) => { //login if (user) { this.setState({user}); localStorage.setItem('user', user.uid); } //logout else { this.setState({ user:null}); localStorage.removeItem('user'); } }); } render() { return ( <div> {this.state.user ? (<Lesson />) : (<Login />)} </div> ) } } class Lesson extends React.Component { render() { return ( <div class = "container"> <div class = "split left"> <div class = "lesson_video"> <iframe src="https://www.youtube.com/embed/OB7qpEFDUzs?rel=0" title="Video" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="true"></iframe> </div> </div> <div class = "split right"> <div class = "lesson_content"> <div class = "lesson_title grow">Special Methods</div> <div class = "tabs"> <Tabs> <div class="tab_label" label="Supplemental"> <div class="paragraph">Let’s go over special methods in Python. Why use them? Well, we use special methods because we can’t have certain methods available to us such as the print method. If we tried to print out an instance of a class we wouldn’t be able to. Let’s look at an example.</div> <div class = "code_block"> <div><div class="blue">def</div> <div class="purp">name_of_function</div>(arg1,arg2):</div> </div> <div class="paragraph">In this supplemental, you’ll learn about how to create an Object type such as a list. Let’s begin by exploring some Objects within Python.As you can see, when we tried to print out an instance of our class we weren’t able to do so. Instead, Python gave us the memory location of our instance game1. To resolve this and have Python return something that is useful for us, what we can use are special methods. These methods allow us to perform actions such as printing out instances of our class. Now, why would we want to do this? Well, there might be scenarios where there’s another programmer who needs to create the exact same instance of a class as you created. So with the same object name, arguments, etc. To provide that type of information, what we can do is use the __repr__() method. You should note that all special methods have double underscores surrounding the method name followed by open and closed parentheses. You’ve already been working with a special method which was __init__ it’s just that you weren’t aware of it. So now that you can identify special methods, let’s go ahead and see them in action.</div> <div class = "code_block"> <div><div class="blue">def</div> <div class="purp">name_of_function</div>(arg1,arg2):</div> </div> <div class="paragraph">To use a special method, go into your class and do double underscores surrounding the method name which in our case is repr. Then place your parentheses and inside of the parentheses type in self. The reason as to why we do this is because we want our method to take in all of the arguments of our instance. By passing in self, we now have access to whatever instance we want to perform our action on. Inside of the method, you can go ahead and type in the code you want executed when you eventually print out the instance of your class and because we wanted other programmers to be able to create a perfect copy of our own instance, we want our print statement to return the name attribute for our instance. By using __repr__() we were able to successfully use the print function to call our instance game1.</div> <div class="paragraph">Another special method that can be used to print out instance of a class is the str method. The str special method is used just like the repr method, however, programmer use it for when we want to output something to a user rather than another programmer. So we use str when we want the outputted information to be more readable. Let’s look at an example.</div> <div class = "code_block"> <div><div class="blue">def</div> <div class="purp">name_of_function</div>(arg1,arg2):</div> </div> <div class="paragraph">As you can see, the formatting of the special method str is the exact same as repr but with a different method name. When we do print(game1) rather than giving us a memory location, we have a readable statement printed out on our screen. So we use the special method str for when we want to print out instances of our class and have them return readable statements.</div> <div class="paragraph">We also have a special method to find the length of an object. Let’s say you had an instance of a class with the number of movies showing at a theatre and you wanted to see how long the movies were. Let’s look at an example:</div> <div class = "code_block"> <div><div class="blue">def</div> <div class="purp">name_of_function</div>(arg1,arg2):</div> </div> <div class="paragraph">So you can see that we have an instance of the class movies called movie1 with the name Star Wars and a run time of 125 minutes. But when we tried to find the length of our object, we get back an error. To resolve this we can use the special method for length. Do the following:</div> <div class = "code_block"> <div><div class="blue">def</div> <div class="purp">name_of_function</div>(arg1,arg2):</div> </div> <div class="paragraph">By having the special method len return the run_time of our object, whenever we call the len of our object movie1, instead of running into errors we now get back how long the movie is.</div> <div class="paragraph">These are the basics of special methods. They allow you to execute method calls on your instances that would have otherwise been impossible to do.</div> </div> <div class="tab_label" label="Quiz"> <Fragment> <Quiz quizdata={ { question:"How can you tell if something is a special method?", FindAnswer:["Surrounded by double underscores with parentheses at the end", "Has a unique name with no special symbols", "Utilizes function calls", "Is nested inside of a dunder init"], rightAnswer:"Surrounded by double underscores with parentheses at the end" } } /> <Quiz quizdata={ { question:"What is the syntax for a special method?", FindAnswer:["(methodName)__", "__methodName__", "__methodName__()", "methodName()"], rightAnswer:"__methodName__()" } } /> <Quiz quizdata={ { question:"What is dunder repr used for?", FindAnswer:["Used to print out code for anyone to see", "Used to print out instances so that other programmers can recreate that specific object", "To avoid errors in print formatting objects", "None of the above"], rightAnswer:"Used to print out instances so that other programmers can recreate that specific object" } } /> </Fragment> </div> <div class="tab_label" label="Assignment"> <div class = "tab_header">Task</div> <div class='paragraph_NI'>Create a program that has a class and multiple instances of that class. Utilize special methods so that when you print out the instance of your class, you’ll receive all the information about the object so that if another programmer wished to create an instance with the exact same attributes, they would be able to do so by looking at the output of the print statement.</div> <iframe height="400px" width="100%" src="https://repl.it/@SursumEducation/Unit6Lesson6?lite=true" title="Code" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </div> </Tabs> </div> </div> </div> <div class = "bottom_section"> <Fade bottom><div><div class ="lesson_backbutton"><Link to='/Python'><button class="grow">View Other Lessons</button></Link></div></div></Fade> </div> </div> ) } } export default Unit6Lesson6;
import { Button, Divider, TextField, Typography } from "@mui/material"; import { Box } from "@mui/system"; import React, { useEffect } from "react"; import { useNavigate } from "react-router-dom"; import DeleteOutlinedIcon from "@mui/icons-material/DeleteOutlined"; import { useCart } from "../../Context/CartContextProvaider"; const Cart = () => { const navigate = useNavigate(); const { getCart, cart, changeProductCount, deleteCartProduct } = useCart(); useEffect(() => { getCart(); }, []); const cartCleaner = () => { localStorage.removeItem("cart"); getCart(); }; if (!cart) return; return ( <> <Typography variant="h4" sx={{ margin: "2% 0 0 6%", fontWeight: 600 }} > Корзина </Typography> {cart.products.length == 0 ? ( <Box sx={{ textAlign: "center", margin: "4%", }} > <Typography sx={{ fontSize: "20px", fontWeight: 600, backgroundColor: "#fbb3db", }} > Ваша корзина пуста </Typography> <Button onClick={() => navigate("/product")} sx={{ backgroundColor: "#fbb3db", color: "white", borderRadius: 0, fontWeight: 500, mt: "2%", }} > Перейти к выбору </Button> </Box> ) : ( <> <Box sx={{ margin: "4%", boxShadow: "0px 0px 8px 5px rgba(34, 60, 80, 0.2)", }} > {cart.products.map((product, index) => ( <Box key={index} sx={{ display: { xs: "block", sm: "flex", md: "flex", lg: "flex", xl: "flex", }, alignContent: "center", alignItems: "center", justifyContent: "space-around", borderBottom: "1px solid #aeaeae", width: "90%", margin: "0 auto", p: 2, }} > <img src={product.item.picture} alt="" width={"10%"} /> <Typography sx={{ textAlign: "left", width: "20%", fontWeight: 600, fontSize: { xs: "10px", sm: "14px", md: "18px", lg: "20px", xl: "20px", }, }} > {product.item.title} </Typography> <Box sx={{ display: "flex", width: { xs: "90%", sm: "50%", md: "50%", lg: "50%", xl: "50%", }, justifyContent: "space-between", }} > <TextField type={"number"} value={product.count} onChange={(e) => changeProductCount( e.target.value, product.item.id ) } sx={{ width: { xs: "35%", sm: "30%", md: "25%", lg: "25%", xl: "25%", }, }} /> <Box sx={{ textAlign: "center" }}> <Typography sx={{ fontSize: { xs: "16px", sm: "20px", md: "22px", lg: "24px", xl: "26px", }, color: "pink", fontWeight: 800, }} > {product.subPrice} $ </Typography> <Typography sx={{ color: "gray", fontSize: { xs: "12px", sm: "14px", md: "14px", lg: "16px", xl: "16px", }, }} ></Typography> </Box> <Button sx={{ padding: 0, display: "block", width: "20px", }} > <DeleteOutlinedIcon onClick={() => deleteCartProduct( product.item.id ) } /> </Button> </Box> </Box> ))} </Box> <Box sx={{ margin: "4%", boxShadow: "0px 0px 6px 4px rgba(34, 60, 80, 0.2)", pb: 4, }} > {" "} <Box sx={{ display: "flex", justifyContent: "space-between", width: "80%", margin: "0 auto", alignItems: "center", }} > <Typography variant="h5" sx={{ fontWeight: 800 }}> ИТОГ: </Typography> <Box sx={{ display: { xs: "block", sm: "flex", md: "flex", lg: "flex", xl: "flex", }, m: 4, alignItems: "center", textAlign: "center", }} > <Typography sx={{ fontSize: "36px", color: "pink", fontWeight: 800, mr: 4, }} > {cart.totalPrice} $ </Typography> <Typography sx={{ color: "gray", fontSize: "20px" }} ></Typography> </Box> </Box> <Box sx={{ display: "flex", justifyContent: "space-between", width: "80%", margin: "0 auto", alignItems: "center", }} > <Box sx={{ display: "flex", flexDirection: "column", width: "40%", }} > <TextField placeholder="Адрес" sx={{ width: "100%", border: "1px solid #fbb3db", mb: 2, }} /> <TextField placeholder="Номер Телефона" sx={{ width: "100%", border: "1px solid #fbb3db", }} /> </Box> <Button sx={{ fontSize: { xs: "10px", sm: "12px", md: "14px", }, backgroundColor: "#fbb3db", color: "white", borderRadius: 0, padding: "15px 18px", fontWeight: 600, width: { xs: "40%", sm: "40%", md: "40%", lg: "30%", xl: "30%", }, borderRadius: "6px", }} onClick={() => navigate("/payment")} > Оформить заказ </Button> </Box> </Box> </> )} </> ); }; export default Cart;
''' @Author Jared Scott ☯ This script will open a socket connection at the specified port number hosted from localhost (127.0.0.1) This socket when conntacted will generate a random data value and return this data over the socket. ''' import socket import random def main(): port = 10150 #Port where the sensor data will be 'Served' sckt = socket.socket() sckt.bind(('localhost', port)) # Creates the port binding for 127.0.0.1:10150 sckt.listen() #Socket object will now listen for activity on the specified port sckt.settimeout(3) print('Serving Belfort 6200 Data at 127.0.0.1:' + str(port) + '\nListening....') while True: conn = None try: #Outer try is watching for a keyboard interrupt coming from the inner try when it throws a timeout exception try: ''' KeyboardInterrupt does not reach main call stack until process is complete. The timeout will complete the process and exit with a timeout exception. If the user has entered a keyboard interrupt, the timeout will allow that exception to be caught ''' conn, address = sckt.accept() # Establish connection with client. print('Incoming connection from address: ', str(address[0]) + ":" + str(address[1])) simulateSensor(conn) except socket.timeout: print("Listening....") continue except KeyboardInterrupt: print("Shutting down sensor sim. . .") if conn: conn.close() break def genBelfortData(): randomValue = random.uniform(12,14) dataString = "\x01\x02\x0DVP" + str(randomValue)[:5] + "DE4" + "\r\n" return dataString def simulateSensor(conn): data = conn.recv(1024) print('Incoming Poll Message:', data.decode()) dataString = genBelfortData() #Generating simulated data byt = dataString.encode() conn.send(byt) if __name__ == '__main__': main()
<div class="col-md-12" id="new_car_form"> <%@user ||=current_user %> <%= simple_form_for(@car, class:"form-horizontal") do |f| %> <div class="col-sm-5 col-md-4"> <div class="text-center"> <section> <%= car_image(@car,:normal, class:"img-rounded img-responsitive") %> </section> <h3><%=t(".upload_text")%></h3> <%= f.simple_fields_for :image, f.object.image || f.object.build_image do |i| %> <%=i.input :img, label: false, input_html:{class:"form-control"}%> <%= i.input :_destroy, as: :boolean, label:t(".img_destroy_txt"), hint:t(".img_destroy_hint") %> <%end%> </div> </div> <div class="col-sm-7 col-md-offset-1 col-md-5 personal-info"> <div class="row"> <%= f.input(:title) %> </div> <div class="row"> <div class="col-md-4"> <%=f.input :color, as: :select do f.select :color, Color.select_array end%> </div> <div class="col-md-4"> <%= f.input :priority%> </div> </div> <div class="row"> <%= f.input :description, as: :text, input_html: {rows: 5, :onkeyup =>"length_check(#{Car::DescriptionLength}, 'car_description', 'counter')", :onclick =>"length_check(#{Car::DescriptionLength}, 'car_description', 'counter')" }%> <span id="counter"> <%= 180-((@car.description.nil?)? 0 : @car.description.length) %> / <%= Car::DescriptionLength %></span> </div> <div class=" center row"> <%= f.button :submit, t('save_but'),class:"btn btn-primary" %> </div> <% end %> </div> </div> <%= javascript_tag do%> $("#car_priority").slider(); <%end%>
import { Schema, Prop, SchemaFactory } from '@nestjs/mongoose'; import { SchemaTypes, Types } from 'mongoose'; import { AgeGroup } from 'src/common/staticSchema/ageGroup.schema'; import { Gender } from 'src/common/staticSchema/gender.schema'; import { v4 as uuidv4 } from 'uuid'; import { ExitSurveyForm } from './exitSurveyForm.schema'; @Schema() export class ExitSurveyResponse { @Prop({ default: uuidv4() }) exitSurveyResponseId: string; @Prop({ type: SchemaTypes.ObjectId, ref: ExitSurveyForm.name }) exitSurveyFormId: Types.ObjectId; @Prop({ required: true }) email: string; @Prop({ required: true }) firstName: string; @Prop({ required: true }) lastName: string; @Prop({ type: SchemaTypes.ObjectId, ref: Gender.name, required: true }) genderId: Types.ObjectId; @Prop({ type: SchemaTypes.ObjectId, ref: AgeGroup.name, required: true }) ageGroupId: Types.ObjectId; @Prop() activityCompletedInEntirety: string; @Prop() beneficiality: string; @Prop() relevance: string; @Prop() expectations: string; @Prop() degreeOfKnowledge: string; @Prop() applicationOfKnowledge: string; @Prop() valuableConcept: string; @Prop() topicsInGreaterDepth: string; @Prop() interactionWithFellowParticipants: string; @Prop() feedback: string; } export const ExitSurveyResponseSchema = SchemaFactory.createForClass(ExitSurveyResponse);
import { useEffect, useState } from 'react' import { useFormik, FormikHelpers } from 'formik'; import useCheckWeb3 from '../../hooks/useWeb3.hook'; import { EChainIds } from '../../interfaces/useCheckWeb3.interface'; import { HomePage } from './home.page'; import { getContractValidSchema } from '../../validations/getContractValid.schema'; import { IValues, IValuesTransfer } from '../../interfaces/homePage.interface'; import { ITokenContract } from '../../interfaces/tokenContract'; import TokenService from '../../services/token.service'; import { Msgs } from '../../utils/msgs'; import { sendSchema } from '../../validations/send.schema'; import { ITsx } from '../../interfaces/tsx.interface'; const initialValues = { address: '', } const HomeContainer = (): JSX.Element => { // check network & existing metamsk const { error } = useCheckWeb3({ network: EChainIds.ROPSTEN }); const [errorData, setErrorData] = useState<string>(""); const [recentTsxs, setRecentTsxs] = useState<ITsx[]>([]); const [isLoading, setIsLoading] = useState<boolean>(false); const [myBalance, setMyBalance] = useState<Omit<ITokenContract, "name" | "symbol">>({ address: "-", value: "-" }) const [tokensContract, setTokensContract] = useState<ITokenContract>({ address: "-", name: "-", symbol: "-", value: "-" }); const cleanError = () => setTimeout(() => setErrorData(""), 5000); // form for get balance of contract const formGetContract = useFormik({ initialValues, validationSchema: getContractValidSchema, onSubmit: getTokenInfo, }); // func for submiting balance of contract async function getTokenInfo( { address }: IValues, { setSubmitting }: FormikHelpers<IValues> ) { setIsLoading(true); const contract = new TokenService(address); try { const { name, symbol, value } = await contract.getTokenInfo(); setTokensContract({ address, name, symbol, value }); setMyBalance({ address: "-", value: "-" }); } catch(_) { setErrorData(Msgs.error.common); cleanError(); } finally { setSubmitting(false); setIsLoading(false); } }; // form for get balance of contract const formTransferTokens = useFormik({ initialValues: { to: "", amount: 0 }, validationSchema: sendSchema, onSubmit: sendTokens, }); // 0x48064A4c359A829D4724F60BD8643D5a6532feE8 // func for submiting balance of contract async function sendTokens( { to, amount }: IValuesTransfer, { setSubmitting }: FormikHelpers<IValuesTransfer> ) { setIsLoading(true); const contract = new TokenService(tokensContract.address); try { await contract.transferToken({ to, amount }); } catch(_) { setErrorData(Msgs.error.common); cleanError(); } finally { setSubmitting(false); setIsLoading(false); } }; // func for submiting balance of contract async function getMyBalance() { setIsLoading(true); const contract = new TokenService(tokensContract.address); try { const { address, value } = await contract.getMyBalance(); setMyBalance({ address, value }) } catch(_) { setErrorData(Msgs.error.common); cleanError(); } finally { setIsLoading(false); } }; useEffect(() => { if(tokensContract.address !== "-") { const contract = new TokenService(tokensContract.address); const erc20 = contract.initCotract; erc20.on("Transfer", (from, to, value) => { const newTsx = { from, to, value, symbol: tokensContract.symbol } setRecentTsxs(state => [newTsx, ...state]); }); } }, [tokensContract]); return <HomePage error={error} formGetContract={formGetContract} tokensContract={tokensContract} errorData={errorData} isLoading={isLoading} getMyBalance={getMyBalance} myBalance={myBalance} formTransferTokens={formTransferTokens} recentTsxs={recentTsxs} />; } export default HomeContainer;
// @ts-nocheck "use client"; import { useSession } from "next-auth/react"; import { useEffect, useState } from "react"; import { useRouter } from "next/navigation"; import ProfilePage from "components/profilepage/ProfilePage"; /** * This function fetches the user details from the database and displays them. * * @constructor - The user page * @returns - The user page */ const MyProfile = () => { useRouter(); const { data: session } = useSession(); const [myUserProfile, setMyUserProfile] = useState(); const fetchMyDetails = async () => { const response = await fetch(`/api/user/${session?.user.id}`); const data = await response.json(); setMyUserProfile(data); }; useEffect(() => { if (session?.user.id) fetchMyDetails(); }, [session?.user.id]); const handleEdit = () => { fetchMyDetails(); }; return <ProfilePage profileDetails={myUserProfile} handleEdit={handleEdit} />; }; export default MyProfile;
import { Navbar, TextInput, Button } from 'flowbite-react'; import { Link, useLocation } from 'react-router-dom'; import { AiOutlineSearch } from 'react-icons/ai'; import { FaMoon } from 'react-icons/fa'; export default function Header() { const path = useLocation().pathname; return ( <Navbar className='border-b-2'> <Link to="/" className='self-center whitespace-nowrap text-sm sm:text-xl font-semibold'> <span className='px-2 py-1 bg-gradient-to-r from-red-400 to-blue-500 rounded-lg text-white'>Bloggy</span> </Link> <form> <TextInput type='text' placeholder='Search...' rightIcon={ AiOutlineSearch } className='hidden lg:inline'/> </form> <Button className='w-12 h-10 lg:hidden' color='gray' pill> <AiOutlineSearch /> </Button> <div className='flex gap-2 md:order-2'> <Button className='w-12 h-10 lg:hidden sm:inline' color='gray' pill> <FaMoon /> </Button> <Link to='/sign-in'> <Button gradientDuoTone='purpleToBlue' outline>Sign In</Button> </Link> <Navbar.Toggle /> </div> <Navbar.Collapse> <Navbar.Link active={path === "/"} as={'div'}> <Link to='/'>Home</Link> </Navbar.Link> <Navbar.Link active={path === "/about"} as={'div'}> <Link to='/about'>About</Link> </Navbar.Link> <Navbar.Link active={path === "/dashboard"} as={'div'}> <Link to='/dashboard'>Dashboard</Link> </Navbar.Link> </Navbar.Collapse> </Navbar> ) }
import React from "react"; import "./content-wrapper.css"; interface ContentWrapperProps { contentSpacing?: "p0" | "p1" | "p2" | "p3" | "p4"; horizontalOnly?: boolean; children: React.ReactNode; } const spacingPropToClassName = ({ contentSpacing, horizontalOnly, }: Pick<ContentWrapperProps, "contentSpacing" | "horizontalOnly">) => contentSpacing ? `content-wrapper--u-spacing-${contentSpacing}${ horizontalOnly ? "-h" : "" }` : ""; export const ContentWrapper = ({ contentSpacing, horizontalOnly, children, }: ContentWrapperProps) => ( <div className="content-wrapper"> <div className={`content-wrapper--inner ${spacingPropToClassName({ contentSpacing, horizontalOnly, })}`} > {children} </div> </div> );
// // MapsViewController.swift // Map App // // Created by Mutlu Çalkan on 20.06.2022. // import UIKit import MapKit import CoreLocation import CoreData class MapsViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var placeNameTF: UITextField! @IBOutlet weak var noteTF: UITextField! @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() var longitude = Double() var latitude = Double() var chosenPlaceName = "" var chosenID : UUID? var annotationTitle = "" var annotationSubtitle = "" var annotationLongitude = Double() var annotationLatitude = Double() override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(locationPicker(gestureRecognizer:))) mapView.addGestureRecognizer(gestureRecognizer) gestureRecognizer.minimumPressDuration = 1.3 fetchData() } @objc func locationPicker(gestureRecognizer: UILongPressGestureRecognizer){ if gestureRecognizer.state == .began { let chosenPoint = gestureRecognizer.location(in: mapView) let chosenLocation = mapView.convert(chosenPoint, toCoordinateFrom: mapView) longitude = chosenLocation.longitude latitude = chosenLocation.latitude let annotation = MKPointAnnotation() annotation.coordinate = chosenLocation annotation.title = placeNameTF.text annotation.subtitle = noteTF.text mapView.addAnnotation(annotation) } } func fetchData(){ if chosenPlaceName != "" { //Fetch data from Core Data if let uuidString = chosenID?.uuidString{ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Location") fetchRequest.returnsObjectsAsFaults = false fetchRequest.predicate = NSPredicate(format: "id = %@", uuidString) do{ let results = try context.fetch(fetchRequest) if results.count > 0{ for result in results as! [NSManagedObject] { if let name = result.value(forKey: "placeName") as? String { annotationTitle = name if let note = result.value(forKey: "note") as? String { annotationSubtitle = note if let latitude = result.value(forKey: "latitude") as? Double { annotationLatitude = latitude if let longitude = result.value(forKey: "longitude") as? Double { annotationLongitude = longitude let annotation = MKPointAnnotation() annotation.title = annotationTitle annotation.subtitle = annotationSubtitle let coordinate = CLLocationCoordinate2D(latitude: annotationLatitude, longitude: annotationLongitude) annotation.coordinate = coordinate mapView.addAnnotation(annotation) placeNameTF.text = annotationTitle noteTF.text = annotationSubtitle locationManager.stopUpdatingLocation() let span = MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03) let region = MKCoordinateRegion(center: coordinate, span: span) mapView.setRegion(region, animated: true) } } } } } } }catch{ print("Error!") } } } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if chosenPlaceName == ""{ let location = CLLocationCoordinate2D(latitude: locations[0].coordinate.latitude, longitude: locations[0].coordinate.longitude) let span = MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) } } // Customize the pin func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if annotation is MKUserLocation{ return nil } let pinViewID = "annotationID" var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: pinViewID) if pinView == nil { pinView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: pinViewID) pinView?.canShowCallout = true pinView?.tintColor = .blue let button = UIButton(type: .detailDisclosure) pinView?.rightCalloutAccessoryView = button }else{ pinView?.annotation = annotation } return pinView } // The action when pressing on callout func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if chosenPlaceName != "" { let requestLocation = CLLocation(latitude: annotationLatitude, longitude: annotationLongitude) CLGeocoder().reverseGeocodeLocation(requestLocation) { placemarkArray, error in if let placemarks = placemarkArray { if placemarks.count > 0 { let newPlacemark = MKPlacemark(placemark: placemarks[0]) let item = MKMapItem(placemark: newPlacemark) item.name = self.annotationTitle // Set the transport option let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving] // Openning apple map item.openInMaps(launchOptions: launchOptions) } } } } } @IBAction func didSaveButtonPressed(_ sender: Any) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let newLocation = NSEntityDescription.insertNewObject(forEntityName: "Location", into: context) newLocation.setValue(placeNameTF.text, forKey: "placeName") newLocation.setValue(noteTF.text, forKey: "note") newLocation.setValue(longitude, forKey: "longitude") newLocation.setValue(latitude, forKey: "latitude") newLocation.setValue(UUID(), forKey: "id") do{ try context.save() // Alert Pop-up let okAction = UIAlertAction(title: "OK", style: .default) let alert = UIAlertController(title: "Saved", message: "Location has been succesfully saved", preferredStyle: .alert) present(alert, animated: true, completion: nil) alert.addAction(okAction) }catch{ print("Error") let alert = UIAlertController(title: "Something went wrong", message: "Fatal Error", preferredStyle: .alert) present(alert, animated: true, completion: nil) let okAction = UIAlertAction(title: "OK", style: .default) alert.addAction(okAction) } NotificationCenter.default.post(name: NSNotification.Name("newLocationAdded"), object: nil) navigationController?.popViewController(animated: true) } }
import { Application } from 'express'; import express from 'express'; import simpleGit from 'simple-git'; import { promises as fs } from 'fs'; import path from 'path'; import { v4 as uuid } from 'uuid'; const app: Application = express(); app.post('/diff', async (req, res) => { const { old: oldContent, new: newContent } = req.body ?? {}; if (!oldContent || !newContent) { return res.status(400).json({ error: 'invalid parameters' }).end(); } const tempDir = await fs.mkdtemp(uuid()); const oldPath = path.join(tempDir, 'old.txt'); const newPath = path.join(tempDir, 'new.txt'); await Promise.all([ fs.writeFile(oldPath, oldContent), fs.writeFile(newPath, newContent) ]); const diff = await simpleGit().diff(['-U1', oldPath, newPath]); res.json({ data: diff }).end(); await fs.rmdir(tempDir); }); export { app as api };
<script lang="ts" setup> import { defineComponent, onMounted, reactive } from 'vue' import DynamicIcon from '@/components/DynamicIcon.vue' import gBack from '@/components/gBack/gBack.vue' import gMusicGalleryList from '@/components/gMusicGallery/gMusicGalleryList.vue' import gMusicSongListNotFound from '@/components/gMusicSong/gMusicSongListNotFound.vue' import { Playlists } from '@/types/artist' import { useTranslation } from '@/composables/lang' import { useAuthStore, useLoadingStore } from '@/stores' import PlaylistsApi from '@/services/playlists' import { declensionOfWord } from '@/utils/utils' import { useMeta } from 'quasar' const { t } = useTranslation() defineComponent({ components: { DynamicIcon, gBack, gMusicGalleryList, gMusicSongListNotFound, }, }) const authStore = useAuthStore() const loadingStore = useLoadingStore() interface Data { avatar: string fullname: string playlists: Array<Playlists> | undefined isLoading: boolean } const data: Data = reactive({ avatar: authStore?.user?.avatar || '', fullname: authStore?.user?.fullname || '', playlists: [], isLoading: false, }) useMeta(() => { return { title: t('pages.profile.details.titleHead'), meta: { description: { name: 'description', content: t('pages.profile.details.contentHead'), }, }, } }) const getPlaylists = async () => { try { const response = await PlaylistsApi.getLikedYour({ count: 6, }) data.playlists = response?.data?.playlists } catch (error: unknown) { console.error(error) } } onMounted(async () => { loadingStore.setLoading() await getPlaylists() loadingStore.hideLoading() }) </script> <template> <div class="q-page"> <div class="row"> <div class="col-12"> <div class="g-profile-details"> <div class="g-profile-details__wrap"> <div class="q-page__header"> <g-back :label="t('pages.profile.details.buttonBackProfileDetails')" href="/profile" icon="back" /> <router-link to="/profile/edit"> <DynamicIcon :size="28" name="pen" /> </router-link> </div> <div class="g-profile-details__header"> <div class="g-profile-details__generic"> <div class="g-profile-details__generic-head"> <q-avatar :size="'200px'" class="g-profile-details__user-default" > <template v-if="data.avatar"> <img :alt="data.fullname" :src="data.avatar" /> </template> </q-avatar> <h3 class="g-profile-details__user-title"> {{ data?.fullname }} </h3> <q-btn :label="t('pages.profile.details.buttonEditProfile')" class="g-profile-details__user-btn q-btn-border q-btn-medium" rounded text-color="''" to="/profile/edit" unelevated /> </div> <div class="g-profile-details__generic-main"> <div class="g-profile-details__user-info"> <div class="g-profile-details__user-info-comments"> <h4>0</h4> <span> {{ declensionOfWord( authStore?.user?.songs?.length || 0, [ t('pages.profile.details.infoComment'), t('pages.profile.details.infoComments'), ] ) }} </span> </div> <div class="g-profile-details__user-info-likes"> <h4>{{ authStore?.user?.songs?.length || 0 }}</h4> <span> {{ declensionOfWord( authStore?.user?.songs?.length || 0, [ t('pages.profile.details.infoLike'), t('pages.profile.details.infoLikes'), ] ) }} </span> </div> </div> </div> </div> </div> <div class="g-profile-details__body"> <g-music-gallery-list v-if="data.playlists?.length" :list="data.playlists" :sub-title=" t('pages.profile.details.galleryListPlaylists.subTitle') " :title="t('pages.profile.details.galleryListPlaylists.title')" :type="`/library/${authStore.user?.nickname}/playlists`" /> <g-music-song-list-not-found v-else /> </div> </div> </div> </div> </div> </div> </template>
// // CategoryTableViewController.swift // Restaurant // // Created by Ahmad Nader on 8/08/23. import UIKit import UserNotifications class CategoryTableViewController: UITableViewController { var categories = [String]() override func viewDidLoad() { super.viewDidLoad() MenuController.shared.fetchCategories{ (categories) in if let categories = categories { self.updateUI(with: categories) } } // getting the user's permission for notification initNotificationSetupCheck() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return categories.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCellIdentifier", for: indexPath) cell.textLabel?.text = categories[indexPath.row].capitalized return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "MenuSegue"{ let menuTableViewController = segue.destination as! MenuTableViewController let index = tableView.indexPathForSelectedRow!.row menuTableViewController.category = categories[index] } } func updateUI(with categories: [String]){ DispatchQueue.main.async { self.categories = categories self.tableView.reloadData() } } // Notification Implimentation func initNotificationSetupCheck() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { (success, error) in if success { print("Permission Accepted") } else { print("No Notification") } } } }
import { spawn } from "node:child_process"; import path from "node:path"; import os from "node:os"; import fs from "node:fs"; import net from "node:net"; import _ from "lodash"; import { Reader } from "gocsv"; import { randEmail, randFullName, randHexaDecimal, randPastDate, randText, } from "@ngneat/falso"; import { version } from "../package.json"; import { Readable } from "node:stream"; import { Commit, CommitTree } from "./commit"; const plat = os.platform(); let arch = os.arch(); arch = arch === "x64" ? "amd64" : arch; export const sleep = (ms: number) => new Promise((resolve) => { setTimeout(resolve, ms); }); export const wrgl = (repoDir: string, args: string[]) => new Promise((resolve, reject) => { const proc = spawn( path.join( "__testcache__", version, `wrgl-${plat}-${arch}`, "bin", "wrgl" ), args.concat(["--wrgl-dir", repoDir]) ); const stdout: string[] = []; const stderr: string[] = []; proc.stdout.on("data", (data) => { stdout.push(data); }); proc.stderr.on("data", (data) => { stderr.push(data); }); proc.on("close", (code) => { if (code !== 0) { reject( new Error( `wrgl exited with code ${code}:\n stdout: ${stdout.join( "" )}\n stderr: ${stderr.join("")}` ) ); } else { resolve(null); } }); }); export const freePort = (): Promise<number> => new Promise((resolve, reject) => { const srv = net.createServer(function (sock) { sock.end(""); }); let port: number; srv.listen(0, function () { port = (srv.address() as net.AddressInfo).port; srv.close(); }); srv.on("error", (err) => { reject(err); }); srv.on("close", () => { resolve(port); }); }); export const startWrgld = async ( repoDir: string, callback: (url: string) => Promise<unknown> ) => { const port: number = await freePort(); const proc = spawn( path.join( "__testcache__", version, `wrgld-${plat}-${arch}`, "bin", "wrgld" ), [repoDir, "-p", port + ""] ); await sleep(1000); try { await callback(`http://localhost:${port}`); } catch (e) { throw e; } finally { proc.kill(); } }; export const commit = async ( repoDir: string, branch: string, message: string, primaryKey: string[], rows: string[][] ) => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrgl-javascript-sdk")); const filePath = path.join(tmpDir, "data.csv"); fs.writeFileSync(filePath, rows.map((row) => row.join(",")).join("\n")); await wrgl(repoDir, [ "commit", branch, filePath, message, "-p", primaryKey.join(","), ]); fs.rmSync(tmpDir, { recursive: true, force: true }); }; export const readAll = async (reader: Reader) => { const result: string[][] = []; await reader.readAll((row) => { result.push(row); }); return result; }; export const initRepo = async ( email: string, name: string, password: string ) => { const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrgl-javascript-sdk")); await wrgl(repoDir, ["init"]); await wrgl(repoDir, ["config", "set", "receive.denyNonFastForwards", "true"]); await wrgl(repoDir, ["config", "set", "user.email", email]); await wrgl(repoDir, ["config", "set", "user.name", name]); await wrgl(repoDir, [ "auth", "add-user", email, "--name", name, "--password", password, ]); await wrgl(repoDir, ["auth", "add-scope", email, "--all"]); await wrgl(repoDir, ["config", "set", "auth.type", "legacy"]); return repoDir; }; export const csvStream = (rows: string[][]) => Readable.from(rows.map((row) => row.join(",")).join("\n")); export const exhaustAsyncIterable = async <T>( iterable: AsyncIterable<T> ): Promise<T[]> => { const result: T[] = []; for await (const value of iterable) { result.push(value); } return result; }; export const randCommit = (): Commit => ({ sum: randHexaDecimal({ length: 32 }).join(""), authorEmail: randEmail(), authorName: randFullName(), message: randText(), table: { sum: randHexaDecimal({ length: 32 }).join(""), }, time: randPastDate(), }); export const randCommitTree = (depth: number): CommitTree => { const root = randCommit(); let commit = root; for (let i = 0; i < depth; i++) { const node = randCommit(); commit.parentCommits = { [node.sum]: node }; commit.parents = [node.sum]; commit = node; } return new CommitTree({ sum: root.sum, root, }); };
# Exercício 1 a) * VARCHAR: serve para qualquer caracteres de até 255; * PRIMARY KEY como id única; * NOT NULL para mostar que é um parametro necessário; * DATE para data. b) * SHOW DATABASES: mostra as informações do meu banco de dados; * SHOW TABLES: mostra minhas tables criadas. c) mostra os detalhes da table. # Exercício 2 a) ``` sql INSERT INTO Actor (id, name, salary, birth_date, gender) VALUES( "002", "Glória Pires", 1200000, "1963-08-23", "female" ); ``` b) Entrada duplicada "002" na key "PRIMARY". Tentou criar uma primary key com valor que já existe. c) Coluna não bate com os valores que foram passados no insert. Falta alguns parametros para que passe corretamente em todos os values da table. d) Campo 'name' nao tem nenhum valor. O nome é um campo obrigatório e) Value incorreto, falta por "" no valor do date. # Exercício 3 a) ``` sql SELECT * FROM Actor; ``` b) ``` sql SELECT salary FROM Actor WHERE name = "Tony Ramos"; ``` c) ``` sql SELECT * from Actor WHERE gender = "invalid"; ``` voltou vazio pois todos os dados tem o gender com male ou female; d) ``` sql SELECT id, name, salary FROM Actor WHERE salary <= 500000; ``` e) Coluna 'nome' desconhecida. correção: ``` sql SELECT id, name from Actor WHERE id = "002" ``` # Exercício 4 a) Busca os atores que comecem com A ou J no nome e depois filtra os que recebem mais de 300.000 b) ``` sql SELECT * FROM Actor WHERE (name NOT LIKE "A%") AND salary > 350000; ``` c) ``` sql SELECT * FROM Actor WHERE name LIKE "%g%"; ``` # Exercício 5 a) bem similar ao VARCHAR mas com menos limitações de caracteres. # Exercício 6 a) ``` sql SELECT id, title, rating from Movie WHERE id ="003"; ``` b) ``` sql SELECT * FROM Movie WHERE title = "Dona Flor e Seus Dois Maridos"; ``` c) ``` sql SELECT id, title, synopsis FROM Movie WHERE rating <= 7; ``` # Exercício 7 a) ``` sql SELECT * FROM Movie WHERE title LIKE "%vida%"; ``` b) ``` sql SELECT * FROM Movie WHERE title LIKE "%termo de busca%" OR synopsis LIKE "%termo de busca"; ``` c) ``` sql SELECT * FROM Movie WHERE release_date < "2021-11-22"; ``` d) ``` sql SELECT * FROM Movie WHERE release_date < "2021-11-22" AND (title LIKE "%termo de busca%" OR synopsis LIKE "%termo de busca") AND rating <= 7; ```
import React from 'react'; import { View, Text, Alert, TextInput, StyleSheet, Image, ImageBackground, } from 'react-native'; const moment = require("moment"); import { Toast } from '../util/Toast'; import { login } from '../Server/login'; import { getRule } from '../Server/getRule'; import AuthorizationScreen from './AuthorizationScreen'; import AsyncStorage from '@react-native-community/async-storage'; export default class SignInScreen extends React.Component { static navigationOptions = { title: null, header: null }; state = { userid: 'bwcsuser', PhoneNum: '13552739927', password: '1', focus: '' } componentDidMount() { } _login = () => { const { userid, password, PhoneNum } = this.state; login(userid, password, PhoneNum).then((res) => { if (res.Code == 200) { this._signInAsync() } else { Alert.alert( '登录失败!', res.Message, [{ text: '关闭' }], { cancelable: false } ); } }).catch((error) => { alert(JSON.stringify(error)); }); } render() { const { focus } = this.state; return ( <View style={styles.container}> {/* <ImageBackground source={{ uri: 'https://facebook.github.io/react-native/img/tiny_logo.png' }} style={{ */} <ImageBackground source={require('../assets/img/login_bg.jpg')} style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', width: '100%', height: '100%' }}> <View> <View style={{ alignItems: 'center', marginBottom: 20 }}> <Image style={{ width: 180, height: 50, resizeMode: 'cover' }} source={require('../assets/img/logo.png')} /> </View> <View style={styles.center}> <View style={focus == 1 ? styles.view_focus : styles.view}> <View style={styles.view_l}> <Image style={{ width: 20, height: 25, resizeMode: 'cover' }} source={require('../assets/img/user.png')} /> </View> <View style={styles.view_r}> <TextInput onFocus={() => this.setState({ focus: 1 })} maxLength={20} placeholder="请输入您的账号" value={this.state.userid} placeholderTextColor='#c5c5c5' onChangeText={(userid) => this.setState({ userid })} /> </View> </View> <View style={focus == 2 ? styles.view_focus : styles.view}> <View style={styles.view_l}> <Image style={{ width: 15, height: 25, resizeMode: 'cover' }} source={require('../assets/img/phone.png')} /> </View> <View style={styles.view_r}> <TextInput maxLength={20} placeholder="请输入您的手机号" placeholderTextColor='#c5c5c5' value={this.state.PhoneNum} onFocus={() => this.setState({ focus: 2 })} onChangeText={(PhoneNum) => this.setState({ PhoneNum })} /> </View> </View> <View style={focus == 3 ? styles.view_focus : styles.view}> <View style={styles.view_l}> <Image style={{ width: 20, height: 24, resizeMode: 'cover' }} source={require('../assets/img/password.png')} /> </View> <View style={styles.view_r}> <TextInput maxLength={20} type='password' secureTextEntry={true} placeholder="请输入您的密码" value={this.state.password} placeholderTextColor='#c5c5c5' onFocus={() => this.setState({ focus: 3 })} onChangeText={(password) => this.setState({ password })} /> </View> </View> <View style={{ marginTop: 20, alignItems: 'center' }}> <ImageBackground style={{ width: 250, height: 35, resizeMode: 'contain' }} source={require('../assets/img/bt_bg.png')} > <Text onPress={this._login} style={{ textAlign: 'center', lineHeight: 30, color: '#fff', fontWeight: '700' }} >立即登录</Text> {/* <Button style={{ height: 60 }} title="登录" onPress={this._signInAsync} /> */} </ImageBackground> </View> </View> </View> </ImageBackground> {/* 权限 */} <AuthorizationScreen /> </View > ); } _signInAsync = async () => { await AsyncStorage.setItem('userToken', 'abc'); await AsyncStorage.setItem('Time', moment(new Date()).format('YYYY-MM-DD')); await AsyncStorage.setItem('userInfo', JSON.stringify({ name: this.state.userid, password: this.state.password, PhoneNum: this.state.PhoneNum, })); await getRule().then(res => { Toast({ visible: true, message: '税务短信规则加载完成' }) }); this.props.navigation.navigate('App'); }; } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', justifyContent: 'center', }, center: { padding: 30, marginLeft: 30, marginRight: 30, borderRadius: 20, backgroundColor: "#fff", }, view: { marginBottom: 15, borderWidth: 2, borderRadius: 10, borderColor: '#f5f5f5', flexDirection: 'row', backgroundColor: '#f5f5f5', }, view_focus: { marginBottom: 15, borderWidth: 2, borderRadius: 10, flexDirection: 'row', borderColor: '#88bfff', backgroundColor: '#f5f5f5' }, view_l: { paddingTop: 10, paddingLeft: 20 }, view_r: { paddingLeft: 15 } })
<!DOCTYPE html> <html> <!-- Toutes les balises d'entête --> <head> <!-- Encodage de la page --> <meta charset="utf-8" lang="fr"/> <!-- Nom de la page --> <title>Fomulaire JS</title> <!-- Lien vers le fichier de style CSS --> <link type="text/css" rel="stylesheet" href="JS_Form_tp_DS.css"/> <!-- Image onglet --> <link rel="shortcut icon" type="image/x-icon" href="../../images/decarboneNon.png"/> </head> <!--Contenu de le page--> <body> <!-- Haut de la page --> <header> </header> <!-- Corps de la page --> <blockquote> <table style="border : 1px solid black;"> <tr><td>couleur de fond(rgb)<td><input type = "range" max = 255 min = 0 id="backgroundColor"> <td rowspan = 6 id="zone"><h3>Zone de test</h3> <tr><td>padding<td><input type = "range" max = 30 min = 0 id="padding"> <tr><td>height<td><input type = "range" max = 500 min = 0 id="height"> <tr><td>width<td><input type = "range" max = 200 min = 0 id="width"> <tr><td>arrondi<td><input type = "range" max = 60 min = 0 id="border-radius"> <tr><td>rotation<td><input type = "range" max = 180 min = 0 id="rotation"> </table> <script> let inputs = document.getElementsByTagName("input"); for(let i = 0; inputs.length; i++) inputs[i].addEventListener("change", changerZone); function changerZone(event) { console.log(event); let zone = document.getElementById("zone"); let id = event.srcElement.id; let value = event.srcElement.value; switch(id) { case ("rotation"): zone.style.transform = "rotate("+value+"deg)"; break; case ("backgroundColor"): zone.style.backgroundColor = "rgb("+value+","+value+","+value+")"; break; default: zone.style.setProperty(id, value + "px"); break; } } </script> </blockquote> <!-- Pas de la page --> <footer> </footer> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf8"> <title></title> <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script> <script type="application/javascript" src="chrome://mochikit/content/chrome-harness.js"></script> <script type="application/javascript;version=1.8" src="head.js"></script> <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"> </head> <body> <script type="application/javascript;version=1.8"> window.onload = function() { SimpleTest.waitForExplicitFinish(); const {GetAvailableAddons} = require("devtools/webide/addons"); const {Devices} = Cu.import("resource://gre/modules/devtools/Devices.jsm"); const {Simulator} = Cu.import("resource://gre/modules/devtools/Simulator.jsm"); let adbAddonsInstalled = promise.defer(); Devices.on("addon-status-updated", function onUpdate1() { Devices.off("addon-status-updated", onUpdate1); adbAddonsInstalled.resolve(); }); function getVersion(name) { return name.match(/(\d+\.\d+)/)[0]; } function onSimulatorInstalled(name) { let deferred = promise.defer(); Simulator.on("register", function onUpdate() { if (Simulator.getByName(name)) { Simulator.off("register", onUpdate); nextTick().then(deferred.resolve); } }); return deferred.promise; } function installSimulatorFromUI(doc, name) { let li = doc.querySelector('[addon="simulator-' + getVersion(name) + '"]'); li.querySelector(".install-button").click(); return onSimulatorInstalled(name); } function uninstallSimulatorFromUI(doc, name) { let deferred = promise.defer(); Simulator.on("unregister", function onUpdate() { nextTick().then(() => { let li = doc.querySelector('[status="uninstalled"][addon="simulator-' + getVersion(name) + '"]'); if (li) { Simulator.off("unregister", onUpdate); deferred.resolve(); } else { deferred.reject("Can't find item"); } }) }); let li = doc.querySelector('[status="installed"][addon="simulator-' + getVersion(name) + '"]'); li.querySelector(".uninstall-button").click(); return deferred.promise; } function uninstallADBFromUI(doc) { let deferred = promise.defer(); Devices.on("addon-status-updated", function onUpdate() { nextTick().then(() => { let li = doc.querySelector('[status="uninstalled"][addon="adb"]'); if (li) { Devices.off("addon-status-updated", onUpdate); deferred.resolve(); } else { deferred.reject("Can't find item"); } }) }); let li = doc.querySelector('[status="installed"][addon="adb"]'); li.querySelector(".uninstall-button").click(); return deferred.promise; } Task.spawn(function* () { ok(!Devices.helperAddonInstalled, "Helper not installed"); let win = yield openWebIDE(true); yield adbAddonsInstalled.promise; ok(Devices.helperAddonInstalled, "Helper has been auto-installed"); yield nextTick(); let addons = yield GetAvailableAddons(); is(addons.simulators.length, 3, "3 simulator addons to install"); let sim10 = addons.simulators.filter(a => a.version == "1.0")[0]; sim10.install(); yield onSimulatorInstalled("Firefox OS 1.0"); win.Cmds.showAddons(); let frame = win.document.querySelector("#deck-panel-addons"); let addonDoc = frame.contentWindow.document; let lis; lis = addonDoc.querySelectorAll("li"); is(lis.length, 5, "5 addons listed"); lis = addonDoc.querySelectorAll('li[status="installed"]'); is(lis.length, 3, "3 addons installed"); lis = addonDoc.querySelectorAll('li[status="uninstalled"]'); is(lis.length, 2, "2 addons uninstalled"); info("Uninstalling Simulator 2.0"); yield installSimulatorFromUI(addonDoc, "Firefox OS 2.0"); info("Uninstalling Simulator 3.0"); yield installSimulatorFromUI(addonDoc, "Firefox OS 3.0"); yield nextTick(); let panelNode = win.document.querySelector("#runtime-panel"); let items; items = panelNode.querySelectorAll(".runtime-panel-item-usb"); is(items.length, 1, "Found one runtime button"); items = panelNode.querySelectorAll(".runtime-panel-item-simulator"); is(items.length, 3, "Found 3 simulators button"); yield uninstallSimulatorFromUI(addonDoc, "Firefox OS 1.0"); yield uninstallSimulatorFromUI(addonDoc, "Firefox OS 2.0"); yield uninstallSimulatorFromUI(addonDoc, "Firefox OS 3.0"); items = panelNode.querySelectorAll(".runtime-panel-item-simulator"); is(items.length, 0, "No simulator listed"); let w = addonDoc.querySelector(".warning"); let display = addonDoc.defaultView.getComputedStyle(w).display is(display, "none", "Warning about missing ADB hidden"); yield uninstallADBFromUI(addonDoc, "adb"); items = panelNode.querySelectorAll(".runtime-panel-item-usb"); is(items.length, 0, "No usb runtime listed"); display = addonDoc.defaultView.getComputedStyle(w).display is(display, "block", "Warning about missing ADB present"); yield closeWebIDE(win); SimpleTest.finish(); }); } </script> </body> </html>
import { Injectable, Logger } from '@nestjs/common'; import Axios, { AxiosRequestConfig, AxiosInstance } from 'axios'; @Injectable() export default class HttpClient { readonly #logger: Logger = new Logger(HttpClient.name); readonly #axios: AxiosInstance = null; constructor() { this.#axios = Axios.create(); this.#axios.interceptors.request.use( (value) => { this.#logger.log(`[${value.method.toUpperCase()}] ${value.url}`); if (value.data) { this.#logger.log(`[Body]: ${JSON.stringify(value.data, null, 4)}`); } return value; }, (error) => { this.#logger.error(error); return error; }, ); this.#axios.interceptors.response.use( (value) => { this.#logger.log(`[Response]: ${JSON.stringify(value.data, null, 4)}`); return value; }, (error) => { this.#logger.error(error); return error; }, ); } get<T = any>(url: string, config?: AxiosRequestConfig<T>) { return this.#axios.get<T>(url, config); } post<T = any>(url: string, data?: T, config?: AxiosRequestConfig<T>) { return this.#axios.post<T>(url, data, config); } }
# Compressed Big Brother FileSystem (CBBFS) The Compressed Big Brother FileSystem (CBBFS) is a userspace filesystem implemented using the FUSE (Filesystem in UserSpace) framework and aims to provide 2 distinct functionalities: 1. Logging any filesystem operation that happens in the cbbfs to a log file 2. Compressing files by storing them internaly as a sequence of data blocks The CBBFS has been implemented using the BBFS (Big Brother FileSystem) as a template which provides the logging part of CBBFS's functionality. ## Features - **Non-Volatile Storage** : CBBFS ensures data persistence across system reboots or power cycles, maintaining stored data integrity over time - **Variable Offset Reads and Writes** : Ability to read from or write to files at any offset, allowing for flexible data manipulation within files - **Variable Length Reads and Writes** : Support for reading from or writing to files of varying sizes, accommodating dynamic data storage requirements - **Variable File Size Support** : CBBFS is capable of handling files of any size, without limitations on maximum file size - **Filesystem Metadata & Directory Support** : Support of filesystem metadata such as file names, sizes, permissions, and directory structures ## Implementation Details CBBFS can be broken down to multiple core data structures, operations and design decisions, specifically : - Inside the rootdir of CBBFS there is a hidden directory (.cbbfsstorage/) which is used as the storage directory for all data blocks, non accesible within mountdir - Every data block consists of 4096 bytes (easily modifiable in source code) and is named after its SHA1 hash in hexadecimal form (40 bytes total). - Data blocks in main memory are represented by struct _blk_ which is a doubly linked list node and stores the hash value and the usage counter of a single block. This structure does not contain the actual block's data and occupies a total of 40 bytes. - Every file is represented in rootdir as a sequence of hashes of their corresponding data blocks. Reads and writes are responsible for translating these sequences and fetching/writing the requested data. - When writing blocks into a file we check if the block already exists by searching for its hash in the _blk_ list. If the hash exists we increase the counter, else we create the block and store its _blk_ structure in the _blk_ list. - If any file has suffix which acquires disk space less than a block then this suffix is stored in the rootdir/.cbbfsstorage/path/of/file and the character L is placed at the end of the file's hash sequence. - The read as well as the writing operation first resolves the given offset and then reads the requested bytes. - The read operation makes sure to not read more than the file's available data. - The getattr operation translates the size of the file which contains its sequence of hashes to its actual size. - The unlink operation, after reading all the hashes that constitute the file, decrements the count of each corresponding data block, and then deletes the file. If a block count reaches 0 (no longer in use), the corresponding data block file is deleted from the storage and removed from the list. ## Usage For ease of use there is a Makefile containg all the necessary fuctionalities for compiling, mounting, testing and unmounting cbbfs. Specifically the available operations are : - **Compile**: make compile - **Mount**: make mount - **Test**: make tests - **Unmount**: make unmount - **Clean**: make clean
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BSONRegExp = void 0; var error_1 = require("./error"); function alphabetize(str) { return str.split('').sort().join(''); } /** * A class representation of the BSON RegExp type. * @public */ var BSONRegExp = /** @class */ (function () { /** * @param pattern - The regular expression pattern to match * @param options - The regular expression options */ function BSONRegExp(pattern, options) { if (!(this instanceof BSONRegExp)) return new BSONRegExp(pattern, options); this.pattern = pattern; this.options = alphabetize(options !== null && options !== void 0 ? options : ''); if (this.pattern.indexOf('\x00') !== -1) { throw new error_1.BSONError("BSON Regex patterns cannot contain null bytes, found: " + JSON.stringify(this.pattern)); } if (this.options.indexOf('\x00') !== -1) { throw new error_1.BSONError("BSON Regex options cannot contain null bytes, found: " + JSON.stringify(this.options)); } // Validate options for (var i = 0; i < this.options.length; i++) { if (!(this.options[i] === 'i' || this.options[i] === 'm' || this.options[i] === 'x' || this.options[i] === 'l' || this.options[i] === 's' || this.options[i] === 'u')) { throw new error_1.BSONError("The regular expression option [" + this.options[i] + "] is not supported"); } } } BSONRegExp.parseOptions = function (options) { return options ? options.split('').sort().join('') : ''; }; /** @internal */ BSONRegExp.prototype.toExtendedJSON = function (options) { options = options || {}; if (options.legacy) { return { $regex: this.pattern, $options: this.options }; } return { $regularExpression: { pattern: this.pattern, options: this.options } }; }; /** @internal */ BSONRegExp.fromExtendedJSON = function (doc) { if ('$regex' in doc) { if (typeof doc.$regex !== 'string') { // This is for $regex query operators that have extended json values. if (doc.$regex._bsontype === 'BSONRegExp') { return doc; } } else { return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options)); } } if ('$regularExpression' in doc) { return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options)); } throw new error_1.BSONTypeError("Unexpected BSONRegExp EJSON object form: " + JSON.stringify(doc)); }; return BSONRegExp; }()); exports.BSONRegExp = BSONRegExp; Object.defineProperty(BSONRegExp.prototype, '_bsontype', { value: 'BSONRegExp' }); //# sourceMappingURL=regexp.js.map
import { isEmpty } from 'lodash'; import Link from 'next/link'; import { useState } from 'react'; const Nav = ({ header, headerMenus }) => { if (isEmpty(headerMenus)) { return null; } const [isMenuVisible, setMenuVisibility] = useState(false); return ( <nav className="flex items-center justify-between flex-wrap bg-gray-500 p-6"> <div className="flex items-center flex-shrink-0 text-white mr-6"> <img src={header?.siteLogoUrl} alt="SEO Booster Club" width="100" className="mr-4" /> <div className="flex flex-col items-start"> <span className="font-semibold text-xl tracking-tight"> {header?.siteTitle} </span> <span className="font-regular text-sm tracking-tight"> {header?.siteTagLine} </span> </div> </div> <div className="block lg:hidden"> <button onClick={() => setMenuVisibility(!isMenuVisible)} className="flex items-center px-3 py-2 border rounded text-gray-200 border-gray-400 hover:text-white hover:border-white" > <svg className="fill-current h-3 w-3" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" > <title>Menu</title> <path d="M0 3h20v2H0V3zm0 6h20v2H0V9zm0 6h20v2H0v-2z" /> </svg> </button> </div> <div className={`${ isMenuVisible ? 'max-h-full' : 'h-0' } overflow-hidden lg:h-auto w-full block flex-grow lg:flex lg:items-center lg:w-auto`} > {headerMenus?.length ? ( <div className="text-sm lg:flex-grow"> {headerMenus?.map((menu) => ( <Link key={menu?.node.id} href={menu?.node?.path}> <a className="block mt-4 lg:inline-block lg:mt-0 text-gray-200 hover:text-white mr-4"> {menu?.node?.label} </a> </Link> ))} </div> ) : null} <div> <a href="#" className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-gray-500 hover:bg-white mt-4 lg:mt-0" > Contact </a> </div> </div> </nav> ); }; export default Nav;
# Display art # Generate random account # format account data # ask user to guess # check if user is correct ## get follower ## use if statement to check if user is correct # give user feedback on their guess # make game repeatable # swap b to a and generate new random b from art import logo, vs import game_data import data import random import os # Function to clear the screen def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def format_data(account): """Format the account data into printable format""" account_name = account["name"] account_descr = account["description"] account_country = account["country"] return f"{account_name}, a {account_descr}, from {account_country}" def check_answer(guess, a_follower_count, b_follower_count): """Take the user guess and follower counts and returns if they got it right""" if a_follower_count > b_follower_count: return guess == "a" else: return guess == "b" print(logo) score = 0 game_should_continue = True account_b = random.choice(data) # reason to put outside, so this wont be used when the game continue, it stuck in the while loop until the game end while game_should_continue: account_a = account_b account_b = random.choice(data) if account_a == account_b: account_b = random.choice(data) print(f"Compare A: {format_data(account_a)}") print(vs) print(f"Compare B: {format_data(account_b)}") # ask user for a guess guess = input("Who has more followers? Type 'a' or 'b': ").lower() # check follower number a_follower_count = account_a["follower_count"] b_follower_count = account_b["follower_count"] is_correct = check_answer(guess, a_follower_count, b_follower_count) clear_screen() if is_correct: score += 1 print(f"You are right! Current score: {score}") else: game_should_continue = False print(f"Sorry, that's wrong. Final Score: {score}")
/** * Basic tool library * Copyright (C) 2014 kunyang kunyang.yk@gmail.com * * @file ky_flags.h * @brief 装配枚举类型为旗语标志 * * @author kunyang * @email kunyang.yk@gmail.com * @version 1.0.1.1 * @date 2018/08/01 * @license GNU General Public License (GPL) * * Change History : * Date | Version | Author | Description * 2018/08/01 | 1.0.0.1 | kunyang | 创建文件 * */ #ifndef KY_FLAGS_H #define KY_FLAGS_H #include "ky_define.h" #define kyDeclareFlags(T, N) \ typedef ky_flags<T> N //! //! \brief The ky_flag class 将枚举类型包装 //! template<typename Enum> class ky_flags { kyCompilerAssert(sizeof(Enum) <= sizeof(int)); kyCompilerAssert(is_enum<Enum>()); public: ky_flags(){flags = 0;} ky_flags(Enum e){flags = e;} ky_flags(int e){flags = e;} inline ky_flags &operator &= (int mask) {flags &= mask; return *this;} inline ky_flags &operator &= (Enum mask) {flags &= (int)mask; return *this;} inline ky_flags &operator |= (ky_flags f) {flags |= f.flags; return *this;} inline ky_flags &operator |= (Enum f) {flags |= (int)f; return *this;} inline ky_flags &operator ^= (ky_flags f) {flags ^= f.flags; return *this;} inline ky_flags &operator ^= (Enum f) {flags ^= (int)f; return *this;} inline operator int() const {return flags;} inline ky_flags operator |(ky_flags f) const {return ky_flags(flags | f.flags);} inline ky_flags operator |(Enum f) const {return ky_flags(flags | (int)f);} inline ky_flags operator ^(ky_flags f) const {return ky_flags(flags ^ f.i);} inline ky_flags operator ^(Enum f) const {return ky_flags(flags ^ (int)f);} inline ky_flags operator &(int mask) const {return ky_flags(flags & mask);} inline ky_flags operator &(Enum f) const {return ky_flags(flags & (int)f);} inline ky_flags operator ~() const {return ky_flags(~flags);} inline bool operator !() const {return !flags;} inline bool operator == (Enum f) const { return ((flags & (int)f) == (int)f) && ((int)f != 0 || flags == (int)f); } inline bool operator == (ky_flags f) const { return flags == f.flags; } inline ky_flags &set(Enum f, bool on = true) { return on ? (*this |= f) : (*this &= ~f); } inline bool is(Enum f) { return (*this & f) == f; } private: int flags; }; #endif // KY_FLAG_H
import { useState } from 'react' import { BsHash } from 'react-icons/bs' import { FaChevronDown, FaChevronRight, FaPlus } from 'react-icons/fa' const topics = ["tailwind-css", "react-js"] const questions = ["jit-compilation", "purging files", "dark/light mode"] const random = ["npm packages", "plugins", "memes"] const ChannelBar = () => { const loop = Array.from(Array(6).keys()) return ( <div className="channel-bar shadow-lg"> <ChannelBlock /> <Divider /> <div className="channel-container"> <Dropdown header="Topics" selections={topics} /> <Dropdown header="Questions" selections={questions} /> {loop.map((key) => { return <Dropdown header={`Random${key+1}`} selections={random} /> })} </div> </div> ) } const Dropdown = ({ header, selections }) => { const [expanded, setExpanded] = useState(true); return ( <div className="dropdown"> <div onClick={() => setExpanded(!expanded)} className="dropdown-header"> <ChevronIcon expanded={expanded} /> <h5 className={expanded ? "dropdown-header-text-selected" : "dropdown-header-text"}> {header} </h5> <FaPlus size="12" className="text-accent text-opacity-80 my-auto ml-auto" /> </div> {expanded && selections && selections?.map((selection) => <TopicSelection selection={selection} />)} </div> ) } const ChevronIcon = ({ expanded }) => { const chevClass = "text-accent text-opacity-80 my-auto mr-1"; return expanded ? ( <FaChevronDown size="14" className={chevClass} /> ) : ( <FaChevronRight size="14" className={chevClass} /> ); } const TopicSelection = ({ selection }) => ( <div className="dropdown-selection"> <BsHash size="24" className="text-gray-400 dark:text-white" /> <h5 className="dropdown-selection-text">{selection}</h5> </div> ) const ChannelBlock = () => ( <div className="channel-block"> <h5 className="channel-block-text ">Discord Server</h5> </div> ) const Divider = () => <hr className="channel-hr" /> export default ChannelBar
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" /> <title>Portfolio</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <link rel="stylesheet" href="style.css"/> </head> <body> <!-- NAVBAR-SECTION-START --> <header> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="d-flex"> <img src="./images/userAsset/NavLogo.avif" class="logo" /> <span class="logo-text d-block mt-3">jay</span> </div> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <div class="container"> <div class="row"> <nav class="navbar-nav d-flex justify-content-end"> <div class="col-md-1"> <li class="nav-item"> <a class="nav-link text-center active" aria-current="page" href="#projects">Projects</a> </li> </div> <div class="col-md-1"> <li class="nav-item"> <a class="nav-link text-center active" aria-current="page" href="#skills">Skills</a> </li> </div> <div class="col-md-1"> <li class="nav-item"> <a class="nav-link text-center active" aria-current="page" href="#contact-me">Contact</a> </li> </div> </nav> </div> </div> </div> </nav> </div> </header> <!-- NAVBAR-SECTION-END --> <!-- HERO-SECTION-START --> <div class="container mt-5"> <div class="row justify-content-evenly"> <div class="col-8 col-sm-12 p-sm-0 col-md-6 col-xl-6"> <div class="hero-section-left"> <div class="hero-section-heading" style="font-family: Arial, Helvetica, sans-serif;">Hi!! Ajay Vishwakarma </div> <div class="hero-section-heading hero-section-sub-heading" style="font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;"> I am a <span class="role"> </span> </div> <div class="hero-section-description" style="font-family:'Times New Roman', Times, serif"> I am a software developer and here is my portfolio website. here you will learn about my journey as a software developer. </div> <a href="https://www.linkedin.com/in/ajayvishwakarma05" style="text-decoration: none"> <div class="btn-pink" style="font-family: 'Times New Roman', Times, serif;">Contact Me</div> </a> </div> </div> <div class="col-8 mt-5 col-sm-8 mt-sm-5 col-xl-4 col-md-4 mt-md-auto mb-md-auto"> <div class="hero-section-right" style="width: auto; min-width: 250px"> <div class="absolute icons icon-dots"> <img src="./images/userAsset/dots.png" alt="" width="50px" /> </div> <div class="absolute icons icon-cube"> <img src="./images/userAsset/cube.webp" alt="" width="35px" /> </div> <div class="absolute icons icon-circle"> <img src="./images/userAsset/circle.png" alt="" width="30px" /> </div> <div class="absolute icons icon-zigzag"> <img src="./images/userAsset/zigzag.png" alt="" width="40px" /> </div> <div class="absolute icons icon-plus"> <img src="./images/userAsset/plus.png" alt="" width="40px" /> </div> <div class="user-img"> <img src="./images/userAsset/User.png" alt="" width="100%" /> </div> </div> </div> <div class="faded-text ms-5">Ajay</div> </div> </div> <!-- HERO-SECTION-END --> <!-- PROJECT SECTION START --> <div class="container-fluid"> <h3 class="page-header">Projects</h3> <div class="container" id="projects"> <div class="row"> <div class="col-md-6 mb-5 order-1"> <div class="card"> <img src="./images/projects/Travel.png" class="card-img-top" alt="..." /> <div class="card-body"> <h6 class="card-title">Travel The World</h6> <p class="card-text"> It is a website where you can explore places. </p> <b>Tecnology Used : HTML-5 ,CSS-3 , Bootstrap-5.</b> <div class="d-flex justify-content-between mt-2"> <a href="https://travel-world-web.netlify.app/index.html" style="text-decoration: none"> <div class="btn-pink">Read More</div> </a> <a href="https://github.com/ajaykarma0508?tab=repositories"><i class="fa fa-github fa-2x mt-3"></i></a> </div> </div> </div> </div> <div class="col-md-6 mb-5 order-2"> <div class="card"> <img src="./images/projects/Amazon.png" class="card-img-top" alt="..." /> <div class="card-body"> <h6 class="card-title">Amazon Clone</h6> <p class="card-text"> An Amazon clone is a website that replicates the UI of Amazon. </p> <b>Tecnology Used : HTML-5 ,CSS-3.</b> <div class="d-flex justify-content-between mt-2"> <a href="https://ajaykarma0508.github.io/AmazonClone/" style="text-decoration: none"> <div class="btn-pink">Read More</div> </a> <a href="https://github.com/ajaykarma0508/AmazonClone"><i class="fa fa-github fa-2x mt-3"></i></a> </div> </div> </div> </div> <div class="col-md-6 mb-5 order-3"> <div class="card"> <img src="./images/projects/JDBC.png" class="card-img-top" alt="..." /> <div class="card-body"> <h6 class="card-title">JDBC CRUD Application</h6> <p class="card-text"> Developed robust Java CRUD application using JDBC. </p> <b>Tecnology Used : Java , JDBC , Swing.</b> <div class="d-flex justify-content-between mt-2"> <a href="https://github.com/ajaykarma0508/JdbcCrudApplication" style="text-decoration: none"> <div class="btn-pink">Read More</div> </a> <a href="https://github.com/ajaykarma0508/JdbcCrudApplication"><i class="fa fa-github fa-2x mt-3"></i></a> </div> </div> </div> </div> <div class="col-md-6 mb-5 order-0"> <div class="card"> <img src="./images/projects/Techblog.png" class="card-img-top" alt="..." /> <div class="card-body"> <h6 class="card-title">Tech Blog</h6> <p class="card-text"> A tech blog is a website that focuses on technology-related topics, such as the latest news, reviews, and tutorials related to computer software. </p> <b>Tecnology Used : HTML-5 ,CSS-3 , Bootstrap-5 , Java , JDBC , JSP , Servlets. </b> <div class="d-flex justify-content-between"> <a href="https://github.com/ajaykarma0508/Techblog" style="text-decoration: none"> <div class="btn-pink">Read More</div> </a> <a href="https://github.com/ajaykarma0508/Techblog"><i class="fa fa-github fa-2x mt-3"></i></a> </div> </div> </div> </div> </div> </div> </div> <!-- PROJECT SECTION END --> <!-- SKILLS SECTION START --> <div class="container"> <div class="row p-5"> <div class="col-md-6" id="skills"> <h2 class="skill-heading"> <span class="caps">M</span>e and <br /> MyTech Stack </h2> <div class="skills-subHeading mt-5" style="width: 100%;"> <p> Hi, I am a final year Under-Graduate student. Currently pursuing Bachelor's of Technology in 'Computer Science and Engineering ' from swami Vivekanand College of engineering. </p> <br /> <p> I am a passionate coder as well as an innovative and creative thinker. Curious person who loves to explore the problem Solving world to gain knowledge. I am always eager to learn about about latest developments in the software Development world . </p> <br /> <p> I have worked on Java and HTML CSS and have good knowledge of C++ as well. </p> <br /> <p> I have good knowledge of Data structures and Algorithms, OOPS, and DBMS. </p> </div> </div> <div class="col-md-6"> <div class="container mt-5 p-0"> <div class="row justify-content-between text-center"> <div class="col-4 col-sm-4 col-md-4 mb-4"> <img class="skills-logo" src="./images/stack/html.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/css.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/c.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4 mb-4"> <img class="skills-logo" src="./images/stack/c++.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/java.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/mysql.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4 mb-4"> <img class="skills-logo" src="./images/stack/DSA.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/visual-studio.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/github.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/leetcode.png" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/GFG.jpeg" alt="" /> </div> <div class="col-4 col-sm-4 col-md-4"> <img class="skills-logo" src="./images/stack/linkedin.png" alt="" /> </div> </div> </div> </div> </div> </div> <!-- SKILLS SECTION END --> <!-- CONTACT SECTION START --> <div class="container-fluid" id="contact-me"> <div class="container"> <h1 class="contactus-heading text-center">Contact Me</h1> <div class="row justify-content-center"> <div class="col-md-8"> <div class="mb-3" style="box-shadow: 2px 2px 5px black"> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter your name" /> </div> <div class="mb-3" style="box-shadow: 2px 2px 5px black"> <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="Enter your email address" /> </div> <div class="mb-3" style="box-shadow: 2px 2px 5px black"> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Enter your subject" /> </div> <div class="mb-3" style="box-shadow: 2px 2px 5px black"> <textarea class="form-control" placeholder="sadsaddddddddd" id="exampleFormControlTextarea1" rows="3"> </textarea> </div> <button class="btn btn-pink btn-project" id="sub-btn" href="#"> Send Message <i class="submit-icon fa-solid fa-paper-plane"></i> </button> </div> </div> </div> </div> <!-- CONTACT SECTION END --> <!-- FOOTER SECTION START --> <footer> <div class="container"> <div class="footer-faded-text">Ajay</div> <div class="row"> <div class="col-md-6 text-center pt-2"> <a style="text-decoration: none; padding: 5px" href="#projects">Prjects</a> <a style="text-decoration: none; padding: 5px" href="#skills">Skills</a> <a style="text-decoration: none; padding: 5px" href="#contectme">Contact Me</a> </div> <div class="col-md-6 text-center"> <a href="https://www.linkedin.com/in/ajayvishwakarma05/"><i style="padding: 5px" class="animate icon fa-brands fa-linkedin"></i></a> <a href="https://github.com/ajaykarma0508"><i style="padding: 5px" class="animate icon fa-brands fa-github"></i></a> </div> </div> </div> </footer> <!-- FOOTER SECTION END --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12"></script> <script src="https://kit.fontawesome.com/58a810656e.js" crossorigin="anonymous"></script> <script> var typeData = new Typed(".role", { strings: [ , "Full Stack Developer", "Web Developer", "Backend Developer", "Coder", ], loop: true, typeSpeed: 100, backSpeed: 80, backDelay: 1000, }); </script> </body> </html>
from __future__ import annotations # coding: utf-8 # graph.py from abc import ABC, abstractmethod from typing import TypeVar, NewType, Tuple, Iterator, Union from UnionFind import * #################### Type #################### Edge = Tuple[Node, Node] Weight = Union[int, float] WeightedEdge = Tuple[Node, Node, Weight] #################### GraphBase #################### class GraphBase(ABC): def __init__(self): pass @abstractmethod def generate_nodes(self) -> Iterator[Node]: pass @abstractmethod def neighbors(self, v0: Node) -> list[Node]: pass def generate_edges(self) -> Iterator[Edge]: for u in self.generate_nodes(): for v in self.neighbors(u): yield (u, v) def divide_nodes_into_connected(self) -> list[list[Node]]: nodes = list(self.generate_nodes()) uf = UnionFind(nodes) for u, v in self.generate_edges(): uf.join(u, v) groups: dict[Node, int] = uf.divide_into_trees() num_groups = max(groups.values()) + 1 vs: list[list[Node]] = [ [] for _ in range(num_groups) ] for v, group_index in groups.items(): vs[group_index].append(v) return vs #################### WeightedGraphBase #################### class WeightedGraphBase(GraphBase): def __init__(self): pass @abstractmethod def generate_weighted_edges(self) -> Iterator[WeightedEdge]: pass __all__ = ['GraphBase', 'WeightedGraphBase', 'Node']
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAddressesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('addresses', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->foreign()->references('id')->on('users')->onDelete('cascade'); $table->boolean('type')->comment('1 => "Current Address" || 0 => "Permanent Address"'); $table->string('line_one'); $table->string('line_two')->nullable(); $table->integer('city_id')->foreign()->references('id')->on('cities'); $table->integer('state_id')->foreign()->references('id')->on('states'); $table->integer('country_id')->foreign()->references('id')->on('countries'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('addresses'); } }
import { Button, Checkbox, FormControl, FormLabel, Input, InputGroup, InputLeftAddon, InputRightElement, Textarea, useToast } from "@chakra-ui/react"; import React, { useContext, useEffect, useState } from "react"; import { FiCheck, FiChevronLeft, FiChevronRight, FiX } from "react-icons/fi"; import { request } from "../../utility/utils"; import { AuthContext } from "../../utility/userAuthContext"; import { useDispatch } from "react-redux"; import { setLivePolls, setRecentPolls } from "../../redux/actions/pollsDataAction"; const Page1 = (props) => { const options = props.options; const optionElement = props.optionElement; const statement = props.statement; const title = props.title return <div className="w-7/12 flex flex-col"> <FormControl className="mb-10"> <FormLabel fontWeight="semibold" fontSize="2xl" className="mb-5">Title:</FormLabel> <Input name="statement" size="lg" placeholder="Statement goes here" variant="filled" width="full" background="DBlue.700" _focus={{ background: "DBlue.700" }} _hover={{ background: "DBlue.700" }} value={title} maxLength="20" onChange={e => props.setTitle(e.target.value)} className="text-white" rounded="xl" /> </FormControl> <FormControl className="mb-10"> <FormLabel fontWeight="semibold" fontSize="2xl" className="mb-5">Statement:</FormLabel> <Textarea name="statement" size="lg" placeholder="Statement goes here" variant="filled" width="full" background="DBlue.700" _focus={{ background: "DBlue.700" }} _hover={{ background: "DBlue.700" }} value={statement} onChange={e => props.setStatement(e.target.value)} className="text-white" rounded="xl" /> </FormControl> <p className="text-2xl font-semibold">Options: </p> <div className="flex flex-col bg-DBlue px-2 rounded-lg my-5 px-5 py-5"> {options.map(optionElement)} <Button width="max-content" className="self-end" colorScheme="Blue" rounded="full" onClick={props.onClickAddOption}>Add Option</Button> </div> </div>; } const Page2 = (props) => { const [selections, makeSelections] = useState({}); const [datetime, setdatetime] = useState(""); const { dateTime, Context } = props; useEffect(() => { dateTime(datetime); }, [datetime]); useEffect(() => { Context(selections); }) useEffect(() => { if (Object.keys(selections).length === 0) { if (props.divisions === null) { } else { let division = {}; for (let item of Object.entries(props.divisions)) { let year = {}; for (let dept of Object.entries(item[1])) { let sec = {}; for (let sec_ of dept[1]) { sec[sec_] = false; } year[dept[0]] = sec; } division[item[0]] = year; } makeSelections(division) } } }, [props.divisions, selections]) const SelectionContext = (props) => { const selections = props.selections; console.log(selections) const [yearState, setYearState] = useState(selections); const bgColors = ["pink-300", "gray-400", "yellow-300", "sky-300"]; useEffect(() => { console.log(yearState); }, [yearState]) const updateYearState = (state, year) => { console.log("calling") let tObj = yearState; tObj[year] = state; setYearState({ ...tObj }); } const InEachDept = props => { const [sectionsSelected, setSectionsSelected] = useState(props.sections); const { dept, updateDeptState } = props; const allChecked = Object.values(sectionsSelected).every(Boolean); const isIndeterminate = Object.values(sectionsSelected).some(Boolean) && !allChecked; return <div className="flex flex-col px-3 py-2 border-black border-2 rounded-lg w-36 mx-3 bg-white flex-shrink-0"> <div className="flex w-full flex-row flex-nowrap justify-around px-2 items-center"> <p className="text-2xl font-semibold whitespace-nowrap">{dept}</p> <Checkbox colorScheme="black" size="lg" className="h-fit" background="#00000011" isIndeterminate={isIndeterminate} isChecked={allChecked} onChange={(e) => { let tArr = Object.keys(sectionsSelected); let tObj = {}; for (let i of tArr) tObj[i] = e.target.checked; setSectionsSelected({ ...tObj }); updateDeptState({ ...tObj }, dept); } } /> </div> <div className="w-full h-1 bg-black" /> <div className="flex flex-row flex-nowrap px-2 justify-around py-2"> {Object.entries(sectionsSelected).map((el, i, arr) => { return <Checkbox key={i} size="lg" colorScheme="Wood" background="#00000011" isChecked={Boolean(Object.values(sectionsSelected)[i])} onChange={e => { let tObj = { ...sectionsSelected }; tObj[Object.keys(sectionsSelected)[i]] = e.target.checked; setSectionsSelected(tObj); console.log(tObj) console.log(sectionsSelected) updateDeptState({ ...tObj }, dept); }} /> })} </div> </div> } const InEachYear = props => { const { year, depts, updateYearState, bgColor } = props; const [allDeptState, setAllDeptState] = useState(depts); const updateDeptState = (state, dept) => { let tObj = allDeptState; tObj[dept] = state; console.log(state) setAllDeptState({ ...tObj }); console.log("called") updateYearState(allDeptState, year); } return <div className={`px-1 rounded-xl my-2 w-full flex flex-col bg-opacity-70 bg-` + bgColor}> <p className="text-4xl font-semibold pl-5 pt-5">{year}</p> <div className="w-full flex flex-nowrap flex-row overflow-auto mb-5"> { Object.entries(allDeptState).map((el, i, arr) => { return Object.keys(el[1]).length > 0 ? <InEachDept dept={el[0]} sections={el[1]} key={i} updateDeptState={updateDeptState} /> : <div key={i}></div> }) } </div> </div> } return <div className="w-full p-5 "> { Object.entries(yearState).map((el, i, arr) => { return <InEachYear year={el[0]} depts={el[1]} key={i} bgColor={bgColors[i]} updateYearState={updateYearState} /> }) } </div> } return <div className="w-full flex flex-col items-center"> <div className="w-7/12 flex flex-col bg-DBlue rounded-lg text-white p-5"> <p className="font-semibold text-3xl mb-5">When the poll ends?</p> <Input type="datetime-local" borderColor="Pink.400" color="white" borderWidth={2} focusBorderColor="Pink.500" placeholder="Choose end time" min={new Date().toISOString().replace(/\.\d{3}/, '')} _hover={{ borderColor: "Pink" }} onChange={e => setdatetime(e.target.value)} /> </div> <div className="w-full rounded-xl my-5"> <p className="mt-5 text-4xl font-semibold pl-5">Select the voters</p> <SelectionContext selections={selections} /> </div> </div> } export const CreatePollAdmin = () => { const user = useContext(AuthContext); const [options, setOptions] = useState([""]); const [statement, setStatement] = useState("") const [pageNo, setPageNo] = useState(1); const [divisions, setDivisions] = useState(null); const [dTime, setdTime] = useState(""); const [context, setContext] = useState({}); const [error, setError] = useState(""); const [loading, setLoading] = useState(false); const [title, setTitle] = useState(""); const toast = useToast(); const dispatch = useDispatch(); const dateTime = (datetime) => { setdTime(datetime); } const Context = (_context) => { setContext(_context); } useEffect(() => { if (divisions === null && user !== null) { request.get("admin/get/divisions").then(result => { setDivisions({ ...result.data }); }) } }, [divisions, user]); const onClickAddOption = (e) => { options.push(""); setOptions([...options]); console.log(options) } const onNextClick = () => { if (pageNo === 1) { setPageNo(2); } else { let opt = options.filter(el => el.trim() !== ""); if (title.trim() !== "" && statement.trim() !== "" && opt.length !== 0 && dTime.trim() !== "" && Object.keys(context).length !== 0) { setLoading(true); request.post("/admin/create/poll", { title: title, statement: statement, options: opt, option_count: opt.length, ends_by: dTime, context: context }).then(result => { toast({ title: "Success", description: "Poll created successfully", variant: "subtle", duration: 2000 }); setLoading(false); dispatch(setRecentPolls(null)); dispatch(setLivePolls(null)); }).catch(err => { toast({ title: "Error", description: "An Error Occured", variant: "subtle", duration: 2000 }); setLoading(false); }) } else { setError("An error occured"); console.log(opt) } } } const optionElement = (option, index, arr) => { return <div className="my-2 w-full h-full" key={index}> <div className="bg-transparent rounded-lg px-5 py-2"> <InputGroup borderColor="Pink.400"> <InputLeftAddon backgroundColor="Pink.400" color="Sandal.100" children={String.fromCharCode(index + 65)} pointerEvents="none" /> <Input borderWidth="medium" focusBorderColor="Pink.600" color="Sandal.100" _hover={{ borderColor: "Pink.600" }} placeholder={"Option " + (index + 1)} value={options[index]} autoFocus={index + 1 === arr.length} onChange={e => { const tArr = options; tArr[index] = e.target.value; setOptions([...tArr]); }} /> {(arr.length !== 1) && <InputRightElement children={<FiX />} cursor="pointer" color="Sandal.100" onClick={e => { const tArr = options; tArr.splice(index, 1); console.log(index); setOptions([...tArr]) }} />} </InputGroup> </div> </div> } return <div className="text-black h-full w-full overflow-y-auto bg-Sandal p-5 rounded-l-3xl"> <h1 className="text-7xl font-bold pl-10 pt-10">Create Poll</h1> <section className="flex items-center mt-5 flex-col w-full justify-center"> <div className="flex flex-col w-full items-center"> {pageNo === 1 ? <Page1 options={options} optionElement={optionElement} onClickAddOption={onClickAddOption} setStatement={setStatement} statement={statement} title={title} setTitle={setTitle} /> : <Page2 divisions={divisions} dateTime={dateTime} Context={Context} />} <p className="text-red-400 font-semibold self-end pr-48">{error}</p> <div className="self-end mt-5 flex justify-between w-full px-48 mb-48"> <Button aria-label="Next" variant="solid" rounded="full" size="lg" colorScheme="pink" visibility={pageNo === 1 ? "hidden" : ""} onClick={e => setPageNo(1)} leftIcon={<FiChevronLeft />}>Previous</Button> <Button aria-label="Prev" variant={pageNo === 1 ? "solid" : "solid"} rounded="full" size="lg" colorScheme="pink" onClick={onNextClick} isLoading={loading} rightIcon={pageNo === 1 ? <FiChevronRight /> : <FiCheck />}>{pageNo === 1 ? "Next" : "Create"}</Button> </div> </div> </section> <div className="bg-pink-300 bg- bg-sky-300 bg-gray-400 bg-yellow-300 hidden" /> </div> }
<?php namespace App\Controllers\admin; use App\Controllers\BaseController; use App\Models\BooksModel; use App\Models\OtherModel; use App\Models\BorrowBooksModel; use App\Models\SettingsModel; use App\Controllers\Mail; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\Validation\ValidationInterface; class Activity extends BaseController { public function __construct() { date_default_timezone_set("Asia/Kolkata"); $this->booksModel = new BooksModel(); $this->borrowbooksModel = new BorrowBooksModel(); $this->otherModel = new OtherModel(); $this->settingsModel = new SettingsModel(); $this->mail = new Mail(); // Inject the ValidationInterface into the controller $this->validation = \Config\Services::validation(); } public function Borrow($var = null) { $session = session(); if ($session->get('role')!="admin") { return redirect()->to('/'); } if($this->request->getMethod() === 'post'){ $bcode = $this->request->getPost('bcode'); $regno = $this->request->getPost('regno'); $sname = $this->request->getPost('sname'); $bno = $this->request->getPost('bno'); $title = $this->request->getPost('title'); $aname = $this->request->getPost('aname'); $publication = $this->request->getPost('publication'); $price = $this->request->getPost('price'); $alamara = $this->request->getPost('alamara'); $rack = $this->request->getPost('rack'); $remark = $this->request->getPost('remark'); // Set the validation rules $validationRules = [ 'bcode' => 'required', 'regno' => 'required', 'sname' => 'required', 'bno' => 'required', // 'title' => 'required', // 'aname' => 'required', // 'publication' => 'required', // 'price' => 'required', // 'reqdate' => 'required', // 'retdate' => 'required' ]; // Set custom error messages for each field $validationMessages = [ 'bcode' => [ 'required' => 'The Barcode No field is required.' ], 'regno' => [ 'required' => 'The Register Number field is required.' ], 'sname' => [ 'required' => 'The Std/Staff Name field is required.' ], 'bno' => [ 'required' => 'The Book No field is required.' ]//, // 'title' => [ // 'required' => 'The Title field is required.' // ], // 'aname' => [ // 'required' => 'The Author Name field is required.' // ], // 'publication' => [ // 'required' => 'The Publication field is required.' // ], // 'price' => [ // 'required' => 'The Price field is required.' // ], // 'reqdate' => [ // 'required' => 'The Request Date field is required.' // ], // 'retdate' => [ // 'required' => 'The ETA Return Date field is required.' // ] ]; $validation = \Config\Services::validation(); $validation->setRules($validationRules, $validationMessages); if($this->validation->withRequest($this->request)->run()){ $res = $this->otherModel->getUserDet($regno); $book = $this->booksModel->getBookDetail($bcode); $Appfine = $this->settingsModel->getAppfine(); $return_date = ($res['role']=="staff") ? date("Y-m-d", strtotime("+". $Appfine['fine_stf_days']." days")) : date("Y-m-d", strtotime("+". $Appfine['fine_std_days']." days")) ; $request_date = date("Y-m-d h:i:s"); $data = [ 'sid' => $res['sid'], 'bid' => $book['bid'], 'role' => $res['role'], 'returned_date' => '0000-00-00', 'status' => 1, 'is_returned' => 0, 'return_date' => $return_date, 'request_date' => $request_date, 'remark' => $remark, ]; if ($book['status']==1) { if($this->borrowbooksModel->setBorrowBook($data)){ $this->booksModel->updateBook($bcode,['status' => 0]); try{ // mail $subject = '(TESTING) You borrowed a book from CA GAC-7 library'; $body = str_replace(array('{name}', '{caname}', '{ctitle}', '{cpublic}', '{crdate}', '{cetdate}'),array($sname, $aname, $title, $publication, date("d-M-Y", strtotime($request_date)), date("d-M-Y", strtotime($return_date)), ),file_get_contents(base_url('assets/Template/mail.phtml'))); // mail trigger (calling send mail function) // $this->mail->sendmail($res['email'],$sname,$subject,$body); } catch(Exception $e){ } $session->setFlashdata('msg', 'Book Borrowed.'); } else{ $session->setFlashdata('msg', 'Book Borrowed Failed.'); } } else{ // echo "<script>alert('Please verify if the book is borrowed or unavailable in the library')</script>"; $session->setFlashdata('msg', 'Please verify if the book is borrowed or unavailable in the library.'); } } else { // Validation failed $errors = $this->validation->getErrors(); } } helper(['form']); echo view('Others/header'); if($var==null){ echo view('Admin/AdminBookBorrow'); } else{ $data = [ 'BooksData' => $this->booksModel->getBookDetail($var), ]; echo view('Admin/AdminBookBorrowA',$data); } echo view('Others/fooder'); } public function Return() { $session = session(); if ($session->get('role')!="admin") { return redirect()->to('/'); } if($this->request->getMethod() === 'post'){ $bcode = $this->request->getPost('bcode'); $regno = $this->request->getPost('regno'); $sname = $this->request->getPost('sname'); $bno = $this->request->getPost('bno'); $remark = $this->request->getPost('remark'); // Set the validation rules $validationRules = [ 'bcode' => 'required', 'regno' => 'required', 'sname' => 'required', 'bno' => 'required', ]; // Set custom error messages for each field $validationMessages = [ 'bcode' => [ 'required' => 'The Barcode No field is required.' ], 'regno' => [ 'required' => 'The Register Number field is required.' ], 'sname' => [ 'required' => 'The Std/Staff Name field is required.' ], 'bno' => [ 'required' => 'The Book No field is required.' ] ]; $validation = \Config\Services::validation(); $validation->setRules($validationRules, $validationMessages); if($this->validation->withRequest($this->request)->run()){ $book = $this->booksModel->getBookDetail($bcode); if ($this->borrowbooksModel->setBookreturn($book['bid'],['is_returned' => 1,'returned_date' => date("Y-m-d h:i:s"),'remark' => $remark ])) { $this->booksModel->updateBook($bcode,['status' => 1]); $session->setFlashdata('msg', 'Book return Successfully.'); } else{ $session->setFlashdata('msg', 'Book return Failed.'); } } else { // Validation failed $errors = $this->validation->getErrors(); } } helper(['form']); echo view('Others/header'); echo view('Admin/AdminBookReturn'); echo view('Others/fooder'); } }
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; import { url } from "./api"; import { jwtDecode } from "jwt-decode"; const initialState = { token: localStorage.getItem("token"), name: "", email: "", _id: "", registerStatus: "", registerError: "", loginStatus: "", loginError: "", userLoaded: false } //action creator export const registerUser = createAsyncThunk( "auth/registerUser", async (values, { rejectWithValue }) => { try { const token = await axios.post(`${url}/register`, { name: values.name, email: values.email, password: values.password, }); localStorage.setItem("token", token.data); return token.data; } catch (error) { console.log(error.response.data); return rejectWithValue(error.response.data); } } ); //login export const loginUser = createAsyncThunk( "auth/loginUser", async (values, { rejectWithValue }) => { try { const token = await axios.post(`${url}/login`, { email: values.email, password: values.password, }); localStorage.setItem("token", token.data); return token.data; } catch (error) { console.log(error.response.data); return rejectWithValue(error.response.data); } } ); const authSlice = createSlice({ name: "auth", initialState, reducers: { loadUser(state, action) { const token = state.token if (token) { const user = jwtDecode(token) return { ...state, token, name: user.name, email: user.email, _id: user._id, userLoaded: true } } }, logoutUser(state, action) { localStorage.removeItem("token") return { ...state, token: "", name: "", email: "", _id: "", registerStatus: "", registerError: "", loginStatus: "", loginError: "", userLoaded: false } } }, extraReducers: (builder) => { builder.addCase(registerUser.pending, (state, action) => { return { ...state, registerStatus: "pending" } }), builder.addCase(registerUser.fulfilled, (state, action) => { const user = jwtDecode(action.payload) if (action.payload) { return { ...state, token: action.payload, name: user.name, email: user.email, _id: user._id, registerStatus: "success" } } else return state; }), builder.addCase(registerUser.rejected, (state, action) => { return { ...state, registerStatus: "rejected", registerError: action.payload } }), //Login builder.addCase(loginUser.pending, (state, action) => { return { ...state, loginStatus: "pending" } }), builder.addCase(loginUser.fulfilled, (state, action) => { const user = jwtDecode(action.payload) if (action.payload) { return { ...state, token: action.payload, name: user.name, email: user.email, _id: user._id, loginStatus: "success" } } else return state; }), builder.addCase(loginUser.rejected, (state, action) => { return { ...state, loginStatus: "rejected", loginError: action.payload } }) }, }) export const { loadUser, logoutUser } = authSlice.actions export default authSlice.reducer
"use client";; import { listInfo } from "../AddressList/state"; import { TabsContent } from "@/components/ui/tabs"; import { Card } from "@/components/ui/card"; import NetCurveChart from "@/components/net-curve-chart"; import { UTCTimestamp } from "lightweight-charts"; import { useSelector } from "@legendapp/state/react"; const formatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }); export default function StatsTab() { const selectedRows = useSelector(listInfo.selectedRows); return selectedRows.length ? ( <TabsContent data-lenis-prevent value="stats"> <Card className="p-6"> <div className="flex flex-col gap-2"> <NetCurveChart charts={selectedRows.map((el) => ({ label: el!.address, data: Object.entries( JSON.parse(el!.net_curve) as Record<string, number> ).map(([date, value], idx) => ({ time: +date as UTCTimestamp, value, })), }))} /> <div className="flex items-center gap-1.5"> <span className="font-semibold">total USD:</span> <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm"> {formatter.format( selectedRows .map((el) => +el!.usd_total) .reduce((a: number, b: number) => a + b, 0) )} </code> </div> <div className="flex items-center gap-1.5"> <span className="font-semibold">avg ROI:</span> <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm"> {( selectedRows .map((el) => +el!.roi) .reduce((a: number, b: number) => a + b, 0) / selectedRows.length ).toFixed(1) + "%"} </code> </div> <div className="flex items-center gap-1.5"> <span className="font-semibold">avg W/L:</span> <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm"> {( selectedRows .map((el) => +el!.winrate) .reduce((a: number, b: number) => a + b, 0) / selectedRows.length ).toFixed(2)} </code> </div> </div> </Card> </TabsContent> ) : null; }
# Valid Anagram # # Given two strings s and t, return true if t is an anagram of s, and false otherwise. # An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. # # Example 1: # Input: s = "anagram", t = "nagaram" # Output: true # # Example 2: # Input: s = "rat", t = "car" # Output: false # # Algorithm: # Sort the input strings: # Sort the characters of both strings s and t. # For example, if s = "anagram" and t = "nagaram", after sorting, sorted_s = "aaagmnr" and sorted_t = "aaagmnr". # Compare the sorted strings: # If the sorted strings are equal, return True, indicating that s and t are anagrams. # Otherwise, return False, indicating that s and t are not anagrams. # # Big-O: # Time: O(n log n) # Space: O(n) # Algorithm class Solution: def isAnagram(self, s: str, t: str) -> bool: sorted_s = sorted(s) sorted_t = sorted(t) return sorted_s == sorted_t # Example: if __name__ == "__main__": solution = Solution() print(solution.isAnagram("anagram", "nagaram")) # Output: True print(solution.isAnagram("rat", "car")) # Output: False
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * This page handles editing and creation of cquiz overrides * * @package mod * @subpackage cquiz * @copyright 2010 Matt Petro * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once(dirname(__FILE__) . '/../../config.php'); require_once($CFG->dirroot.'/mod/cquiz/lib.php'); require_once($CFG->dirroot.'/mod/cquiz/locallib.php'); require_once($CFG->dirroot.'/mod/cquiz/override_form.php'); $cmid = optional_param('cmid', 0, PARAM_INT); $overrideid = optional_param('id', 0, PARAM_INT); $action = optional_param('action', null, PARAM_ALPHA); $reset = optional_param('reset', false, PARAM_BOOL); $override = null; if ($overrideid) { if (! $override = $DB->get_record('cquiz_overrides', array('id' => $overrideid))) { print_error('invalidoverrideid', 'cquiz'); } if (! $cquiz = $DB->get_record('cquiz', array('id' => $override->cquiz))) { print_error('invalidcoursemodule'); } if (! $cm = get_coursemodule_from_instance("cquiz", $cquiz->id, $cquiz->course)) { print_error('invalidcoursemodule'); } } else if ($cmid) { if (! $cm = get_coursemodule_from_id('cquiz', $cmid)) { print_error('invalidcoursemodule'); } if (! $cquiz = $DB->get_record('cquiz', array('id' => $cm->instance))) { print_error('invalidcoursemodule'); } } else { print_error('invalidcoursemodule'); } $course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); $url = new moodle_url('/mod/cquiz/overrideedit.php'); if ($action) { $url->param('action', $action); } if ($overrideid) { $url->param('id', $overrideid); } else { $url->param('cmid', $cmid); } $PAGE->set_url($url); require_login($course, false, $cm); $context = context_module::instance($cm->id); // Add or edit an override. require_capability('mod/cquiz:manageoverrides', $context); if ($overrideid) { // Editing an override. $data = clone $override; } else { // Creating a new override. $data = new stdClass(); } // Merge cquiz defaults with data. $keys = array('timeopen', 'timeclose', 'timelimit', 'attempts', 'password'); foreach ($keys as $key) { if (!isset($data->{$key}) || $reset) { $data->{$key} = $cquiz->{$key}; } } // If we are duplicating an override, then clear the user/group and override id // since they will change. if ($action === 'duplicate') { $override->id = null; $override->userid = null; $override->groupid = null; } // True if group-based override. $groupmode = !empty($data->groupid) || ($action === 'addgroup' && empty($overrideid)); $overridelisturl = new moodle_url('/mod/cquiz/overrides.php', array('cmid'=>$cm->id)); if (!$groupmode) { $overridelisturl->param('mode', 'user'); } // Setup the form. $mform = new cquiz_override_form($url, $cm, $cquiz, $context, $groupmode, $override); $mform->set_data($data); if ($mform->is_cancelled()) { redirect($overridelisturl); } else if (optional_param('resetbutton', 0, PARAM_ALPHA)) { $url->param('reset', true); redirect($url); } else if ($fromform = $mform->get_data()) { // Process the data. $fromform->cquiz = $cquiz->id; // Replace unchanged values with null. foreach ($keys as $key) { if ($fromform->{$key} == $cquiz->{$key}) { $fromform->{$key} = null; } } // See if we are replacing an existing override. $userorgroupchanged = false; if (empty($override->id)) { $userorgroupchanged = true; } else if (!empty($fromform->userid)) { $userorgroupchanged = $fromform->userid !== $override->userid; } else { $userorgroupchanged = $fromform->groupid !== $override->groupid; } if ($userorgroupchanged) { $conditions = array( 'cquiz' => $cquiz->id, 'userid' => empty($fromform->userid)? null : $fromform->userid, 'groupid' => empty($fromform->groupid)? null : $fromform->groupid); if ($oldoverride = $DB->get_record('cquiz_overrides', $conditions)) { // There is an old override, so we merge any new settings on top of // the older override. foreach ($keys as $key) { if (is_null($fromform->{$key})) { $fromform->{$key} = $oldoverride->{$key}; } } // Delete the old override. $DB->delete_records('cquiz_overrides', array('id' => $oldoverride->id)); } } if (!empty($override->id)) { $fromform->id = $override->id; $DB->update_record('cquiz_overrides', $fromform); } else { unset($fromform->id); $fromform->id = $DB->insert_record('cquiz_overrides', $fromform); } cquiz_update_open_attempts(array('cquizid'=>$cquiz->id)); cquiz_update_events($cquiz, $fromform); add_to_log($cm->course, 'cquiz', 'edit override', "overrideedit.php?id=$fromform->id", $cquiz->id, $cm->id); if (!empty($fromform->submitbutton)) { redirect($overridelisturl); } // The user pressed the 'again' button, so redirect back to this page. $url->remove_params('cmid'); $url->param('action', 'duplicate'); $url->param('id', $fromform->id); redirect($url); } // Print the form. $pagetitle = get_string('editoverride', 'cquiz'); $PAGE->navbar->add($pagetitle); $PAGE->set_pagelayout('admin'); $PAGE->set_title($pagetitle); $PAGE->set_heading($course->fullname); echo $OUTPUT->header(); echo $OUTPUT->heading($pagetitle); $mform->display(); echo $OUTPUT->footer();
<template> <div> <div class="blog-card mt-4"> <img :src="image" alt="" class="img-responsive" /> <div class="card-body"> <p class="header m-0"> {{ post.title }} </p> <span> Posted on {{ callDate(post.created_at, "fullDate") }}</span> <p class="card-text"> {{ post.description }} </p> <router-link class="btn post-btn" :to="{ name: 'Blog', params: { id: post.id } }" > Read <Arrow class="arrow arrow-light " /> </router-link> </div> </div> </div> </template> <script> import Arrow from "../../assets/Icons/arrow-right-light.svg"; import moment from "moment"; export default { name: "BlogCardlog", props: ["post"], components: { Arrow, }, data() { return { image: "", }; }, mounted() { this.getImage(); }, methods: { getImage() { this.image = this.post.image_url; }, callDate(date, dateType) { const date1 = new Date(date); if (dateType === "fullDate") { return moment(date1).format("ddd, MMMM Do YYYY"); } else { return moment(date1).format("HH:mm"); } }, }, }; </script> <style lang="scss" scoped> .blog-card { width: 400px; border: none; border-radius: 7px; overflow: hidden; @media (max-width: 934px) { width: 100%; margin: 0px auto; } @media (max-width: 470px) { width: 100%; margin: 0 auto; } .header { font-size: 20px; font-weight: 600; color: #fff; } span { font-size: 14px; color: rgb(174, 174, 174); } img { height: 180px; width: 100%; object-fit: cover; } .card-body { background: rgb(255, 102, 0); } .card-text { height: 60px; overflow-y: scroll; color: #fff; font-size: 18px; } .post-btn { align-self: flex-start; display: inline-block; background: #000; color: #fff; padding: 7px 15px; border-radius: 1px; cursor: pointer; text-decoration: none; text-transform: uppercase; font-size: 15px; font-weight: 600; font-family: inherit; transition: 0.3s all ease; &:focus { outline: none; } &:active { transform: scale(0.98); } &:hover { color: white; background: rgb(255, 102, 0); border: 2px solid white; } } } </style>
import { Dispatch, SetStateAction } from "react" import { Border, Cursor, GradientType, paddingSizeButton, sizeVariant, typeOfButton, variant } from "../constants/constant" export interface CardsProps { className?: string, nameCard: string, buttons?: ButtonProps[], inputBox?: JSX.Element, typograph?: JSX.Element, cardFooter?: JSX.Element, variant: variant | undefined, selectOptions?: JSX.Element } export interface ButtonHeaderProps { buttonName: string, url: string } export interface ButtonProps { label: string, onClick: () => void, className?: string } export interface DropdownCustomName { dropdownName: string } export interface InputCustomProps { className?: string, label?: string, type: string, inputClassName?: string, dropdown?: JSX.Element, unitCurrencyConverter?: string, walletBalance?: string, placeHolder?: string } export interface TabsCustom { data: TabProps[] } export interface TabProps { label: string, value: string, content: JSX.Element, target?: string } export interface SelectProps { className?: string } export interface BoardProps { gradientType?: GradientType, nameBoard: string, content?: JSX.Element, width?: string } export interface StatusStProps { name: string, value?: string, unit?: string, icon?: JSX.Element, classNameCustom?: string } export interface ButtonBuilderProps { btnName: string | null, classNameCustom?: string, sizeVariant: sizeVariant, paddingSize: paddingSizeButton, btnType: typeOfButton, icon?: JSX.Element, cursor?: Cursor, onClick?: () => void | Promise<void>, border?: Border, } export declare interface SizeButton { small: string, medium: string, large: string } function updateButtonPaddingAndRounded(btnType: typeOfButton): any { if (btnType === "circle") { return { sizeButtonPaddingLarge: { small: 'px-16px py-8px font-medium rounded-custom-xxl text-fs-sm', // Small variant classes medium: 'px-16px py-8px font-medium rounded-custom-xxl text-fs-md', // Medium variant classes large: 'px-16px py-8px font-medium rounded-custom-xxl text-fs-lg', // Large variant classes }, sizeButtonPaddingMedium: { small: 'px-12px py-6px font-semibold rounded-custom-xxl text-fs-sm', // Small variant classes medium: 'px-12px py-6px font-semibold rounded-custom-xxl text-fs-md', // Medium variant classes large: 'px-12px py-6px font-semibold rounded-custom-xxl text-fs-lg', // Large variant classes }, sizeButtonPaddingSmall: { small: 'px-8px py-4px font-bold rounded-custom-xxl text-fs-sm', // Small variant classes medium: 'px-8px py-4px font-bold rounded-custom-xxl text-fs-md', // Medium variant classes large: 'px-8px py-4px font-bold rounded-custom-xxl text-fs-lg', // Large variant classes } }; } else if (btnType === "circle-square") { return { sizeButtonPaddingSmall: { small: 'p-6px font-medium rounded-custom-ssm text-fs-sm', medium: 'p-6px font-medium rounded-custom-ssm text-fs-md', large: 'p-6px font-medium rounded-custom-ssm text-fs-lg', }, sizeButtonPaddingMedium: { small: 'p-12px font-semibold rounded-custom-ssm text-fs-sm', medium: 'p-12px font-semibold rounded-custom-ssm text-fs-md', large: 'p-12px font-semibold rounded-custom-ssm text-fs-lg', }, sizeButtonPaddingLarge: { small: 'p-18px font-bold rounded-custom-ssm text-fs-sm', medium: 'p-18px font-bold rounded-custom-ssm text-fs-md', large: 'p-18px font-bold rounded-custom-ssm text-fs-lg', } }; } } export interface StatePublicKey { publickey: string, disconnect: () => void, } export { updateButtonPaddingAndRounded };
import { ReactNode } from "react" import { IconContext } from "react-icons/lib" import { useTheme } from "styled-components" import { StyledButton, StyledOutlineButton, RightSpace } from "./style" interface TextIconButtonProps { icon: ReactNode iconSize?: string iconColor?: 'primary' | string text: string } const Content = ({ icon, iconSize = '12px', iconColor, text }: TextIconButtonProps) => { const theme = useTheme() return <> <IconContext.Provider value={{ color: iconColor === 'primary' ? theme.primaryColor : iconColor, size: iconSize }}> {icon} </IconContext.Provider> {text} <RightSpace iconSize={iconSize} /> </> } export const TextIconButton = (props: TextIconButtonProps) => { return <StyledButton> <Content {...props} /> </StyledButton> } export const OutlineTextIconButton = (props: TextIconButtonProps) => { return <StyledOutlineButton> <Content {...props} /> </StyledOutlineButton> }
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> void printMenu(); //void function (with no parameters) prototype bool checkChoice(char iChoice); //non-void function with a parameter and formal argument iChoice int readInteger(); //non-void function with no parameters double tackyAdd(int iNum1, int iNum2); double tackySubtract(int iNum1, int iNum2); double tackyMultiply(int iNum1, int iNum2); double tackyDivide(int iNum1, int iNum2); double tackyMod(int iNum1, int iNum2); void printResult(double iResult); //void function with a parameter double bigBoy(char iChoice, int iNum1, int iNum2); void printMenu(){ //function definition printf("Press + to perform ADDITION\n"); printf("Press - to perform SUBTRACTION\n"); printf("Press * to perform MULTIPLICATION\n"); printf("Press / to perform DIVISION\n"); printf("Press %% to perform MODULO\n"); printf("Press any other character to QUIT\n"); //function body return; //function return statement that returns nothing } bool checkChoice(char iChoice){ return iChoice != '+' && iChoice != '-' && iChoice != '*' && iChoice != '/' && iChoice != '%'; } int readInteger(){ int num; printf("> "); scanf("%d", &num); return num; } double tackyAdd(int iNum1, int iNum2){ return iNum1 + iNum2; } double tackySubtract(int iNum1, int iNum2){ return iNum1 - iNum2; } double tackyMultiply(int iNum1, int iNum2){ return iNum1 * iNum2; } double tackyDivide(int iNum1, int iNum2){ return (double)iNum1 / iNum2; } double tackyMod(int iNum1, int iNum2){ return iNum1 % iNum2; } void printResult(double iResult){ printf("The result is %f\n", iResult); return; } double bigBoy(char iChoice, int iNum1, int iNum2){ if (iChoice == '+') { // Addition return tackyAdd(iNum1, iNum2); } else if (iChoice == '-') { // Subtraction return tackySubtract(iNum1, iNum2); } else if (iChoice == '*') { // Multiplication return tackyMultiply(iNum1, iNum2); } else if (iChoice == '/') { // Division // Check that we aren't dividing by zero if (iNum2 == 0) { printf("Since the denominator is zero, the operation is not possible and it will lead to DIVIDE BY ZERO ERROR\n"); // If the first number is *not* zero, then flip the operands if (iNum1 != 0) { return tackyDivide(iNum2, iNum1); } // Otherwise, we can't do anything useful with these numbers else { printf("Since both operands are zero, the operation is not possible and it will lead to DIVIDE BY ZERO ERROR\n"); exit(0); } } else { return tackyDivide(iNum1, iNum2); } } else if (iChoice == '%') { // Modulo // Check that we aren't dividing by zero if (iNum2 == 0) { printf("Since the denominator is zero, the operation is not possible and it will lead to DIVIDE BY ZERO ERROR\n"); // If the first number is *not* zero, then flip the operands if (iNum1 != 0) { return tackyMod(iNum2, iNum1); } // Otherwise, we can't do anything useful with these numbers else { printf("Since both operands are zero, the operation is not possible and it will lead to DIVIDE BY ZERO ERROR\n"); exit(0); } } else { return tackyMod(iNum1, iNum2); } } return 0; } int main(void){ int iNum1, iNum2; double iResult; char iChoice; // Print the menu printMenu(); //function call // Ask the user for their choice printf("> "); scanf("%c", &iChoice); // If the user wants to quit, we can do that right now and not // bother asking for numbers. If the user did not type in + - * / or %, // then they want to quit the program. if(checkChoice(iChoice)) { //actual argument iChoice // End the program early exit(0); } // Ask the user for the numbers printf("Please type in two integers.\n"); iNum1 = readInteger(); iNum2 = readInteger(); iResult = bigBoy(iChoice, iNum1, iNum2); // Print the result printResult(iResult); }
scalar Date schema { query: Query mutation: Mutation subscription: Subscription } type Product { id: ID! name: String! shortDescription: String } type Variant { id: ID! name: String! shortDescription: String } type Question { id: ID! textA: String! textB: String! textC: String! } type Query { # ### GET products # # _Arguments_ # - **id**: Product's id (optional) products(id: Int): [Product] # ### GET variants # # _Arguments_ # - **id**: Variant's id (optional) variants(id: Int): [Variant] } input AvatarOptions { format: String filter: String }
package lv.lu.df.combopt.domain; import ai.timefold.solver.core.api.domain.entity.PlanningEntity; import ai.timefold.solver.core.api.domain.variable.PlanningListVariable; import ai.timefold.solver.core.api.domain.variable.PlanningVariable; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIdentityReference; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.util.ArrayList; import java.util.List; @PlanningEntity @Getter @Setter @NoArgsConstructor @JsonIdentityInfo(scope = Vehicle.class, property = "regNr", generator = ObjectIdGenerators.PropertyGenerator.class) public class Vehicle { private String regNr; private Integer capacity; @PlanningListVariable private List<Visit> visits = new ArrayList<>(); private Location depot; private Integer twStart; private Integer twFinish; private Integer srvSTime; private Integer srvFTime; private Integer maxWorkTime; private Double costWorkTime; private Double costDistance; private Double costUsage; @JsonIgnore public Double getTotalDistance() { Double totalDistance = 0.0; Location prevLoc = this.getDepot(); for (Visit visit: this.getVisits()) { totalDistance = totalDistance + prevLoc.distanceTo(visit.getLocation()); prevLoc = visit.getLocation(); } totalDistance = totalDistance + prevLoc.distanceTo(this.getDepot()); return totalDistance; } @JsonIgnore public Boolean isGoodsConstraintBroken() { Integer undelivered = 0, picked = 0; for (Visit visit : this.getVisits()) { switch (visit.getVisitType()) { case DELIVERY -> { undelivered = undelivered - visit.getVolume(); } case PICKUP -> { picked = picked + visit.getVolume(); } case STOCK -> { undelivered = this.getCapacity(); picked = 0; } default -> throw new IllegalStateException("Unexpected value: " + visit.getVisitType()); } if (undelivered + picked > this.getCapacity() || undelivered < 0) return true; } return (picked > 0); } @Override public String toString() { return this.getRegNr(); } }
# Best Practices in ETL Het implementeren van best practices in ETL-processen is essentieel voor efficiëntie, schaalbaarheid en gegevenskwaliteit. Hier zijn enkele belangrijke richtlijnen: ## Efficiëntiepraktijken: Verbetering van de efficiëntie van ETL - **Optimaliseer gegevensverwerking:** Minimaliseer resource-intensieve operaties. - **Parallelle verwerking:** Gebruik parallelisme om gegevensverwerking te versnellen. - **Incrementeel laden:** Laad alleen nieuwe of gewijzigde gegevens waar mogelijk om tijd en middelen te besparen. ## Gegevenskwaliteit: Zorgen voor hoge gegevenskwaliteit - **Gegevensprofiel:** Analyseer regelmatig de gegevens op kwaliteit en consistentie. - **Gegevensreiniging:** Implementeer routines om gegevens schoon te maken en te standaardiseren. - **Validatiecontroles:** Stel validatieregels in om gegevensintegriteit te waarborgen. ## Schaalbaarheid en prestaties: Tips voor schaalvergroting - **Resourcebeheer:** Wijs middelen efficiënt toe op basis van belasting en gegevensvolume. - **Modulaire opzet:** Bouw ETL-processen die gemakkelijk kunnen worden opgeschaald of aangepast. - **Cloudgebaseerde oplossingen:** Maak gebruik van cloudservices voor flexibele schaalopties. ## Monitoring en foutafhandeling: Traceren en beheren van fouten - **Logging:** Implementeer uitgebreide logging om ETL-processen te volgen. - **Meldingen en notificaties:** Stel meldingen in voor eventuele afwijkingen of fouten in de ETL-pijplijn. - **Foutenherstelmechanismen:** Ontwikkel strategieën om om te gaan met en te herstellen van fouten.
(function (window) { var createModule = function (angular) { var module = angular.module('FBAngular', []); module.factory('Fullscreen', ['$document', function ($document) { var document = $document[0]; var serviceInstance = { all: function () { serviceInstance.enable(document.documentElement); }, enable: function (element) { if (element.requestFullScreen) { element.requestFullScreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullScreen) { element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } }, cancel: function () { if (document.cancelFullScreen) { document.cancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } }, isEnabled: function () { var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement; return fullscreenElement; }, toggleAll: function () { serviceInstance.isEnabled() ? serviceInstance.cancel() : serviceInstance.all(); }, isSupported: function () { var docElm = document.documentElement; return docElm.requestFullScreen || docElm.mozRequestFullScreen || docElm.webkitRequestFullScreen || docElm.msRequestFullscreen; } }; return serviceInstance; }]); module.directive('fullscreen', ['Fullscreen', function (Fullscreen) { return { link: function ($scope, $element, $attrs) { // Watch for changes on scope if model is provided if ($attrs.fullscreen) { $scope.$watch($attrs.fullscreen, function (value) { var isEnabled = Fullscreen.isEnabled(); if (value && !isEnabled) { Fullscreen.enable($element[0]); $element.addClass('isInFullScreen'); } else if (!value && isEnabled) { Fullscreen.cancel(); $element.removeClass('isInFullScreen'); } }); $element.on('fullscreenchange webkitfullscreenchange mozfullscreenchange', function () { if (!Fullscreen.isEnabled()) { $scope.$evalAsync(function () { $scope[$attrs.fullscreen] = false $element.removeClass('isInFullScreen'); }) } }) } else { $element.on('click', function (ev) { Fullscreen.enable($element[0]); }); if ($attrs.onlyWatchedProperty !== undefined) { return; } } } }; }]); return module; }; if (typeof define === "function" && define.amd) { define("FBAngular", ['angular'], function (angular) { return createModule(angular); }); } else { createModule(window.angular); } })(window);
import WeekDayButtons from "../WeekDayButtons/WeekDayButtons" import { Form, ButtonsContainer, Footer, CloseButton, SaveButton } from "./styled" import StyledInput from "../StyledInput" import { useContext, useState } from "react" import apiHabits from "../../services/apiHabits" import { UserContext } from "../../contexts/UserContext" import { ThreeDots } from "react-loader-spinner" export default function CriarHabito({ isOpened, setIsOpened, getHabitsList }) { const [form, setForm] = useState({ name: "" }) const [days, setDays] = useState([]) const [isLoading, setIsLoading] = useState(false) const { user } = useContext(UserContext) function handleForm(e) { setForm({ ...form, [e.target.name]: e.target.value }) } function handleCreate(e) { e.preventDefault() setIsLoading(true) const body = { ...form, days } apiHabits.createHabit(user.token, body) .then(res => { setIsLoading(false) setForm({ name: "" }) setDays([]) setIsOpened(false) getHabitsList() }) .catch(err => { setIsLoading(false) alert(err.response.data.message) }) } return ( <Form isOpened={isOpened} onSubmit={handleCreate}> <ButtonsContainer> <StyledInput name="name" placeholder="nome do hábito" type="text" required disabled={isLoading} value={form.name} onChange={handleForm} /> <WeekDayButtons selectedDays={days} setSelectedDays={setDays} isLoading={isLoading} /> </ButtonsContainer> <Footer> <CloseButton type="button" disabled={isLoading} onClick={() => setIsOpened(false)} > Cancelar </CloseButton> <SaveButton type="submit" disabled={isLoading} > {isLoading ? ( <ThreeDots width={50} height={50} color="#FFFFFF" /> ) : "Salvar"} </SaveButton> </Footer> </Form> ) }
/* Write a program to calculate the total salary of a person. The user has to enter the basic salary (an integer) and the grade (an uppercase character), and depending upon which the total salary is calculated as - totalSalary = basic + hra + da + allow – pf where : hra = 20% of basic da = 50% of basic allow = 1700 if grade = ‘A’ allow = 1500 if grade = ‘B’ allow = 1300 if grade = ‘C' or any other character pf = 11% of basic. Round off the total salary and then print the integral part only. Note for C++ users : To round off the value , please include<cmath> library in the start of the program. And round off the values in this way int ans = round(yourFinalValue); Input format : Basic salary & Grade (separated by space) Output Format : Total Salary Constraints 0<=salary<=10000 Sample Input 1 : 10000 A Sample Output 1 : 17600 Sample Input 2 : 4567 B Sample Output 2 : 8762 Explanation of Input 2: We have been given the basic salary as Rs. 4567. We need to calculate the hra, da and pf. Now when we calculate each of the, it turns out to be: hra = 20% of Rs. 4567 = Rs. 913.4 da = 50% od Rs. 4567 = Rs. 2283.5 pf = 11% of Rs. 4567 = Rs. 502.37 Since, the grade is 'B', we take allowance as Rs. 1500. On substituting these values to the formula of totalSalary, we get Rs. 8761.53 and now rounding it off will result in Rs. 8762 and hence the Answer. */ #include <iostream> #include <cmath> int main() { int basic; char grade; std::cin >> basic >> grade; double hra = 0.2 * basic; double da = 0.5 * basic; double allow; if (grade == 'A') { allow = 1700; } else if (grade == 'B') { allow = 1500; } else { allow = 1300; } double pf = 0.11 * basic; double totalSalary = basic + hra + da + allow - pf; int roundedSalary = round(totalSalary); std::cout << roundedSalary << std::endl; return 0; }
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.appbar.AppBarLayout android:id="@+id/app_bar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <com.google.android.material.appbar.CollapsingToolbarLayout android:id="@+id/toolbar_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/white" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <ImageView android:id="@+id/iv_movie_cover" android:layout_width="match_parent" android:layout_height="350dp" android:contentDescription="@string/app_name" android:scaleType="centerCrop" app:layout_collapseMode="parallax" /> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:title="@string/app_name" app:titleTextColor="@android:color/black" /> </com.google.android.material.appbar.CollapsingToolbarLayout> </com.google.android.material.appbar.AppBarLayout> <androidx.core.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:clipToPadding="false" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" app:cardElevation="5dp" app:cardUseCompatPadding="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:id="@+id/iv_poster" android:background="@color/purple_700" android:layout_width="110dp" android:layout_height="140dp" android:contentDescription="@string/app_name" /> <TextView android:id="@+id/tv_original_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:padding="5dp" android:layout_toEndOf="@id/iv_poster" android:textColor="@android:color/black" android:textSize="25sp" android:textStyle="bold" tools:text="@string/app_name" /> <TextView android:id="@+id/tv_title" tools:text="@string/app_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toEndOf="@id/iv_poster" android:textSize="20sp" android:padding="5dp" android:layout_below="@id/tv_original_title"/> </RelativeLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="10dp" android:paddingStart="10dp" tools:ignore="RtlSymmetry,UseCompoundDrawables"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/app_name" android:src="@drawable/ic_release_date" /> <TextView android:id="@+id/tv_release_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingStart="15dp" tools:text="@string/app_name" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingStart="10dp" tools:ignore="RtlSymmetry,UseCompoundDrawables"> <ImageView android:layout_width="wrap_content" android:layout_height="match_parent" android:contentDescription="@string/app_name" android:src="@drawable/ic_rating" /> <TextView android:id="@+id/tv_movie_rating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingStart="15dp" tools:ignore="RtlSymmetry" tools:text="@string/app_name" /> </LinearLayout> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingTop="10dp" android:paddingBottom="5dp" android:text="@string/overview" android:textColor="@android:color/black" android:textSize="22sp" android:textStyle="bold" /> <TextView android:id="@+id/tv_movie_description" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingBottom="5dp" android:textSize="16sp" tools:text="@string/app_name" /> <Button android:id="@+id/btn_demo" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/watch_demo"/> </LinearLayout> </androidx.cardview.widget.CardView> </androidx.core.widget.NestedScrollView> <com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:baselineAlignBottom="false" android:clickable="true" android:src="@drawable/ic_fav_border" app:fabSize="normal" app:layout_anchor="@id/toolbar_layout" app:layout_anchorGravity="end|bottom" android:layout_marginEnd="30dp" android:focusable="true" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
use nom::{ number::complete::{be_u16, be_u32, be_u8}, IResult, }; use super::PageType; #[derive(Debug)] pub struct PageHeader { pub page_type: PageType, pub first_free_block: u16, pub cell_count: usize, pub cell_start_index: usize, pub fragmented_free_bytes_count: u8, pub right_most_pointer: Option<u32>, } impl PageHeader { pub fn parse(input: &[u8]) -> IResult<&[u8], Self> { let (input, page_type) = PageType::parse(input)?; let (input, first_free_block) = be_u16(input)?; let (input, cell_count) = be_u16(input)?; let (input, cell_start_index) = be_u16(input)?; let (input, fragmented_free_bytes_count) = be_u8(input)?; let (input, right_most_pointer) = if matches!(page_type, PageType::InteriorIndex | PageType::InteriorTable) { let (i, r) = be_u32(input)?; (i, Some(r)) } else { (input, None) }; Ok(( input, Self { page_type, first_free_block, cell_count: cell_count as usize, cell_start_index: cell_start_index as usize, fragmented_free_bytes_count, right_most_pointer, }, )) } }
export class ClaimDocument { private documentName: string; private documentUrl: string; private documentType: string; constructor(obj: any) { this.documentName = obj.documentName; this.documentUrl = obj.documentUrl; this.documentType = obj.documentType; } /** * Getter $documentName * @return {string} */ public get $documentName(): string { return this.documentName; } /** * Getter $documentUrl * @return {string} */ public get $documentUrl(): string { return this.documentUrl; } /** * Getter $documentType * @return {string} */ public get $documentType(): string { return this.documentType; } /** * Setter $documentName * @param {string} value */ public set $documentName(value: string) { this.documentName = value; } /** * Setter $documentUrl * @param {string} value */ public set $documentUrl(value: string) { this.documentUrl = value; } /** * Setter $documentType * @param {string} value */ public set $documentType(value: string) { this.documentType = value; } }
package com.indivisible.clearmeout.service; // //import java.io.File; //import java.io.FilenameFilter; //import android.app.Service; //import android.content.Intent; //import android.content.SharedPreferences; //import android.content.SharedPreferences.Editor; //import android.os.IBinder; //import android.preference.PreferenceManager; //import android.util.Log; //import android.widget.Toast; //import com.indivisible.clearmeout.R; // //public class DeleteService // extends Service //{ // // //// data // // private String folder; // private File root; // private boolean recursiveDelete; // private boolean deleteFolders; // private boolean notifyOnDelete; // // private static final String TAG = "CMO:DeleteService"; // // // //// perform on intent calls for this service // // @Override // public void onCreate() // { // super.onCreate(); // Log.d(TAG, "DeleteService started..."); // // // get needed settings and test folder pref saved // SharedPreferences prefs = PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()); // folder = prefs.getString(getString(R.string.pref_delete_targetFolder_key), "---"); // // if (folder.equals("---")) // { // Log.w(TAG, // "Default folder value found. Shutting down (and disabling service)"); // disableService(); // } // else // { // Log.d(TAG, "ClearMeOut emptying folder: " + folder); // recursiveDelete = prefs // .getBoolean(getString(R.string.pref_delete_doRecursiveDelete_key), // false); // deleteFolders = prefs // .getBoolean(getString(R.string.pref_delete_doDeleteFolders_key), // false); // notifyOnDelete = prefs // .getBoolean(getString(R.string.pref_service_notifyOnDelete_key), // false); // // performDelete(); // stopSelf(); // } // } // // // /** // * Parent method to delete files and/or folders from a directory based on // * the shared preference "recursive_delete" // */ // private void performDelete() // { // root = new File(folder); // // if (root.exists()) // { // if (root.canWrite()) // { // Log.d(TAG, "Can write to: " + root.getAbsolutePath()); // } // else // { // Log.e(TAG, "Cannot perform delete: " + root.getAbsolutePath()); // if (notifyOnDelete) // { // Toast.makeText(this, // "ClearMeOut failed to clear:\n" // + folder // + "\nDid not have required access.\nDoes the directory exist?", // Toast.LENGTH_LONG).show(); // } // stopSelf(); // } // } // else // { // Log.w(TAG, "Folder not exists: " + folder); // disableService(); // stopSelf(); // } // // // // apply delete to sub-folders also? // if (recursiveDelete) // { // Log.d(TAG, "Performing recursive delete on " + root.getAbsolutePath()); // performRecursiveDelete(root); // } // else // { // Log.d(TAG, "Performing non-recursive delete on " + root.getAbsolutePath()); // performNonRecursiveDelete(); // } // // Log.d(TAG, "Finished delete"); // // if (notifyOnDelete) // { // Toast.makeText(this, "ClearMeOut emptied:\n" + folder, Toast.LENGTH_LONG) // .show(); //TODO strings.xml // } // } // // // /** // * Delete all files AND folders from a directory // * // * @param file // */ // private void performRecursiveDelete(File file) // { // if (file.isFile()) // { // Log.d(TAG, "Del (F): " + file.getAbsolutePath()); // file.delete(); // } // else // { // String[] filesAndFolders = file.list(); // // for (String fname : filesAndFolders) // { // performRecursiveDelete(new File(file, fname)); // } // // if (file.isDirectory() && deleteFolders) // { // if (file != root) // { // Log.d(TAG, "Del (D): " + file.getAbsolutePath()); // file.delete(); // } // else // { // Log.d(TAG, "Did not delete root dir: " + file.getAbsolutePath()); // } // } // else // { // Log.d(TAG, "Skipping delete of folder: " + file.getAbsolutePath()); // } // } // } // // // /** // * Delete ONLY the files from a folder leaving all sub-folders untouched // */ // private void performNonRecursiveDelete() // { // FilenameFilter fileOnlyFilter = new FilenameFilter() // { // // @Override // public boolean accept(File dir, String filename) // { // if ((new File(dir, filename).isFile())) // return true; // else // return false; // } // }; // // String[] files = root.list(fileOnlyFilter); // File delFile; // if (files != null) // { // for (String file : files) // { // delFile = new File(root, file); // Log.d(TAG, "Del: " + delFile.getAbsolutePath()); // delFile.delete(); // } // } // } // // /** // * Set service to inactive if we hit an error // */ // private void disableService() // { // Log.w(TAG, "Disabling service"); // // SharedPreferences prefs = PreferenceManager // .getDefaultSharedPreferences(getApplicationContext()); // if (prefs.getBoolean(getString(R.string.pref_service_notifyOnDelete_key), false)) //FIXME need separate bool pref for error disp // { // Toast.makeText(getApplicationContext(), // "Disabling ClearMeOut service due to an error. Is the target folder set and exist?", //TODO strings.xml // Toast.LENGTH_LONG).show(); // } // // Editor editPrefs = prefs.edit(); // editPrefs.putBoolean(getString(R.string.pref_service_isActive_key), false); // editPrefs.commit(); // // Intent updateIntent = new Intent(getApplicationContext(), // UpdateAlarmsService.class); // startService(updateIntent); // // stopSelf(); // } // // //// unused binder // // @Override // public IBinder onBind(Intent arg0) // { // return null; // } // // //}
//binary-tree-right-side-view import java.util.List; import java.util.Queue; import java.util.ArrayList; import java.util.LinkedList; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } class Solution { public List<Integer> rightSideView(TreeNode root) { if (root == null) return new ArrayList<Integer>(); Queue<TreeNode> queue = new LinkedList(){{ offer(root); offer(null); }}; TreeNode prev, curr = root; List<Integer> rightside = new ArrayList(); while (!queue.isEmpty()) { prev = curr; curr = queue.poll(); while (curr != null) { // add child nodes in the queue if (curr.left != null) { queue.offer(curr.left); } if (curr.right != null) { queue.offer(curr.right); } prev = curr; curr = queue.poll(); } // the current level is finished // and prev is its rightmost element rightside.add(prev.val); // add a sentinel to mark the end // of the next level if (!queue.isEmpty()) queue.offer(null); } return rightside; } }
import {rpc} from 'sock-harness'; import loglevel from 'loglevel-decorator'; import roles from '../middleware/rpc/roles.js'; import {on} from 'emitter-binder'; import PlayerDeck from 'models/PlayerDeck'; import DeckStoreError from 'errors/DeckStoreError'; /** * RPC handler for the matchmaker component */ @loglevel export default class LobbyRPC { constructor(matchmaker, cardManager) { this.matchmaker = matchmaker; this.cardManager = cardManager; this.clients = {}; } /** * Drop a player into the queue */ @rpc.command('queue') @rpc.middleware(roles(['player'])) async queuePlayer(client, params, auth) { const playerId = auth.sub.id; const {deckId} = params; await this.matchmaker.queuePlayer(playerId, deckId); } /** * And back out again */ @rpc.command('dequeue') @rpc.middleware(roles(['player'])) async dequeuePlayer(client, params, auth) { const playerId = auth.sub.id; await this.matchmaker.dequeuePlayer(playerId); } /** * When a client connects */ @rpc.command('_token') async hello(client, params, auth) { // connection from in the mesh if (!auth || !auth.sub) { return; } let playerId = client && client.auth ? client.auth.sub.id : null; if(!playerId){ this.log.warn('Connecting client missing auth creds'); return; } if(this.clients[playerId]){ this.disconnectClient(this.clients[playerId], 'reconnect') } this.clients[playerId] = client; // drop player when they DC client.once('close', () => this.disconnectClient(client, 'close')); client.once('error', () => this.disconnectClient(client, 'error')); client.once('disconnected', () => this.disconnectClient(client, 'disconnect')); } disconnectClient(client, reason){ let playerId = client && client.auth ? client.auth.sub.id : null; this.log.info('Closing connection for %s for player %s', reason, playerId); if(reason === 'reconnect'){ //boot any still connected clients out on reconnect client.send("socket:alreadysignedin", {}); client.disconnect(); } if(playerId){ this.matchmaker.dequeuePlayer(playerId); delete this.clients[playerId]; } } /** * If a player is connected, inform them of their current game * don't think this is needed anymore, */ @on('game:current') _broadcastCurrentGame({game, playerId}) { this.sendToPlayer(playerId, 'game:current', game); } /** * broadcast status */ @on('matchmaker:status') _status(status) { this.sendToPlayer(status.playerId, 'status', status); } /** * Get decks, duh */ @rpc.command('getDecks') @rpc.middleware(roles(['player'])) async getDecks(client, params, auth) { const playerId = auth.sub.id; let decks = await this.cardManager.getDecks(playerId); this.sendToPlayer(playerId, 'decks:current', decks); } @rpc.command('saveDeck') @rpc.middleware(roles(['player'])) async saveDeck(client, params, auth) { const playerId = auth.sub.id; let deck; try{ deck = PlayerDeck.fromData(params); deck = await this.cardManager.saveDeck(playerId, deck); }catch(e){ this.log.warn('Deck Save failed for player %s, reason: %s', playerId, e.message); let message = e.message; if (!(e instanceof DeckStoreError)) { message = 'Error saving deck, please try again later'; } this.sendToPlayer(playerId, 'decks:saveFailed', message); return; } this.log.info('Created/Saved deck %s for player %s', deck.id, playerId); this.sendToPlayer(playerId, 'decks:saveSuccess', deck); } @rpc.command('deleteDeck') @rpc.middleware(roles(['player'])) async deleteDeck(client, deckId, auth) { const playerId = auth.sub.id; try{ await this.cardManager.deleteDeck(playerId, deckId); }catch(e){ this.log.warn('Deck delete failed for player %s, reason: %s', playerId, e.message); let message = e.message; if (!(e instanceof DeckStoreError)) { message = 'Error deleting deck, please try again later'; } this.sendToPlayer(playerId, 'decks:saveFailed', message); return; } this.log.info('Deleted deck %s for player %s', deckId, playerId); } sendToPlayer(playerId, message, data){ // this.log.info('Lobby Clients %j', Object.keys(this.clients)); let client = this.clients[playerId]; if(client){ client.send(message, data); } } }
/** Сущность "Генератор случайных чисел" */ import Foundation protocol GeneratorProtocol { // хранит алгоритм, возвращаюший новое случайное значение func getRandomValue() -> Int } class NumberGenerator: GeneratorProtocol { private let startRangeValue: Int private let endRangeValue: Int init?(startValue: Int, endValue: Int) { guard startValue <= endValue else { return nil } startRangeValue = startValue endRangeValue = endValue } // загадать и вернуть новое случайное значение func getRandomValue() -> Int { (startRangeValue...endRangeValue).randomElement()! } }
<?php namespace backend\modules\sys\controllers; use Yii; use yii\data\Pagination; use yii\web\NotFoundHttpException; use common\enums\StatusEnum; use common\helpers\ArrayHelper; use common\models\sys\Config; use common\models\sys\ConfigCate; use common\helpers\ResultDataHelper; use common\components\CurdTrait; /** * 配置控制器 * * Class ConfigController * * @package backend\modules\sys\controllers * @author jianyan74 <751393839@qq.com> */ class ConfigController extends SController { use CurdTrait; /** * * @var * */ public $modelClass = 'common\models\sys\Config'; /** * 首页 * * @param string $cate_id * @return string */ public function actionIndex() { $keyword = Yii::$app->request->get('keyword', ''); $cate_id = Yii::$app->request->get('cate_id', null); // 查询所有子分类 $cateIds = []; if (! empty($cate_id)) { $cates = ConfigCate::getMultiDate([ 'status' => StatusEnum::ENABLED ], [ '*' ]); $cateIds = ArrayHelper::getChildIds($cates, $cate_id); array_push($cateIds, $cate_id); } $data = Config::find()->filterWhere([ 'in', 'cate_id', $cateIds ])->andFilterWhere([ 'or', [ 'like', 'title', $keyword ], [ 'like', 'name', $keyword ] ]); $pages = new Pagination([ 'totalCount' => $data->count(), 'pageSize' => $this->pageSize ]); $models = $data->offset($pages->offset) ->orderBy('cate_id asc, sort asc') ->with('cate') ->limit($pages->limit) ->all(); return $this->render($this->action->id, [ 'models' => $models, 'pages' => $pages, 'cate_id' => $cate_id, 'keyword' => $keyword, 'cateDropDownList' => ConfigCate::getDropDownList() ]); } /** * 编辑/创建 * * @return array|mixed|string|\yii\web\Response */ public function actionAjaxEdit() { $request = Yii::$app->request; $id = $request->get('id'); $model = $this->findModel($id); if ($model->load(Yii::$app->request->post())) { if ($request->isAjax) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return \yii\widgets\ActiveForm::validate($model); } return $model->save() ? $this->message('操作成功', $this->redirect(Yii::$app->request->referrer)) : $this->message($this->analyErr($model->getFirstErrors()), $this->redirect(Yii::$app->request->referrer), 'error'); } return $this->renderAjax($this->action->id, [ 'model' => $model, 'configTypeList' => Yii::$app->params['configTypeList'], 'cateDropDownList' => ConfigCate::getDropDownList() ]); } /** * 网站设置 * * @return string */ public function actionEditAll() { return $this->render($this->action->id, [ 'cates' => ConfigCate::getItemsMergeList() ]); } /** * ajax批量更新数据 * * @return array * @throws NotFoundHttpException * @throws \yii\base\InvalidConfigException */ public function actionUpdateInfo() { $request = Yii::$app->request; if ($request->isAjax) { // 记录行为日志 Yii::$app->services->sys->log('updateConfig', '修改配置信息'); $config = $request->post('config', []); foreach ($config as $key => $value) { if ($model = Config::find()->where([ 'name' => $key ])->one()) { $model->value = is_array($value) ? serialize($value) : $value; if (! $model->save()) { return $this->message($this->analyErr($model->getFirstErrors()), $this->redirect(['edit-all'])); } } else { return $this->message("配置不存在,请刷新页面", $this->redirect(['edit-all'])); } } Yii::$app->debris->clearConfigCache(); return $this->message("修改成功", $this->redirect(['edit-all'])); } throw new NotFoundHttpException('请求出错!'); } }
<div class="container-table"> <div class="title-button"> <h1>LISTADO CLIENTES</h1> <button class="btn" onclick="location.href='registrar-cliente';"> Registrar Clientes </button> </div> <div class="mb-3 row d-flex justify-content-center"> <div class="col-sm-auto search align-self-end"> <input id="table-complete-search" type="text" class="form-control" name="searchTerm" (keyup)="filtrar($event)" placeholder="Consultar Nombre del Cliente" /> </div> </div> <table class="table table-striped"> <thead> <tr> <th scope="col">NOMBRE</th> <th scope="col">TIPO DE CLIENTE</th> <th scope="col">NUMERO DE CONTRATO</th> <th scope="col">ARCHIVO</th> <th scope="col" class="width-1">ACCIONES</th> </tr> </thead> <tbody> <tr *ngFor="let cliente of clientes"> <td> {{ cliente.nombre }} </td> <td> {{ cliente.tipoContrato.nombre }} </td> <td> {{ cliente.numeroContrato }} </td> <td class="width-1"> <a> <button class="button-list" (click)="clickEvent(cliente.id, cliente.archivo)" > <img class="img-list" src="../../../../../assets/imgs/iconFile.png" alt="" /> </button> </a> </td> <td class="d-flex"> <button (click)="eliminar(cliente.id)" class="button-list" *ngIf="superAdmin" > <img class="img-list" src="../../../../../assets/imgs/papelera.png" alt="" /> </button> <button [routerLink]="['/editar-clientes', cliente.id]" class="button-list" > <img class="img-list" src="../../../../../assets/imgs/lapiz.png" alt="" /> </button> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5"> <div class="d-flex justify-content-end p-2"> <select class="form-select" style="width: auto" [(ngModel)]="pageSize" (ngModelChange)="refreshClients()" > <option [ngValue]="2">2 items for page</option> <option [ngValue]="4">4 items for page</option> <option [ngValue]="6">6 items for page</option> <option [ngValue]="8">8 items for page</option> <option [ngValue]="10">10 items for page</option> </select> <ngb-pagination class="pagination" [collectionSize]="collectionSize" [(page)]="page" [pageSize]="pageSize" (pageChange)="refreshClients()" > </ngb-pagination> </div> </td> </tr> </tfoot> </table> </div>
import { Component, OnInit } from '@angular/core'; import { GithubService } from '../services/github.service'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-projects', templateUrl: './projects.component.html', styleUrls: ['./projects.component.css'] }) export class ProjectsComponent implements OnInit { projects: any[] = []; reposToHide: string[] = ['alextina']; projectImages: { [key: string]: string } = {}; constructor( private githubSvc: GithubService, private http: HttpClient, ) { } ngOnInit() { this.http.get<any>('assets/data/db.json').subscribe((data) => { this.projectImages = data.projects.reduce((acc: any, project: any) => { acc[project.name] = project.image; return acc; }, {}); }); this.githubSvc.getRepositories().subscribe({ next: (data) => { this.projects = data; this.projects.sort((a, b) => { const dateA = new Date(a.created_at); const dateB = new Date(b.created_at); return dateB.getTime() - dateA.getTime(); }); this.projects = this.projects.filter(project => !this.reposToHide.includes(project.name)); }, error: (error) => { console.log(error); }, }); } openRepository(url: string) { window.open(url, '_blank'); } getProjectImageUrl(projectName: string): string { const imageUrl = this.projectImages[projectName]; if (imageUrl) { return imageUrl; } else { return `https://opengraph.githubassets.com/1/alextina/${projectName}`; } } }
import { Entity, Column, PrimaryGeneratedColumn, UpdateDateColumn, CreateDateColumn, ManyToMany, JoinTable, OneToMany, } from 'typeorm'; import { Roles } from '../roles/roles.entity'; import { Posts } from '../posts/posts.entity'; @Entity() export class Users { @PrimaryGeneratedColumn('uuid') id: string; @Column() email: string; @Column() password: string; @Column({ default: false }) banned: boolean; @Column({ default: '' }) banReason: string; @ManyToMany(() => Roles, (roles) => roles.user) @JoinTable({ name: 'users_roles', joinColumn: { name: 'usersId', referencedColumnName: 'id', }, inverseJoinColumn: { name: 'rolesId', referencedColumnName: 'id', }, }) roles: Roles[]; @OneToMany(() => Posts, (posts) => posts.user) posts: Posts[]; @Column({ default: '', length: 1000 }) jwtToken: string; @UpdateDateColumn() updatedDate: Date; @CreateDateColumn() createdDate: Date; }
package org.gnori.bunkerbot.service.command.impl.text.commands.state.impl; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import lombok.experimental.FieldDefaults; import org.gnori.bunkerbot.domain.BotUserState; import org.gnori.bunkerbot.service.BunkerGame; import org.gnori.bunkerbot.service.MessageEditor; import org.gnori.bunkerbot.service.MessageSender; import org.gnori.bunkerbot.service.command.constants.ResponseConst; import org.gnori.bunkerbot.service.command.impl.text.commands.state.StateCommand; import org.gnori.bunkerbot.service.command.impl.text.commands.state.StateCommandUtils; import org.gnori.bunkerbot.service.impl.domain.BotUserActiveChanger; import org.gnori.bunkerbot.service.impl.domain.BotUserStateChanger; import org.gnori.bunkerbot.service.impl.editor.EditKeyboardMarkupParams; import org.gnori.bunkerbot.service.impl.sender.SendTextParams; import org.gnori.bunkerbot.service.keyboard.generator.KeyboardGeneratorContainer; import org.springframework.stereotype.Component; import org.telegram.telegrambots.meta.api.objects.Update; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import java.util.List; @Component @RequiredArgsConstructor @FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true) public class NextStepGameStateCommand implements StateCommand { BunkerGame bunkerGame; MessageSender messageSender; BotUserStateChanger botUserStateChanger; BotUserActiveChanger botUserActiveChanger; KeyboardGeneratorContainer keyboardGeneratorContainer; @Override public void execute(Update update) { final long chatId = update.getMessage().getChatId(); final String userIdRaw = update.getMessage().getText(); StateCommandUtils.extractId(userIdRaw).ifPresentOrElse( userId -> { deactivateUserAndChangeState(userId, chatId); bunkerGame.deleteUser(userId); bunkerGame.nextStep(); }, () -> sendInvalidId(chatId) ); } @Override public BotUserState getSupportedKey() { return BotUserState.WAITING_DELETE_ID; } private void sendInvalidId(long chatId) { final SendTextParams sendTextParams = SendTextParams.builder() .chatId(chatId) .text(ResponseConst.INVALID_ID_INPUT) .replyKeyboard(keyboardGeneratorContainer.generateForState(BotUserState.WAITING_DELETE_ID)) .build(); messageSender.sendMessage(sendTextParams); } private void deactivateUserAndChangeState(Long userId, long chatId) { botUserStateChanger.changeState(chatId, BotUserState.DEFAULT); boolean isChanged = botUserActiveChanger.changeActive(userId, false); final String text = isChanged ? ResponseConst.DEACTIVATE_USER_SUCCESS : String.format(ResponseConst.FIND_USER_FAILURE_PATTERN, userId); final SendTextParams sendParams = SendTextParams.builder() .chatId(chatId) .replyKeyboard(keyboardGeneratorContainer.generateForState(BotUserState.DEFAULT)) .text(text) .build(); messageSender.sendMessage(sendParams); } }
import os import logging import requests import json import subprocess from celery import Celery from jinja2 import Environment, FileSystemLoader from requests.auth import HTTPBasicAuth logging.basicConfig(level=logging.INFO) app = Celery('worker', broker=os.environ.get('CELERY_BROKER_URL')) app.conf.task_queues = { os.environ.get('QUEUE_NAME'): { 'exchange': os.environ.get('QUEUE_EXCHANGE'), 'routing_key': os.environ.get('QUEUE_ROUTING_KEY'), }, } #TODO: Improve error handling i want everything worng to fail task @app.task(bind=True, name=os.environ.get('QUEUE_CELERY_TASK_BUILD_CV')) def process_message_and_compile_latex(self, message): try: logging.info(f"Received message: {message}") message_id = message.get('id', '') template_content = message.get('template_content', '') data = message.get('json_content', {}) output_tex_filename = f'filled_template_{message_id}.tex' output_pdf_filename = f'filled_template_{message_id}.pdf' username = os.environ.get('SPRING_SINGLE_LOGIN') password = os.environ.get('SPRING_SINGLE_PASSWORD') url = f"http://springboot-server:8080/{os.environ.get('QUEUE_EXCHANGE')}/api/v1/cv-build-job/{message_id}/status" env = Environment( loader=FileSystemLoader('.'), block_start_string='\BLOCK{', block_end_string='}', variable_start_string='\VAR{', variable_end_string='}', comment_start_string='\#{', comment_end_string='}', line_statement_prefix='%%', line_comment_prefix='%#', trim_blocks=True, autoescape=False, ) logging.info(f"Template with filled content {data}") data_dict = json.loads(data) template = env.from_string(template_content) filled_content = template.render(data_dict) logging.info(f"Template with filled content {filled_content}") with open(output_tex_filename, 'w') as file: file.write(filled_content) logging.info(f"Template rendered and saved to {output_tex_filename}") compile_cmd = ['pdflatex', '-interaction=nonstopmode', output_tex_filename] subprocess.run(compile_cmd, check=True) logging.info(f"Compiled LaTeX document to PDF: {output_pdf_filename}") except Exception as e: logging.error(f"Error processing template: {e}") return report_task_failure(url, username, password) status_update = json.dumps({'status': 'COMPLETED'}) files = { 'statusUpdate': ('', status_update, 'application/json'), 'compiledCvFile': (output_pdf_filename, open(output_pdf_filename, 'rb'), 'application/pdf') } try: response = requests.patch(url, files=files, auth=HTTPBasicAuth(username, password)) logging.info(f"PATCH request to {url} returned: {response.status_code}") except Exception as e: logging.error(f"Error sending status update and file: {e}") finally: os.remove(output_tex_filename) os.remove(output_pdf_filename) def report_task_failure(url, username, password): status_update_failed = json.dumps({'status': 'FAILED'}) files_failed = { 'statusUpdate': ('', status_update_failed, 'application/json'), 'file': ('', '', 'application/octet-stream') } try: response = requests.patch(url, files=files_failed, auth=HTTPBasicAuth(username, password)) logging.info(f"PATCH request with failure status to {url} returned: {response.status_code}") except Exception as e: logging.error(f"Error sending failed status update: {e}") if __name__ == '__main__': app.worker_main(argv=[ 'worker', '--loglevel=INFO', '--concurrency=4', '-Q', os.environ.get('QUEUE_NAME', 'resumebuilder'), ])
// Copyright 2019 The Abseil Authors. // // 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 // // https://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 "absl/functional/function_ref.h" #include <functional> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/memory/memory.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { void RunFun(FunctionRef<void()> f) { f(); } TEST(FunctionRefTest, Lambda) { bool ran = false; RunFun([&] { ran = true; }); EXPECT_TRUE(ran); } int Function() { return 1337; } TEST(FunctionRefTest, Function1) { FunctionRef<int()> ref(&Function); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, Function2) { FunctionRef<int()> ref(Function); EXPECT_EQ(1337, ref()); } int NoExceptFunction() noexcept { return 1337; } // TODO(jdennett): Add a test for noexcept member functions. TEST(FunctionRefTest, NoExceptFunction) { FunctionRef<int()> ref(NoExceptFunction); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, ForwardsArgs) { auto l = [](std::unique_ptr<int> i) { return *i; }; FunctionRef<int(std::unique_ptr<int>)> ref(l); EXPECT_EQ(42, ref(absl::make_unique<int>(42))); } TEST(FunctionRef, ReturnMoveOnly) { auto l = [] { return absl::make_unique<int>(29); }; FunctionRef<std::unique_ptr<int>()> ref(l); EXPECT_EQ(29, *ref()); } TEST(FunctionRef, ManyArgs) { auto l = [](int a, int b, int c) { return a + b + c; }; FunctionRef<int(int, int, int)> ref(l); EXPECT_EQ(6, ref(1, 2, 3)); } TEST(FunctionRef, VoidResultFromNonVoidFunctor) { bool ran = false; auto l = [&]() -> int { ran = true; return 2; }; FunctionRef<void()> ref(l); ref(); EXPECT_TRUE(ran); } TEST(FunctionRef, CastFromDerived) { struct Base {}; struct Derived : public Base {}; Derived d; auto l1 = [&](Base* b) { EXPECT_EQ(&d, b); }; FunctionRef<void(Derived*)> ref1(l1); ref1(&d); auto l2 = [&]() -> Derived* { return &d; }; FunctionRef<Base*()> ref2(l2); EXPECT_EQ(&d, ref2()); } TEST(FunctionRef, VoidResultFromNonVoidFuncton) { FunctionRef<void()> ref(Function); ref(); } TEST(FunctionRef, MemberPtr) { struct S { int i; }; S s{1100111}; auto mem_ptr = &S::i; FunctionRef<int(const S& s)> ref(mem_ptr); EXPECT_EQ(1100111, ref(s)); } TEST(FunctionRef, MemberFun) { struct S { int i; int get_i() const { return i; } }; S s{22}; auto mem_fun_ptr = &S::get_i; FunctionRef<int(const S& s)> ref(mem_fun_ptr); EXPECT_EQ(22, ref(s)); } TEST(FunctionRef, MemberFunRefqualified) { struct S { int i; int get_i() && { return i; } }; auto mem_fun_ptr = &S::get_i; S s{22}; FunctionRef<int(S && s)> ref(mem_fun_ptr); EXPECT_EQ(22, ref(std::move(s))); } #if !defined(_WIN32) && defined(GTEST_HAS_DEATH_TEST) TEST(FunctionRef, MemberFunRefqualifiedNull) { struct S { int i; int get_i() && { return i; } }; auto mem_fun_ptr = &S::get_i; mem_fun_ptr = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<int(S && s)> ref(mem_fun_ptr); }, ""); } TEST(FunctionRef, NullMemberPtrAssertFails) { struct S { int i; }; using MemberPtr = int S::*; MemberPtr mem_ptr = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<int(const S& s)> ref(mem_ptr); }, ""); } #endif // GTEST_HAS_DEATH_TEST TEST(FunctionRef, CopiesAndMovesPerPassByValue) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](absl::test_internal::CopyableMovableInstance) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(instance); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 1); } TEST(FunctionRef, CopiesAndMovesPerPassByRef) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](const absl::test_internal::CopyableMovableInstance&) {}; FunctionRef<void(const absl::test_internal::CopyableMovableInstance&)> ref(l); ref(instance); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); } TEST(FunctionRef, CopiesAndMovesPerPassByValueCallByMove) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](absl::test_internal::CopyableMovableInstance) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(std::move(instance)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 2); } TEST(FunctionRef, CopiesAndMovesPerPassByValueToRef) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](const absl::test_internal::CopyableMovableInstance&) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(std::move(instance)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); } TEST(FunctionRef, PassByValueTypes) { using absl::functional_internal::Invoker; using absl::functional_internal::VoidPtr; using absl::test_internal::CopyableMovableInstance; struct Trivial { void* p[2]; }; struct LargeTrivial { void* p[3]; }; static_assert(std::is_same<Invoker<void, int>, void (*)(VoidPtr, int)>::value, "Scalar types should be passed by value"); static_assert( std::is_same<Invoker<void, Trivial>, void (*)(VoidPtr, Trivial)>::value, "Small trivial types should be passed by value"); static_assert(std::is_same<Invoker<void, LargeTrivial>, void (*)(VoidPtr, LargeTrivial &&)>::value, "Large trivial types should be passed by rvalue reference"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance>, void (*)(VoidPtr, CopyableMovableInstance &&)>::value, "Types with copy/move ctor should be passed by rvalue reference"); // References are passed as references. static_assert( std::is_same<Invoker<void, int&>, void (*)(VoidPtr, int&)>::value, "Reference types should be preserved"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance&>, void (*)(VoidPtr, CopyableMovableInstance&)>::value, "Reference types should be preserved"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance&&>, void (*)(VoidPtr, CopyableMovableInstance &&)>::value, "Reference types should be preserved"); // Make sure the address of an object received by reference is the same as the // addess of the object passed by the caller. { LargeTrivial obj; auto test = [&obj](LargeTrivial& input) { ASSERT_EQ(&input, &obj); }; absl::FunctionRef<void(LargeTrivial&)> ref(test); ref(obj); } { Trivial obj; auto test = [&obj](Trivial& input) { ASSERT_EQ(&input, &obj); }; absl::FunctionRef<void(Trivial&)> ref(test); ref(obj); } } } // namespace ABSL_NAMESPACE_END } // namespace absl
package co.syalar.sfdiexample.didemo.controllers; import co.syalar.sfdiexample.didemo.services.GreetingService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; /** * Created by jd.rodriguez */ @Controller public class SetterInjectedController { private GreetingService greetingService; public String sayHello() { return greetingService.sayGreeting(); } @Autowired public void setGreetingService(@Qualifier("setterGreetingService") GreetingService greetingService) { this.greetingService = greetingService; } }
import { useReactTable, getPaginationRowModel, getFilteredRowModel, getCoreRowModel, getExpandedRowModel, ColumnDef, SortingState, getSortedRowModel, PaginationState, } from '@tanstack/react-table' import React, { useMemo, useState, useCallback } from 'react' import { Table } from '.'; import { ITableGenericHeader } from '@/app/model/TableHeader'; interface ITableGenericProps { readonly headers: ITableGenericHeader[]; readonly data: any[]; } function TableGeneric({ headers, data }: ITableGenericProps) { const [sorting, setSorting] = useState<SortingState>([]) const sizeOptions = useMemo(() => [10, 20, 30, 40, 50], []) const columns = useMemo<ColumnDef<any>[]>( () => headers.map((header) => ({ accessorKey: header.accessorKey, header: header.header, cell: info => info.getValue(), footer: props => props.column.id, ...headers })), [headers]) const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({ pageIndex: 0, pageSize: 10, }) const pagination = React.useMemo( () => ({ pageIndex, pageSize, }), [pageIndex, pageSize] ) const [search, setSearch] = useState<string>("") const table = useReactTable({ data: data.slice(pageIndex * pageSize, (pageIndex + 1) * pageSize), columns, pageCount: data.length / pageSize, state: { sorting, pagination, globalFilter: search, }, getPaginationRowModel: getPaginationRowModel(), getFilteredRowModel: getFilteredRowModel(), getExpandedRowModel: getExpandedRowModel(), getSortedRowModel: getSortedRowModel(), getCoreRowModel: getCoreRowModel(), onPaginationChange: setPagination, onSortingChange: setSorting, manualPagination: true, onGlobalFilterChange: setSearch, debugTable: false, }) const resetSearch = useCallback(() => { setSearch("") }, []) const handlerChangeSearch = useCallback((e: React.ChangeEvent<HTMLInputElement>) => { e.preventDefault(); setSearch(e.target.value) }, []) return ( <div className="p-2 w-full"> <div className='flex justify-between my-2 items-end gap-2'> <Table.LimitSize table={table} sizeOptions={sizeOptions} /> <Table.Search resetSearch={resetSearch} search={search} handlerChangeSearch={handlerChangeSearch} /> </div> <div className="overflow-y-auto"> <table className='striped-table w-full border rounded-lg !important'> <Table.Header table={table} /> <Table.Body table={table} /> </table> </div> <Table.Footer table={table} /> </div> ) } export default TableGeneric
import { graphql } from "gatsby" import _get from "lodash/get" import React from "react" import PageWideWrapper from "../../components/PageWideWrapper" import PostAuthorAbout from "../../components/PostAuthorAbout" import PostBody from "../../components/PostBody" import PostLayout from "../../components/PostLayout" import PostRelatedPosts from "../../components/PostRelatedPosts" import PostShareLinks from "../../components/PostShareLinks" import SEO from "../../components/SEO" import "~/src/common/base.scss" import * as styles from "./index.module.scss" export const query = graphql` query ($cover: String, $seoImage: String, $slug: String!) { markdownRemark(frontmatter: { path: { eq: $slug } }) { fields { cover seoImage url } frontmatter { author { key name initials bio photo { childImageSharp { gatsbyImageData( width: 50 height: 50 transformOptions: { fit: COVER, cropFocus: ATTENTION } ) } } } categories { key label } date intro seoDescription title } html } coverFile: file(absolutePath: { eq: $cover }) { childImageSharp { gatsbyImageData( width: 980 transformOptions: { grayscale: true } layout: CONSTRAINED ) } } seoImageFile: file(absolutePath: { eq: $seoImage }) { childImageSharp { gatsbyImageData( width: 2160 height: 1080 placeholder: NONE layout: FIXED ) } } } ` function BlogPostTemplate({ title, author, categories, date, html, intro, seoDescription, seoImage, url, }) { return ( <PostLayout title={title} author={author} date={date} categories={categories} > <SEO description={seoDescription || intro} image={seoImage} title={title} url={url} /> <div className={styles.root}> <article className={styles.article}> <section> <PageWideWrapper> <div className={styles.outerWrapper}> <PostBody className={styles.innerWrapper} html={html} /> </div> </PageWideWrapper> </section> </article> <div className={styles.bio}> {author.bio && <PostAuthorAbout author={author} date={date} />} </div> <PageWideWrapper padded> <PostShareLinks className={styles.shareLinks} url={url} /> <PostRelatedPosts categories={categories} title={title} /> </PageWideWrapper> </div> </PostLayout> ) } function Template({ data, pageContext }) { const { seoImage, cover } = pageContext const { markdownRemark, coverFile, seoImageFile } = data const { fields, frontmatter, html } = markdownRemark const { url } = fields const { author, date, categories, title, intro, seoDescription } = frontmatter return ( <BlogPostTemplate {...{ author, date: new Date(date), categories, cover, coverFile, html, intro, seoDescription, seoImage: _get( seoImageFile, "childImageSharp.gatsbyImageData.images.fallback.src", seoImage ), title, url, }} /> ) } export default Template
--- title: เพิ่มสี่เหลี่ยมผืนผ้าลงในเอกสาร XPS ด้วย Aspose.Page สำหรับ .NET linktitle: เพิ่มสี่เหลี่ยมผืนผ้าลงในเอกสาร XPS second_title: Aspose.Page .NET API description: ปรับปรุงการสร้างเอกสารด้วย Aspose.Page สำหรับ .NET เรียนรู้วิธีเพิ่มสี่เหลี่ยมลงในเอกสาร XPS ในบทช่วยสอนทีละขั้นตอนนี้ type: docs weight: 13 url: /th/net/drawing-shapes/add-rectangle-to-xps-document/ --- ## การแนะนำ Aspose.Page สำหรับ .NET เป็นไลบรารีที่มีประสิทธิภาพซึ่งมีคุณสมบัติที่หลากหลายสำหรับการทำงานกับเอกสาร XPS (XML Paper Specification) ในแอปพลิเคชัน .NET ในบทช่วยสอนนี้ เราจะเน้นที่การเพิ่มสี่เหลี่ยมให้กับเอกสาร XPS โดยใช้ Aspose.Page สำหรับ .NET ปฏิบัติตามคำแนะนำทีละขั้นตอนนี้เพื่อปรับปรุงกระบวนการสร้างเอกสารของคุณ ## ข้อกำหนดเบื้องต้น ก่อนที่คุณจะเริ่มด้วยบทช่วยสอนนี้ ตรวจสอบให้แน่ใจว่าคุณมีข้อกำหนดเบื้องต้นต่อไปนี้: 1. Aspose.Page สำหรับ .NET Library: ตรวจสอบให้แน่ใจว่าคุณได้ติดตั้งไลบรารี Aspose.Page สำหรับ .NET ในสภาพแวดล้อมการพัฒนาของคุณ คุณสามารถดาวน์โหลดได้[ที่นี่](https://releases.aspose.com/page/net/). 2. ไดเร็กทอรีเอกสาร: ตั้งค่าไดเร็กทอรีที่คุณต้องการจัดเก็บเอกสาร XPS ของคุณ ## นำเข้าเนมสเปซ ในแอปพลิเคชัน .NET ของคุณ ให้รวมเนมสเปซที่จำเป็นเพื่อใช้ฟังก์ชัน Aspose.Page ```csharp using Aspose.Page.XPS; using Aspose.Page.XPS.XpsModel; using System.Drawing; ``` ## ขั้นตอนที่ 1: ตั้งค่าไดเร็กทอรีเอกสาร ```csharp // เอ็กซ์สตาร์ท:3 // เส้นทางไปยังไดเร็กทอรีเอกสาร string dataDir = "Your Document Directory"; // สิ้นสุด:3 ``` ## ขั้นตอนที่ 2: สร้างเอกสาร XPS ใหม่ ```csharp // เอ็กซ์สตาร์ท:4 // สร้างเอกสาร XPS ใหม่ XpsDocument doc = new XpsDocument(); // สิ้นสุด:4 ``` ## ขั้นตอนที่ 3: เพิ่มสี่เหลี่ยมผืนผ้า ```csharp // เอ็กซ์สตาร์ท:5 // สี่เหลี่ยมผืนผ้าขีดสีทึบ CMYK (สีน้ำเงิน) ที่ด้านซ้ายล่าง XpsPath path = doc.AddPath(doc.CreatePathGeometry("M 20,10 L 220,10 220,100 20,100 Z")); path.Stroke = doc.CreateSolidColorBrush( doc.CreateColor(dataDir + "uswebuncoated.icc", 1.0f, 1.000f, 0.000f, 0.000f, 0.000f)); path.StrokeThickness = 12f; // สิ้นสุด:5 ``` ## ขั้นตอนที่ 4: บันทึกเอกสาร ```csharp // เอ็กซ์สตาร์ท:6 // บันทึกเอกสาร XPS ที่เป็นผลลัพธ์ doc.Save(dataDir + "AddRectangleXPS_out.xps"); // สิ้นสุด:6 ``` ยินดีด้วย! คุณได้เพิ่มสี่เหลี่ยมลงในเอกสาร XPS เรียบร้อยแล้วโดยใช้ Aspose.Page สำหรับ .NET ## บทสรุป Aspose.Page สำหรับ .NET ช่วยให้งานการจัดการเอกสารง่ายขึ้น ช่วยให้นักพัฒนาสามารถสร้างและแก้ไขเอกสาร XPS ได้อย่างง่ายดาย คำแนะนำทีละขั้นตอนนี้สาธิตวิธีเพิ่มสี่เหลี่ยมผืนผ้าลงในเอกสาร XPS ของคุณ ซึ่งเป็นรากฐานที่มั่นคงสำหรับการสำรวจเพิ่มเติม ## คำถามที่พบบ่อย ### คำถามที่ 1: Aspose.Page เข้ากันได้กับแอปพลิเคชัน .NET ทั้งหมดหรือไม่ ตอบ 1: ใช่ Aspose.Page ได้รับการออกแบบมาให้ทำงานได้อย่างราบรื่นกับแอปพลิเคชัน .NET ทั้งหมด ### คำถามที่ 2: ฉันจะหาเอกสารสำหรับ Aspose.Page สำหรับ .NET ได้ที่ไหน A2: มีเอกสารประกอบให้[ที่นี่](https://reference.aspose.com/page/net/). ### คำถามที่ 3: ฉันสามารถลองใช้ Aspose.Page สำหรับ .NET ฟรีก่อนซื้อได้หรือไม่ A3: ใช่ คุณสามารถทดลองใช้ฟรีได้[ที่นี่](https://releases.aspose.com/). ### คำถามที่ 4: ฉันจะขอรับใบอนุญาตชั่วคราวสำหรับ Aspose.Page สำหรับ .NET ได้อย่างไร A4: เยี่ยมเลย[ลิงค์นี้](https://purchase.aspose.com/temporary-license/) เพื่อขอรับใบอนุญาตชั่วคราว ### คำถามที่ 5: ฉันจะขอการสนับสนุนจากชุมชนหรือถามคำถามที่เกี่ยวข้องกับ Aspose.Page สำหรับ .NET ได้ที่ไหน A5: เยี่ยมชม[ฟอรั่ม Aspose.Page](https://forum.aspose.com/c/page/39) เพื่อสนับสนุนชุมชน
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Plot init and final Temperature salinity diagrams %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% You can change number of the bins by a_bins %% %% ex.: %% %% >> a_bins=50.; %% %% >> a_diag_ts; %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% N. Grima 2007 %% %%%%%%%%%%%%%%%%%%% addpath(genpath(fullfile(pwd,'bg_routines'))); if ~exist('init_temp' ) || ... ~exist('init_salt' ) || ... ~exist('final_temp') || ... ~exist('final_salt') caca; ncload('ariane_positions_quantitative.nc'); end %%%%%%%%%%%%%%%%%%%%%%% %% Open a new figure %% %%%%%%%%%%%%%%%%%%%%%%% fid1=figure; nb_x=2; nb_y=1; %%%%%%%%%%%% %% FIGURE %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Initial temperature and salinity diagram %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% s1=subplot(nb_y,nb_x,[1]); plot(init_salt,init_temp,'.','Color',[0.8 0.8 0.8]); h1=gca; xlim1=get(h1, 'XLim'); ylim1=get(h1, 'YLim'); title('Initial positions','FontWeight','bold','FontSize',14); xlabel('Salinity \rm(psu)','FontWeight','bold','FontSize',12); ylabel('Temperature \rm(\circC)','FontWeight','bold','FontSize',12); grid on; %%%%%%%%%%%% %% FIGURE %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Final temperature and salinity diagram %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% s2=subplot(nb_y,nb_x,[2]); plot(final_salt,final_temp,'.','Color',[0.8 0.8 0.8]); h2=gca; xlim2=get(h2, 'XLim'); ylim2=get(h2, 'YLim'); title('Final positions','FontWeight','bold','FontSize',14); xlabel('Salinity \rm(psu)','FontWeight','bold','FontSize',12); ylabel('Temperature \rm(\circC)','FontWeight','bold','FontSize',12); grid on; %%%%%%%%%%%%%%%%%%%%%%%%%%% %% To have the same axes %% %%%%%%%%%%%%%%%%%%%%%%%%%%% xlim=xlim1; xlim(1)=min(xlim1(1),xlim2(1)); xlim(2)=max(xlim1(2),xlim2(2)); ylim=ylim1; ylim(1)=min(ylim1(1),ylim2(1)); ylim(2)=max(ylim1(2),ylim2(2)); set(h1,'Xlim',xlim,'Ylim',ylim); set(h2,'Xlim',xlim,'Ylim',ylim); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('a_bins'), a_bins=100.; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% delta in T and delta in S %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% delta_t=(ylim(2)-ylim(1))/a_bins; delta_s=(xlim(2)-xlim(1))/a_bins; area_ts=delta_t * delta_s; %% Initialize 2 2D arrays init_2Dar=zeros(a_bins,a_bins); final_2Dar=zeros(a_bins,a_bins); %%%%%%%%%%%%%%%%%%%%%%%% %% Fill the 2D arrays %% %%%%%%%%%%%%%%%%%%%%%%%% max_init_transp =max(init_transp(:)); max_final_transp=max(final_transp(:)); nb_part=size(init_temp,1); for is = 1:nb_part ind_t = round((init_temp(is)-ylim(1)) / delta_t) + 1; ind_s = round((init_salt(is)-xlim(1)) / delta_s) + 1; init_2Dar(ind_s,ind_t) = init_2Dar(ind_s,ind_t) + ... ((init_transp(is)/max_init_transp) * 100.); ind_t = round((final_temp(is)-ylim(1)) / delta_t) + 1; ind_s = round((final_salt(is)-xlim(1)) / delta_s) + 1; final_2Dar(ind_s,ind_t) = final_2Dar(ind_s,ind_t) + ... ((final_transp(is)/max_final_transp) * 100.); end %% Results are ponderated by the surface of each cells (area_ts); init_2Dar(:,:) = init_2Dar(:,:) / area_ts; final_2Dar(:,:) = final_2Dar(:,:) / area_ts; %% Max of concentration max_init=max(max(init_2Dar)); max_final=max(max(final_2Dar)); %%%%%%%%%%%%%%%%%%%%%%%%%%% %% Axes of the 2D arrays %% %%%%%%%%%%%%%%%%%%%%%%%%%%% x_2Daxe=zeros(a_bins,a_bins); y_2Daxe=zeros(a_bins,a_bins); for is=1:a_bins; for js=1:a_bins; x_2Daxe(is,js)= xlim(1) + (is-1)*delta_s; y_2Daxe(is,js)= ylim(1) + (js-1)*delta_t; end end %%%%%%%%%%%%%%%%%%%%%% %% Replace 0 by NaN %% %%%%%%%%%%%%%%%%%%%%%% %init_2Dar(find(init_2Dar == 0))=NaN; %final_2Dar(find(final_2Dar == 0))=NaN; %%%%%%%%%%%%%%%%%%%%%%%% %% Inverse hot colors %% %%%%%%%%%%%%%%%%%%%%%%%% hot_=hot; invhot=hot; for is = 1:size(hot_,1); invhot(size(hot_,1)-is+1,1)=hot_(is,1); invhot(size(hot_,1)-is+1,2)=hot_(is,2); invhot(size(hot_,1)-is+1,3)=hot_(is,3); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% %% FIGURE %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Initial temperature and salinity diagram %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sub1=subplot(nb_y,nb_x,[1]); hold on; [Xi,Yi]=meshgrid(x_2Daxe(:,1),y_2Daxe(1,:)); zi=interp2(Xi,Yi,init_2Dar,Xi,Yi,'nearest'); contour(x_2Daxe,y_2Daxe,zi,'LineWidth',2); h1=gca; title({'Initial positions'},'FontWeight','bold','FontSize',14); xlabel('Salinity \rm(psu)','FontWeight','bold','FontSize',12); ylabel('Temperature \rm(\circC)','FontWeight','bold','FontSize',12); grid on; colormap(invhot); %%%%%%%%%%%% %% FIGURE %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Final temperature and salinity diagram %% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sub2=subplot(nb_y,nb_x,[2]); hold on; zf=interp2(Xi,Yi,final_2Dar,Xi,Yi,'nearest'); contour(x_2Daxe,y_2Daxe,zf,'LineWidth',2); h2=gca; title({'Final positions'},'FontWeight','bold','FontSize',14); xlabel('Salinity \rm(psu)','FontWeight','bold','FontSize',12); ylabel('Temperature \rm(\circC)','FontWeight','bold','FontSize',12); grid on; colormap(invhot); set(h2,'Xlim',xlim,'Ylim',ylim); %%%%%%%%%%%%% %% %%%%%%%%%%%%% %% s5=subplot(nb_y,nb_x,[7 8]); %% set(axes,'Visible','off'); %% hc=colorbar('north'); if exist('a_figname'), print -dtiff a_figname; clear a_figname; else print -dtiff diag_TS.tif; end
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from 'src/app/services/auth.service'; import { DarkModeService } from 'src/app/services/dark-mode.service'; import { ManageLanguageService } from 'src/app/services/manage-language.service'; @Component({ selector: 'app-nav-bar', templateUrl: './nav-bar.component.html', styleUrls: ['./nav-bar.component.css'], }) export class NavBarComponent implements OnInit { user: any = this.authService.getUserData(); onDarkMode!: boolean; selectedLanguage: string = this.translate.getCurrentLanguage(); constructor( private authService: AuthService, private router: Router, private darkMode: DarkModeService, private translate: ManageLanguageService ) {} ngOnInit() { this.darkMode.darkModeStatus.subscribe((res) => { this.onDarkMode = res; }); } public logout() { this.authService.logout(); this.router.navigateByUrl('/login'); } public setDarkMode(e: any) { this.darkMode.setDarkModeStatus = e.target.checked; } public changeLanguage(e: any) { if (e.target.checked) { this.translate.setSelectedLanguage('es'); } else { this.translate.setSelectedLanguage('en'); } } }
using PagedList; using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using YueBoAdmin.Models; namespace YueBoAdmin.Controllers { public class PostsController : Controller { private YueBoDB db = new YueBoDB(); // GET: Posts public ActionResult Index(int page = 1) { var post = db.Post.OrderByDescending(p => p.PostTime).Include(p => p.UserInfo).Include(p => p.PostStatus); return View(post.ToPagedList(page, 10)); } [HttpPost] public ActionResult Index(string reportname, string postname, int page = 1) { if (reportname == null || reportname == "") { var post = db.Post.OrderByDescending(p => p.PostTime).Include(p => p.UserInfo).Include(p => p.PostStatus).Where(p => p.PostContent.Contains(postname)); return View(post.ToPagedList(page, 10)); } else if (postname == null || postname == "") { var post = db.Post.OrderByDescending(p => p.PostTime).Include(p => p.UserInfo).Include(p => p.PostStatus).Where(p => p.UserInfo.UserAccount.Contains(reportname)); return View(post.ToPagedList(page, 10)); } else { var post = db.Post.OrderByDescending(p => p.PostTime).Include(p => p.UserInfo).Include(p => p.PostStatus); return View(post.ToPagedList(page, 10)); } } // GET: Posts/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Post post = db.Post.Find(id); if (post == null) { return HttpNotFound(); } return View(post); } // GET: Posts/Create public ActionResult Create() { ViewBag.UserID = new SelectList(db.UserInfo, "UserID", "UserName"); ViewBag.StatusID = new SelectList(db.PostStatus, "StatusID", "Status"); return View(); } // POST: Posts/Create // 为了防止“过多发布”攻击,请启用要绑定到的特定属性。有关 // 详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "PostID,PostPic,PostVideo,PostContent,IsHot,IsBan,IsDIY,PostTime,UserID,StatusID")] Post post) { if (ModelState.IsValid) { db.Post.Add(post); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.UserID = new SelectList(db.UserInfo, "UserID", "UserName", post.UserID); ViewBag.StatusID = new SelectList(db.PostStatus, "StatusID", "Status", post.StatusID); return View(post); } // GET: Posts/Edit/5 public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Post post = db.Post.Find(id); if (post == null) { return HttpNotFound(); } ViewBag.UserID = new SelectList(db.UserInfo, "UserID", "UserName", post.UserID); ViewBag.StatusID = new SelectList(db.PostStatus, "StatusID", "Status", post.StatusID); return View(post); } // POST: Posts/Edit/5 // 为了防止“过多发布”攻击,请启用要绑定到的特定属性。有关 // 详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "PostID,PostPic,PostVideo,PostContent,IsHot,IsBan,IsDIY,PostTime,UserID,StatusID")] Post post) { if (ModelState.IsValid) { db.Entry(post).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.UserID = new SelectList(db.UserInfo, "UserID", "UserName", post.UserID); ViewBag.StatusID = new SelectList(db.PostStatus, "StatusID", "Status", post.StatusID); return View(post); } // GET: Posts/DeleteConfirmed/5 public ActionResult DeleteConfirmed(int id) { int Aid = int.Parse(Request.Cookies["AdminID"].Value); AdminControl ac = new AdminControl(); ac.AdminContent = "删除了帖子"; ac.PostID = id; ac.ReportID = null; ac.UserID = null; ac.RecordTime = DateTime.Now; ac.AdminID = Aid; db.AdminControl.Add(ac); Post p = db.Post.Find(id); db.Post.Remove(p); db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Hot(int id) { int Aid = int.Parse(Request.Cookies["AdminID"].Value); AdminControl ac = new AdminControl(); ac.AdminContent = "设置了帖子上热门"; ac.PostID = id; ac.ReportID = null; ac.UserID = null; ac.RecordTime = DateTime.Now; ac.AdminID = Aid; db.AdminControl.Add(ac); db.Post.Find(id).IsHot = true; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult CancelHot(int id) { int Aid = int.Parse(Request.Cookies["AdminID"].Value); AdminControl ac = new AdminControl(); ac.AdminContent = "取消了帖子上热门"; ac.PostID = id; ac.ReportID = null; ac.UserID = null; ac.RecordTime = DateTime.Now; ac.AdminID = Aid; db.AdminControl.Add(ac); db.Post.Find(id).IsHot = false; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult Ban(int id) { int Aid = int.Parse(Request.Cookies["AdminID"].Value); AdminControl ac = new AdminControl(); ac.AdminContent = "屏蔽了帖子"; ac.PostID = id; ac.ReportID = null; ac.UserID = null; ac.RecordTime = DateTime.Now; ac.AdminID = Aid; db.AdminControl.Add(ac); db.Post.Find(id).IsBan = true; db.SaveChanges(); return RedirectToAction("Index"); } public ActionResult CancelBan(int id) { int Aid = int.Parse(Request.Cookies["AdminID"].Value); AdminControl ac = new AdminControl(); ac.AdminContent = "取消屏蔽了帖子"; ac.PostID = id; ac.ReportID = null; ac.UserID = null; ac.RecordTime = DateTime.Now; ac.AdminID = Aid; db.AdminControl.Add(ac); db.Post.Find(id).IsBan = false; db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }