text
stringlengths
184
4.48M
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>4 Chai aur code | DOM</title> </head> <body style="background-color: #212121; color: white;"> <ul class="language"> <li>Javascript</li> </ul> <script> function addLanguage(langName){ const parentEl = document.querySelector(".language"); const childEl = document.createElement("li"); childEl.innerHTML = `${langName}`; // not optimised parentEl.appendChild(childEl); } addLanguage("Java"); // optimised function function addOptiLanguage(langName){ const parentEl = document.querySelector(".language"); const childEl = document.createElement("li"); childEl.appendChild(document.createTextNode(`${langName}`)); document.querySelector(".language").appendChild(childEl); } addOptiLanguage("goLang"); addOptiLanguage("rust"); // Edit function replace1(whatTo, from){ const nthChild = document.querySelector(whatTo); const newLi = document.createElement(from); newLi.textContent = "Python"; nthChild.replaceWith(newLi); }; replace1("li:nth-child(2)", "li"); // Edit function replace2(whatTo, html){ const firstLang = document.querySelector(whatTo); firstLang.outerHTML = html; } replace2("li:first-child", "<li>TypeScript</li>"); // remove function remove(whatTo){ const lastLang = document.querySelector(whatTo); lastLang.remove(); } remove("li:last-child"); // rust removed </script> </body> </html>
import React from 'react'; import { classNames, TailwindSize } from '../../utils/tailwind'; import { Avatar } from '../Avatar'; export type MediaObjectProps = { title: string, src?: string, description?: string, size?: TailwindSize, className?: string, dark?: boolean, }; export function MediaObject({ title, src, description, size, className, dark, }: MediaObjectProps) { const textClassName = dark ? 'text-white' : 'text-black'; return ( <div className={classNames('flex items-center space-x-2', className)}> <div className="flex-shrink-0"> <Avatar size={size} src={src} /> </div> <div className={classNames('flex flex-col justify-center overflow-hidden', textClassName)}> <p className={`font-medium text-${size} truncate m-0`}> {title} </p> <p className="text-xs truncate m-0"> {description} </p> </div> </div> ); }
<?php namespace App\Imports; use Illuminate\Support\Collection; use Maatwebsite\Excel\Concerns\ToCollection; use App\Models\UploadData; use Illuminate\Support\Facades\Auth; class ImportData implements ToCollection { public function collection(Collection $rows) { dd($rows); $records = []; // Skip the first row (header row) $rows->shift(); foreach ($rows as $row) { $records[] = [ 'gov_id_no' => $row['govt_id_number'], 'gov_id_type' => $row['gov_id_type'], // 'photo' => $filePath, 'name' => $row['name'], 'dob' => $row['dob'], 'father_name' => $row['father_name'], 'age' => $row['age'], 'sex' => $row['sex'], 'phone' => $row['phone'], 'address' => $row['address'], 'district' => $row['district'], 'state' => $row['state'], 'pincode' => $row['pincode'], 'created_by' => Auth::user()->name, ]; } UploadData::insert($records); return back()->with('success', 'Data Uploaded successfully'); } }
type Query { tables(nameFilter: String): [Table] count(tableName: String!): Int taskResults(taskId: String): [TaskResult] surveyResponse(taskId: String!, includeAttributes: [String!]): [TaskItemResponse] healthDataOverview(offset: Int!, limit: Int!, orderByColumn: ParticipantListColumn, orderBySort: Sort, includeAttributes: [String!]): [HealthDataOverview] healthDataOverviewOfUser(userId: String!, includeAttributes: [String!]): HealthDataOverview rawHealthData(from: String, to: String, includeAttributes: [String!]): [UserHealthData] averageHealthData(from: String, to: String, includeAttributes: [String!]): [AverageHealthData] } enum ParticipantListColumn { ID, EMAIL, AVG_HR, AVG_BG, AVG_RR, AVG_SPO2, AVG_BP, AVG_SLEEP, TOTAL_STEPS, LAST_SYNCED } enum Sort { ASC, DESC } type OrderBy { column: ParticipantListColumn sort: Sort } type Table { name: String columns: [Column] } type Column { name: String type: String } type TaskResult { taskId: String, numberOfRespondedUser: TaskResponseCount completionTime: CompletionTime } type TaskResponseCount { count : Int } type CompletionTime { averageInMS: Float } type TaskItemResponse { itemName: String userId: String result: String profiles: [Attribute] } type Attribute { key: String value: String } type HealthDataOverview { userId: String lastSyncTime: String profiles: [Attribute] latestAverageHR: Float latestAverageBG: Float latestAverageRR: Float latestAverageSPO2: Float latestAverageSystolicBP: Float latestAverageDiastolicBP: Float averageSleep: Float latestTotalStep: Float } type HeartRate { time: String bpm: Int } type UserHealthData { userId: String profiles: [Attribute] healthData: HealthData } type HealthData { heartRates: [HeartRate] } type AverageHealthData { userId: String lastSyncTime: String profiles: [Attribute] averageHR: Float }
#include <stdlib.h> #include "dog.h" /** * _strlen - return lenght of a string * @s: string pointer * * Return: length of string */ int _strlen(char *s) { int len = 0; while (*(s + len) != 0) { len++; } return (len); } /** * _strcpy - copies string pointed to * @dest: first char * @src: second char * * Return: the pointer to dest */ char *_strcpy(char *dest, char *src) { int i; for (i = 0; *(src + i) != '\0'; i++) *(dest + i) = *(src + i); *(dest + i) = '\0'; return (dest); } /** * new_dog - creates a new dog * @name: dog name * @age: dog age * @owner: dog owner * * Return: pointer to new dog, else NULL */ dog_t *new_dog(char *name, float age, char *owner) { dog_t *dog; int len1, len2; len1 = _strlen(name); len2 = _strlen(owner); dog = malloc(sizeof(dog_t)); if (dog == NULL) return (NULL); dog->name = malloc(sizeof(char) * (len1 + 1)); dog->owner = malloc(sizeof(char) * (len2 + 1)); if (dog->name == NULL || dog->owner == NULL) { free(dog); free(dog->name); free(dog->owner); return (NULL); } _strcpy(dog->name, name); _strcpy(dog->owner, owner); dog->age = age; return (dog); }
#Copyright (C)2001-2003 Altera Corporation #Any megafunction design, and related net list (encrypted or decrypted), #support information, device programming or simulation file, and any other #associated documentation or information provided by Altera or a partner #under Altera's Megafunction Partnership Program may be used only to #program PLD devices (but not masked PLD devices) from Altera. Any other #use of such megafunction design, net list, support information, device #programming or simulation file, or any other related documentation or #information is prohibited for any other purpose, including, but not #limited to modification, reverse engineering, de-compiling, or use with #any other silicon devices, unless such use is explicitly licensed under #a separate agreement with Altera or a megafunction partner. Title to #the intellectual property, including patents, copyrights, trademarks, #trade secrets, or maskworks, embodied in any such megafunction design, #net list, support information, device programming or simulation file, or #any other related documentation or information provided by Altera or a #megafunction partner, remains with Altera, the megafunction partner, or #their respective licensors. No other licenses, including any licenses #needed under any third party's intellectual property, are provided herein. #Copying or modifying any file, or portion thereof, to which this notice #is attached violates this copyright. package vars; require 5.002; # The following require can't be removed during maintenance # releases, sadly, because of the risk of buggy code that does # require Carp; Carp::croak "..."; without brackets dying # if Carp hasn't been loaded in earlier compile time. :-( # We'll let those bugs get found on the development track. require Carp if $] < 5.00450; sub import { my $callpack = caller; my ($pack, @imports, $sym, $ch) = @_; foreach $sym (@imports) { ($ch, $sym) = unpack('a1a*', $sym); if ($sym =~ tr/A-Za-z_0-9//c) { # time for a more-detailed check-up if ($sym =~ /::/) { require Carp; Carp::croak("Can't declare another package's variables"); } elsif ($sym =~ /^\w+[[{].*[]}]$/) { require Carp; Carp::croak("Can't declare individual elements of hash or array"); } elsif ($^W and length($sym) == 1 and $sym !~ tr/a-zA-Z//) { require Carp; Carp::carp("No need to declare built-in vars"); } } *{"${callpack}::$sym"} = ( $ch eq "\$" ? \$ {"${callpack}::$sym"} : $ch eq "\@" ? \@ {"${callpack}::$sym"} : $ch eq "\%" ? \% {"${callpack}::$sym"} : $ch eq "\*" ? \* {"${callpack}::$sym"} : $ch eq "\&" ? \& {"${callpack}::$sym"} : do { require Carp; Carp::croak("'$ch$sym' is not a valid variable name"); }); } }; 1; __END__ =head1 NAME vars - Perl pragma to predeclare global variable names =head1 SYNOPSIS use vars qw($frob @mung %seen); =head1 DESCRIPTION This will predeclare all the variables whose names are in the list, allowing you to use them under "use strict", and disabling any typo warnings. Unlike pragmas that affect the C<$^H> hints variable, the C<use vars> and C<use subs> declarations are not BLOCK-scoped. They are thus effective for the entire file in which they appear. You may not rescind such declarations with C<no vars> or C<no subs>. Packages such as the B<AutoLoader> and B<SelfLoader> that delay loading of subroutines within packages can create problems with package lexicals defined using C<my()>. While the B<vars> pragma cannot duplicate the effect of package lexicals (total transparency outside of the package), it can act as an acceptable substitute by pre-declaring global symbols, ensuring their availability to the later-loaded routines. See L<perlmodlib/Pragmatic Modules>. =cut
require 'rails_helper' RSpec.describe 'posts #show', type: :feature do before :each do @user = User.create( name: 'Benson', photo: 'https://www.pexels.com/photo/cottages-in-the-middle-of-beach-753626/', bio: "I'm finding it hard coping with ruby on rails", posts_counter: 0 ) Post.create(author: @user, title: 'Title', text: 'Text', comments_counter: 0, likes_counter: 0) Post.create(author: @user, title: 'Title2', text: 'Text2', comments_counter: 0, likes_counter: 0) Post.create(author: @user, title: 'Title3', text: 'Text3', comments_counter: 0, likes_counter: 0) @post = Post.create(author: @user, title: 'Title4', text: 'Text4', comments_counter: 0, likes_counter: 0) visit "/users/#{@user.id}/posts/#{@post.id}" end describe 'post show page' do it 'shows the post\'s title' do expect(page).to have_content(@post.title) end it 'shows who wrote the post' do expect(page).to have_content(@user.name) end it 'shows number of comments the post has' do expect(page.body).to include('Number of comments') end it 'shows number of likes the post has' do expect(page.body).to include('Number of likes') end it 'shows the post body' do expect(page).to have_content(@post.text) end it 'shows all comments and the author name' do comments = @post.comments comments.each do |comment| expect(page).to have_content(comment.author.name) expect(page).to have_content(comment.text) end end end end
import Layout from '/components/layout' export default (props) => { const posts = props.stats; return ( <Layout> <div className="relative"> <div className="grid grid-flow-col auto-cols-auto gap-x-1"> {posts.map(post => <div className="float-left bg-green-500 text-white rounded-md text-center shadow-xl" key={post.key} style={{ padding: 20, borderBottom: '1px solid #ccc' }}> <h2>{post.title}</h2> <strong>{post.value}</strong> </div>)} </div> </div> </Layout> ) } import fsPromises from 'fs/promises' import path from 'path' // getStaticProps : 빌드 시 고정되는 값. 배포 이후에는 변경되지 않는다. // getStaticPaths : 동적 라우팅 + getStaticProps // getServerSideProps : 매 요청 시 서버에 요청 export async function getServerSideProps() { const filePath = path.join(process.cwd(), '/assets/data.json'); const jsonData = await fsPromises.readFile(filePath); const objectData = JSON.parse(jsonData); return { props: objectData } }
using CSD.AppointmentApp.Repository; using CSD.AppointmentApp.Service; using CSD.DbUtil.Provider; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace CSD.WebApp { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services .AddSingleton<IClientRepository, ClientRepository>() .AddSingleton<IAppointmentRepository, AppointmentRepository>() .AddSingleton<IAppointmentAppService, AppointmentAppService>(); services .AddMvc() .AddMvcOptions(options => options.ModelMetadataDetailsProviders.Add(new DisableConvertEmptyStringToNullProvider())); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else app.UseExceptionHandler("/Home/Error"); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}" ); }); } } }
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:homme_service_app/animation/fadeanimation.dart'; import 'package:homme_service_app/models/service.dart'; import 'package:homme_service_app/pages/select_service.dart'; class StartPage extends StatefulWidget { const StartPage({Key? key}) : super(key: key); @override State<StartPage> createState() => _StartPageState(); } class _StartPageState extends State<StartPage> { int selectedService = 4; @override void initState() { Timer.periodic(Duration(seconds: 2), (timer) { setState(() { selectedService = Random().nextInt(services.length); }); }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ SizedBox( height: 100, ), Container( padding: EdgeInsets.symmetric(horizontal: 50), height: MediaQuery.of(context).size.height * 0.45, width: MediaQuery.of(context).size.width, child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( childAspectRatio: 1.0, crossAxisCount: 3, crossAxisSpacing: 8.0, mainAxisSpacing: 8.0, ), physics: NeverScrollableScrollPhysics(), itemCount: services.length, itemBuilder: (BuildContext context, int index) { return FadeAnimation( delay: (1.0 + index) / 4, child: serviceContainer( services[index].imgUrl, services[index].name, index)); }, ), ), Expanded( child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(80), topRight: Radius.circular(80), ), ), child: Column( children: [ SizedBox( height: 50, ), FadeAnimation( delay: 1.5, child: Container( padding: EdgeInsets.symmetric(horizontal: 40), child: Center( child: Text( 'Easy, reliable way take \ncare of yoour home', textAlign: TextAlign.center, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.grey.shade900, ), ), ), ), ), SizedBox( height: 20, ), FadeAnimation( delay: 1.5, child: Container( padding: EdgeInsets.symmetric(horizontal: 60), child: Center( child: Text( 'We provide yoou with the best people to help take of your home.', style: TextStyle( fontSize: 16, color: Colors.grey.shade600, ), ), ), ), ), FadeAnimation( delay: 1.5, child: Padding( padding: EdgeInsets.all(50.0), child: MaterialButton( elevation: 0, color: Colors.black, onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => SelectService())); }, height: 55, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), child: Center( child: Text( 'Get Started', style: TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.w500, ), ), ), ), ), ), ], ), ), ), ], ), ); } serviceContainer(String image, String name, int index) { return GestureDetector( onTap: () {}, child: AnimatedContainer( duration: Duration(milliseconds: 500), padding: EdgeInsets.all(8.0), decoration: BoxDecoration( color: selectedService == index ? Colors.white : Colors.grey.shade100, border: Border.all( color: selectedService == index ? Color.fromARGB(255, 94, 95, 95) : Color.fromARGB(255, 44, 44, 44).withOpacity(0), width: 2.0, ), borderRadius: BorderRadius.circular(15.0), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Image.asset( image, height: 30, fit: BoxFit.cover, ), SizedBox( height: 10, ), Text( name, style: TextStyle(fontSize: 14), ) ]), ), ); } }
<?php use App\Application; use App\ApplicationTransaction; use Faker\Generator as Faker; use Illuminate\Support\Arr; $factory->define(Application::class, function (Faker $faker) { return [ 'rebate_id' => function() { return factory(App\Rebate::class)->create()->id; }, 'applicant_id' => function() { return factory(App\Applicant::class)->create()->id; }, 'admin_id' => function() { return factory(App\Admin::class)->create()->id; }, 'rebate_code' => function(array $application) { $rebate = App\Rebate::find($application['rebate_id']); return Application::generateUniqueCode($rebate->partner); }, 'fy_year' => Arr::random(range(2016, 2018)), 'status' => Arr::random(['expired', 'approved', 'denied', 'pending-review', 'new']), 'rebate_count' => Arr::random([1,2]), 'desired_rebate_count' => Arr::random([1,15]), 'wait_listed' => 0, 'notification_sent' => 0, 'notification_sent_at' => null, 'created_at' => $faker->dateTimeBetween('-1 years', 'now')->format('Y-m-d H:i:s'), ]; }); $factory->afterCreating(Application::class, function($app, $faker) { factory(App\ApplicationComment::class, 3)->create([ 'application_id' => $app->id, 'admin_id' => $app->admin_id, ]); if ($app->wait_listed) { return; } switch ($app->status) { case Application::ST_APPROVED: factory(ApplicationTransaction::class)->create([ 'application_id' => $app->id, 'admin_id' => $app->admin_id ?? 1, 'type' => ApplicationTransaction::ST_APPROVED, ]); break; case Application::ST_DENIED: factory(ApplicationTransaction::class)->create([ 'application_id' => $app->id, 'admin_id' => $app->admin_id ?? 1, 'type' => ApplicationTransaction::ST_DENIED, ]); break; case Application::ST_PENDING_REVIEW: $app->admin_first_viewed_at = $app->created_at; $app->save(); case Application::ST_NEW: case Application::ST_EXPIRED: # do nothing break; } });
import React from "react"; interface Props { label: string | null; onClick: React.MouseEventHandler<HTMLButtonElement>; leadingIcon: React.ReactNode; ariaLabel?: string; className?: string; } const Button: React.FC<Props> = ({ label = null, onClick = () => {}, leadingIcon = null, ariaLabel = undefined, className = undefined }) => { return ( <button className={ "flex gap-2 items-center justify-center bg-transparent cursor-pointer border-2 border-solid border-main rounded-md py-1 px-3 font-medium hover:bg-surface-3 active:bg-surface-1 select-none" + (className ? " " + className : "") } onClick={onClick} aria-label={ariaLabel} > {leadingIcon} {label && <span>{label}</span>} </button> ) } export default Button;
package com.locnavi.watch.utils.KeyboardVisibilityEvent; import android.app.Activity; import android.graphics.Rect; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import com.locnavi.location.xunjimap.utils.DensityUtils; /** * author:chen * time:2017/10/30 * desc: */ public class KeyboardVisibilityEvent { private final static int KEYBOARD_VISIBLE_THRESHOLD_DP = 100; /** * Set keyboard visibility change event listener. * * @param activity Activity * @param listener KeyboardVisibilityEventListener * @return Unregistrar */ public static Unregister registerEventListener(final Activity activity, final KeyboardVisibilityEventListener listener) { if (activity == null) { throw new NullPointerException("Parameter:activity must not be null"); } int softInputMethod = activity.getWindow().getAttributes().softInputMode; if (WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE != softInputMethod && WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED != softInputMethod) { throw new IllegalArgumentException("Parameter:activity window SoftInputMethod is not ADJUST_RESIZE"); } if (listener == null) { throw new NullPointerException("Parameter:listener must not be null"); } final View activityRoot = getActivityRoot(activity); final ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { private final Rect r = new Rect(); private final int visibleThreshold = Math.round( DensityUtils.dp2px(activity, KEYBOARD_VISIBLE_THRESHOLD_DP)); private boolean wasOpened = false; @Override public void onGlobalLayout() { activityRoot.getWindowVisibleDisplayFrame(r); int heightDiff = activityRoot.getRootView().getHeight() - r.height(); boolean isOpen = heightDiff > visibleThreshold; if (isOpen == wasOpened) { // keyboard state has not changed return; } wasOpened = isOpen; listener.onVisibilityChanged(isOpen); } }; activityRoot.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener); return new SimpleUnregister(activity, layoutListener); } /** * Determine if keyboard is visible * * @param activity Activity * @return Whether keyboard is visible or not */ public static boolean isKeyboardVisible(Activity activity) { Rect r = new Rect(); View activityRoot = getActivityRoot(activity); int visibleThreshold = Math.round(DensityUtils.dp2px(activity, KEYBOARD_VISIBLE_THRESHOLD_DP)); activityRoot.getWindowVisibleDisplayFrame(r); int heightDiff = activityRoot.getRootView().getHeight() - r.height(); return heightDiff > visibleThreshold; } static View getActivityRoot(Activity activity) { return ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); } }
package com.hixtrip.sample.app.service; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import com.hixtrip.sample.app.api.OrderService; import com.hixtrip.sample.app.service.paycallback.PayCallbackProcess; import com.hixtrip.sample.client.order.dto.CommandOderCreateDTO; import com.hixtrip.sample.client.order.dto.CommandPayDTO; import com.hixtrip.sample.client.order.enums.OrderStatusEnum; import com.hixtrip.sample.domain.commodity.CommodityDomainService; import com.hixtrip.sample.domain.inventory.InventoryDomainService; import com.hixtrip.sample.domain.order.OrderDomainService; import com.hixtrip.sample.domain.order.model.Order; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.Date; /** * app层负责处理request请求,调用领域服务 */ @Slf4j @Component public class OrderServiceImpl implements OrderService { @Autowired private OrderDomainService orderDomainService; @Autowired private CommodityDomainService commodityDomainService; @Autowired private InventoryDomainService inventoryDomainService; @Autowired private PayCallbackProcess payCallbackProcess; /** * 下单 * @param commandOderCreateDTO 下单对象 * @return */ @Override public Long createOrder(CommandOderCreateDTO commandOderCreateDTO) { // 采用redis做库存缓存,下单扣减库存;订单超时时间10分钟,取消后回退库存 boolean changeInventory = inventoryDomainService.changeInventory(commandOderCreateDTO.getSkuId(), commandOderCreateDTO.getAmount()); if (!changeInventory) { log.info("商品已售罄"); return 0L; } try { Order order = new Order(); order.setId(IdWorker.getId()); order.setUserId(commandOderCreateDTO.getUserId()); order.setSkuId(commandOderCreateDTO.getSkuId()); order.setAmount(commandOderCreateDTO.getAmount()); order.setMoney(commodityDomainService.getSkuPrice(order.getSkuId())); order.setPayTime(LocalDateTime.now()); order.setPayStatus(OrderStatusEnum.WAIT_PAY.getStatus()); orderDomainService.createOrder(order); return order.getId(); } catch (Exception e) { // 业务逻辑出错,返还库存 inventoryDomainService.changeInventory(commandOderCreateDTO.getSkuId(), - commandOderCreateDTO.getAmount()); } return 0L; } /** * 订单支付回调操作 * @param commandPayDTO 回调对象 * @return 处理结果 */ @Override public boolean payCallback(CommandPayDTO commandPayDTO) { return payCallbackProcess.process(commandPayDTO); } }
#pragma once #include "Component.h" #include "../Head/CppHead.h" #include "../Head/ConfigHead.h" #include "../Renderer/RenderObject.h" namespace tezcat::Tiny { class Shader; class BaseGraphics; /* * Camera * * @brief 相机模块,负责在渲染流程中查找可见单位,以及提供ViewMatrix的数据 * @brief 相机可以把自己看到 */ class TINY_API Camera : public ComponentT<Camera>, public IRenderObserver { //创建一个forward主相机 Camera(); //创建一个forward相机 Camera(bool mainCamera); TINY_Factory(Camera); TINY_RTTI_H(Camera); public: virtual ~Camera(); uint32_t getID() const { return mUID; } void render(BaseGraphics* graphics); void submit(BaseGraphics* graphics, Shader* shader) override; void submitViewMatrix(BaseGraphics* graphics, Shader* shader) override; public: bool isMain() const { return mIsMain; } void setMain(); void clearMain() { mIsMain = false; } protected: void onStart() override; void onEnable() override; void onDisable() override; private: bool mIsMain; uint32_t mUID; }; }
import { URL } from "../../utils/consts"; import { checkResponse } from "../../utils/utils"; import { AppDispatch, AppThunk } from "../types"; import { TIngredient } from "../../services/types/data"; export const INGREDIENTS_REQUEST: "INGREDIENTS_REQUEST" = "INGREDIENTS_REQUEST"; export const INGREDIENTS_SUCCESS: "INGREDIENTS_SUCCESS" = "INGREDIENTS_SUCCESS"; export const INGREDIENTS_FAILED: "INGREDIENTS_FAILED" = "INGREDIENTS_FAILED"; export const SELECT_INGREDIENT: "SELECT_INGREDIENT" = "SELECT_INGREDIENT"; export interface IIngredientsRequestAction { readonly type: typeof INGREDIENTS_REQUEST; } export interface IIngredientsSuccessAction { readonly type: typeof INGREDIENTS_SUCCESS; readonly ingredients: Array<TIngredient>; } export interface IIngredientsFailedAction { readonly type: typeof INGREDIENTS_FAILED; } export interface IIngredientsSelectedAction { readonly type: typeof SELECT_INGREDIENT; readonly ingredient: TIngredient; } export type TIngredientsActions = | IIngredientsRequestAction | IIngredientsSuccessAction | IIngredientsFailedAction | IIngredientsSelectedAction; export const IngredientsRequest = (): IIngredientsRequestAction => ({ type: INGREDIENTS_REQUEST, }); export const IngredientsSuccess = ( ingredients: Array<TIngredient> ): IIngredientsSuccessAction => ({ type: INGREDIENTS_SUCCESS, ingredients, }); export const IngredientsFailed = (): IIngredientsFailedAction => ({ type: INGREDIENTS_FAILED, }); export const getIngredients: AppThunk = () => { return (dispatch: AppDispatch) => { dispatch(IngredientsRequest()); fetch(`${URL}/ingredients`) .then(checkResponse) .then((res) => { if (res && res.success) { dispatch(IngredientsSuccess(res.data)); } else { dispatch(IngredientsFailed()); } }) .catch(() => dispatch(IngredientsFailed())); }; };
import React from 'react'; import "./ProductCard.css"; import { useLocation, useNavigate } from "react-router-dom"; const ProductCard = ({ product }) => { const { title, brand, imageUrl, price, discountedPrice, color, discountPersent } = product; const navigate = useNavigate(); // console.log("product",product) const handleNavigate = () => { //chuyen den trang chi tiet san pham, neu ko có id thi chuyen den trang 2 navigate(`/product/${product?.id || product?._id || 2}`) } return ( <div onClick={handleNavigate} className='productCard w-[15rem] border m-3 transition-all cursor-pointer '> <div className='h-[20rem]'> <img className='h-full w-full object-cover object-left-top' src={imageUrl} alt="" /> </div> <div className='textPart bg-white p-3 '> <div> <p className='font-bold opacity-60'>{brand}</p> <p className=''>{title}</p> <p className='font-semibold opacity-50'>{color}</p> </div> <div className='flex space-x-2 items-center'> <p className='font-semibold'>{discountedPrice}đ</p> <p className='opacity-50 line-through'>{price}đ</p> <p className='text-green-600 font-semibold'>{discountPersent}% off</p> </div> </div> </div> ); }; export default ProductCard;
import React, { useContext } from 'react' import { AppContext } from '../context/AppContext' import './Pagination.css' export default function Pagination() { const {pageCount, changePageHandler, totalPageCount} = useContext(AppContext); return ( <> <div className=' inset-x-0 flex justify-center items-center border-t-2 border-t-gray-300 fixed bottom-0 bg-slate-300 py-3'> <div className=' w-11/12 max-w-2xl flex items-center justify-between'> <div className=' flex gap-x-4'> { pageCount > 1 && (<button className=' pagination__button border border-black rounded-md px-3 py-1' onClick={() => changePageHandler(pageCount - 1)}> Previous </button>) } { pageCount < totalPageCount && (<button className=' pagination__button border border-black rounded-md px-3 py-1' onClick={() => changePageHandler(pageCount + 1)}> Next </button>) } </div> <p className=' font-bold text-sm'> PAGE {pageCount} of {totalPageCount} </p> </div> </div> </> ) }
import React, { useState } from 'react'; import './App.css'; import InputField from './components/InputField'; import TodoList from './components/TodoList'; import { Todo } from './model'; import {DragDropContext } from 'react-beautiful-dnd'; //React.FC = Functional component for React const App: React.FC = () => { const [todo, setTodo] = useState<string>(""); const [todos, setTodos] = useState<Todo[]>([]); const [completedTodos, setCompletedTodos] = useState<Todo[]>([]); const handleAdd = (e: React.FormEvent) => { e.preventDefault(); if(todo) { setTodos([...todos, {id: Date.now(), todo, isDone: false}]) setTodo(""); } }; console.log(todos); return ( <DragDropContext onDragEnd={() => {}}> <div className="App"> <span className='heading'>Task Manager</span> <InputField todo={todo} setTodo={setTodo} handleAdd={handleAdd}/> <TodoList todos={todos} setTodos={setTodos} completedTodos={completedTodos} setCompletedTodos= {setCompletedTodos}/> </div> </DragDropContext> ); } export default App;
# [Sum of Two Lowest Positive Integers](https://www.codewars.com/kata/558fc85d8fd1938afb000014) ## Description Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed. For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`. `[10, 343445353, 3453445, 3453545353453]` should return `3453455`. ## My Solution **JavaScript** ```js const sumTwoSmallestNumbers = (nums) => (([a, b] = [...nums].sort((a, b) => a - b)), a + b); ``` ```js const sumTwoSmallestNumbers = (numbers) => numbers .sort((a, b) => a - b) .slice(0, 2) .reduce((acc, curr) => acc + curr, 0); ```
import React, { useEffect } from "react"; export function useOnOutsideClick( ref: React.RefObject<any>, functionToRun = () => {} ) { useEffect(() => { function handleClickOutside(event: any) { if (ref?.current && !ref?.current?.contains(event.target)) { functionToRun(); } } document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [ref, functionToRun]); }
# This agent script is designed to be used on the agentverse.ai website as a hosted agent. # As such, is does not import all of the necessary modules to run locally. # the boca user agent communicates with the t5_base agent, as well as the match_maker agent, as well as the another boca_user agent that they have been paired with for a chat (from the match_maker agent) # to be stored in the .env file if NATIVE_LANGUAGE == "": raise Exception( "Provide a valid native language -- English, French, German, or Romanian." ) # to be stored in the .env file if TARGET_LANGUAGE == "": raise Exception( "Provide a valid native language -- English, French, German, or Romanian." ) # to be stored in the .env file if BOCA_MATCH_MAKER == "": raise Exception("Provide the correct BOCA_MATCH_MAKER agent address.") # to be stored as an "Agent Secret" if HUGGING_FACE_ACCESS_TOKEN == "": raise Exception("Provide a HuggingFace API key for t5_base translation requests.") # to be stored in the .env file if T5_BASE_AGENT_ADDRESS == "": raise Exception("Provide a t5_base_agent address for translation requests.") # text you want to translate user_input = input("Type a syntactically correct message in your native language.") # check if user input is empty if user_input == "": raise Exception("User input is empty. Please provide a valid input.") INPUT_TEXT = ( "translate " + NATIVE_LANGUAGE + " to " + TARGET_LANGUAGE + ": " + user_input ) ### Define the t5_base protocol t5_base = Protocol(name="t5_base", version="0.0.1") @t5_base.on_interval(period=30, messages=TranslationRequest) async def transcript(ctx: Context): TranslationDone = ctx.storage.get("TranslationDone") if not TranslationDone: await ctx.send(T5_BASE_AGENT_ADDRESS, TranslationRequest(text=INPUT_TEXT)) @t5_base.on_message(model=TranslationResponse) async def handle_data(ctx: Context, sender: str, response: TranslationResponse): ctx.logger.info(f"Translated text: {response.translated_text}") ctx.storage.set("TranslationDone", True) @t5_base.on_message(model=Error) async def handle_error(ctx: Context, sender: str, error: Error): ctx.logger.info(f"Got error from uagent: {error}") # Define the boca_user protocol boca_user = Protocol(name="boca_user", version="0.0.1") @boca_user.on_event("startup") async def request_chat(ctx: Context, BOCA_MATCH_MAKER, message=MatchRequest): ctx.logger.info(f"Requesting a new chat... {NATIVE_LANGUAGE} to {TARGET_LANGUAGE}.") await ctx.send( BOCA_MATCH_MAKER, MatchRequest(native=NATIVE_LANGUAGE, translation=TARGET_LANGUAGE), ) @boca_user.on_message(model=MatchResponse) async def handle_chat_request_response( ctx: Context, sender: str, message=MatchResponse ): ctx.logger.info( f"Received chat request response.\n" f"New chat partner: {message.partner}" ) ctx.storage.set("partner", message.partner) @boca_user.on_message(model=TranslationResponse) # when the agent receives a translation response from the base agent, it will send a BocaMessage to the BOCA_LIBRE using the input text and the translated text from the response async def send_boca_message(ctx: Context, sender: str, response: TranslationResponse): ctx.storage.get("partner") await ctx.send( partner, BocaMessage(native=user_input, translation=response.translated_text) ) ctx.logger.info(f"Sent BocaMessage to BOCA_MATCH_MAKER agent: {BOCA_MATCH_MAKER}") @boca_user.on_message(model=BocaMessage) async def handle_boca_message(ctx: Context, sender: str, message: BocaMessage): ctx.logger.info( f"Received BocaMessage from {sender}: {message.native} -> {message.translation}" ) # add the BocaMessage to the storage as a list with indices for each message received chronologically messages = ctx.storage.get("messages", []) messages.append(message) ctx.storage.set("messages", messages) # register the protocol with the agent agent.include(boca_user, t5_base) # Messages # to request to the hf agent class TranslationRequest(Model): text: str api_key: str # response from the hf agent class TranslationResponse(Model): translated_text: str # error from hf agent class Error(Model): error: str class MatchRequest(Model): native_language: str target_language: str class MatchResponse(Model): partner: str partner_native_language: str class UpdateMatchRequest(Model): native_language: str target_language: str class UpdateMatchRequestResponse(Model): success: bool class Message(Model): message: str # Boca message to send to whoever you are matched with class BocaMessage(Model): native: str translation: str # TODO: write boca_user protocol # send match request message to match_maker # hanlde match response message from match_maker # send update match request message to match_maker # handle update match request response from match_maker # store match response partner in storage # send boca message to partner agent # handle boca message from partner agent # store message in storage # TODO: Review t5_base protocol # send translation request message to t5_base # handle translation response message from t5_base # handle error message from t5_base
<template> <ValidationForm v-slot="{ errors }" class="w-full lg:w-940 px-8" @submit="handleSubmit()"> <input-movie label="Movie name" name="movie_name_en" v-model="movieData.movie_name_en" type="text" language="Eng" rules="required|english-text" :error="errors.movie_name_en" /> <input-movie label="ფილმის სახელი" name="movie_name_ka" v-model="movieData.movie_name_ka" type="text" language="ქარ" rules="required|georgian-text" :error="errors.movie_name_ka" /> <input-genre :error="errors.genres" :chosen-genres="chosenGenres" :genres-list="genresList" @add-chosen-genre="addChosenGenre" @remove-chosen-genre="removeChosenGenre" > <Field name="genres" rules="required" v-model="movieData.genres" class="hidden" /> </input-genre> <input-movie label="წელი/Year" name="release_date" v-model="movieData.release_date" type="text" rules="required|between:1888,2023" :error="errors.release_date" /> <input-movie label="Director" name="director_en" v-model="movieData.director_en" type="text" language="Eng" rules="required|english-text" :error="errors.director_en" /> <input-movie label="რეჟისორი" name="director_ka" v-model="movieData.director_ka" type="text" language="ქარ" rules="required|georgian-text" :error="errors.director_ka" /> <input-text-area-movie label="Movie description" name="description_en" v-model="movieData.description_en" type="text" language="Eng" rules="required|english-text" :error="errors.description_en" /> <input-text-area-movie label="ფილმის აღწერა" name="description_ka" v-model="movieData.description_ka" type="text" language="ქარ" rules="required|georgian-text" :error="errors.description_ka" /> <input-picture-default name="picture" rules="required|image" :error="errors.picture" v-model="movieData.picture" /> <span v-if="serverErrorMessage" class="text-red mt-7 block">{{ serverErrorMessage }}</span> <button-base class="bg-red w-full mt-7 py-2"> {{ $t('movies.add_movie_normal_case') }} </button-base> </ValidationForm> </template> <script setup> import InputMovie from '@/components/ui/inputs/InputMovie.vue' import InputGenre from '@/components/ui/inputs/InputGenre.vue' import InputTextAreaMovie from '@/components/ui/inputs/InputTextAreaMovie.vue' import InputPictureDefault from '@/components/ui/inputs/InputPictureDefault.vue' import ButtonBase from '@/components/ui/buttons/ButtonBase.vue' import { Field, Form as ValidationForm } from 'vee-validate' import { onMounted, reactive, ref } from 'vue' import { useModalStore } from '@/stores/useModalStore' import { addMovie, getMovieGenres } from '@/services/api/movies' import { storeToRefs } from 'pinia' import { useMovieStore } from '@/stores/useMovieStore' import scrollToTop from '@/helpers/scrollToTop' const genresList = ref([]) const chosenGenres = ref([]) const addChosenGenre = (genreId, genreName) => { chosenGenres.value.push({ id: genreId, name: genreName }) genresList.value = genresList.value.filter((genre) => genre.id !== genreId) movieData.genres = chosenGenres.value.map((obj) => obj.id).join(',') } const removeChosenGenre = (genreName, genreId) => { const index = chosenGenres.value.findIndex((genre) => genre.id === genreId) if (index !== -1) { const removedGenre = chosenGenres.value.splice(index, 1)[0] genresList.value.unshift(removedGenre) } movieData.genres = chosenGenres.value .filter((obj) => obj.id !== genreId) .map((obj) => obj.id) .join(',') } const movieData = reactive({ movie_name_en: '', movie_name_ka: '', genres: '', release_date: '', director_en: '', director_ka: '', description_en: '', description_ka: '', picture: null }) const modalStore = useModalStore() const movieStore = useMovieStore() const { isNewMovieAdded } = storeToRefs(movieStore) const serverErrorMessage = ref('') const handleSubmit = async () => { await addMovie(movieData) .then((response) => { if (response.status === 201) { modalStore.toggleModalVisibility('movieAddModal') isNewMovieAdded.value = true scrollToTop() } }) .catch((error) => { serverErrorMessage.value = error.response.data.message }) } onMounted(async () => { await getMovieGenres().then((response) => { if (response.status === 200) { genresList.value = [...response.data.genres] } }) }) </script>
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:http/http.dart' as axios; import 'package:pengaduan_flutter/models/PetugasModel.dart'; class PetugasController extends GetxController { RxInt show = RxInt(0); RxBool isLoading = RxBool(false); RxList<PetugasModel> listpetugas = RxList<PetugasModel>([]); TextEditingController idPetugasController = TextEditingController(); TextEditingController namaPetugasController = TextEditingController(); TextEditingController usernameController = TextEditingController(); TextEditingController passwordController = TextEditingController(); TextEditingController telpController = TextEditingController(); TextEditingController levelController = TextEditingController(); TextEditingController editNamaPetugasController = TextEditingController(); TextEditingController editUsernameController = TextEditingController(); TextEditingController editPasswordController = TextEditingController(); TextEditingController editTelpController = TextEditingController(); TextEditingController editLevelController = TextEditingController(); @override void onInit() { getData(); super.onInit(); } void getData() async { try { isLoading.value == true; var res = await axios.get(Uri.parse('http://192.168.116.118:5000/petugas')); print(res); if (res.statusCode == 200) { isLoading.value == false; final content = jsonDecode(res.body); for (Map<String, dynamic> i in content) { listpetugas.add(PetugasModel.fromJson(i)); } } } catch (e) { print(e.toString()); } } Future<bool> postData() async { final Map<String, dynamic> datas = { "id_petugas": idPetugasController.text, "nama_petugas": namaPetugasController.text, "username": usernameController.text, "password": passwordController.text, "telp": telpController.text, "level": levelController.text, }; final response = await axios.post( Uri.parse('http://192.168.116.118:5000/petugas'), headers: {"content-type": "application/json"}, body: jsonEncode(datas)); if (response.statusCode == 201) { // ignore: invalid_use_of_protected_member listpetugas.value.clear(); getData(); return true; } else { return false; } } final id = 0.obs; void getId(int ids) async { id.value = ids; } Future<bool> updateData(id) async { final Map<String, dynamic> datas = { "nama_petugas": editNamaPetugasController.text, "username": editUsernameController.text, "password": editPasswordController.text, "telp": editTelpController.text, "level": editLevelController.text, }; final response = await axios.patch( Uri.parse('http://192.168.116.118:5000/petugas/${id}'), headers: {"content-type": "application/json"}, body: jsonEncode(datas)); if (response.statusCode == 201) { // ignore: invalid_use_of_protected_member listpetugas.value.clear(); getData(); return true; } else { return false; } } void getId2(int ids) async { id.value = ids; } Future<bool> deleteData(id) async { final response = await axios.delete( Uri.parse('http://192.168.116.118:5000/petugas/${id}'), headers: {"content-type": "application/json"}); if (response.statusCode == 201) { return true; } else { return false; } } }
import { createStore, Store } from 'vuex' import { computed, App, ComputedRef } from 'vue' import { StoreRootState } from './define' import RouteStore from './stores/RouteStore' import BreadStore from './stores/BreadStore' let store: Store<StoreRootState> function initStore(): Store<StoreRootState> { return createStore<StoreRootState>({ strict: import.meta.env.VITE_PROFILE === 'development', devtools: import.meta.env.VITE_PROFILE === 'development', modules: { route: RouteStore.store, bread: BreadStore.store } }) } function getStore() { return store } function mapState<Key extends string>(namespace: string, map: Key[]): { [key in Key]: ComputedRef } { const result: { [key in Key]: ComputedRef } = {} as { [key in Key]: ComputedRef } return map.reduce((item, cur) => { item[cur] = computed(() => store.state[namespace][cur]) return item }, result) } export default { install(app: App) { const vueApp = app store = initStore() vueApp.use(store) vueApp.config.globalProperties.$cRoute = RouteStore.operator(store) vueApp.config.globalProperties.$bread = BreadStore.operator(store) } } export { mapState, getStore }
function particle_init() particles={} end function particle_update(self) if self.delay>0 then self.delay-=1 return end self.x+=self.dx self.y+=self.dy self.dy+=0.1 if self.life~=nil then self.life-=1 end if self.y>127 or self.x>127 or self.x<0 or self.y<0 or (self.life~=nil and self.life<0) then del(particles,self) if self.callback~=nil then self:callback() end end end function particle_draw(self) spr(self.t,self.x-4,self.y-4,1,1) end function particle_add(x,y,dx,dy,t,delay,life,callback) if dx==nil then dx=0 end if dy==nil then dy=0 end if delay==nil then delay=0 end local ob = { x=x+rnd(4)-2, y=y+rnd(4)-2, h=1/8, w=1/8, dx=dx, dy=dy, t=t, delay=delay, life=life, callback=callback, draw=particle_draw, update=particle_update } add(particles,ob) end -- smoke = circles function smoke_add(x,y,dy,cl,delay,size) if dy==nil then dy=0 end if delay==nil then delay=0 end if cl==nil then cl=col.white end if size==nil then size=2 end local ob = { x=x+rnd(4)-2, y=y+rnd(4)-2, type=type, dx=0, dy=dy, dr=-0.15, r=size+rnd(2), phase=0, col=cl, delay=delay, draw=smoke_draw, update=smoke_update } add(particles,ob) end function smoke_update(self) if self.delay~=nil and self.delay>0 then self.delay-=1 return end self.x+=self.dx self.y+=self.dy -- self.phase=(self.phase+1)%2 -- change size self.r+=self.dr -- if 0 remove if self.r<=0 then del(particles,self) end end function smoke_draw(self) circfill(self.x,self.y,self.r,self.col) end
import { GoogleOAuthProvider, TokenResponse, googleLogout, useGoogleLogin } from "@react-oauth/google" import VoteForm from "../../components/VoteForm"; import { useEffect, useState } from "react"; import axios from "axios"; type Props = { children?: React.ReactNode, } const GoogleProvider : React.FC<Props> = ({children}) => { return ( <GoogleOAuthProvider clientId="653962216255-dhs8b8tuvbq5c8ugn9o25pjh77hcqj46.apps.googleusercontent.com"> {children} <Profile /> </GoogleOAuthProvider> ) } type UserProfile = { email: string, name: string, picture: string, } const Profile: React.FC = () => { const [ accessToken, setAccessToken ] = useState(""); const [ profile, setProfile ] = useState({} as UserProfile); const login = useGoogleLogin({ onSuccess: (codeResponse: TokenResponse) => { setAccessToken(codeResponse.access_token) }, onError: (error) => console.log('Login Failed:', error) }); useEffect( () => { console.log("accessToken: ",accessToken) if (accessToken !== "") { axios .get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${accessToken}`, { headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' } }) .then((res) => { setProfile(res.data); }) .catch((err) => console.log(err)); } }, [ accessToken ] ); // log out function to log the user out of google and set the profile array to null const logOut = () => { googleLogout(); setProfile({} as UserProfile); }; return ( <div> {profile.email !== undefined ? ( <div> <div> <img src={profile.picture} alt="user" style={{verticalAlign:"top", marginRight: "10px"}} /> <div style={{display:"inline-block"}}> <p>Name: {profile.name}</p> <p>Email Address: {profile.email}</p> <button onClick={logOut}>Log out</button> </div> </div> <VoteForm provider="google" identity={profile.email} /> </div> ) : ( <button onClick={() => login()}>Sign in with Google 🚀 </button> )} </div> ); } export default GoogleProvider
require 'rails_helper' RSpec.describe '管理ユーザーモデル機能', type: :model do describe 'バリデーションテスト' do context '新規管理ユーザー作成時' do it '名前が空欄だとバリデーションエラーが出る' do admin = Admin.new(name: '', email: "test", password: "test") expect(admin).not_to be_valid end it 'メールアドレスが空欄だとバリデーションエラーが出る' do admin = Admin.new(name: 'test', email: "", password: "test") expect(admin).not_to be_valid end it 'パスワードが空欄だとバリデーションエラーが出る' do admin = Admin.new(name: 'test', email: "test", password: "") expect(admin).not_to be_valid end it 'メールが正しいフォーマットでない場合は作成されない' do admin = Admin.new(name: 'test', email: "test", password: "testpass") expect(admin).not_to be_valid end it '名前、メール、パスワードの記入があれば作成される' do admin = Admin.new(name: 'test', email: "test@test.com", password: "testpass") expect(admin).to be_valid end end end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="/output.css" rel="stylesheet"> <title>Quizzes</title> <style> p{ display: inline; } </style> </head> <body> <nav class=" bg-gray-600 p-10"> <ul class="flex flex-row justify-between"> <a class="hover:text-white" href="/isTriangle.html"><li>isTriangle?</li></a> <a class="hover:text-white text-white" href="/quiz.html"><li>Quiz</li></a> <a class="hover:text-white " href="/hypotenuse.html"><li>Hypotenuse</li> <a class="hover:text-white" href="/index.html"><li>Area of Triangle</li></a> </ul> </nav> <div class="border-4 border-blue-500"> <h1 class="text-center font-extrabold h-6">Quiz on triangles</h1> <h2 class="text-center font-semibold">For each correct answer you will get 1 point</h2> <form id="quizForm"> <ol> <li class="bg-emerald-200 m-4 p-5"> <p> What is the third angle for the triangle where angle1 = 45° and angle2 = 45°?</p><br> <p class="mr-3"><input type="radio" name="q1" value="45°">45°</p> <p class="mr-3"><input type="radio" name="q1" value="90°">90°</p> <p class="mr-3"><input type="radio" name="q1" value="60°">60°</p> </li> <li class="bg-emerald-200 m-4 p-5"> <p> If a triangle has an angle of 90 degrees, what is it called?</p><br> <p class="mr-3"><input type="radio" name="q2" value="obtuse">obtuse</p> <p class="mr-3"><input type="radio" name="q2" value="acute">acute</p> <p class="mr-3"><input type="radio" name="q2" value="right-angled">right-angled</p> </li> <li class="bg-emerald-200 m-4 p-5"> <p> What type of triangle has 3 equal sides and 3 equal angles that measure 60°</p><br> <p class="mr-3"><input type="radio" name="q3" value="Equilateral">Equilateral</p> <p class="mr-3"><input type="radio" name="q3" value="acute">acute</p> <p class="mr-3"><input type="radio" name="q3" value="right-angled">right-angled</p> </li> <li class="bg-emerald-200 m-4 p-5"> <p> A right triangle is a triangle that has one 90 degree angle.</p><br> <p class="mr-3"><input type="radio" name="q4" value="True">True</p> <p class="mr-3"><input type="radio" name="q4" value="False">False</p> <p class="mr-3"><input type="radio" name="q4" value="Can't Say">Can't Say</p> </li> <li class="bg-emerald-200 m-4 p-5"> <p> What is an isosceles triangle?</p><br> <p class="mr-3"><input type="radio" name="q5" value="A triangle with 3 equal sides">A triangle with 3 equal sides</p> <p class="mr-3"><input type="radio" name="q5" value="A triangle with 2 equal sides">A triangle with 2 equal sides</p> <p class="mr-3"><input type="radio" name="q5" value="A triangle with no equal sides">A triangle with no equal sides</p> </li> </ol> <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-3 rounded m-auto" id="submit">Submit</button> <div class="m-5 bg-amber-200 " id="output"></div> </form> </div> <script> const correctAnswers=['90°','right-angled','Equilateral','True','A triangle with 2 equal sides'] let submit=document.getElementById('submit') let output=document.getElementById('output') submit.addEventListener('click',function(){ let score=0; let index=0; const data = new FormData(quizForm); for(let entry of data.values()){ if(entry==correctAnswers[index]){ score+=1; } index+=1; } if(score<3){ output.style.color="red" output.innerText="Your Score is "+ " "+ score; } else{ output.style.color="green" output.innerText="Your Score is "+ " "+ score; } event.preventDefault(); }) </script> </body> </html>
from dataclasses import dataclass import logging print("Hello world") @dataclass class MyData: name: str age: int data = MyData( name="lister", age=18 ) logging.warning(data) def Fibonacci(n): if n<= 0: print("Incorrect input") # First Fibonacci number is 0 elif n == 1: return 0 # Second Fibonacci number is 1 elif n == 2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program print(Fibonacci(10)) def fib(n, a = 0, b = 1): if n == 0: return a if n == 1: return b return fib(n - 1, b, a + b); # Driver Code n = 9; print("fib("+str(n)+") = "+str(fib(n))) import time as tt def func(): num = 0 for i in range(10): num += i return num def main(): return func() + func() + func() + func() + func() + func() + func() t1 = tt.time() main() print("Time taken: {}".format(tt.time() - t1)) # 9.05990e-6 def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global(): global spam spam = "global spam" spam = "test spam" do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam) class MyClass: """A simple example class""" i = 12345 def f(self): return f'hello world {self.i}' my = MyClass() print(my.i) print(my.__doc__) print(my.f())
package com.knowledgegraph.neo4j.domain; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.knowledgegraph.common.annotation.Excel; import com.knowledgegraph.common.core.domain.BaseEntity; /** * 申请审核对象 graph_apply * * @author liaoquefei * @date 2022-04-11 */ public class GraphApply extends BaseEntity { private static final long serialVersionUID = 1L; /** 申请主键 */ private String applyKey; /** 申请人 */ @Excel(name = "申请人") private String applyUserName; private String applyUser; /** 申请图 */ @Excel(name = "申请图") private String graphName; private String graphKey; /** 申请时间 */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "申请时间", width = 30, dateFormat = "yyyy-MM-dd") private Date applyTime; /** 申请备注 */ @Excel(name = "申请备注") private String applyRemark; /** 审核状态 */ @Excel(name = "审核状态") private String applySign; /** 审核结果 */ @Excel(name = "审核结果") private String applyFlag; /** 审核时间 */ @JsonFormat(pattern = "yyyy-MM-dd") @Excel(name = "审核时间", width = 30, dateFormat = "yyyy-MM-dd") private Date examineTime; /** 审核意见 */ @Excel(name = "审核意见") private String examineRemark; /** $column.columnComment */ private String deleteFlag; public void setApplyKey(String applyKey) { this.applyKey = applyKey; } public String getApplyKey() { return applyKey; } public void setApplyUser(String applyUser) { this.applyUser = applyUser; } public String getApplyUser() { return applyUser; } public void setGraphKey(String graphKey) { this.graphKey = graphKey; } public String getGraphKey() { return graphKey; } public void setApplyTime(Date applyTime) { this.applyTime = applyTime; } public Date getApplyTime() { return applyTime; } public void setApplyRemark(String applyRemark) { this.applyRemark = applyRemark; } public String getApplyRemark() { return applyRemark; } public void setApplySign(String applySign) { this.applySign = applySign; } public String getApplySign() { return applySign; } public void setApplyFlag(String applyFlag) { this.applyFlag = applyFlag; } public String getApplyFlag() { return applyFlag; } public void setExamineTime(Date examineTime) { this.examineTime = examineTime; } public Date getExamineTime() { return examineTime; } public void setExamineRemark(String examineRemark) { this.examineRemark = examineRemark; } public String getExamineRemark() { return examineRemark; } public void setDeleteFlag(String deleteFlag) { this.deleteFlag = deleteFlag; } public String getDeleteFlag() { return deleteFlag; } public String getApplyUserName() { return applyUserName; } public void setApplyUserName(String applyUserName) { this.applyUserName = applyUserName; } public String getGraphName() { return graphName; } public void setGraphName(String graphName) { this.graphName = graphName; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("applyKey", getApplyKey()) .append("applyUser", getApplyUser()) .append("graphKey", getGraphKey()) .append("applyUserName", getApplyUserName()) .append("graphName", getGraphName()) .append("applyTime", getApplyTime()) .append("applyRemark", getApplyRemark()) .append("applySign", getApplySign()) .append("applyFlag", getApplyFlag()) .append("examineTime", getExamineTime()) .append("examineRemark", getExamineRemark()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("deleteFlag", getDeleteFlag()) .toString(); } }
# hp_4.py # from datetime import datetime, timedelta from csv import DictReader, DictWriter from collections import defaultdict def reformat_dates(old_dates): """Accepts a list of date strings in format yyyy-mm-dd, re-formats each element to a format dd mmm yyyy--01 Jan 2001.""" dates_new = [datetime.strptime(old_, "%Y-%m-%d").strftime('%d %b %Y') for old_ in old_dates] return dates_new def date_range(start, n): """For input date string `start`, with format 'yyyy-mm-dd', returns a list of of `n` datetime objects starting at `start` where each element in the list is one day after the previous.""" if not isinstance(start, str) or not isinstance(n, int): raise TypeError() return_outpt = [] # returning the empty list called return_outpt dew = datetime.strptime(start, '%Y-%m-%d') for i in range(n): return_outpt.append(dew + timedelta(days=i)) return return_outpt def add_date_range(values, start_date): """Adds a daily date range to the list `values` beginning with `start_date`. The date, value pairs are returned as tuples in the returned list.""" bc = date_range(start_date, len(values)) z = list(zip(bc, values)) #creating list called and using zipping function return z def UtilityMethod(infile): headSet = ("book_uid,isbn_13,patron_id,date_checkout,date_due,date_returned". split(',')) #creating variable called headSet by using split function of "," with open(infile, 'r') as f: rhdr = DictReader(f, fieldnames=headSet) alltherestrows = [row for row in rhdr] alltherestrows.pop(0) return alltherestrows def fees_report(infile, outfile): """Calculates late fees per patron id and writes a summary report to outfile.""" frmt = '%m/%d/%Y' rows = UtilityMethod(infile) fees_of = defaultdict(float) for single_each_line in rows: patron = single_each_line['patron_id'] lastdate = datetime.strptime(single_each_line['date_due'], frmt) returned_date = datetime.strptime(single_each_line['date_returned'], frmt) dos = (returned_date - lastdate).days fees_of[patron] += 0.25 * dos if dos > 0 else 0.0 final_out = [ {'patron_id': pn, 'late_fees': f'{fs:0.2f}'} for pn, fs in fees_of.items() ] with open(outfile, 'w') as wrt: #opening the file using writing function docrr = DictWriter(wrt, ['patron_id', 'late_fees']) docrr.writeheader() docrr.writerows(final_out) # The following main selection block will only run when you choose # "Run -> Module" in IDLE. Use this section to run test code. The # template code below tests the fees_report function. # # Use the get_data_file_path function to get the full path of any file # under the data directory. if __name__ == '__main__': try: from src.util import get_data_file_path except ImportError: from util import get_data_file_path # BOOK_RETURNS_PATH = get_data_file_path('book_returns.csv') BOOK_RETURNS_PATH = get_data_file_path('book_returns_short.csv') OUTFILE = 'book_fees.csv' fees_report(BOOK_RETURNS_PATH, OUTFILE) # Print the data written to the outfile with open(OUTFILE) as f: print(f.read())
import Shader from "../../shaders/Shader"; import GLInstance from "../../GLInstance"; export class TexturedModelShader extends Shader { mainTexture: WebGLTexture = -1 constructor(gl:GLInstance,pMatrix:Float32Array){ super(gl,vertexShaderGLSL, fragmentShaderGLSL) let glContext = gl.glContext this.setPerspective(pMatrix) glContext.useProgram(null) } setTexture(texture:WebGLTexture) { this.mainTexture = texture return this } preRender() { let glContext = this.gl.glContext glContext.activeTexture(glContext.TEXTURE0) glContext.bindTexture(glContext.TEXTURE_2D,this.mainTexture) glContext.uniform1i(this.uniformLoc.mainTexture, 0) return this } } let vertexShaderGLSL = `#version 300 es in vec4 a_position; //Standard position data. in vec3 a_norm; in vec2 a_uv; uniform mat4 uPMatrix; uniform mat4 uMVMatrix; uniform mat4 uCameraMatrix; out highp vec2 texCoord; void main(void) { texCoord = a_uv; gl_Position = uPMatrix * uCameraMatrix * uMVMatrix * vec4(a_position.xyz, 1.0); } ` let fragmentShaderGLSL = `#version 300 es precision mediump float; in highp vec2 texCoord; uniform sampler2D uMainTex; out vec4 finalColor; void main(void) { finalColor = texture(uMainTex,vec2(texCoord.s, texCoord.t)); } `
package cc.ArraysAndStrings; import java.util.Comparator; import java.util.PriorityQueue; //1167. Minimum Cost to Connect Sticks public class MinimumCosttoConnectSticks { public int connectSticks(int[] sticks) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }); for(int stick: sticks){ pq.offer(stick); } int rst = 0; while(pq.size() > 1){ int i1 = pq.poll(); int i2 = pq.poll(); rst += i1 + i2; pq.offer(i1 + i2); } return rst; } public static void main(String[] args) { int[] sticks = { 2,4,3 }; MinimumCosttoConnectSticks minimumCosttoConnectSticks = new MinimumCosttoConnectSticks(); int rst = minimumCosttoConnectSticks.connectSticks(sticks); System.out.println(rst); } }
/* GStreamer Adaptive Multi-Rate parser plugin * Copyright (C) 2006 Edgard Lima <edgard.lima@indt.org.br> * Copyright (C) 2008 Nokia Corporation. All rights reserved. * * Contact: Stefan Kost <stefan.kost@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301, USA. */ /** * SECTION:element-amrparse * @short_description: AMR parser * @see_also: #GstAmrnbDec, #GstAmrnbEnc * * This is an AMR parser capable of handling both narrow-band and wideband * formats. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch-1.0 filesrc location=abc.amr ! amrparse ! amrdec ! audioresample ! audioconvert ! alsasink * ]| * </refsect2> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #include "gstamrparse.h" #include <gst/pbutils/pbutils.h> static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/AMR, " "rate = (int) 8000, " "channels = (int) 1;" "audio/AMR-WB, " "rate = (int) 16000, " "channels = (int) 1;") ); static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS ("audio/x-amr-nb-sh; audio/x-amr-wb-sh")); GST_DEBUG_CATEGORY_STATIC (amrparse_debug); #define GST_CAT_DEFAULT amrparse_debug static const gint block_size_nb[16] = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 }; static const gint block_size_wb[16] = { 17, 23, 32, 36, 40, 46, 50, 58, 60, 5, -1, -1, -1, -1, 0, 0 }; /* AMR has a "hardcoded" framerate of 50fps */ #define AMR_FRAMES_PER_SECOND 50 #define AMR_FRAME_DURATION (GST_SECOND/AMR_FRAMES_PER_SECOND) #ifdef GST_EXT_AMRPARSER_MODIFICATION /* added to include amrnb header size */ #define AMR_MIME_HEADER_SIZE 6 #else #define AMR_MIME_HEADER_SIZE 9 #endif static gboolean gst_amr_parse_start (GstBaseParse * parse); static gboolean gst_amr_parse_stop (GstBaseParse * parse); static gboolean gst_amr_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps); static GstCaps *gst_amr_parse_sink_getcaps (GstBaseParse * parse, GstCaps * filter); static GstFlowReturn gst_amr_parse_handle_frame (GstBaseParse * parse, GstBaseParseFrame * frame, gint * skipsize); static GstFlowReturn gst_amr_parse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame); #ifdef GST_EXT_AMRPARSER_MODIFICATION /* make full amr index table when seek */ #define AMR_MAX_PULL_RANGE_BUF (5 * 1024 * 1024) /* 5 mbyte */ static gboolean gst_amr_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event); #define gst_amr_parse_parent_class parent_class #endif G_DEFINE_TYPE (GstAmrParse, gst_amr_parse, GST_TYPE_BASE_PARSE); /** * gst_amr_parse_class_init: * @klass: GstAmrParseClass. * */ static void gst_amr_parse_class_init (GstAmrParseClass * klass) { GstElementClass *element_class = GST_ELEMENT_CLASS (klass); GstBaseParseClass *parse_class = GST_BASE_PARSE_CLASS (klass); GST_DEBUG_CATEGORY_INIT (amrparse_debug, "amrparse", 0, "AMR-NB audio stream parser"); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&sink_template)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&src_template)); gst_element_class_set_static_metadata (element_class, "AMR audio stream parser", "Codec/Parser/Audio", "Adaptive Multi-Rate audio parser", "Ronald Bultje <rbultje@ronald.bitfreak.net>"); parse_class->start = GST_DEBUG_FUNCPTR (gst_amr_parse_start); parse_class->stop = GST_DEBUG_FUNCPTR (gst_amr_parse_stop); parse_class->set_sink_caps = GST_DEBUG_FUNCPTR (gst_amr_parse_sink_setcaps); parse_class->get_sink_caps = GST_DEBUG_FUNCPTR (gst_amr_parse_sink_getcaps); parse_class->handle_frame = GST_DEBUG_FUNCPTR (gst_amr_parse_handle_frame); parse_class->pre_push_frame = GST_DEBUG_FUNCPTR (gst_amr_parse_pre_push_frame); #ifdef GST_EXT_AMRPARSER_MODIFICATION /* make full amr index table when seek */ parse_class->src_event = GST_DEBUG_FUNCPTR (gst_amr_parse_src_eventfunc); #endif } /** * gst_amr_parse_init: * @amrparse: #GstAmrParse * @klass: #GstAmrParseClass. * */ static void gst_amr_parse_init (GstAmrParse * amrparse) { /* init rest */ gst_base_parse_set_min_frame_size (GST_BASE_PARSE (amrparse), 62); GST_DEBUG ("initialized"); GST_PAD_SET_ACCEPT_INTERSECT (GST_BASE_PARSE_SINK_PAD (amrparse)); } /** * gst_amr_parse_set_src_caps: * @amrparse: #GstAmrParse. * * Set source pad caps according to current knowledge about the * audio stream. * * Returns: TRUE if caps were successfully set. */ static gboolean gst_amr_parse_set_src_caps (GstAmrParse * amrparse) { GstCaps *src_caps = NULL; gboolean res = FALSE; if (amrparse->wide) { GST_DEBUG_OBJECT (amrparse, "setting srcpad caps to AMR-WB"); src_caps = gst_caps_new_simple ("audio/AMR-WB", "channels", G_TYPE_INT, 1, "rate", G_TYPE_INT, 16000, NULL); } else { GST_DEBUG_OBJECT (amrparse, "setting srcpad caps to AMR-NB"); /* Max. size of NB frame is 31 bytes, so we can set the min. frame size to 32 (+1 for next frame header) */ gst_base_parse_set_min_frame_size (GST_BASE_PARSE (amrparse), 32); src_caps = gst_caps_new_simple ("audio/AMR", "channels", G_TYPE_INT, 1, "rate", G_TYPE_INT, 8000, NULL); } gst_pad_use_fixed_caps (GST_BASE_PARSE (amrparse)->srcpad); res = gst_pad_set_caps (GST_BASE_PARSE (amrparse)->srcpad, src_caps); gst_caps_unref (src_caps); return res; } /** * gst_amr_parse_sink_setcaps: * @sinkpad: GstPad * @caps: GstCaps * * Returns: TRUE on success. */ static gboolean gst_amr_parse_sink_setcaps (GstBaseParse * parse, GstCaps * caps) { GstAmrParse *amrparse; GstStructure *structure; const gchar *name; amrparse = GST_AMR_PARSE (parse); structure = gst_caps_get_structure (caps, 0); name = gst_structure_get_name (structure); GST_DEBUG_OBJECT (amrparse, "setcaps: %s", name); if (!strncmp (name, "audio/x-amr-wb-sh", 17)) { amrparse->block_size = block_size_wb; amrparse->wide = 1; } else if (!strncmp (name, "audio/x-amr-nb-sh", 17)) { amrparse->block_size = block_size_nb; amrparse->wide = 0; } else { GST_WARNING ("Unknown caps"); return FALSE; } amrparse->need_header = FALSE; gst_base_parse_set_frame_rate (GST_BASE_PARSE (amrparse), 50, 1, 2, 2); gst_amr_parse_set_src_caps (amrparse); return TRUE; } /** * gst_amr_parse_parse_header: * @amrparse: #GstAmrParse * @data: Header data to be parsed. * @skipsize: Output argument where the frame size will be stored. * * Check if the given data contains an AMR mime header. * * Returns: TRUE on success. */ static gboolean gst_amr_parse_parse_header (GstAmrParse * amrparse, const guint8 * data, gint * skipsize) { GST_DEBUG_OBJECT (amrparse, "Parsing header data"); if (!memcmp (data, "#!AMR-WB\n", 9)) { GST_DEBUG_OBJECT (amrparse, "AMR-WB detected"); amrparse->block_size = block_size_wb; amrparse->wide = TRUE; *skipsize = amrparse->header = 9; } else if (!memcmp (data, "#!AMR\n", 6)) { GST_DEBUG_OBJECT (amrparse, "AMR-NB detected"); amrparse->block_size = block_size_nb; amrparse->wide = FALSE; *skipsize = amrparse->header = 6; } else return FALSE; gst_amr_parse_set_src_caps (amrparse); return TRUE; } /** * gst_amr_parse_check_valid_frame: * @parse: #GstBaseParse. * @buffer: #GstBuffer. * @framesize: Output variable where the found frame size is put. * @skipsize: Output variable which tells how much data needs to be skipped * until a frame header is found. * * Implementation of "check_valid_frame" vmethod in #GstBaseParse class. * * Returns: TRUE if the given data contains valid frame. */ static GstFlowReturn gst_amr_parse_handle_frame (GstBaseParse * parse, GstBaseParseFrame * frame, gint * skipsize) { GstBuffer *buffer; GstMapInfo map; gint fsize = 0, mode, dsize; GstAmrParse *amrparse; GstFlowReturn ret = GST_FLOW_OK; gboolean found = FALSE; amrparse = GST_AMR_PARSE (parse); buffer = frame->buffer; gst_buffer_map (buffer, &map, GST_MAP_READ); dsize = map.size; GST_LOG ("buffer: %d bytes", dsize); if (amrparse->need_header) { if (dsize >= AMR_MIME_HEADER_SIZE && gst_amr_parse_parse_header (amrparse, map.data, skipsize)) { amrparse->need_header = FALSE; gst_base_parse_set_frame_rate (GST_BASE_PARSE (amrparse), 50, 1, 2, 2); } else { GST_WARNING ("media doesn't look like a AMR format"); } /* We return FALSE, so this frame won't get pushed forward. Instead, the "skip" value is set, so next time we will receive a valid frame. */ goto done; } *skipsize = 1; /* Does this look like a possible frame header candidate? */ if ((map.data[0] & 0x83) == 0) { /* Yep. Retrieve the frame size */ mode = (map.data[0] >> 3) & 0x0F; fsize = amrparse->block_size[mode] + 1; /* +1 for the header byte */ /* We recognize this data as a valid frame when: * - We are in sync. There is no need for extra checks then * - We are in EOS. There might not be enough data to check next frame * - Sync is lost, but the following data after this frame seem * to contain a valid header as well (and there is enough data to * perform this check) */ if (fsize) { *skipsize = 0; /* in sync, no further check */ if (!GST_BASE_PARSE_LOST_SYNC (parse)) { found = TRUE; } else if (dsize > fsize) { /* enough data, check for next sync */ if ((map.data[fsize] & 0x83) == 0) found = TRUE; } else if (GST_BASE_PARSE_DRAINING (parse)) { /* not enough, but draining, so ok */ found = TRUE; } } } done: gst_buffer_unmap (buffer, &map); if (found && fsize <= map.size) { ret = gst_base_parse_finish_frame (parse, frame, fsize); } return ret; } /** * gst_amr_parse_start: * @parse: #GstBaseParse. * * Implementation of "start" vmethod in #GstBaseParse class. * * Returns: TRUE on success. */ static gboolean gst_amr_parse_start (GstBaseParse * parse) { GstAmrParse *amrparse; amrparse = GST_AMR_PARSE (parse); GST_DEBUG ("start"); amrparse->need_header = TRUE; amrparse->header = 0; amrparse->sent_codec_tag = FALSE; return TRUE; } /** * gst_amr_parse_stop: * @parse: #GstBaseParse. * * Implementation of "stop" vmethod in #GstBaseParse class. * * Returns: TRUE on success. */ static gboolean gst_amr_parse_stop (GstBaseParse * parse) { GstAmrParse *amrparse; amrparse = GST_AMR_PARSE (parse); GST_DEBUG ("stop"); amrparse->need_header = TRUE; amrparse->header = 0; return TRUE; } static GstCaps * gst_amr_parse_sink_getcaps (GstBaseParse * parse, GstCaps * filter) { GstCaps *peercaps, *templ; GstCaps *res; templ = gst_pad_get_pad_template_caps (GST_BASE_PARSE_SINK_PAD (parse)); peercaps = gst_pad_peer_query_caps (GST_BASE_PARSE_SRC_PAD (parse), filter); if (peercaps) { guint i, n; /* Rename structure names */ peercaps = gst_caps_make_writable (peercaps); n = gst_caps_get_size (peercaps); for (i = 0; i < n; i++) { GstStructure *s = gst_caps_get_structure (peercaps, i); if (gst_structure_has_name (s, "audio/AMR")) gst_structure_set_name (s, "audio/x-amr-nb-sh"); else gst_structure_set_name (s, "audio/x-amr-wb-sh"); } res = gst_caps_intersect_full (peercaps, templ, GST_CAPS_INTERSECT_FIRST); gst_caps_unref (peercaps); res = gst_caps_make_writable (res); /* Append the template caps because we still want to accept * caps without any fields in the case upstream does not * know anything. */ gst_caps_append (res, templ); } else { res = templ; } if (filter) { GstCaps *intersection; intersection = gst_caps_intersect_full (filter, res, GST_CAPS_INTERSECT_FIRST); gst_caps_unref (res); res = intersection; } return res; } static GstFlowReturn gst_amr_parse_pre_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame) { GstAmrParse *amrparse = GST_AMR_PARSE (parse); if (!amrparse->sent_codec_tag) { GstTagList *taglist; GstCaps *caps; taglist = gst_tag_list_new_empty (); /* codec tag */ caps = gst_pad_get_current_caps (GST_BASE_PARSE_SRC_PAD (parse)); gst_pb_utils_add_codec_description_to_tag_list (taglist, GST_TAG_AUDIO_CODEC, caps); gst_caps_unref (caps); gst_pad_push_event (GST_BASE_PARSE_SRC_PAD (amrparse), gst_event_new_tag (taglist)); /* also signals the end of first-frame processing */ amrparse->sent_codec_tag = TRUE; } return GST_FLOW_OK; } #ifdef GST_EXT_AMRPARSER_MODIFICATION /* make full amr index table when seek */ /** * gst_amr_parse_src_eventfunc: * @parse: #GstBaseParse. #event * * before baseparse handles seek event, make full amr index table. * * Returns: TRUE on success. */ static gboolean gst_amr_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event) { gboolean handled = FALSE; GstAmrParse *amrparse; amrparse = GST_AMR_PARSE (parse); switch (GST_EVENT_TYPE (event)) { case GST_EVENT_SEEK: { GstFlowReturn res = GST_FLOW_OK; gint64 base_offset = 0, sync_offset = 0, cur = 0; gint32 frame_count = 1; /* do not add first frame because it is already in index table */ gint64 total_file_size = 0, start_offset = 0; GstClockTime current_ts = GST_CLOCK_TIME_NONE; GstPadMode pad_mode = GST_PAD_MODE_NONE; #ifdef GST_EXT_BASEPARSER_MODIFICATION /* check baseparse define these fuction */ gst_base_parse_get_pad_mode (parse, &pad_mode); if (pad_mode != GST_PAD_MODE_PULL) { GST_INFO_OBJECT (amrparse, "amr parser is not pull mode. amr parser can not make index table."); return FALSE; } gst_base_parse_get_upstream_size (parse, &total_file_size); gst_base_parse_get_index_last_offset (parse, &start_offset); gst_base_parse_get_index_last_ts (parse, &current_ts); #else GST_WARNING_OBJECT (amrparse, "baseparser does not define get private param functions. can not make index table here."); break; #endif GST_LOG_OBJECT (amrparse, "gst_amr_parse_src_eventfunc GST_EVENT_SEEK enter"); if (total_file_size == 0 || start_offset >= total_file_size) { GST_ERROR ("last index offset %d is larger than file size %d", start_offset, total_file_size); break; } gst_event_parse_seek (event, NULL, NULL, NULL, NULL, &cur, NULL, NULL); if (cur <= current_ts) { GST_INFO_OBJECT (amrparse, "seek to %"GST_TIME_FORMAT" within index table %"GST_TIME_FORMAT". do not make index table", GST_TIME_ARGS(cur), GST_TIME_ARGS(current_ts)); break; } else { GST_INFO_OBJECT (amrparse, "seek to %"GST_TIME_FORMAT" without index table %"GST_TIME_FORMAT". make index table", GST_TIME_ARGS(cur), GST_TIME_ARGS(current_ts)); } GST_INFO_OBJECT (amrparse, "make AMR Index Table. file_size = %"G_GINT64_FORMAT" last idx offset=%"G_GINT64_FORMAT ", last idx ts=%"GST_TIME_FORMAT, total_file_size, start_offset, GST_TIME_ARGS(current_ts)); base_offset = start_offset; /* set base by start offset */ /************************************/ /* STEP 1: MAX_PULL_RANGE_BUF cycle */ /************************************/ while (total_file_size - base_offset >= AMR_MAX_PULL_RANGE_BUF) { gint64 offset = 0; GstBuffer *buffer = NULL; guint8 *buf = NULL; GstMapInfo map; GST_INFO_OBJECT (amrparse, "gst_pad_pull_range %d bytes (from %"G_GINT64_FORMAT") use max size", AMR_MAX_PULL_RANGE_BUF, base_offset); res = gst_pad_pull_range (parse->sinkpad, base_offset, base_offset + AMR_MAX_PULL_RANGE_BUF, &buffer); if (res != GST_FLOW_OK) { GST_ERROR_OBJECT (amrparse, "gst_pad_pull_range failed!"); break; } gst_buffer_map (buffer, &map, GST_MAP_READ); buf = map.data; if (buf == NULL) { gst_buffer_unmap (buffer, &map); GST_WARNING ("buffer is NULL in make amr seek table's STEP1"); gst_buffer_unref (buffer); goto amr_seek_null_exit; } while (offset <= AMR_MAX_PULL_RANGE_BUF) { gint mode = 0, frame_size = 0; if ((buf[offset] & 0x83) == 0) { mode = (buf[offset] >> 3) & 0x0F; frame_size = amrparse->block_size[mode] + 1; /* +1 for the header byte */ if (frame_size < 13) { GST_WARNING_OBJECT (amrparse, "frame_size is Invalid (%d) - seek event END at offset %"G_GINT64_FORMAT"", frame_size, base_offset + offset); break; } if (frame_count % 50 == 0) { /* 1 sec == 50 frames. we make idx per sec */ gst_base_parse_add_index_entry (parse, base_offset +offset, current_ts, TRUE, TRUE); /* force */ GST_DEBUG_OBJECT (amrparse, "Adding index ts=%"GST_TIME_FORMAT" offset %"G_GINT64_FORMAT, GST_TIME_ARGS(current_ts), base_offset + offset); } current_ts += 20 * 1000 * 1000; /* each frame is 20ms */ offset += frame_size; frame_count++; } else { GST_WARNING_OBJECT (amrparse, "we lost sync"); offset++; } } /* while */ base_offset = base_offset + offset; gst_buffer_unref (buffer); } /* end MAX buffer cycle */ /*******************************/ /* STEP 2: Remain Buffer cycle */ /*******************************/ if (total_file_size - base_offset > 0) { gint64 offset = 0; GstBuffer *buffer = NULL; guint8 *buf = NULL; GstMapInfo map; GST_INFO_OBJECT (amrparse, "gst_pad_pull_range %"G_GINT64_FORMAT" bytes (from %"G_GINT64_FORMAT") use remain_buf size", total_file_size - base_offset, base_offset); res = gst_pad_pull_range (parse->sinkpad, base_offset, total_file_size, &buffer); if (res != GST_FLOW_OK) { GST_ERROR ("gst_pad_pull_range failed!"); break; } gst_buffer_map (buffer, &map, GST_MAP_READ); buf = map.data; if (buf == NULL) { gst_buffer_unmap (buffer, &map); GST_WARNING ("buffer is NULL in make amr seek table's STEP2"); gst_buffer_unref (buffer); goto amr_seek_null_exit; } while (base_offset + offset < total_file_size) { gint mode = 0, frame_size = 0; if ((buf[offset] & 0x83) == 0) { mode = (buf[offset] >> 3) & 0x0F; frame_size = amrparse->block_size[mode] + 1; /* +1 for the header byte */ if (frame_size < 13) { GST_WARNING_OBJECT (amrparse, "frame_size is Invalid (%d) - seek event END at offset %"G_GINT64_FORMAT"", frame_size, base_offset + offset); break; } if (frame_count % 50 == 0) { /* 1 sec == 50 frames. we make idx per sec */ gst_base_parse_add_index_entry (parse, base_offset +offset, current_ts, TRUE, TRUE); /* force */ GST_DEBUG_OBJECT (amrparse, "Adding index ts=%"GST_TIME_FORMAT" offset %"G_GINT64_FORMAT, GST_TIME_ARGS(current_ts), base_offset + offset); } current_ts += 20 * 1000 * 1000; /* each frame is 20ms */ offset += frame_size; frame_count++; } else { GST_WARNING_OBJECT (amrparse, "we lost sync"); offset++; } } /* while */ gst_buffer_unref (buffer); } /* end remain_buf buffer cycle */ GST_LOG_OBJECT (amrparse, "gst_amr_parse_src_eventfunc GST_EVENT_SEEK leave"); } break; default: break; } amr_seek_null_exit: /* call baseparse src_event function to handle event */ handled = GST_BASE_PARSE_CLASS (parent_class)->src_event (parse, event); return handled; } #endif
import { createInjector, destroyInjector } from '@spryker-oryx/di'; import { IndexedDbService } from '@spryker-oryx/indexed-db'; import { nextTick } from '@spryker-oryx/utilities'; import { Table } from 'dexie'; import { of } from 'rxjs'; import { SyncStatus } from '../models'; import { SyncActionRegistryService } from './sync-action-registry.service'; import { SyncExecutorDefaultService } from './sync-executor-default.service'; import { SyncExecutorService } from './sync-executor.service'; import { SyncSchedulerService } from './sync-scheduler.service'; const mockError = String( new Error('SyncExecutorDefaultService: Could not complete Sync(123)!') ); export const mockSync = { action: 'mock' as any, id: 123, prevSyncIds: [], status: SyncStatus.Processing, payload: {} as any, scheduledAt: new Date(), retries: 0, errors: [], whenCompleted: vi.fn(), cancel: vi.fn(), handleSync: vi.fn().mockReturnValue(of(undefined)), isSyncing: vi.fn().mockReturnValue(of(false)), }; class MockIndexedDbService implements Partial<IndexedDbService> { getStore = vi.fn().mockImplementation(() => of(mockTable)); } class MockTable implements Partial<Table> { update = vi.fn().mockReturnValue(mockSync); } const mockTable = new MockTable(); class MockSyncSchedulerService implements Partial<SyncSchedulerService> { getPending = vi.fn().mockReturnValue(of([mockSync])); } class MockSyncActionRegistryService implements Partial<SyncActionRegistryService> { handleSync = vi.fn().mockReturnValue(of(undefined)); } describe('SyncExecutorDefaultService', () => { let service: SyncExecutorService; let syncScheduler: MockSyncSchedulerService; let syncActionRegistry: MockSyncActionRegistryService; beforeEach(() => { const testInjector = createInjector({ providers: [ { provide: SyncExecutorService, useClass: SyncExecutorDefaultService, }, { provide: IndexedDbService, useClass: MockIndexedDbService, }, { provide: SyncActionRegistryService, useClass: MockSyncActionRegistryService, }, { provide: SyncSchedulerService, useClass: MockSyncSchedulerService, }, ], }); service = testInjector.inject(SyncExecutorService); syncScheduler = testInjector.inject( SyncSchedulerService ) as unknown as MockSyncSchedulerService; syncActionRegistry = testInjector.inject( SyncActionRegistryService ) as unknown as MockSyncActionRegistryService; }); afterEach(() => { vi.clearAllMocks(); destroyInjector(); }); it('should be provided', () => { expect(service).toBeInstanceOf(SyncExecutorDefaultService); }); describe('when processing', () => { const callback = vi.fn(); it('should call SyncSchedulerService', () => { service.processPendingSyncs().subscribe(callback); expect(syncScheduler.getPending).toHaveBeenCalled(); }); describe('and there are no pending syncs', () => { beforeEach(() => { syncScheduler.getPending.mockReturnValue(of([])); service.processPendingSyncs().subscribe(callback); }); it('should return 0', () => { expect(callback).toHaveBeenCalledWith(0); }); it('should not call SyncActionRegistryService', () => { expect(syncActionRegistry.handleSync).not.toHaveBeenCalled(); }); }); describe('and there are pending syncs', () => { const date = new Date(); beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(date); }); afterEach(() => { vi.useRealTimers(); }); it('should return 1', async () => { service.processPendingSyncs().subscribe(callback); await nextTick(8); expect(callback).toHaveBeenCalledWith(1); }); it('should call SyncActionRegistryService', () => { service.processPendingSyncs().subscribe(callback); expect(syncActionRegistry.handleSync).toHaveBeenCalledWith(mockSync); }); it('should call store update', () => { service.processPendingSyncs().subscribe(callback); expect(mockTable.update).toHaveBeenCalledWith(mockSync.id, { status: SyncStatus.Completed, completedAt: date, retries: 0, }); }); describe('and store fails to update', () => { beforeEach(() => { mockTable.update.mockReturnValue(0); service.processPendingSyncs().subscribe({ error: callback }); }); it('should throw error', () => { expect(mockTable.update).toHaveBeenLastCalledWith( mockSync.id, expect.objectContaining({ status: SyncStatus.Queued, retries: 0, errors: [mockError], }) ); expect(callback).toHaveBeenCalledWith( new Error( 'SyncExecutorDefaultService: Could not update failed Sync(123)!' ) ); }); describe('and store fails to update multiple times', () => { beforeEach(() => { syncScheduler.getPending.mockReturnValue( of([ { ...mockSync, retries: 1, errors: [mockError], }, ]) ); service.processPendingSyncs().subscribe(); }); it('should increment retries', () => { expect(mockTable.update).toHaveBeenCalledWith( mockSync.id, expect.objectContaining({ retries: 2, status: SyncStatus.Completed, }) ); expect(mockTable.update).toHaveBeenLastCalledWith( mockSync.id, expect.objectContaining({ status: SyncStatus.Queued, errors: [mockError, mockError], }) ); }); }); describe('and retry limit is reached', () => { beforeEach(() => { syncScheduler.getPending.mockReturnValue( of([ { ...mockSync, retries: 3, errors: [mockError, mockError, mockError], }, ]) ); service.processPendingSyncs().subscribe(); }); it('should set status to failed', () => { expect(mockTable.update).toHaveBeenLastCalledWith( mockSync.id, expect.objectContaining({ retries: 3, status: SyncStatus.Failed, }) ); }); }); }); }); }); });
import Image from "next/image"; import LoginVector from "@/images/signupVector.png"; import Link from "next/link"; import { db } from "../firebase/config"; import { doc, setDoc, collection, addDoc } from "firebase/firestore"; import { useState } from "react"; import { createUserWithEmailAndPassword, sendEmailVerification, } from "firebase/auth"; import { auth } from "../firebase/config"; const Signup = () => { const [user, setUser] = useState({ firstName: "", lastName: "", email: "", phoneNumber: "", password: "", confirmPassword: "", }); async function handleSubmit(event) { event.preventDefault(); try { // Create the user in Firebase Authentication const { user: authUser } = await createUserWithEmailAndPassword( auth, user.email, user.password ); // Save the user information to the Firestore collection 'users' const userRef = doc(db, "users", authUser.uid); await setDoc(userRef, { firstName: user.firstName, lastName: user.lastName, email: user.email, phoneNumber: user.phoneNumber, password: user.password, }); // Send a verification email to the user await sendEmailVerification(auth.currentUser); // Reset the form and notify the user of success event.target.reset(); alert( "User added successfully! Please check your email to verify your account." ); } catch (error) { console.error("Error adding document: ", error); alert("Error adding user. Please try again." + error); } } function handleChange(event) { event.preventDefault(); const { name, value } = event.target; setUser((prevUser) => ({ ...prevUser, [name]: value, })); } return ( <> <div className="main bg-slate-300 w-full sm:h-screen h-full flex items-center justify-center"> <div className="card overflow-y-auto scrollbar-thin scrollbar-thumb-gray-500 scrollbar-track-gray-200 sm:bg-custom-blue pt bg-slate-300 w-3/4 sm:h-5/6 h-full rounded-xl flex items-center justify-center"> <div className="Ads w-1/2 h-full rounded-l-xl hidden lg:block bg-lightBlue"> <div className=" flex-col flex sm:justify-center sm:items-center h-full "> <Image src={LoginVector} alt="Example Image" width={500} height={500} />{" "} <h1 className="p-8 text-2xl font-semibold"> join now for exclusive benefits and a better experience. </h1> </div> </div> <div className="Login sm:w-1/2 w-sceen h-full flex items-center justify-center"> <section class="w-full flex items-center justify-center"> <div class=" h-full flex pt-2 justify-center "> <div class="sm:w-full w-screen flex h-5/6 items-center justify-center bg-lightBlue rounded-lg shadow dark:border md:mt-0"> <div class=" p-8 "> <h1 class="text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white"> Create a new account </h1> <form class="space-y-4 md:space-y-6" onSubmit={handleSubmit} > <div> <label for="firstName" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > first name </label> <input onChange={handleChange} type="text" name="firstName" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Ahmed" required="" /> </div> <div> <label for="lastName" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Last name </label> <input onChange={handleChange} type="text" name="lastName" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Ali" required="" /> </div> <div> <label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Your email </label> <input onChange={handleChange} type="email" name="email" id="email" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="name@company.com" required="" /> </div> <div> <label for="phoneNumber" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > phone number </label> <input onChange={handleChange} type="tel" name="phoneNumber" id="phone" placeholder="771234567" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required="" /> <label className="block mb-2 mt-4 text-sm font-medium text-gray-900 dark:text-white"> Government </label> <select // value={selectedGovernment} //onChange={handleGovernmentChange} className="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:custom-blue focus:border-custom-blue block w-full p-2.5 dark:placeholder-gray-400 focus:bg-lightBlue" required > <option value="" disabled> Select a government </option> <option value="Sana'a">Sanaa</option> <option value="Hadhramout">Hadhramout</option> <option value="Shabwa">Shabwa</option> <option value="Aden">Aden</option> <option value="Taiz">Taiz</option> </select> </div> <div className="flex sm:flex-row flex-col"> <div className="sm:pr-8"> <label for="password" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > Password </label> <input onChange={handleChange} type="password" name="password" id="password" placeholder="••••••••" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" required="" /> </div> <div> <label for="confirmPassword" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white" > confirm Password </label> <input onChange={handleChange} type="password" name="confirmPassword" id="password" placeholder="••••••••" class="bg-gray-50 border border-gray-300 text-gray-900 sm:text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 " required="" /> </div> </div> <div class="flex items-center justify-between"> <div class="flex items-start"></div> </div> <button type="submit" class="w-full text-black bg-custom-blue hover:bg-blue-500 focus:ring-4 focus:ring-blue-900 font-medium rounded-lg text-sm px-5 py-2.5 text-center" > Sign in </button> <p class="text-sm font-light text-gray-500 dark:text-gray-400"> Do you have an account?{" "} <Link href="/signup" class="font-medium text-primary-600 hover:underline dark:text-primary-500" > Login </Link> </p> </form> </div> </div> </div> </section> </div> </div> </div> </> ); }; export default Signup;
export class TodoPage { navigate(): Cypress.Chainable<Cypress.AUTWindow> { return cy.visit('https://todomvc-app-for-testing.surge.sh') } addTodo(todoText: string): Cypress.Chainable<JQuery<HTMLElement>> { return cy.get('.new-todo').type(todoText + '{enter}') } toggleTodo(todoIndex: number): Cypress.Chainable<JQuery<HTMLElement>> { return cy.get(`.todo-list li:nth-child(${todoIndex + 1}) .toggle`).click() } clearCompleted(): Cypress.Chainable<JQuery<HTMLElement>> { return cy.contains('Clear completed').click() } showOnlyCompleteTodos(): Cypress.Chainable<JQuery<HTMLElement>> { return cy.contains('Completed').click() } showOnlyActiveTodos(): Cypress.Chainable<JQuery<HTMLElement>> { return cy.contains('Active').click() } showAllTodos(): Cypress.Chainable<JQuery<HTMLElement>> { return cy.contains('All').click() } validateTodoText( todoIndex: number, expectedText: string ): Cypress.Chainable<JQuery<HTMLElement>> { return cy .get(`.todo-list li:nth-child(${todoIndex + 1}) label`) .should('have.text', expectedText) } validateToggleState( todoIndex: number, shouldBeToggled: boolean ): Cypress.Chainable<JQuery<HTMLElement>> { const label = cy .get(`.todo-list li:nth-child(${todoIndex + 1})`) .get('label') console.log(label) return label.should(`${shouldBeToggled ? '' : 'not.'}be.checked`) } validateNumberOfTodosShown( expectedNumberOfTodos: number ): Cypress.Chainable<JQuery<HTMLElement>> { return cy.get('.todo-list li').should('have.length', expectedNumberOfTodos) } validateTodoCompletedState( todoIndex: number, shouldBeCompleted: boolean ): Cypress.Chainable<JQuery<HTMLElement>> { const label = cy .get(`.todo-list li:nth-child(${todoIndex + 1})`) .get('label') return label.should( `${shouldBeCompleted ? '' : 'not.'}have.css`, 'text-decoration-line', 'line-through' ) } }
<?php namespace App\Http\Controllers\V2; use App\Actions\CancelReservation; use App\Actions\NewReservationAction; use App\Events\NewReservationCreated; use App\Http\Resources\ReservationCollection; use App\Http\Resources\ReservationResource; use App\Models\Membership; use App\Models\Reservation; use App\Models\SchoolGroup; use App\Models\Team; use App\Models\UserMembership; use App\Notifications\AddedToReservation; use App\Notifications\InvitedToReservation; use App\Notifications\ReservationCanceled; use App\Notifications\WatcherAnnounced; use Carbon\Carbon; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Spatie\QueryBuilder\AllowedFilter; use Spatie\QueryBuilder\QueryBuilder; class ReservationController extends Controller { /** * @var Membership|null */ private $active_membership = null; public function __construct() { $this->middleware('auth:api')->except('index'); } // TODO: move to middleware private function load_membership() { if (! $this->active_membership) { //load user membership $um = UserMembership::where('user_id', Auth::id())->whereHas('membership', function ($query) { $query->where('club_id', request()->get('club')->id); })->first(); if ($um) { $this->active_membership = $um->membership; } if (! $this->active_membership) { // get club basic $this->active_membership = Membership::where('club_id', request()->get('club')->id)->where('basic', 1)->first(); } } } /** * Display a listing of the resource. * * @return ReservationCollection */ public function index(Request $request) { $club = $request->get('club'); if (!$club || $club->id === 26) { $club = 0; } else { $club = $club->id; } $reservations = QueryBuilder::for(Reservation::class) ->allowedFilters([ 'name', AllowedFilter::callback('player', function ($query, $value) { $query->whereHas('game', function ($query) use ($value) { $query->whereHas('players', function ($q) use ($value) { $q->whereHas('players', function ($q) use ($value) { $q->where('player_id', $value); }); }); }); }), AllowedFilter::callback('team', function ($query, $value) { $query->whereHas('game', function ($query) use ($value) { $query->whereHas('players', function ($q) use ($value) { $q->where('user_id', $value); }); }); }), AllowedFilter::callback('club', function ($query, $value) { if ($value) { $query->whereHas('court', function ($q) use ($value) { $q->where('club_id', $value); }); } })->default($club), 'school_group_id', AllowedFilter::callback('from', function ($query, $value) { $query->whereDate('from', '>=', $value); }), AllowedFilter::callback('to', function ($query, $value) { $query->whereDate('to', '<=', $value); }), AllowedFilter::exact('court', 'court_id'), AllowedFilter::callback('canceled', function ($query, $value) { $query->onlyTrashed(); }), AllowedFilter::callback('active_between', function($query, $value) { $query->whereBetween('from', [ Carbon::parse($value[0]), Carbon::parse($value[1]??'now') ]); }), AllowedFilter::callback('category', function($query, $value) { if ($value === 'all') { return $query->whereHas('category'); } if ($value === 'none') { return $query->whereDoesntHave('category'); } $id = intval($value); if ($id) { return $query->where('category_id', $id); } return $query->whereHas('category', function($q) use ($value) { $q->where('name', 'LIKE', '%' . $value . '%'); }); }), AllowedFilter::callback('series', function($query, $value) { if ($value == 1) { return $query->whereNotNull('series'); } if ($value == 0) { return $query->whereNull('series'); } return $query->where('series', $value); }), 'status' ]) ->allowedIncludes(['attendances', 'school_group', 'payment_user', 'players.wallet', 'payments', 'school_performances']) ->orderBy('id', 'desc') ->with(['court', 'players', 'watchers']) ->paginate($request->input('limit')) ->appends($request->query()); return new ReservationCollection($reservations); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @param NewReservationAction $newReservationAction * @return ReservationCollection */ public function store(Request $request, NewReservationAction $newReservationAction) { $reservations = collect($newReservationAction->executeFromRequest($request)); return response()->json(['message' => 'success', 'reservations' => $reservations->pluck('id')]); //return ReservationCollection::make($reservations); } /** * Display the specified resource. * * @param Reservation $reservation * @return ReservationResource */ public function show($reservation) { $reservation = QueryBuilder::for(Reservation::query()->where('id', $reservation)) ->allowedIncludes(['attendances', 'school_group', 'payment_user', 'players.wallet', 'payments', 'watchers', 'court', 'school_performances']) ->with([ 'players.players.wallets', 'game.players.players.wallets','players.players.memberships', 'game.players.players.memberships']) ->first(); return new ReservationResource($reservation); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param Reservation $reservation * @return \Illuminate\Http\Response */ public function update(Request $request, Reservation $reservation) { $group = $request->input('group'); if ($request->has('name')) { $reservation->name = $request->input('name'); } if ($group && $group['id']) { $group = SchoolGroup::with(['players'])->find($group['id']); foreach ($group->players as $player) { $reservation->players()->attach($player->id, ['status' => 'player']); } $reservation->name = $group->name; $reservation->type = 'group-'.$group->id; } if ($request->has('players') && count($request->input('players'))) { $reservation_players = []; $game_players = []; foreach ($request->input('players') as $item) { if (!isset($item['id'])) { continue; } if (!isset($item['type']) || $item['type'] === 'player') { $team = Team::where('number_of_players', 1)->where('primary_contact_id', $item['id'])->first(); } else { $team = Team::find($item['id']); } $reservation_players[$team->id] = ['status' => 'player']; $game_players[$team->id] = ['player' => 1]; } $reservation->players()->sync($reservation_players); if ($reservation->game) { $reservation->game->players()->sync($game_players); } foreach ($reservation->players as $player) { foreach ($player->players as $p) { $p->notify((new AddedToReservation($reservation, \Auth::user()))->locale($p->lang)); } // \Notification::send($player->players, new AddedToReservation($reservation, \Auth::user())); } } if ($request->has('watchers') && count($request->input('watchers'))) { $players = collect($request->input('watchers'))->mapWithKeys(function ($item) { return [$item['id'] => ['status' => 'watcher']]; }); $reservation->watchers()->sync($players); foreach ($reservation->watchers() as $player) { $player->notify((new InvitedToReservation($reservation, \Auth::user()))->locale($player->lang)); } } if ($request->has('watcher')) { $reservation->watchers()->toggle($request->input('watcher.id')); $reservation->load(['watchers', 'court', 'players']); foreach ($reservation->players as $player) { foreach ($player->players as $p) { $p->notify((new WatcherAnnounced($reservation, \Auth::user()))->locale($p->lang)); } //\Notification::send($player->players, new WatcherAnnounced($reservation, \Auth::user())); } } if ($request->has('is_paid')) { if ($request->input('is_paid')) { if ($request->input('payment_invoice') && $reservation->payment_invoice !== $request->input('payment_invoice')) { $reservation->payment_invoice = $request->input('payment_invoice'); } $reservation->payment_note = $request->input('payment_note'); $reservation->payment_user_id = Auth::id(); $reservation->payment_date = Carbon::now(); } else { $reservation->payment_invoice = null; $reservation->payment_date = null; } } $reservation->save(); broadcast(new NewReservationCreated($reservation)); return ReservationResource::make($reservation); } /** * Remove the specified resource from storage. * * @param Reservation $reservation * @return \Illuminate\Http\Response */ public function destroy(Reservation $reservation, CancelReservation $cancelReservation) { $cancelReservation->execute($reservation, request()->get('club')); return response()->noContent(); } public function deleteMany(Request $request, CancelReservation $cancelReservation) { $reservations = $request->input('reservations'); foreach ($reservations as $reservation) { if ($reservation['id']) { $r = Reservation::find($reservation['id']); if ($r) { $cancelReservation->execute(Reservation::find($reservation['id']), $request->get('club')); } } } return response()->noContent(); } }
import React from "react"; import { Movies } from "../components/Movies"; import { Preloader } from "../components/preloader"; import { Search } from "../components/search"; const API_KEY =process.env.REACT_APP_API_KEY; class Main extends React.Component { state = { movies: [], whatSearch: "", type: "", loading: true, }; componentDidMount() { fetch(`https://www.omdbapi.com/?apikey=${API_KEY}&s=matrix`) .then((response) => response.json()) .then((data) => this.setState({ movies: data.Search, loading: false })) .catch((err) => { console.log(err); this.setState({loading:false}) }) } searchMovie = (kino, tip) => { this.setState({ loading: true }); fetch(`https://www.omdbapi.com/?apikey=${API_KEY}&s=${kino}&type=${tip}`) .then((response) => response.json()) .then((data) => this.setState({ movies: data.Search, loading: false })) .catch((err) => { console.log(err); this.setState({loading:false}) }) }; render() { const { movies, loading } = this.state; return ( <main className="container content"> <Search searchMovie={this.searchMovie} /> {loading ? ( <Preloader /> ):( <Movies movies={this.state.movies} /> )} </main> )} } export { Main };
// // ModifySenseSheetView.swift // Jisho // // Created by Thomas Choquet on 2022/05/04. // import SwiftUI fileprivate class ModifySenseSheetViewModel: ObservableObject { @Published var showSheet = false var sheetView:AnyView = AnyView(EmptyView()) func showSheet<Content: View>(view: Content) { sheetView = AnyView(view) showSheet.toggle() } } struct ModifySenseSheetView: View { @Environment(\.editMode) var editMode @EnvironmentObject private var settings: Settings @StateObject private var vm = ModifySenseSheetViewModel() @ObservedObject var modifiableSense: Sense var body: some View { List { Section( header: Text("MetaDatas"), footer: Button("Ajouter") { addNewMetaData() } ) { if modifiableSense.metaDatas?.isEmpty == false { metadataSection } else { Text("Pas de MetaData") } } Section( header: Text("Traductions"), footer: Button("Ajouter") { addNewTrad() } ) { if modifiableSense.traductionsArray?.isEmpty == false { traductionSection } else { Text("Pas de Traduction") } } } .navigationBarTitleDisplayMode(.inline) .sheet(isPresented: $vm.showSheet) { vm.sheetView } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } } } //MARK: Traductions Section var traductionSection: some View { ForEach(modifiableSense.traductionsArray ?? []) { trad in HStack { FlagMenuView(langue: Binding(get: { trad.langue }, set: { trad.langue = $0 }), existingLangues: Set( modifiableSense.traductionsArray?.map { $0.langue } ?? [] ) ) TextField("Traductions", text: Binding(get: { trad.traductions?.joined(separator: ", ") ?? "" }, set: { trad.traductions = $0.components(separatedBy: ", ") })) } } .onDelete(perform: deleteTrad) .onMove(perform: moveTrad) } func addNewTrad() { let newTrad = Traduction(langue: .none, traductions: nil, context: modifiableSense.context) modifiableSense.traductionsArray = (modifiableSense.traductionsArray ?? []) + [newTrad] } func deleteTrad(_ indexSet: IndexSet) { modifiableSense.traductionsArray?.remove(atOffsets: indexSet) } func moveTrad(sources: IndexSet, destination: Int) { modifiableSense.traductionsArray?.move(fromOffsets: sources, toOffset: destination) editMode?.wrappedValue = .inactive editMode?.wrappedValue = .active } //MARK: MetaDatas Section var metadataSection: some View { ForEach(Binding(get: { modifiableSense.metaDatas ?? [] }, set: { modifiableSense.metaDatas = $0 })) { $metaData in HStack { Button(metaData.description(settings.metaDataDict)) { vm.showSheet(view: MetaDataPickerSheetView(selectedMetaData: $metaData )) } } } .onDelete(perform: deleteMetaData) .onMove(perform: moveMetaData) } func addNewMetaData() { modifiableSense.metaDatas = (modifiableSense.metaDatas ?? []) + [CommunMetaData.nomCommun] } func deleteMetaData(_ indexSet: IndexSet) { modifiableSense.metaDatas?.remove(atOffsets: indexSet) } func moveMetaData(sources: IndexSet, destination: Int) { modifiableSense.metaDatas?.move(fromOffsets: sources, toOffset: destination) editMode?.wrappedValue = .inactive editMode?.wrappedValue = .active } } fileprivate struct FlagMenuView: View { // @Environment(\.languesPref) var languesPref // @Environment(\.languesAffichées) var languesAffichées @EnvironmentObject private var settings: Settings @Binding var langue: Langue var existingLangues: Set<Langue> var body: some View { let selectableOrderedLangues = Array(settings.languesAffichées).sorted(languesPref: settings.languesPref).compactMap { langue -> Langue? in if langue == .none { return nil as Langue? } else if existingLangues.contains(langue) { return nil as Langue? } else { return langue } } Menu(langue.flag) { ForEach(selectableOrderedLangues) { lang in Button("\(lang.flag) \(lang.fullName)") { langue = lang } } Button("\(Langue.none.flag) Pas de langue") { langue = .none } } } } /* struct ModifySenseSheetView_Previews: PreviewProvider { static var previews: some View { ModifySenseSheetView() } } */
//SPDX-License-Identifier: MIT pragma solidity 0.8.17; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable2Step.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // LightLink 2022 contract LLPurchase is Ownable2Step { using SafeERC20 for IERC20; struct CurrencyInfo { bool active; address currency; uint16 decimals; uint16 rate; uint256 minimumPurchase; } // variables uint16 public constant ONE_RATE = 10_000; address public llCurrency; uint256 public totalSold; mapping(address => CurrencyInfo) public currencies; // events event Purchase( address indexed user, address indexed currency, CurrencyInfo currencyInfo, uint256 currencyAmount, uint256 llAmount ); constructor() {} /** User */ function purchase(address _currency, uint256 _currencyAmount) external { CurrencyInfo storage currency = currencies[_currency]; require(currency.active, "Not active"); require(_currencyAmount >= currency.minimumPurchase, "Minimum purchase"); uint256 llDecimals = 10**18; uint256 llAmount = (_currencyAmount * ONE_RATE * llDecimals) / currency.rate; require(llAmount <= IERC20(llCurrency).balanceOf(address(this)), "Insufficient supply"); uint256 currencyAmountWithDecimals = currency.minimumPurchase * (10**currency.decimals); IERC20(_currency).safeTransferFrom(msg.sender, address(this), currencyAmountWithDecimals); IERC20(llCurrency).safeTransfer(msg.sender, llAmount); totalSold += llAmount; emit Purchase(msg.sender, _currency, currencies[_currency], currencyAmountWithDecimals, llAmount); } /** Admin */ // verified function setLLCurrency(address _address) external onlyOwner { llCurrency = _address; } // verified function setupCurrency( address _currency, uint16 _decimals, uint16 _rate, uint256 _minimumPurchase ) external onlyOwner { currencies[_currency] = CurrencyInfo(false, _currency, _decimals, _rate, _minimumPurchase); } // verified function toggleSaleActive(address _currency, bool _status) external onlyOwner { currencies[_currency].active = _status; } // verified function updateTokenDecimals(address _currency, uint16 _decimals) external onlyOwner { currencies[_currency].decimals = _decimals; } // verified function updateTokenRate(address _currency, uint16 _rate) external onlyOwner { currencies[_currency].rate = _rate; } // verified function updateTokenMinimumPurchase(address _currency, uint256 _minimumPurchase) external onlyOwner { currencies[_currency].minimumPurchase = _minimumPurchase; } // verified function withdrawERC20(address _currency, address _to) external onlyOwner { uint256 balance = IERC20(_currency).balanceOf(address(this)); IERC20(_currency).safeTransfer(_to, balance); } function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /* Internal */ function renounceOwnership() public virtual override onlyOwner { revert("Ownable: renounceOwnership function is disabled"); } }
-- 9. Get all the total revenues done by each films for each directors -- What is the first table or left table : films or directors SELECT d.first_name, d.last_name, SUM(r.revenues_domestic + r.revenues_international) AS "Total Revenues" FROM directors d LEFT JOIN movies m ON d.director_id = m.director_id LEFT JOIN movies_revenues r ON m.movie_id = r.movie_id GROUP BY d.first_name, d.last_name HAVING SUM(r.revenues_domestic + r.revenues_international) > 0 ORDER BY 3 DESC ;
import React, { useEffect, useState } from 'react' import { Provider, useSelector } from 'react-redux' function ProviderConfig() { const { rtl, isLoggedIn, topMenu, darkMode } = useSelector((state) => { return { darkMode: state.ChangeLayoutMode.data, rtl: state.ChangeLayoutMode.rtlData, topMenu: state.ChangeLayoutMode.topMenu, isLoggedIn: state.auth.login, } }) const [path, setPath] = useState(window.location.pathname) useEffect(() => { let unmounted = false if (!unmounted) { setPath(window.location.pathname) } // eslint-disable-next-line no-return-assign return () => (unmounted = true) }, [setPath]) return ( <ConfigProvider direction={rtl ? 'rtl' : 'ltr'}> <ThemeProvider theme={{ ...theme, rtl, topMenu, darkMode }}> <Router basename={process.env.PUBLIC_URL}> {!isLoggedIn ? ( <Route path="/" component={Auth} /> ) : ( <ProtectedRoute path="/admin" component={Admin} /> )} {isLoggedIn && (path === process.env.PUBLIC_URL || path === `${process.env.PUBLIC_URL}/`) && ( <Redirect to="/admin" /> )} </Router> </ThemeProvider> </ConfigProvider> ) } export default function App() { return ( <div className="test"> <p>Hi! Welcome Everyone</p> </div> ) }
<div> <h2> <span>Finansal Hareket Detays</span> <button class="btn btn-primary float-right jh-create-entity create-finansal-hareket-detay" [routerLink]="['/', { outlets: { popup: ['finansal-hareket-detay-new'] } }]"> <span class="fa fa-plus"></span> <span class="hidden-sm-down" > Create new Finansal Hareket Detay </span> </button> </h2> <jhi-alert></jhi-alert> <div class="form-group"> <label class="form-control-label" for="field_dosya">Dosya</label> <select class="form-control" id="field_dosya" name="dosya" [(ngModel)]="comboSelModel.comboSel" (change)="onChange($event)"> <option [ngValue]="null"></option> <option [ngValue]="selectedOption" *ngFor="let selectedOption of comboSelModel.comboList; trackBy: trackDosyaById">{{selectedOption.kod}}</option> </select> </div> <br/> <div class="table-responsive" *ngIf="finansalHareketDetays"> <table class="table table-striped"> <thead> <tr jhiSort [(predicate)]="predicate" [(ascending)]="reverse" [callback]="transition.bind(this)"> <th jhiSortBy="id"><span>ID</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="kod"><span>Kod</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="islemTutari"><span>Islem Tutari</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="hesapYonu"><span>Hesap Yonu</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="hesapId"><span>Hesap Id</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="karsiHesapId"><span>Karsi Hesap Id</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="finansalHareket.kod"><span>Finansal Hareket</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="dosyaBorc.kod"><span>Dosya Borc</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="dosyaBorcKalem.kod"><span>Dosya Borc Kalem</span> <span class="fa fa-sort"></span></th> <th jhiSortBy="karsiFhd.kod"><span>Karsi Fhd</span> <span class="fa fa-sort"></span></th> <th></th> </tr> </thead> <tbody> <tr *ngFor="let finansalHareketDetay of finansalHareketDetays ;trackBy: trackId"> <td><a [routerLink]="['../finansal-hareket-detay', finansalHareketDetay.id ]">{{finansalHareketDetay.id}}</a></td> <td>{{finansalHareketDetay.kod}}</td> <td>{{finansalHareketDetay.islemTutari}}</td> <td>{{finansalHareketDetay.hesapYonu}}</td> <td>{{finansalHareketDetay.hesapId}}</td> <td>{{finansalHareketDetay.karsiHesapId}}</td> <td> <div *ngIf="finansalHareketDetay.finansalHareket"> <a [routerLink]="['../finansal-hareket', finansalHareketDetay.finansalHareket?.id ]" >{{finansalHareketDetay.finansalHareket?.kod}}</a> </div> </td> <td> <div *ngIf="finansalHareketDetay.dosyaBorc"> <a [routerLink]="['../dosya-borc', finansalHareketDetay.dosyaBorc?.id ]" >{{finansalHareketDetay.dosyaBorc?.kod}}</a> </div> </td> <td> <div *ngIf="finansalHareketDetay.dosyaBorcKalem"> <a [routerLink]="['../dosya-borc-kalem', finansalHareketDetay.dosyaBorcKalem?.id ]" >{{finansalHareketDetay.dosyaBorcKalem?.kod}}</a> </div> </td> <td> <div *ngIf="finansalHareketDetay.karsiFhd"> <a [routerLink]="['../finansal-hareket-detay', finansalHareketDetay.karsiFhd?.id ]" >{{finansalHareketDetay.karsiFhd?.kod}}</a> </div> </td> <td class="text-right"> <div class="btn-group flex-btn-group-container"> <button type="submit" [routerLink]="['../finansal-hareket-detay', finansalHareketDetay.id ]" class="btn btn-info btn-sm"> <span class="fa fa-eye"></span> <span class="d-none d-md-inline">View</span> </button> <button type="submit" [routerLink]="['/', { outlets: { popup: 'finansal-hareket-detay/'+ finansalHareketDetay.id + '/edit'} }]" replaceUrl="true" queryParamsHandling="merge" class="btn btn-primary btn-sm"> <span class="fa fa-pencil"></span> <span class="d-none d-md-inline">Edit</span> </button> <button type="submit" [routerLink]="['/', { outlets: { popup: 'finansal-hareket-detay/'+ finansalHareketDetay.id + '/delete'} }]" replaceUrl="true" queryParamsHandling="merge" class="btn btn-danger btn-sm"> <span class="fa fa-remove"></span> <span class="d-none d-md-inline">Delete</span> </button> </div> </td> </tr> </tbody> </table> </div> <div *ngIf="finansalHareketDetays && finansalHareketDetays.length"> <div class="row justify-content-center"> <jhi-item-count [page]="page" [total]="queryCount" [maxSize]="5" [itemsPerPage]="itemsPerPage"></jhi-item-count> </div> <div class="row justify-content-center"> <ngb-pagination [collectionSize]="totalItems" [(page)]="page" [pageSize]="itemsPerPage" [maxSize]="5" [rotate]="true" [boundaryLinks]="true" (pageChange)="loadPage(page)"></ngb-pagination> </div> </div> </div>
package bulby.cloner; import haxe.ds.IntMap; import haxe.ds.StringMap; import bulby.cloner.MapCloner; import haxe.ds.ObjectMap; class Cloner { var cache:ObjectMap<Dynamic, Dynamic>; var classHandles:Map<String, Dynamic->Dynamic>; var stringMapCloner:MapCloner<String>; var intMapCloner:MapCloner<Int>; public function new() { stringMapCloner = new MapCloner(this, StringMap); intMapCloner = new MapCloner(this, IntMap); classHandles = new Map<String, Dynamic->Dynamic>(); classHandles.set('String', (v:String) -> { return v; }); classHandles.set('Array', cloneArray); classHandles.set('haxe.ds.StringMap', stringMapCloner.clone); classHandles.set('haxe.ds.IntMap', intMapCloner.clone); } public static function clone<T>(v:T) { return new Cloner().beginClone(v); } public function beginClone<T>(v:T) { cache = new ObjectMap<Dynamic, Dynamic>(); var outcome = _clone(v); cache = null; return outcome; } public function _clone<T>(v:T):T { #if js if (Std.is(v, String)) return v; #end try { if (Type.getClassName(cast v) != null) return v; } catch (e:Dynamic) {} switch (Type.typeof(v)) { case TNull: return null; case TInt | TFloat | TBool: return v; case TObject: return handleAnonymous(v); case TFunction: return null; case TClass(c): if (!cache.exists(v)) cache.set(v, handleClass(c, v)); return cache.get(v); case TEnum(e): return v; case TUnknown: return null; } } function cloneArray<T>(inValue:Array<T>):Array<T> { var array:Array<T> = inValue.copy(); for (i in 0...array.length) array[i] = _clone(array[i]); return array; } function handleClass<T>(c:Class<T>, v:T):T { var handle:Null<T->T> = classHandles.get(Type.getClassName(c)); if (handle == null) { handle = cloneClass; } return handle(v); } function cloneClass<T>(v:T):T { if (Type.getInstanceFields(Type.getClass(v)).contains("clonerCopy")) { return cast (Reflect.getProperty(v, "clonerCopy") : Void -> T)(); } var outValue = Type.createEmptyInstance(Type.getClass(v)); var fields = Reflect.fields(v); for (field in fields) { var property = Reflect.getProperty(v, field); Reflect.setProperty(outValue, field, property); } return outValue; } function handleAnonymous(v:Dynamic):Dynamic { var properties:Array<String> = Reflect.fields(v); var anonymous:Dynamic = {}; for (i in 0...properties.length) { var property:String = properties[i]; Reflect.setField(anonymous, property, _clone(Reflect.getProperty(v, property))); } return anonymous; } }
import socket import sys import os import struct import ssl import datetime TCP_IP = "127.0.0.1" TCP_PORT = 1456 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH) ssl_context.check_hostname = False ssl_context.load_verify_locations("certificate.crt") # Wrap the socket with SSL/TLS s_ssl = ssl_context.wrap_socket(s, server_side=False) def conn(): # Connect to the server print("Sending server request...") try: s_ssl.connect((TCP_IP, TCP_PORT)) print("Connection successful") while True: # Send authentication credentials username = input("Enter username: ") password = input("Enter password: ") s_ssl.sendall(f"AUTH {username}:{password}".encode()) auth_response = s_ssl.recv(BUFFER_SIZE).decode() print("server response:" + auth_response) if auth_response == "OK": print("Authentication successful") break else: print("Authentication failed. Please try again.") except Exception as e: print("Connection unsuccessful. Make sure the server is online.") print(f"Error: {str(e)}") def upld(file_name): file_name = os.path.abspath(file_name) # Upload a file print("\nUploading file: {}...".format(file_name)) try: # Check if the file exists if not os.path.isfile(file_name): print("Couldn't open file. Make sure the file name was entered correctly.") return # Make upload request s_ssl.sendall(b"UPLD") except Exception as e: print("Couldn't make server request. Make sure a connection has been established.") print(f"Error: {str(e)}") return try: # Wait for server acknowledgement then send file details # Wait for server ok s_ssl.recv(BUFFER_SIZE) # Send file name size and file name file_name_size = struct.pack("h", len(file_name.encode())) s_ssl.send(file_name_size) s_ssl.send(file_name.encode()) # Wait for server ok then send file size s_ssl.recv(BUFFER_SIZE) file_size = os.path.getsize(file_name) s_ssl.send(struct.pack("i", file_size)) except Exception as e: print("Error sending file details") print(f"Error: {str(e)}") return try: # Send the file in chunks defined by BUFFER_SIZE # Doing it this way allows for unlimited potential file sizes to be sent with open(file_name, "rb") as content: print("\nSending...") while True: chunk = content.read(BUFFER_SIZE) if not chunk: break s_ssl.send(chunk) # Get upload performance details upload_time = struct.unpack("f", s_ssl.recv(4))[0] upload_size = struct.unpack("i", s_ssl.recv(4))[0] print("\nSent file: {}\nTime elapsed: {}s\nFile size: {}b".format( file_name, upload_time, upload_size)) except Exception as e: print("Error sending file") print(f"Error: {str(e)}") return def list_files(): # List the files available on the file server print("Requesting files...\n") try: # Send list request s_ssl.sendall(b"LIST") except Exception as e: print("Couldn't make server request. Make sure a connection has been established.") print(f"Error: {str(e)}") return try: # First get the number of files in the directory number_of_files = struct.unpack("i", s_ssl.recv(4))[0] # Then enter into a loop to receive details of each, one by one for _ in range(number_of_files): # Get the file name size first to slightly lessen the amount transferred over the socket file_name_size = struct.unpack("i", s_ssl.recv(4))[0] file_name = s_ssl.recv(file_name_size).decode() # Also get the file size for each item on the server file_size = struct.unpack("i", s_ssl.recv(4))[0] # Also get the file list modify time for each item on the server file_modify_time = struct.unpack("i", s_ssl.recv(4))[0] # Also get the file create time for each item on the server file_create_time = struct.unpack("i", s_ssl.recv(4))[0] file_modify_time = datetime.datetime.fromtimestamp(file_modify_time) file_create_time = datetime.datetime.fromtimestamp(file_create_time) file_modify_time = file_modify_time.strftime('%Y-%m-%d %H:%M:%S') file_create_time = file_create_time.strftime('%Y-%m-%d %H:%M:%S') print("\t{} - {}b - {} - {}".format(file_name, file_size, file_modify_time, file_create_time)) # Make sure that the client and server are synchronized s_ssl.sendall(b"1") # Get total size of the directory total_directory_size = struct.unpack("i", s_ssl.recv(4))[0] print("Total directory size: {}b".format(total_directory_size)) except Exception as e: print("Couldn't retrieve listing") print(f"Error: {str(e)}") return try: # Final check s_ssl.sendall(b"1") return except Exception as e: print("Couldn't get final server confirmation") print(f"Error: {str(e)}") return def dwld(file_name): # Download given file print("Downloading file: {}".format(file_name)) base_dir = os.path.join(os.path.dirname(os.getcwd()), "Files") path_to_file = os.path.join(base_dir, file_name) try: # Check if the file exists if not os.path.isfile(path_to_file): print("Couldn't open file. Make sure the file name was entered correctly.") return # Send server request s_ssl.sendall(b"DWLD") except Exception as e: print("Couldn't make server request. Make sure a connection has been established.") print(f"Error: {str(e)}") return try: # Wait for server ok, then make sure file exists s_ssl.recv(BUFFER_SIZE) # Send file name length, then name file_name_size = struct.pack("h", len(file_name.encode())) s_ssl.send(file_name_size) s_ssl.send(file_name.encode()) # Get file size (if exists) file_size = struct.unpack("i", s_ssl.recv(4))[0] if file_size == -1: # If file size is -1, the file does not exist print("File does not exist. Make sure the name was entered correctly.") return except Exception as e: print("Error checking file") print(f"Error: {str(e)}") return try: # Send ok to receive file content s_ssl.sendall(b"1") # Enter loop to receive file print(file_name) with open(file_name, "wb") as output_file: bytes_received = 0 print("\nDownloading...") while bytes_received < file_size: # Again, file broken into chunks defined by the BUFFER_SIZE variable chunk = s_ssl.recv(BUFFER_SIZE) output_file.write(chunk) bytes_received += len(chunk) print("Successfully downloaded {}".format(file_name)) # Tell the server that the client is ready to receive the download performance details s_ssl.sendall(b"1") # Get performance details time_elapsed = struct.unpack("f",s_ssl.recv(4))[0] print("Time elapsed: {}s\nFile size: {}b".format(time_elapsed, file_size)) except Exception as e: print("Error downloading file") print(f"Error: {str(e)}") return def delf(file_name): # Delete specified file from the file server print("Deleting file: {}...".format(file_name)) try: # Check if the file exists if not os.path.isfile(file_name): print("Couldn't open file. Make sure the file name was entered correctly.") return # Send request, then wait for go-ahead s_ssl.sendall(b"DELF") s_ssl.recv(BUFFER_SIZE) except Exception as e: print("Couldn't connect to server. Make sure a connection has been established.") print(f"Error: {str(e)}") return try: # Send file name length, then file name file_name_size = struct.pack("h", len(file_name.encode())) s_ssl.send(file_name_size) s_ssl.send(file_name.encode()) except Exception as e: print("Couldn't send file details") print(f"Error: {str(e)}") return try: # Get confirmation that file does/doesn't exist file_exists = struct.unpack("i", s_ssl.recv(4))[0] if file_exists == -1: print("The file does not exist on the server") return except Exception as e: print("Couldn't determine file existence") print(f"Error: {str(e)}") return try: # Confirm user wants to delete the file confirm_delete = input( "Are you sure you want to delete {}? (Y/N)\n".format(file_name)).upper() # Make sure input is valid # Unfortunately, Python doesn't have a do-while style loop, as that would have been better here while confirm_delete != "Y" and confirm_delete != "N" and confirm_delete != "YES" and confirm_delete != "NO": # If user input is invalid print("Command not recognized, try again") confirm_delete = input( "Are you sure you want to delete {}? (Y/N)\n".format(file_name)).upper() except Exception as e: print("Couldn't confirm deletion status") print(f"Error: {str(e)}") return try: # Send confirmation if confirm_delete == "Y" or confirm_delete == "YES": # User wants to delete the file s_ssl.sendall(b"Y") # Wait for confirmation the file has been deleted delete_status = struct.unpack("i", s_ssl.recv(4))[0] if delete_status == 1: print("File successfully deleted") return else: # Client will probably send -1 to get here, but an else is used as more of a catch-all print("File failed to delete") return else: s_ssl.sendall(b"N") print("Delete abandoned by user!") return except Exception as e: print("Couldn't delete file") print(f"Error: {str(e)}") return def quit_ftp(): s_ssl.sendall(b"QUIT") # Wait for server go-ahead data = s_ssl.recv(BUFFER_SIZE) s_ssl.close() print("Server connection ended") return print("\n\nWelcome to the FTP client.\n\nCall one of the following functions:\nCONN : Connect to the server\nUPLD file_path : Upload a file\nLIST : List files\nDWLD file_path : Download a file\nDELF file_path : Delete a file\nQUIT : Exit") while True: # Listen for a command prompt = input("\nEnter a command: ") if prompt[:4].upper() == "CONN": conn() elif prompt[:4].upper() == "UPLD": upld(prompt[5:]) elif prompt[:4].upper() == "LIST": list_files() elif prompt[:4].upper() == "DWLD": dwld(prompt[5:]) elif prompt[:4].upper() == "DELF": delf(prompt[5:]) elif prompt[:4].upper() == "QUIT": quit_ftp() break else: print("Command not recognized; please try again")
import React, {useEffect} from 'react'; import SweetAlert from "react-bootstrap-sweetalert"; function Toast({toastShow = false, setToastShow, toastMessage = "success!!", toastType = "success"}) { const hideAlert = () => setToastShow = false useEffect(() => { toastShow == true && setTimeout(() => { setToastShow(false) }, 2000) }, [toastShow]) return ( <> {/*success toast*/} {toastType == "success" && <SweetAlert show={toastShow} success onConfirm={hideAlert} showConfirm={false} > <span className="text-muted">{toastMessage}</span> </SweetAlert>} {/*danger toast*/} {toastType == "danger" && <SweetAlert show={toastShow} danger onConfirm={hideAlert} showConfirm={false} > <span className="text-muted">{toastMessage}</span> </SweetAlert>} </> ); } export default Toast;
doctype html html head meta(charset='UTF-8') meta(name='viewport' content='width=device-width initial-scale=1') meta(name='keyword' content='basco template') meta(name='author' content='By sara') title Basco Project block cssStyle link(rel='stylesheet' href='./css/main.css') link(rel='stylesheet' href='./css/main.css.map') link(rel="preconnect" href="https://fonts.googleapis.com") link(rel="preconnect" href="https://fonts.gstatic.com" crossorigin) link(href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,900&display=swap" rel="stylesheet") body div(class='header') div.logo a(href='./index.html'): img(src='./images/logo_footer.png') .navbar ul li i(class="fa-solid fa-location-dot") p: a(href='./contact.html') location li i(class="fa-solid fa-phone") p +71 1234567890 li i(class="fa-solid fa-envelope") a(href='./contact.html' id='email') demo@gmail.com li a(id='login' href='./login.html') login i(class="fa-solid fa-user") li i(class="fa-solid fa-magnifying-glass" id='magnifying-glass') li#bars img(src='./images/menu_btn.png') div.side-bar .close i(class="fa-solid fa-xmark") ul.side-list li: a(href='./index.html') home li: a(href='./about.html') about li: a(href='./services.html') services li: a(href='./contact.html') contact block pageContent main.landing .container .landing-content .slider .text h1 Welcome To our span Interior Design p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as button(id='read-more') Read more .slider .text h1 Welcome To our span Interior Design p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as button(id='read-more') Read more .slider .text h1 Welcome To our span Interior Design p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as button(id='read-more') Read more .list ul li(class='active') li li section.about .container .about-head h1 about us p It is a long established fact that a reader will be distracted by the readable content .about-content .text .head h2 BEST INTERIOR DESIGN p There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour,There are many variations of passages of button: a(href='./about.html') read more .image img(src='./images/about_img.png') section.features .container .text h1 if a building <span> becomes architecture</span> then it is art p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, asIt is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, asIt is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as section.services .container .services-head h1 services p It is a long established fact that a reader will be distracted by the readable content ul.list li(class='active' id='residental'): a(href='#') residental li(id='retinal-design'): a(href='#') retail design li(id='space-adaptation'): a(href='#') space adaptation .images .div-img: img(src='./images/service_img1.png') .div-img: img(src='./images/service_img2.png') .div-img: img(src='./images/service_img3.png') .div-img: img(src='./images/service_img4.png') button: a(href='./services.html') read more .services-end img(src='./images/cr00s1.png') section.estimates .container .text h1 get an instant estimates p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, button get a quote .img img(src='./images/pc.png') .img-2 img(src='./images/cr00s.png') footer .container .icons ul li: a(href='https://www.facebook.com'): i(class="fa-brands fa-facebook-f") li: a(href='https://www.twitter.com'): i(class="fa-brands fa-twitter") li: a(href='https://www.linkedin.com'): i(class="fa-brands fa-linkedin") li: a(href='https://www.instagram.com'): i(class="fa-brands fa-instagram") .content .div-1 img(src='./images/logo_footer.png') p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, .div-2 h1 explore ul li: a(href='./index.html') home li: a(href='./about.html') about li: a(href='./services.html') services li: a(href='./contact.html') contact us .div-3 h1 recent posts .img img(src='./images/re_img1.jpg') img(src='./images/re_img2.jpg') img(src='./images/re_img3.jpg') img(src='./images/re_img4.jpg') .div-4 h1 contact us p It is a long established fact that a reader will be distracted by the readable content of a page when looking at its div.last p Copyright 2022 All Right Reserved By Free Html Template script(src='js/all.min.js') script(src='js/bootstrap.bundle.min.js') script(src='js/main.js')
import { ref, computed, isRef, isReactive, reactive } from 'vue'; // isRef : can be use to check if a variable is reactive that was created with ref func // isRef : can be use to check if a variable is reactive that was created with reactive func export const useNumber = ()=>{ let num = ref(0); const accounts = reactive({ checking: 234, savings: 123, }); console.log(isRef(num)); console.log(isReactive(accounts)); function increment() { num.value++; }; // return reactive reference that can be used in the template const double = computed(()=> { return num.value * 2; }); return {num, increment, double}; }
<!DOCTYPE html> <html lang="en" data-lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="description" content="Projeto 17: Website Responsivo utilizando React, Node.js, Webpack e Babel para desenvolvimento full stack."> <meta name="keywords" content="HTML, CSS & JavaScript" /> <meta name="author" content="Evandro M Oliveira" /> <meta property="og:image" content="<%= require('../images/javascript-original.svg')%>" /> <meta property="og:image:type" content="image/svg" /> <meta property="og:image:width" content="800" /> <meta property="og:image:height" content="430" /> <link rel="icon" href="<%= require(`../images/javascript-original.svg`)%>" type="image/svg" /> <title>Around The U.S.</title> </head> <body> <div id="page" class="page"> <div id="root" class="root"> <header class="header"></header> <main> <section class="profile"> <div class="profile__container"> <div class="profile__avatar-edit" id="profile__avatar-edit"> <picture> <img src="#" alt="#" class="profile__avatar" id="profile__avatar" data-translate="profile.avatarImage" /> </picture> <picture> <img src="<%= require(`../images/button_update_avatar.svg`)%>" alt="#" data-translate="profile.editBtnImage" class="button-avatar-edit" id="button-avatar-edit" /> </picture> </div> <div class="profile__briefing"> <h1 class="profile__title"></h1> <h2 class="profile__subtitle"></h2> <picture> <source media="(max-width: 608px)" srcset="<%= require(`../images/button_edit_small.svg`)%>" /> <img class="button-edit" src="<%= require(`../images/button_edit.svg`)%>" alt="#" data-translate="profile.btnImage" id="button-edit" /> </picture> </div> </div> <picture> <source media="(max-width: 608px)" srcset="<%= require(`../images/button_add_large.svg`)%>" /> <img src="<%= require(`../images/button_add.svg`)%>" alt="#" class="button-add" id="button-add" data-translate="profile.addBtnImage" /> </picture> </section> <section class="popup" id="popup"> <form class="popup__form" id="popup__form" novalidate> <picture> <source media="(max-width: 580px)" srcset="<%= require(`../images/close_icon_small.svg`)%>" /> <img src="<%= require(`../images/close_icon.svg`)%>" alt="#" class="popup__closed-btn" id="popup__closed-btn" data-translate="common.closeIcon" /> </picture> <h2 class="popup__heading" id="popup__heading_profile"></h2> <label class="popup__field"> <input type="text" name="name" class="popup__input popup__input_type_name" id="popup-input-type-name" required minlength="2" maxlength="40" /> <span class="popup__input-error popup-input-type-name-error"></span> </label> <label class="popup__field"> <input type="text" name="about" class="popup__input popup__input_type_job" id="popup-input-type-job" required minlength="2" maxlength="200" /> <span class="popup__input-error popup-input-type-job-error"></span> </label> <button type="submit" class="popup__button" id="popup__button"></button> </form> </section> <section class="popup popup_avatar-edit" id="popup_avatar-edit"> <form class="popup__form popup__form_avatar-edit" id="popup__form_avatar-edit" novalidate> <picture> <source media="(max-width: 580px)" srcset="<%= require(`../images/close_icon_small.svg`)%>" /> <img src="<%= require(`../images/close_icon.svg`)%>" alt="#" class="popup__closed-btn popup__closed-btn_avatar-edit" id="popup_avatar-edit__closed-btn" data-translate="common.closeIcon" /> </picture> <h2 class="popup__heading popup__heading_avatar-edit" id="popup__heading_avatar-edit"></h2> <label class="popup__field"> <input type="url" name="avatar" class="popup__input popup__input_type_avatar-img-link" id="popup-input-type-avatar-img-link" required pattern="https?://.+" /> <span class="popup__input-error popup-input-type-avatar-img-link-error"></span> </label> <button type="submit" class="popup__button popup__button_avatar-edit" id="popup__button_avatar-edit"></button> </form> </section> <section class="popup popup_card-add" id="popup_card-add"> <form class="popup__form popup__form_card-add" id="popup__form_card-add" novalidate> <picture> <source media="(max-width: 580px)" srcset="<%= require(`../images/close_icon_small.svg`)%>" /> <img src="<%= require(`../images/close_icon.svg`)%>" alt="#" class="popup__closed-btn popup__closed-btn_card-add" id="popup_card-add__closed-btn" data-translate="common.closeIcon" /> </picture> <h2 class="popup__heading popup__heading_card-add" id="popup__heading_card-add"></h2> <label class="popup__field"> <input type="text" name="placeName" class="popup__input popup__input_type_place" id="popup-input-type-place" required minlength="2" maxlength="30" /> <span class="popup__input-error popup-input-type-place-error"></span> </label> <label class="popup__field"> <input type="url" name="link" class="popup__input popup__input_type_img-link" id="popup-input-type-img-link" required pattern="https?://.+" /> <span class="popup__input-error popup-input-type-img-link-error"></span> </label> <button type="submit" class="popup__button popup__button_card-add" id="popup__button_card-add" data-translate="common.saveBtn"></button> </form> </section> <section class="popup popup_with-confirmation" id="popup_with-confirmation"> <form class="popup__form popup__form_with-confirmation" id="popup__form_with-confirmation" novalidate> <picture> <source media="(max-width: 580px)" srcset="<%= require(`../images/close_icon_small.svg`)%>" /> <img src="<%= require(`../images/close_icon.svg`)%>" alt="#" class="popup__closed-btn popup__closed-btn_with-confirmation" id="popup_with-confirmation__closed-btn" data-translate="common.closeIcon" /> </picture> <h2 class="popup__heading popup__heading_with-confirmation" id="popup__heading_with-confirmation"></h2> <button type="submit" class="popup__button popup__button_with-confirmation" id="popup__button_with-confirmation"></button> </form> </section> <section class="img-popup-card" id="img-popup-card"> <div class="img-popup-card__container" id="img-popup-card__container"> <picture> <img type="url" src="#" alt="#" class="img-popup-card__image" /> </picture> <h2 class="img-popup-card__title"></h2> <picture> <source media="(max-width: 580px)" srcset="<%= require(`../images/close_icon_small.svg`)%>" /> <img src="<%= require(`../images/close_icon.svg`)%>" alt="#" class="img-popup-card__closed-btn" id="img-popup-card__closed-btn" data-translate="common.closeIcon" /> </picture> </div> </section> <section class="cards"></section> <section id="infoTooltip-container"></section> </main> <footer class="footer"></footer> </div> </div> <template id="cards-template"> <section class="cards"> <ul class="card"> <picture> <img src="<%= require(`../images/trash_icon.svg`)%>" alt="#" data-translate="card.trashIconAlt" class="button-trash-icon" id="button-trash-icon" /> </picture> <picture> <img src="#" alt="#" class="card__image" /> </picture> <li class="card__briefing"> <h2 class="card__title"></h2> <div class="card__like-container"> <picture> <img src="<%= require(`../images/heart_icon_disabled.svg`)%>" alt="#" class="button-heart-icon" id="button-heart-icon" /> </picture> <p class="card__likes"></p> </div> </li> </ul> </section> </template> <template id="header-template"> <div class="header__user-panel"> <div class="header__branding"> <picture> <source media="(max-width: 608px)" srcset="<%= require('../images/logo_small.svg') %>" /> <img src="<%= require('../images/logo.svg') %>" alt="Logo Around The U.S." class="header__logo" /> </picture> <div class="header__lang-switch"> <span class="header__lang" data-lang="en">EN</span> | <span class="header__lang" data-lang="pt">PT</span> </div> </div> <div class="header__auth"> <p id="user-email" class="header__user-email"></p> <p id="auth-status" class="header__auth-status"></p> </div> </div> <div class="header__line"></div> </template> <template id="footer-template"> <p class="footer__copyrights">&copy; 2023 Around The U.S.</p> <aside class="footer__aside"> <div class="footer__social-links"> <ul class="footer__list"> <li> <a href="https://www.linkedin.com/in/evandrodemelo/" target="_blank" rel="noopener noreferrer"> <svg fill="#000000" version="1.1" class="footer__linkedin-icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32px" height="32px" viewBox="0 0 490.732 490.732" xml:space="preserve"> <defs> <style> .background { fill: #545454; } .icon-color { fill: #ffffff; } </style> </defs> <rect class="background" width="490.732" height="490.732" /> <g class="icon-color"> <path d="M472.366,0.003H18.36C8.219,0.003,0,8.222,0,18.363v454.005c0,10.143,8.219,18.361,18.36,18.361h454.012 c10.142,0,18.36-8.219,18.36-18.361V18.363C490.727,8.222,482.507,0.003,472.366,0.003z M130.375,403.808 c0,6.762-5.478,12.238-12.24,12.238H69.132c-6.756,0-12.24-5.477-12.24-12.238V189.625c0-6.763,5.484-12.24,12.24-12.24h49.003 c6.762,0,12.24,5.477,12.24,12.24V403.808z M130.375,127.482c0,6.763-5.478,12.24-12.24,12.24H69.132 c-6.756,0-12.24-5.478-12.24-12.24V83.969c0-6.763,5.484-12.24,12.24-12.24h49.003c6.762,0,12.24,5.477,12.24,12.24V127.482z M433.835,403.808c0,6.762-5.483,12.238-12.24,12.238h-49.003c-6.763,0-12.24-5.477-12.24-12.238v-90.436 c0-29.988-1.566-49.383-4.712-58.189c-3.14-8.807-8.237-15.649-15.3-20.526c-7.062-4.884-15.558-7.32-25.496-7.32 c-12.729,0-24.149,3.488-34.26,10.459c-10.11,6.977-17.038,16.211-20.79,27.717c-3.745,11.506-5.618,32.779-5.618,63.807v74.488 c0,6.762-5.483,12.238-12.24,12.238h-49.003c-6.756,0-12.24-5.477-12.24-12.238V189.625c0-6.763,5.483-12.24,12.24-12.24h43.771 c6.763,0,12.24,5.477,12.24,12.24v16.316c0,6.763,3.312,7.852,7.858,2.852c22.864-25.123,50.753-37.687,83.673-37.687 c16.212,0,31.028,2.919,44.455,8.758c13.422,5.838,23.58,13.292,30.466,22.356c6.885,9.063,11.683,19.351,14.382,30.857 c2.699,11.505,4.058,27.98,4.058,49.426V403.808L433.835,403.808z" /> </g> </svg> </a> </li> <li> <a href="https://github.com/evandro-developer" target="_blank" rel="noopener noreferrer"> <svg width="32" height="32" viewBox="4 4 24 24" class="footer__github-icon" xmlns="http://www.w3.org/2000/svg"> <rect x="0" y="0" width="32" height="32" fill="#FFFFFF" /> <path d="M28 1c1.654 0 3 1.346 3 3v24c0 1.654-1.346 3-3 3H4c-1.654 0-3-1.346-3-3V4c0-1.654 1.346-3 3-3h24m0-1H4C1.8 0 0 1.8 0 4v24c0 2.2 1.8 4 4 4h24c2.2 0 4-1.8 4-4V4c0-2.2-1.8-4-4-4z" fill="#FFFFFF" class="color000 svgShape"></path> <path d="M19.613 25.958h-5.309s.007-1.575 0-2.656c-3.633.782-4.647-1.992-4.647-1.992-.664-1.328-1.328-1.992-1.328-1.992-1.328-.789 0-.664 0-.664 1.328 0 1.992 1.328 1.992 1.328 1.165 1.978 3.238 1.66 3.983 1.328 0-.664.291-1.668.664-1.992-2.9-.327-5.314-1.992-5.314-5.311s.667-3.983 1.33-4.647c-.134-.327-.69-1.537.021-3.319 0 0 1.305 0 2.632 1.992.658-.658 2.656-.664 3.32-.664.663 0 2.661.006 3.318.664 1.328-1.992 2.636-1.992 2.636-1.992.71 1.783.155 2.992.02 3.319.664.664 1.328 1.328 1.328 4.647s-2.411 4.984-5.311 5.311c.374.324.664 1.467.664 1.992l.001 4.648z" fill="#545454" class="color000 svgShape"></path> </svg> </a> </li> </ul> </div> <div class="footer__author-info"> <p class="footer__author" data-translate="footer.author"></p> <p class="footer__profession" data-translate="footer.profession"></p> </div> </aside> </template> <template id="auth-container-template"> <div class="auth"> <header class="header"></header> <section class="auth-container"> <h2 class="auth-container__title" id="auth-container__title"></h2> <form class="auth-container__form" id="auth-form" novalidate> <label class="auth-container__field"> <input class="auth-container__input" type="email" name="email" id="auth-email" required autocomplete="email" /> <span class="auth-container__input-error auth-email-error" id="auth-email-error" data-translate="validation.emailRequired"></span> </label> <label class="auth-container__field"> <input class="auth-container__input" type="password" name="password" id="auth-password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[A-Za-z\d\W_]{6,100}$" required autocomplete="current-password" minlength="6" maxlength="20" /> <span class="auth-container__input-error auth-password-error" id="auth-password-error"></span> </label> <button type="submit" class="button-auth" id="auth-submit-button"></button> <a href="#" class="auth-container__link" id="toggle-auth-route"></a> </form> </section> <footer class="footer"></footer> </div> </template> <template id="infoToolTip-template"> <div class="infoToolTip"> <div class="infoToolTip__container"> <img src="" alt="" class="infoToolTip__img" /> <p class="infoToolTip__text"></p> <picture> <source media="(max-width: 580px)" srcset="<%= require(`../images/close_icon_small.svg`)%>" /> <img src="<%= require(`../images/close_icon.svg`)%>" alt="#" class="infoToolTip__closed-btn" id="infoToolTip__closed-btn" data-translate="common.closeIcon" /> </picture> </div> </div> </template> </body> </html>
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity ^0.8.0; import "forge-std/Test.sol"; // Internal Dependencies import {ProposalFactory} from "src/factories/ProposalFactory.sol"; // External Interfaces import {IERC20} from "@oz/token/ERC20/IERC20.sol"; // Internal Interfaces import { IProposalFactory, IModule, IProposal } from "src/factories/IProposalFactory.sol"; import {Proposal} from "src/proposal/Proposal.sol"; // Mocks import {ModuleFactoryMock} from "test/utils/mocks/factories/ModuleFactoryMock.sol"; import {ERC20Mock} from "test/utils/mocks/ERC20Mock.sol"; // Errors import {OZErrors} from "test/utils/errors/OZErrors.sol"; contract ProposalFactoryTest is Test { bool hasDependency; string[] dependencies = new string[](0); // SuT ProposalFactory factory; Proposal target; // Mocks ModuleFactoryMock moduleFactory; // Metadata IProposalFactory.ProposalConfig proposalConfig = IProposalFactory .ProposalConfig({ owner: address(this), token: IERC20(new ERC20Mock("Mock Token", "MOCK")) }); IProposalFactory.ModuleConfig fundingManagerConfig = IProposalFactory .ModuleConfig( IModule.Metadata(1, 1, "https://fundingmanager.com", "FundingManager"), bytes("data"), abi.encode(hasDependency, dependencies) ); IProposalFactory.ModuleConfig authorizerConfig = IProposalFactory .ModuleConfig( IModule.Metadata(1, 1, "https://authorizer.com", "Authorizer"), bytes("data"), abi.encode(hasDependency, dependencies) ); IProposalFactory.ModuleConfig paymentProcessorConfig = IProposalFactory .ModuleConfig( IModule.Metadata( 1, 1, "https://paymentprocessor.com", "SimplePaymentProcessor" ), bytes("data"), abi.encode(hasDependency, dependencies) ); IProposalFactory.ModuleConfig moduleConfig = IProposalFactory.ModuleConfig( IModule.Metadata(1, 1, "https://module.com", "Module"), bytes(""), abi.encode(hasDependency, dependencies) ); function setUp() public { moduleFactory = new ModuleFactoryMock(); target = new Proposal(); factory = new ProposalFactory(address(target), address(moduleFactory)); } function testValidProposalId(uint getId, uint proposalsCreated) public { // Note to stay reasonable proposalsCreated = bound(proposalsCreated, 0, 50); for (uint i = 0; i < proposalsCreated; ++i) { _deployProposal(); } if (getId > proposalsCreated) { vm.expectRevert( IProposalFactory.ProposalFactory__InvalidId.selector ); } factory.getProposalByID(getId); } function testDeploymentInvariants() public { assertEq(factory.target(), address(target)); assertEq(factory.moduleFactory(), address(moduleFactory)); } function testCreateProposal(uint modulesLen) public { // Note to stay reasonable modulesLen = bound(modulesLen, 0, 50); // Create optional ModuleConfig instances. IProposalFactory.ModuleConfig[] memory moduleConfigs = new IProposalFactory.ModuleConfig[]( modulesLen ); for (uint i; i < modulesLen; ++i) { moduleConfigs[i] = moduleConfig; } // Deploy Proposal with id=1 IProposal proposal = factory.createProposal( proposalConfig, fundingManagerConfig, authorizerConfig, paymentProcessorConfig, moduleConfigs ); // Check that proposal's strorage correctly initialized. assertEq(proposal.proposalId(), 1); assertEq(address(proposal.token()), address(proposalConfig.token)); assertTrue(address(proposal.authorizer()) != address(0)); assertTrue(address(proposal.paymentProcessor()) != address(0)); // Check that other proposal's dependencies correctly initialized. // Ownable: assertEq(proposal.manager(), address(proposalConfig.owner)); // Deploy Proposal with id=2 proposal = factory.createProposal( proposalConfig, fundingManagerConfig, authorizerConfig, paymentProcessorConfig, moduleConfigs ); // Only check that proposal's id is correct. assertEq(proposal.proposalId(), 2); //check that proposalFactory idCounter is correct. assertEq(factory.getProposalIDCounter(), 2); } function testProposalMapping(uint proposalAmount) public { // Note to stay reasonable proposalAmount = bound(proposalAmount, 0, 50); for (uint i = 1; i < proposalAmount; ++i) { address proposal = _deployProposal(); assertEq(proposal, factory.getProposalByID(i)); } } function _deployProposal() private returns (address) { //Create Empty ModuleConfig IProposalFactory.ModuleConfig[] memory moduleConfigs = new IProposalFactory.ModuleConfig[](0); // Deploy Proposal IProposal proposal = factory.createProposal( proposalConfig, fundingManagerConfig, authorizerConfig, paymentProcessorConfig, moduleConfigs ); return address(proposal); } }
import 'package:flutter/material.dart'; import 'package:my_portfolio/core/layout/adaptive.dart'; import 'package:my_portfolio/core/utils/functions.dart'; import 'package:my_portfolio/presentation/pages/portfolio/portfolio_page.dart'; import 'package:my_portfolio/presentation/widgets/app_drawer.dart'; import 'package:my_portfolio/presentation/widgets/circular_container.dart'; import 'package:my_portfolio/presentation/widgets/content_wrapper.dart'; import 'package:my_portfolio/presentation/widgets/socials.dart'; import 'package:my_portfolio/presentation/widgets/spaces.dart'; import 'package:my_portfolio/values/values.dart'; import 'home_page.dart'; class HomePageMobile extends StatefulWidget { const HomePageMobile({super.key}); @override _HomePageMobileState createState() => _HomePageMobileState(); } class _HomePageMobileState extends State<HomePageMobile> { final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey(); @override Widget build(BuildContext context) { ThemeData theme = Theme.of(context); return Scaffold( key: _scaffoldKey, drawer: AppDrawer( menuList: Data.menuList, selectedItemRouteName: HomePage.homePageRoute, ), body: Stack( children: [ Column( children: [ Row( children: [ ContentWrapper( width: assignWidth(context: context, fraction: 0.8), color: AppColors.primaryColor, // gradient: Gradients.primaryGradient, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: assignHeight( context: context, fraction: 0.2, ), ), Container( padding: const EdgeInsets.only(left: 24.0), child: ListBody( children: [ Text( StringConst.DEV_NAME, style: theme.textTheme.headlineMedium!.copyWith( color: AppColors.secondaryColor, ), ), const SpaceH8(), Text( StringConst.SPECIALITY, style: theme.textTheme.titleLarge!.copyWith( color: AppColors.secondaryColor, ), ), ], ), ), const Spacer(flex: 1), InkWell( onTap: () { Navigator.pushNamed( context, PortfolioPage.portfolioPageRoute, ); }, child: Container( padding: const EdgeInsets.only(left: 24.0), child: Column( children: [ RotatedBox( quarterTurns: 3, child: Text( StringConst.VIEW_PORTFOLIO, textAlign: TextAlign.end, style: theme.textTheme.bodyLarge!.copyWith( color: AppColors.secondaryColor, fontSize: Sizes.TEXT_SIZE_18, ), ), ), const SpaceH12(), const CircularContainer( width: Sizes.WIDTH_24, height: Sizes.HEIGHT_24, color: AppColors.secondaryColor, child: Icon( Icons.keyboard_arrow_down, color: AppColors.primaryColor, ), ), ], ), ), ), SizedBox( height: assignHeight( context: context, fraction: 0.05, ), ), ], ), ), ContentWrapper( width: assignWidth(context: context, fraction: 0.2), color: AppColors.secondaryColor, child: Container(), ), ], ) ], ), _buildAppBar(), _buildDevImage(), _buildSocials(), ], ), ); } Widget _buildAppBar() { return Container( padding: const EdgeInsets.symmetric( horizontal: Sizes.PADDING_16, vertical: Sizes.PADDING_16, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( onPressed: () { if (_scaffoldKey.currentState!.isEndDrawerOpen) { _scaffoldKey.currentState!.openEndDrawer(); } else { _scaffoldKey.currentState!.openDrawer(); } }, icon: const Icon(Icons.menu), ), CircularContainer( color: AppColors.primaryColor, child: InkWell( onTap: () { Functions.launchUrl(StringConst.EMAIL_URL); // Navigator.pushNamed( // context, // ContactPage.contactPageRoute, // ); }, child: const Icon( Icons.email, color: AppColors.secondaryColor, ), ), ), ], ), ); } Widget _buildDevImage() { return Positioned( top: 56, right: -assignWidth(context: context, fraction: 0.42), child: Image.asset( ImagePath.DEV, height: assignHeight(context: context, fraction: 1), fit: BoxFit.cover, ), ); } Widget _buildSocials() { return const Positioned( right: Sizes.SIZE_16, bottom: Sizes.SIZE_30, child: Socials( isVertical: true, alignment: Alignment.centerRight, color: AppColors.secondaryColor, barColor: AppColors.secondaryColor, crossAxisAlignment: CrossAxisAlignment.end, ), ); } }
import {ChannelData} from "./data/channel"; import {ChannelData as ChannelAPIData} from "./apis/channel"; import {Credential} from "./models/Credential"; import {request} from "./utils/network"; /** * 根据 tid 获取频道信息。 * * param tid(number): 频道 tid * * @returns {Object[Object, Object]} 第一项是主分区,第二项是子分区,没有时返回 None。 */ export function get_channel_info_by_tid({tid}: {tid: number}) { for (let channel of ChannelData) { if (channel.tid ? false : true) { continue; } if (tid === Number(channel.tid)) { return [channel, null] } for (let sub_channel of channel.sub) { if (sub_channel.tid ? false : true) { continue; } if (tid === Number(sub_channel.tid)) { return [channel, sub_channel]; } } } return [null, null] } /** * 根据频道名称获取频道信息。 * * param name(string): 频道的名称 * * @returns {Object[Object, Object]} 第一项是主分区,第二项是子分区,没有时返回 None。 */ export function get_channel_info_by_name({name}:{name: string}) { for (let main_ch of ChannelData) { if (main_ch.name.indexOf(name) !== -1) { return [main_ch, null]; } for (let sub_ch of main_ch.sub) { if (sub_ch.name.indexOf(name) !== -1) { return [main_ch, sub_ch] } } } } /** * 获取分区前十排行榜。 * * param tid(number) : 频道的 tid * * param day(number, optional) : 3 天排行还是 7 天排行,defaults to 7 * * param credential(Credential, optional): 凭据类 * @returns */ export async function get_top10({tid, day, credential}: {tid: number, day?: number, credential?: Credential}) { if (credential === null || credential === undefined) { credential = new Credential({}); } if (day === null || day === undefined) { day = 7; } if (day !== 3 && day !== 7) { throw "参数 day 只能是 3,7。"; } var api = ChannelAPIData.ranking.get_top10; var params = { rid: tid, day: day }; return await request({ method: "GET", url: api.url, params: params, credential: credential }); } /** * 获取所有分区的数据 * * @returns {any[]} 所有分区的数据 */ export function get_channel_list({}) { var channel_list = []; for (let channel_big of ChannelData) { var channel_big_copy = JSON.parse(JSON.stringify(channel_big)); delete channel_big_copy['sub']; channel_list.push(channel_big_copy); for (let channel_sub of channel_big.sub) { var channel_sub_copy = JSON.parse(JSON.stringify(channel_sub)); channel_sub_copy['father'] = channel_big_copy; channel_list.push(channel_sub_copy); } } return channel_list; } /** * 获取所有分区的数据 * 含父子关系(即一层次只有主分区) * * @returns {Object} 所有主分区的数据 */ export function get_channel_list_sub({}) { return ChannelData; }
import React, { useState, useEffect } from 'react' import { getRecentlyPlayed } from '../spotify' import { catchErrors } from '../utils' import Loader from './Loader' import TrackItem from './TrackItem' import styled from 'styled-components/macro' import { Main } from '../styles' const RecentlyPlayed = () => { const [recentlyPlayed, setRecentlyPlayed] = useState(null) useEffect(() => { const fetchData = async () => { const { data } = await getRecentlyPlayed() setRecentlyPlayed(data) } catchErrors(fetchData()) }, []) return ( <Main> <h2>Recently Played Tracks</h2> <TracksContainer>{recentlyPlayed ? recentlyPlayed.items.map(({ track }, i) => <TrackItem track={track} key={i} />) : <Loader />}</TracksContainer> </Main> ) } const TracksContainer = styled.ul` margin-top: 50px; ` export default RecentlyPlayed
// PlantPreferencePage.js import React, { useState, useEffect } from "react"; import axios from "axios"; import { View, Text, Image, TouchableOpacity, StyleSheet } from "react-native"; import { useNavigation } from "@react-navigation/native"; const PlantPreferencePage = ({ route }) => { const { flower } = route.params; const [data, setData] = useState([]); const [loading, setLoading] = useState(false); // Add loading state const navigation = useNavigation(); const handleViewClick = async (id) => { try { const response = await axios.get( `http://54.252.43.250/api/view/flower?id=${id}` ); const flowerData = response.data; const flowerDataUnique = { name: flowerData.name, light: flowerData.light, fertilizer: flowerData.fertilizer, water: flowerData.water, soil: flowerData.soil, precaution: flowerData.precaution, imagePath: flowerData.imagePath, }; navigation.navigate("FlowerDetails", { flower: flowerDataUnique }); } catch (error) { console.error(error); } }; return ( <View style={styles.container}> <Image source={require("../assets/questionBg.png")} style={styles.backgroundImage} /> <View style={styles.rowContainer}> {flower.map((flower, index) => { return ( <View key={index} style={styles.flowerContainer}> <Image source={{ uri: `https://drive.google.com/uc?id=${flower.imagePath}`, }} style={{ width: 100, height: 100 }} /> <Text style={styles.name}> {flower.name}</Text> <TouchableOpacity style={styles.viewButton} onPress={() => handleViewClick(flower.id)} > <Text style={styles.viewButtonText}>View</Text> </TouchableOpacity> </View> ); })} </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, backgroundImage: { flex: 1, resizeMode: "cover", position: "absolute", width: "100%", height: "100%", }, rowContainer: { flexDirection: "row", marginTop: "10px", justifyContent: "space-between", flexWrap: "wrap", padding: 8, marginTop: "30%", }, flowerContainer: { position: "relative", width: "48%", marginBottom: 16, borderWidth: 1, borderColor: "#ddd", borderRadius: 8, padding: 8, alignItems: "center", overflow: "hidden", shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.5, shadowRadius: 2, elevation: 3, }, image: { width: 100, height: 100, borderRadius: 50, }, name: { marginTop: 8, fontSize: 16, fontWeight: "bold", }, viewButton: { marginTop: 8, backgroundColor: "#4CAF50", padding: 8, borderRadius: 4, }, viewButtonText: { color: "#fff", fontWeight: "bold", }, }); export default PlantPreferencePage;
import {toast} from "react-hot-toast" import{setUser} from "../../slices/profileSlice" import { apiConnector } from "../apiconnector" import { settingsEndpoints } from "../apis" import {logout} from "./authAPI" const { UPDATE_DISPLAY_PICTURE_API, UPDATE_PROFILE_API, CHANGE_PASSWORD_API, DELETE_PROFILE_API, } = settingsEndpoints export function updateDisplayPicture(token,formData){ console.log("token in update display-",token); return async(dispatch)=>{ const toastId =toast.loading("Loading...") try { const response=await apiConnector("PUT",UPDATE_DISPLAY_PICTURE_API,formData, { "content-Type":"multipart/form-data", Authorization: `Bearer ${token}` } ) //checking the updated api ; console.log( "UPDATE_DISPLAY_PICTURE_API API RESPONSE.....", response ) //check if response is not found if(!response.data.success){ throw new Error(response.data.message) } //return successfull status... toast.success("Display PIcture Updated Successfully") dispatch(setUser(response)) } catch (error) { console.log("UDPATE_DISPLAY_PICTUREAPI API ERROR.....",error) toast.error("Could Not Updated Display Picture"); } toast.dismiss(toastId) } } export function updateProfile(token,formData){ return async(dispatch) =>{ const toastId=toast.loading("Loading..."); try { const response =await apiConnector("PUT",UPDATE_PROFILE_API,formData,{ Authorization:`Bearer ${token}`, }) console.log("UPDATE_PROFILE_API API RESPOSNE.........",response) if(!response.data.success){ throw new Error(response.data.message) } const userImage=response.data.updatedUserDetails.image? response.data .updatedUserDetails.image :`https://api.dicebear.com/5.x/initials/svg?seed=${response.data.updatedUserDetails.firstName} ${response.data.updatedUserDetails.lastName}` dispatch( setUser({...response.data.updatedUserDetails,image:userImage}) ) toast.success("Profile Updated Successfully") } catch (error) { console.log("UPDATE_PROFILE_API API ERROR.......",error) toast.error("Could Not Update Profile") } toast.dismiss(toastId) } } export async function changePassword(token,formData){ const toastId=toast.loading("Loading..."); try { const response=await apiConnector("PUT",CHANGE_PASSWORD_API,formData,{ Authorization:`Bearer ${token}`, }) console.log("CHANGE_PASSWORD_API API RESPONSE.....",response) if (!response.data.success){ throw new Error(response.data.message) } toast.success("Password change successfully ") } catch (error) { console.log("CHANGE_PASSWORD_API API ERROR.......",error) toast.error(error.respose.data.message) } toast.dismiss(toastId) } export async function deleteProfile(token,navigate){ return async(dispatch)=>{ const toastId=toast.loading("Loading....") try { const response =await apiConnector("DELETE",DELETE_PROFILE_API,null,{ Authorization: `Bearer ${token}`, }) console.log("DELETE_PROFILE_API API RESPONSE.....",response) if(!response.data.success){ throw new Error(response.data.message) } toast.success("Profile Deleted successfully ") dispatch(logout(navigate)) } catch (error) { console.log("DELETE_PROFILE_API API ERROR.....",error) toast.error("Could Not Delete Profile"); } toast.dismiss(toastId) } }
<div id="main-navigation" class="sticky top-0 w-full h-0 z-50"> <nav class="bg-zinc-800 absolute top-0 w-full"> <div class="container max-w-screen-xl px-4 py-2.5 mx-auto flex flex-wrap justify-between items-center"> <%= link_to root_path, class: "flex items-center" do %> <%= current_account.content.image_tag(:logo, {}, {class: "h-8 sm:h-10"}) %> <% end %> <button data-collapse-toggle="mobile-menu" type="button" class="inline-flex items-center p-2 ml-3 text-sm text-gray-500 rounded-lg md:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200" aria-controls="mobile-menu" aria-expanded="false"> <span class="sr-only">Hauptmenü öffnen</span> <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"></path></svg> <svg class="hidden w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg> </button> <div class="hidden w-full md:block md:w-auto my-4 md:my-0" id="mobile-menu"> <ul class="flex flex-col md:flex-row md:space-x-6 space-y-6 md:space-y-0"> <%# Admin Edit Button %> <% if current_spina_user.present? %> <li><%= link_to "Edit Page", spina.edit_admin_page_path(current_page), class: "block text-white text-base", target: "_blank" %></li> <% end %> <%# Main Navigation %> <% nav = Spina::Navigation.find_by(name: 'main') %> <% items = nav.navigation_items.regular_pages.sorted.live.in_menu.active %> <% any_page_active = false %> <% nav_items = [].tap do |out| %> <% items.each do |item| %> <% if item.page.materialized_path %> <% active_page = item.page.id == current_page.id || ( current_page.resource.present? && item.page.name == current_page.resource.name ) %> <% out << [item.page.menu_title, item.page.materialized_path, active_page] %> <% any_page_active ||= active_page %> <% end %> <% end %> <% end.each do |item| %> <li> <% classes = [].tap { |out| out << "block text-gray-400 text-base hover:text-white"; out << "!text-white" if item[2] || !any_page_active }.join(' ') %> <%= link_to item[0], item[1], class: classes %> </li> <% end %> <%# Language Toggle %> <% existing_locales = current_page.translations.pluck(:locale).map(&:to_sym) %> <% current_locale = params[:locale]&.to_sym || I18n.default_locale&.to_sym %> <% existing_locales.each do |locale| %> <% if locale != current_locale %> <li><%= link_to t("spina.languages.#{locale}"), current_page.materialized_path(locale: locale), class: "block text-white text-base" %></li> <% end %> <% end %> </ul> </div> </div> </nav> </div>
"""Multispectral Spectral Responses and Generators """ from ._spectral import _SRF, bands_from_step_func, band_QE from .datasets import _dload class Sentinel2A(_SRF): """Sentinel 2A - all spectral bands. Simulates the Sentinel 2A satellite using SRF values published by ESA (ref: COPE-GSEG-EOPG-TN-15-0007) and estimates of the PSF properties (https://doi.org/10.3390/rs8060488). """ def _load_srfs(self): spx = _dload('SRF_SENTINEL_2') self.band_wavelengths = { 'B2': 492., 'B3': 560., 'B4': 664., 'B5': 704., 'B6': 740., 'B7': 780., 'B8': 832., 'B8A': 864. } self.band_names = list(self.band_wavelengths.keys()) return spx['S2A'] class Sentinel2B(_SRF): """Sentinel 2B - all bands. Simulates the Sentinel 2B satellite """ def _load_srfs(self): spx = _dload('SRF_SENTINEL_2') self.band_wavelengths = { 'B2': 492., 'B3': 560., 'B4': 664., 'B5': 704., 'B6': 740., 'B7': 780., 'B8': 832., 'B8A': 864. } self.band_names = list(self.band_wavelengths.keys()) return spx['S2B'] class Sentinel2VNIR(_SRF): """Sentinel 2A - vis-VNIR only. Hypothetical satellite with spectral responses equivalent to vis-NIR Sentinel 2 """ def _load_srfs(self): spx = _dload('SRF_SENTINEL_2') vals = spx['S2A'] # drop SWIR vals.pop('B11') vals.pop('B12') self.band_wavelengths = { 'B2': 492., 'B3': 560., 'B4': 664., 'B5': 704., 'B6': 740., 'B7': 780., 'B8': 832., 'B8A': 864. } self.band_names = list(self.band_wavelengths.keys()) return vals class SuperDove(_SRF): """SuperDove Super Dove estimated spectral response digitised from published plots """ def _load_srfs(self): vals = _dload('SRF_SUPERDOVE') self.band_wavelengths = { 'CoastalBlue': 443., 'Blue': 490., 'Green_1': 531., 'Green_2': 565., 'Yellow': 611., 'Red': 666., 'RedEdge': 705., 'NIR': 865. } self.band_names = list(self.band_wavelengths.keys()) return vals class TreeView_1(_SRF): """TreeView Version 1 """ def _load_srfs(self): band_defs = { 'Clouds': (445, 20), 'Carotenoids': (490, 40), 'PRI_1': (531, 10), 'PRI_2': (560, 20), 'Chlorophyll_1': (620, 20), 'Chlorophyll_2': (665, 30), 'RedEdge_1': (700, 15), 'RedEdge_2': (740, 15), 'RedEdge_3': (780, 15), 'NIR': (865, 30) } self.band_wavelengths = {k: v[0] for (k, v) in band_defs.items()} self.band_names = list(self.band_wavelengths.keys()) return bands_from_step_func(band_defs) class TreeView_2(_SRF): """TreeView Version 2 Version 2 based on the a widened bandpass profile in the vis """ def _load_srfs(self): band_defs = { 'Aerosol': (440, 20), 'Carotenoids': (480, 40), 'PRI_1': (525, 50), 'PRI_2': (585, 50), 'Chlorophyll_1': (630, 40), 'Chlorophyll_2': (670, 40), 'RedEdge_1': (700, 15), 'RedEdge_2': (740, 15), 'RedEdge_3': (780, 15), 'NIR': (865, 30) } self.band_wavelengths = {k: v[0] for (k, v) in band_defs.items()} self.band_names = list(self.band_wavelengths.keys()) return bands_from_step_func(band_defs) class TreeView_3(_SRF): """TreeView Version 3 As for v2 but without Carotenoids and RE1 bands """ def _load_srfs(self): band_defs = { 'Aerosol': (440, 20), # 'Carotenoids': (480, 40), 'PRI_1': (525, 50), 'PRI_2': (585, 50), 'Chlorophyll_1': (630, 40), 'Chlorophyll_2': (670, 40), # 'RedEdge_1': (700, 15), 'RedEdge_2': (740, 15), 'RedEdge_3': (780, 15), 'NIR': (865, 30) } self.band_wavelengths = {k: v[0] for (k, v) in band_defs.items()} self.band_names = list(self.band_wavelengths.keys()) return bands_from_step_func(band_defs)
import pickle import argparse parser = argparse.ArgumentParser() parser.add_argument("--test_case", type=int, default=1) args = parser.parse_args() import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = sns.load_dataset("exercise") # Make catplots of scatter plots by using "time" as x, "pulse" as y, "kind" as hue, and "diet" as col # Change the subplots titles to "Group: Fat" and "Group: No Fat" # SOLUTION START [insert] # SOLUTION END plt.savefig('result/plot.png', bbox_inches ='tight') #Image Testing from PIL import Image import numpy as np code_img = np.array(Image.open('result/plot.png')) oracle_img = np.array(Image.open('ans/oracle_plot.png')) sample_image_stat = ( code_img.shape == oracle_img.shape and np.allclose(code_img, oracle_img) ) if sample_image_stat: with open('result/result_1.pkl', 'wb') as file: # if image test passed, we save True to the result file pickle.dump(True, file) # Testing axs = plt.gcf().axes assert axs[0].get_title() == "Group: Fat" assert axs[1].get_title() == "Group: No Fat" import matplotlib is_scatter_plot = False for c in axs[0].get_children(): if isinstance(c, matplotlib.collections.PathCollection): is_scatter_plot = True assert is_scatter_plot with open('result/result_1.pkl', 'wb') as file: # or if execution-based test passed, we save True to the result file pickle.dump(True, file)
#define SWITCH_PIN 10 // input for toggle switch #define LED_PIN1 6 // output to FET module #define LED_PIN2 7 // output to FET module #define STROBE_COUNT_DELAY 18000 // [ms] time between strobe cycles int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin int num_presses = 0; int strobe_count = 0; // byte target, current; // target and current pwm value int FADE_INTERVAL_1 = 30; // [ms] time between fade steps int NEXTFADE_INTERVAL_1 = 1500; // [ms] time between fade cycles int FADE_INTERVAL_2 = 30; // [ms] time between fade steps int NEXTFADE_INTERVAL_2 = 1500; // [ms] time between fade cycles byte current; // current pwm value byte target; // target pwm value unsigned long time_for_fadestep_1; unsigned long time_for_nextfade_1; unsigned long time_for_fadestep_2; unsigned long time_for_nextfade_2; unsigned long time_for_strobe_delay; unsigned long lastDebounceTime; // the last time the output pin was toggled unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(SWITCH_PIN, INPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); Serial.begin(9600); } void loop() { // read the state of the switch into a local variable: int reading = digitalRead(SWITCH_PIN); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited long enough // since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonState) { buttonState = reading; // only toggle the LED if the new button state is HIGH if (buttonState == HIGH) { // increment our count for number of times pressed num_presses += 1; Serial.println("button is being pressed!"); } } } // save the reading. Next time through the loop, it'll be the lastButtonState: lastButtonState = reading; // button hasn't been pressed yet (or has been reset) if (num_presses == 0) { digitalWrite(4, LOW); digitalWrite(5, LOW); digitalWrite(6, LOW); digitalWrite(7, LOW); Serial.println("num_presses 0"); } // button has been pressed once! if (num_presses == 1) { digitalWrite(4, HIGH); digitalWrite(5, HIGH); digitalWrite(6, LOW); digitalWrite(7, LOW); Serial.println("num_presses 1"); } // button has been pressed twice! if (num_presses == 2) { digitalWrite(4, HIGH); digitalWrite(5, HIGH); Serial.println("num_presses 2"); if (millis() > time_for_nextfade_1) { time_for_nextfade_1 = millis() + (unsigned long)NEXTFADE_INTERVAL_1; if (current == 0) { target = 20; strobe_count += 1; Serial.println("strobe_count"); }} if (current == 20) { target = 0; } if (millis() > time_for_fadestep_1) { time_for_fadestep_1 = millis() + (unsigned long)FADE_INTERVAL_1; if (current < target) current+=4; if (current > target) current-=.5; analogWrite(LED_PIN1, current); Serial.print(target); Serial.print(" "); Serial.println(current); } if (millis() > time_for_nextfade_2) { time_for_nextfade_2 = millis() + (unsigned long)NEXTFADE_INTERVAL_2; if (current == 1) { target = 20; }} if (current == 20) { target = 0; } if (millis() > time_for_fadestep_2) { time_for_fadestep_2 = millis() + (unsigned long)FADE_INTERVAL_2; if (current < target) current+=4; if (current > target) current-=.5; analogWrite(LED_PIN2, current); Serial.print(target); Serial.print(" "); Serial.println(current); } } if (digitalRead(10) == HIGH && num_presses == 3) { Serial.println("num_presses 3, resetting num_presses to 0"); num_presses = 0; } // stobe count causes reset if (strobe_count == 6) { num_presses = 1; Serial.println("stobe count delay"); if (millis() > time_for_strobe_delay) { time_for_strobe_delay = millis() + (unsigned long)STROBE_COUNT_DELAY; strobe_count = 0; num_presses = 2; } } }
<template> <div v-if="show" class="modal-mask"> <div class="modal-wrapper"> <div class="modal-container"> <div class="modal-header" :class="mode"> <h3>{{ mode }} sentence</h3> </div> <div class="modal-body"> <div class="sentence"> <input type="text" v-model="updateSentence.sentence" placeholder="sentence" required /> <div> <button @click.prevent=" updateSentence.favorite = !updateSentence.favorite " :class=" updateSentence.favorite === true ? 'fav-btn' : 'unfav-btn' " :style="{ background: updateSentence.sgId != 'all' && updateSentence.favorite === true ? groupStore.getSGroupById(updateSentence.sgId).color : 'white', }" > &#x2665; </button> </div> </div> <input type="text" v-model="updateSentence.translate" placeholder="translate" /> <textarea v-model="updateSentence.description" placeholder="description" rows="5" ></textarea> <div class="group-select"> <select class="sgs" v-model="updateSentence.sgId" :style="{ background: updateSentence.sgId != 'all' ? groupStore.getSGroupById(updateSentence.sgId).color : 'white', }" required > <option value="all" disabled>odaberi</option> <option v-for="group in groupStore.sgroups" :key="group.id" :value="group.id" :style="{ background: group.color }" > Grupa: {{ group.name }} -- [{{ group.numOfItems }}] </option> </select> <button @click="showModal = true" class="new-group-btn">new</button> </div> <br /> </div> <div class="modal-footer"> <slot name="footer"> <button @click="save">save</button> <button @click.prevent="closeModal">cancel</button> </slot> </div> </div> </div> <AddEditGroupModal v-if="showModal" :show="showModal" :group="newGroup" :mode="'new'" @close="switchSg" /> </div> </template> <script setup> import { reactive, ref } from "vue"; import useCrud from "../../composables/useCRUD.js"; import AddEditGroupModal from "../../views/groups/AddEditGroupModal.vue"; import { useSentenceStore } from "../../stores/sentences.js"; import { useGroupStore } from "../../stores/groups.js"; import { useToastStore } from "../../stores/toast.js"; const props = defineProps({ sentence: Object, idx: Number, show: Boolean, mode: String, }); const emit = defineEmits(["close"]); const { createFun, readFun, patchFun } = useCrud(); const sentenceStore = useSentenceStore(); const groupStore = useGroupStore(); const toastStore = useToastStore(); const updateSentence = reactive({ ...props.sentence }); async function save() { if (props.mode === "new") { sentenceStore.saveSentence(updateSentence); toastStore.showToast("recenica dodata", "success"); } else { sentenceStore.editSentence(updateSentence, props.idx); //provjeri ako se ne poklapaju grupe - u jednoj oduzimas u drugoj dodaje if (props.sentence.sgId !== updateSentence.sgId) { sentenceStore.decreaseNumOfSentencesInGroup(props.sentence.sgId); sentenceStore.increaseNumOfSentencesInGroup(updateSentence.sgId); } // toastStore.showToast("recenica izmjenjena", "info"); toastStore.showToast2("recenica izmjenjena", groupStore.getSgColor()); } if ( updateSentence.sgId !== groupStore.activeSgId && groupStore.activeSgId !== "all" ) { groupStore.activeSgId = updateSentence.sgId; sentenceStore.getSentences("SG", updateSentence.sgId); } closeModal(); } const numOfGroups = ref(groupStore.sgroups.length); function switchSg() { //provjera da li je dodata nova grupe ako jeste - prebaci na tu grupu if (groupStore.sgroups.length > numOfGroups.value) { console.log("vece je"); updateSentence.sgId = groupStore.sgroups[0].id; } showModal.value = false; } const showModal = ref(false); const newGroup = reactive({ name: "", description: "", dicId: props.sentence.dicId, color: "#ffffff", numOfItems: 0, type: "SGROUP", }); function closeModal() { emit("close"); } </script> <style scoped> .modal-container { width: 300px; } .sentence { display: flex; } .group-select { display: flex; align-content: center; align-items: center; } .new-group-btn { padding: 3px; margin-left: 3px; background: blue; color: cyan; } </style>
<template> <div class="todo-container"> <div class="todo-wrap"> <MyHeader :addTodo="addTodo"/> <MyList :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/> <MyFooter :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"/> </div> </div> </template> <script> import MyHeader from './components/MyHeader' import MyList from './components/MyList' import MyFooter from './components/MyFooter' export default { name: "App", components: { MyHeader, MyList, MyFooter }, data() { return { todos:[ {id:'001', title:'抽烟', done:true}, {id:'002', title:'喝酒', done:false}, {id:'003', title:'开车', done:true} ] } }, methods: { // 添加一个todo addTodo(todoObj){ this.todos.unshift(todoObj) }, // 勾选or取消勾选一个todo checkTodo(id){ this.todos.forEach((todo) => { if(todo.id === id) todo.done = !todo.done }); }, // 删除一个todo deleteTodo(id){ this.todos = this.todos.filter(todo=> todo.id !== id ) }, // 全选or取消全选 checkAllTodo(done){ this.todos.forEach((todo)=>{ todo.done = done }) }, // 清楚所有已经完成的todo clearAllTodo(){ this.todos = this.todos.filter((todo)=>{ return !todo.done }) } }, } </script> <style> /* base */ body { background-color: #fff; } .btn { display: inline-block; padding: 4px 12px; margin-bottom: 0; font-size: 14px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; box-shadow: inset 0 1px 0 rgba(255,255,255,0.2), 0 1px 2px rgba(0, 0,0,0.05); border-radius: 4px; } .btn-danger{ color: #fff; background-color: #da4f49; border: 1px solid #bd362f; } .btn-danger:hover{ color: #fff; background-color: #bd362f; } .btn:focus{ outline: none; } .todo-container{ width: 600px; margin: 0 auto; } .todo-container .todo-wrap{ padding: 10px; border: 1px solid #ddd; border-radius: 5px; } </style>
# Zoning Map PoC This mapping application shows zoning and other related data on a map of NYC. It is intended as a proof of concept for using React, Deck.gl, Chakra, and other related technologies. ## Running the project locally ### Make sure you're using the correct version of Node The `.nvmrc` file tells you which version of node you should be using to run the project. If you're using [nvm](https://github.com/nvm-sh/nvm) and already have the correct version installed, you can switch by running `nvm use` from the root of this repo. ### Install dependencies Once you have cloned this repo, install the necessary dependencies: ``` npm i ``` ### Set up your `.env` file to point to a running instance of the [Zoning API](https://github.com/NYCPlanning/ae-zoning-api) This project relies on data from a companion PoC API known as the "Zoning API". You will need to set up a `.env` file pointing to a URL where an instance of the Zoning API is hosted. The easiest way to do this is to clone that repo and run it locally. To do that, follow these steps: 1. Go to the [GitHub repo](https://github.com/NYCPlanning/ae-zoning-api) for Zoning API 2. Follow the steps there to clone the project, run the API, and run its database using docker compose 3. Leave that Zoning API and its database running in a separate terminal, and navigate back to where you cloned this repo. 4. Back in your cloned copy of this repo, create a file called `.env` in the root folder of the project and copy the contents of `sample.env` into that new file. The default value in `sample.env` should set the Zoning API URL variable to the correct value for your locally running instance of Zoning API ### Run the project Finally, to run this project locally: ``` npm run dev ``` ## Pulling data from [Zoning API](https://github.com/NYCPlanning/ae-zoning-api) This app relies heavily on data from the Zoning API backend application. It makes use of some front end libraries to make pulling data and managing the state of that data easier: * [Axios](https://axios-http.com/docs/intro) - A framework-agnostic HTTP client for javascript and typescript applications * [TanStack Query](https://tanstack.com/query/v4) - This is a general purpose asynchronous state management library for React. You can read more about what problems TanStack Query strives to solve [here](https://tanstack.com/query/v4/docs/react/overview#motivation). It provides useful state management such as caching and managing loading states. * [Kubb](https://www.kubb.dev/introduction) - A code generation library that reads [OpenAPI specification](https://www.openapis.org/) documents and generates typescript "client" libraries (sometimes also referred to as "SDKs"). It features a set of plugins to generate code for various JS/TS libraries, including Axios and TanStack Query. By pointing Kubb at the [OpenAPI document for Zoning API](https://github.com/NYCPlanning/ae-zoning-api/blob/main/openapi/openapi.yaml), we can avoid writing a lot of boilerplate code. ### Regenerating the Zoning API client code When the OpenAPI spec file for Zoning API changes, we will need to regenerate the client code in this repo. To do that, simply run `npm run generate`. Kubb is configured to put all generated code in `/src/gen`. Note that even though that code is generated, we do want to commit it and includes updates in PRs as necessary. A developer should **never** make manually changes or additions to code in the `/src/gen` folder. It should be purely what is outputted by Kubb. > You may see an error in your terminal after running `npm run generate` referring to the "path" argument being undefined. The root cause of this is still being looked into but it doesn't seem to affect the generated code so you can safely ignore it for now. Unless you think the contents of the Zoning API OpenAPI spec file have changed since the last time the client code was generated, you can safely skip this step. ### Using the Zoning API client code Once you have this application configured to point to a running instance of Zoning API, you can start to pull in data. To query data from the Zoning API in our React code, we only need to import and call the hooks generated by Kubb. The `Providers` component makes sure our entire application is wrapped by TanStack Query's `QueryClientProvider` component, so we should be able to call the hooks within any component. To query data, simply import the hook corresponding to the data you need from the `/src/gen` folder and call it within your React component. ``` import { useGetLandUses } from "./gen" // Update relative import path based on your component's file location // Within your component code const { isLoading, error, data, isFetching } = useGetLandUses(); ``` > In this example, the actual data returned from the API will be on the `data` property of the object returned by the hook. `useGetLandUses` is a hook generated by Kubb, but under the hood, it is using TanStack Query's `useQuery` hook. To learn more about what these hooks return, check out TanStack Query's documentation, particularly these [Query Basics](https://tanstack.com/query/v4/docs/react/guides/queries)
using bitirmeProje.Domain.Entities; using bitirmeProje.Domain.IRepositories; using bitirmeProje.Dto; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; namespace bitirmeProje.Controllers { [AllowAnonymous] public class LoginController : Controller { private readonly IUserRepository _userRepository; public LoginController(IUserRepository userRepository) { _userRepository = userRepository; } public IActionResult Index() { return View(); } [HttpPost] public async Task<IActionResult> UserLogin(LoginDto loginDto) { var loginUserData = await _userRepository.FirstOrDefaultAsync(x => x.Username == loginDto.Username && x.Password == loginDto.Password); if (loginUserData == null) { return Json(new Response<object> { Success = false, Message = "Kullanıcı adı veya şifre hatalı!", }); } var claims = new List<Claim>() { new Claim(ClaimTypes.Name, loginUserData.Username), new Claim(ClaimTypes.Role, loginUserData.IsAdmin ?"admin" : "user"), new Claim(ClaimTypes.NameIdentifier,loginUserData.Id.ToString()),//claimin içine kullanıcının id sini kaydettik, artık istediğimiz her yerden erişebiliriz. }; var userIdentity = new ClaimsIdentity(claims, "Login"); var principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(principal); //burada tokenı oluşturuyor. return Json(new Response<object> { Success = true, Message = "Giriş Yapıldı", Result = loginUserData }); } [HttpPost] public async Task<IActionResult> UserLogout() { await HttpContext.SignOutAsync(); // Kullanıcının oturumunu sonlandırır. return Json(new Response<object> { Success = true, Message = "Çıkış Yapıldı" }); } } }
import { useState, useContext } from "react"; import { Link } from "react-router-dom"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { IconDefinition, faPlus, faTrash, } from "@fortawesome/free-solid-svg-icons"; import { toast } from "react-toastify"; import { APIContext } from "@mwdb-web/commons/api"; import { AuthContext } from "@mwdb-web/commons/auth"; import { ObjectContext } from "@mwdb-web/commons/context"; import { ObjectLink, ActionCopyToClipboard, ConfirmationModal, TagList, } from "@mwdb-web/commons/ui"; import { getErrorMessage } from "@mwdb-web/commons/helpers"; import { useRemotePath } from "@mwdb-web/commons/remotes"; import { RelationsAddModal } from "../Actions/RelationsAddModal"; import { Capability, RelationItem } from "@mwdb-web/types/types"; type RelationToRemove = { relation: "parent" | "child"; id: string; }; type Props = { children?: RelationItem[]; parents?: RelationItem[]; header?: string; icon?: IconDefinition; updateRelationsActivePage?: () => void; }; export function RelationsBox(props: Props) { const api = useContext(APIContext); const auth = useContext(AuthContext); const context = useContext(ObjectContext); const remotePath = useRemotePath(); const [isAttributeAddModalOpen, setAttributeAddModalOpen] = useState<boolean>(false); const [isAttributeDeleteModalOpen, setAttributeDeleteModalOpen] = useState<boolean>(false); const [disabledModalButton, setDisabledModalButton] = useState<boolean>(false); const [relationToRemove, setRelationToRemove] = useState<RelationToRemove>( {} as RelationToRemove ); const updateRelationsActivePage = props.updateRelationsActivePage; async function addObjectRelations(relation: string, value: string) { try { if (relation === "child") { await api.addObjectRelation(context.object!.id!, value); } if (relation === "parent") { await api.addObjectRelation(value, context.object!.id!); } context.updateObject(); setAttributeAddModalOpen(false); } catch (error: any) { if (error.response && error.response.status === 404) { toast("Object not found or incorrect SHA256 hash.", { type: "error", }); } else { toast(getErrorMessage(error), { type: "error", }); } } } async function removeObjectRelations(relation: string, value: string) { try { setDisabledModalButton(true); if (relation === "child") { await api.removeObjectRelation(context.object!.id!, value); } if (relation === "parent") { await api.removeObjectRelation(value, context.object!.id!); } context.updateObject(); setAttributeDeleteModalOpen(false); setDisabledModalButton(false); } catch (error: any) { if (error.response && error.response.status === 404) { toast("Object not found or incorrect SHA256 hash.", { type: "error", }); } else { toast(getErrorMessage(error), { type: "error", }); } setDisabledModalButton(false); } } const parents = (props.parents || []).map((parent, index, array) => ( <tr key={`parent-${parent.id}`} className="flickerable"> <th>parent</th> <td> <span> <ObjectLink {...parent} inline /> </span> <span className="ml-2"> <ActionCopyToClipboard text={parent.id} tooltipMessage="Copy sha256 to clipboard" /> </span> {auth.hasCapability(Capability.removingParents) && ( <span className="ml-2" data-toggle="tooltip" title="Remove relation to parent object." onClick={() => { setRelationToRemove({ relation: "parent", id: parent.id, }); setAttributeDeleteModalOpen(true); }} > <i> <FontAwesomeIcon icon={faTrash} size="sm" style={{ cursor: "pointer" }} /> </i> </span> )} </td> <td> <TagList tag="" tags={parent.tags} searchEndpoint={`${remotePath}/search`} /> </td> </tr> )); const children = (props.children || []).map((child, index, array) => ( <tr key={`child-${child.id}`} className="flickerable"> <th>child</th> <td> <span> <ObjectLink {...child} inline /> </span> <span className="ml-2"> <ActionCopyToClipboard text={child.id} tooltipMessage="Copy sha256 to clipboard" /> </span> {auth.hasCapability(Capability.removingParents) && ( <span className="ml-2" data-toggle="tooltip" title="Remove relation to child object." onClick={() => { setRelationToRemove({ relation: "child", id: child.id, }); setAttributeDeleteModalOpen(true); }} > <i> <FontAwesomeIcon icon={faTrash} size="sm" style={{ cursor: "pointer" }} /> </i> </span> )} </td> <td> <TagList tag="" tags={child.tags} /> </td> </tr> )); return ( <div className="card card-default"> <div className="card-header"> {props.icon && <FontAwesomeIcon icon={props.icon} size="1x" />} {props.header || "Relations"} {!api.remote ? ( <Link to="#" className="float-right" onClick={(ev) => { ev.preventDefault(); setAttributeAddModalOpen(true); }} > <FontAwesomeIcon icon={faPlus} pull="left" size="1x" /> Add </Link> ) : ( [] )} </div> {parents.length + children.length > 0 ? ( <table className="table table-striped table-bordered table-hover" id="rel_table" > <tbody id="rel_body"> {parents} {children} </tbody> </table> ) : ( <div className="card-body text-muted"> No relations to display </div> )} <RelationsAddModal isOpen={isAttributeAddModalOpen} onSubmit={addObjectRelations} onRequestModalClose={() => setAttributeAddModalOpen(false)} /> <ConfirmationModal isOpen={isAttributeDeleteModalOpen} disabled={disabledModalButton} onRequestClose={() => setAttributeDeleteModalOpen(false)} onConfirm={() => { removeObjectRelations( relationToRemove.relation, relationToRemove.id ); updateRelationsActivePage && updateRelationsActivePage(); }} message="Are you sure you want to delete this relation?" buttonStyle="btn btn-danger" confirmText="yes" cancelText="no" /> </div> ); }
package com.lenovo.dsa.page; import com.codeborne.selenide.SelenideElement; import io.appium.java_client.pagefactory.AndroidFindBy; import static com.codeborne.selenide.Condition.visible; public class TestPage { <#list elements as element> /** * ${element.note} */ @AndroidFindBy(id = "${element.id}") private SelenideElement ${element.name}; <#if element.isClickElement()> public void click${element.name?cap_first}() { ${element.name}.as("${element.note}").shouldBe(visible).click(); } </#if> <#if element.isTextElement()> public String get${element.name?cap_first}Text() { return ${element.name}.as("${element.note}").shouldBe(visible).getText(); } </#if> <#if element.isInputFieldElement()> public void enter${element.name?cap_first}(String text) { ${element.name}.as("${element.note}").shouldBe(visible).setValue(text); } </#if> </#list> }
package com.example.applazada.Adapter; import android.annotation.SuppressLint; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.applazada.API.ApiService; import com.example.applazada.LocalVariablesAndMethods; import com.example.applazada.Model.DangNhapSQLite.ModelNhanVien; import com.example.applazada.Model.MessageResponse; import com.example.applazada.Model.SanPham; import com.example.applazada.Model.SanPhamMua; import com.example.applazada.R; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class AdapterSanPhamDangXuLy extends RecyclerView.Adapter<AdapterSanPhamDangXuLy.ViewHolderSanPhamMua>{ Context context; List<SanPhamMua> sanPhamList; ModelNhanVien modelNhanVien = new ModelNhanVien(); public AdapterSanPhamDangXuLy(Context context, List<SanPhamMua> sanPhamList) { this.context = context; this.sanPhamList = sanPhamList; } public class ViewHolderSanPhamMua extends RecyclerView.ViewHolder { TextView txtTenSanPham, txtSoLuong, txtDonGia, txtTongTien, txtTrangThai; Button btnXuLy; public ViewHolderSanPhamMua(@NonNull View itemView) { super(itemView); txtTenSanPham = itemView.findViewById(R.id.txtTenSanPham); txtSoLuong = itemView.findViewById(R.id.txtSoLuong); txtDonGia = itemView.findViewById(R.id.txtDonGia); txtTongTien = itemView.findViewById(R.id.txtTongTien); btnXuLy = itemView.findViewById(R.id.btnXuLy); txtTrangThai = itemView.findViewById(R.id.txtTrangThai); } } @NonNull @Override public ViewHolderSanPhamMua onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom_layout_chitietdonmua, parent, false); ViewHolderSanPhamMua viewHolderSanPhamMua = new ViewHolderSanPhamMua(view); return viewHolderSanPhamMua; } @SuppressLint("RecyclerView") @Override public void onBindViewHolder(@NonNull ViewHolderSanPhamMua holder, int position) { SanPhamMua sanPham = sanPhamList.get(position); NumberFormat numberFormat = new DecimalFormat("###,###"); holder.txtTenSanPham.setText(sanPham.getTenSP()); holder.txtSoLuong.setText(String.valueOf(sanPham.getSoLuong())); String donGia = numberFormat.format(sanPham.getGia()).toString(); holder.txtDonGia.setText(donGia); String tongTien = numberFormat.format(sanPham.getGia() * sanPham.getSoLuong()).toString(); holder.txtTongTien.setText(tongTien + " VNĐ"); holder.txtTrangThai.setText(LocalVariablesAndMethods.DANGXULY); holder.btnXuLy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { modelNhanVien.MoKetNoiSQL(context); int MaNV = modelNhanVien.LayNhanVien().getMaNV(); int MaSP = sanPham.getMaSP(); int MaHD = sanPham.getMaHD(); ApiService.apiService.HuyDonHang(LocalVariablesAndMethods.DANGXULY, LocalVariablesAndMethods.DAHUY, MaHD, MaNV, MaSP).enqueue(new Callback<MessageResponse>() { @SuppressLint("NotifyDataSetChanged") @Override public void onResponse(Call<MessageResponse> call, Response<MessageResponse> response) { MessageResponse messageResponse = response.body(); if (messageResponse.getMessage().equals("Success")) { Toast.makeText(context, "Huỷ đơn hàng thành công", Toast.LENGTH_SHORT).show(); notifyDataSetChanged(); notifyItemRemoved(position); } else { Toast.makeText(context, "Có lỗi xảy ra", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<MessageResponse> call, Throwable t) { } }); } }); } @Override public int getItemCount() { return sanPhamList.size(); } }
const app = require('../src/app') const debug = require('debug')('balta:server'); const http = require('http'); const port = normalizePort(process.env.PORT || '3000'); app.set('port', port); const server = http.createServer(app); server.listen(port); server.on('error', onError); // no caso de erro com o servidor a função on Error é chamada server.on('listening', onListening); console.log('Server Ok, using port ' + port); // essa função busca a porta disponível para evitar problemas de portas em uso function normalizePort(val) { const port = parseInt(val, 10); if (isNaN(port)){ return val; } if (port > 0) { return port; } return false; } // essa função retorna posíveis erro do servidor como por exemplo porta em uso function onError(error) { if (error.syscall != 'listen'){ throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port' + port; switch (error.code) { case 'EACCES': console.error(bind + ' require elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } // essa função será usada para debug function onListening(){ const addr = server.address(); const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port' + addr.port; debug('Listening on ' + bind); }
<!DOCTYPE html> <html> <head> <title>AngularJS-Prayoga (5180411043)</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> </head> <body ng-app="myApps"> <div ng-controller="MHSController"> <p> Search : <input type="text" ng-model="Searchtext"> </p> <table width="50%" border="1" cellpadding="5" cellspacing="0"> <thead> <tr> <th><input type="text" ng-model="NIM"></th> <th> <input type="text" ng-model="NAMA"></th> </th> <th><input type="text" ng-model="ALAMAT"></th> <th><input type="text" ng-model="jurusan"></th> <th><button ng-click="insert()">Add</button></th> </tr> <tr> <th>NIM</th> <th>NAMA</th> <th>ALAMAT</th> <th>JURUSAN</th> </tr> </thead> <tbody> <tr ng-show="filteredData==0"> <td colspan="4"> No Data! </td> </tr> <tr ng-repeat="player in players | filter:Searchtext "> <td>{{ player.NIM }}</td> <td>{{ player.NAMA }}</td> <td>{{ player.ALAMAT }}</td> <td>{{ player.jurusan }}</td> <td><a href="#" ng-click="delete($index)">Delete</a></td> </tr> </tbody> </table> </div> </body> <script type="text/javascript" > var app = angular.module("myApps", []); app.controller("MHSController", function($scope){ $scope.players = [ {NIM:"5180411047", ALAMAT:"Makasar", NAMA:"Joko prabowo", jurusan:"Informatika"}, {NIM:"5180411021", ALAMAT:"Lampung", NAMA:"Siswanto", jurusan:"Management"}, {NIM:"5180411031", ALAMAT:"Surabaya", NAMA:"Bambang", jurusan:"Akuntansi"}, {NIM:"5180411051", ALAMAT:"Yogyakarta", NAMA:"Andi", jurusan:"Perbankan"}, {NIM:"5180411012", ALAMAT:"Jakarta", NAMA:"Bagus Setiawan", jurusan:"Sistem Informatika"}, {NIM:"5180411044", ALAMAT:"Lombok", NAMA:"Uzumaki Bayu", jurusan:"Elektro"}, ]; $scope.alamat = [ "Yogyakarta", "Jakarta", "Surabaya", "Lombok", "Lampung", "Makasar", "Bali" ]; $scope.insert = function(){ $scope.players.push({ NIM: $scope.NIM, NAMA : $scope.NAMA, ALAMAT : $scope.ALAMAT, jurusan: $scope.jurusan }); $scope.clearForm(); }; $scope.clearForm = function(){ $scope.NIM = ""; $scope.NAMA = ""; $scope.ALAMAT = ""; $scope.jurusan = "" } $scope.delete = function(index){ $scope.players.splice(index, 1); } }); </script> </html>
import 'package:bruceboard/models/firestoredoc.dart'; import 'package:bruceboard/models/game.dart'; import 'package:bruceboard/models/series.dart'; import 'package:bruceboard/pages/game/game_maintain.dart'; import 'package:bruceboard/pages/game/game_tile.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:bruceboard/models/player.dart'; import 'package:bruceboard/services/databaseservice.dart'; import 'package:bruceboard/shared/loading.dart'; class GameList extends StatefulWidget { final Series series; const GameList({super.key, required this.series}); @override _GameListState createState() => _GameListState(); } class _GameListState extends State<GameList> { late Series series; @override void initState() { series = widget.series; super.initState(); } @override Widget build(BuildContext context) { void callback() { setState(() { }); } BruceUser bruceUser = Provider.of<BruceUser>(context); return StreamBuilder<List<FirestoreDoc>>( stream: DatabaseService(FSDocType.game, sidKey: series.key).fsDocListStream, builder: (context, snapshots) { if(snapshots.hasData) { List<Game> game = snapshots.data!.map((g) => g as Game).toList(); return Scaffold( appBar: AppBar( // backgroundColor: Colors.blue[900], title: Text('Manage Games - Count: ${series.noGames}/${game.length}'), centerTitle: true, elevation: 0, leading: IconButton( icon: const Icon(Icons.arrow_back), // if user presses back, cancels changes to list (order/deletes) onPressed: () { Navigator.of(context).pop(); }, ), actions: [ IconButton( onPressed: () async { await Navigator.of(context).push( MaterialPageRoute(builder: (context) => GameMaintain(series: series))); setState(() {}); // Set state to refresh series changes. }, icon: const Icon(Icons.add_circle_outline), ) ]), body: ListView.builder( itemCount: game.length, itemBuilder: (context, index) { return GameTile(callback: callback, series: series, game: game[index]); }, ), ); } else { return const Loading(); } } ); } }
import os import logging import vtk import re import slicer from slicer.ScriptedLoadableModule import * from slicer.util import VTKObservationMixin import sitkUtils as su import SimpleITK as sitk import vtkSegmentationCorePython as vtkSegmentationCore import torch import sysconfig try: from tumorsegmentator.python_api import tumorsegmentator except: slicer.util.pip_install('git+https://github.com/ReubenDo/TumorSegmentator#egg=TumorSegmentator') # slicer.util.pip_install('tumorsegmentator') from tumorsegmentator.python_api import tumorsegmentator try: from HD_BET.run import run_hd_bet except: slicer.util.pip_install('git+https://github.com/ReubenDo/HD-BET#egg=HD-BET') from HD_BET.run import run_hd_bet import HD_BET.paths os.makedirs(HD_BET.paths.folder_with_parameter_files, exist_ok=True) from pathlib import Path # # SlicerTumorSegmentator # REPO = 'https://github.com/ReubenDo/SlicerSlicerTumorSegmentator/' PARAMETERS_BRAINSFIT = ['--samplingPercentage', '0.02', '--useRigid', '--useAffine', '--initializeTransformMode', 'useCenterOfHeadAlign' ] class SlicerTumorSegmentator(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent): ScriptedLoadableModule.__init__(self, parent) self.parent.title = 'Brain Tumor Segmentator' self.parent.categories = ['Segmentation'] self.parent.dependencies = [] self.parent.contributors = ["Reuben Dorent (Harvard University)"] self.parent.helpText = ( 'Brain Tumor segmentator based on SlicerTotalSegmentator.' f'<p>Code: <a href="{REPO}">here</a>.</p>' ) # self.parent.acknowledgementText = ( # 'This work was was funded by the Engineering and Physical Sciences' # ' Research Council (EPSRC) and supported by the School of Biomedical Engineering' # " & Imaging Sciences (BMEIS) of King's College London." # ) # # SlicerTumorSegmentatorWidget # class SlicerTumorSegmentatorWidget(ScriptedLoadableModuleWidget, VTKObservationMixin): """Uses ScriptedLoadableModuleWidget base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self, parent=None): """ Called when the user opens the module the first time and the widget is initialized. """ ScriptedLoadableModuleWidget.__init__(self, parent) VTKObservationMixin.__init__(self) # needed for parameter node observation self.logic = None self._parameterNode = None self._updatingGUIFromParameterNode = False def setup(self): """ Called when the user opens the module the first time and the widget is initialized. """ ScriptedLoadableModuleWidget.setup(self) # Load widget from .ui file (created by Qt Designer). # Additional widgets can be instantiated manually and added to self.layout. uiWidget = slicer.util.loadUI(self.resourcePath('UI/SlicerTumorSegmentator.ui')) self.layout.addWidget(uiWidget) self.ui = slicer.util.childWidgetVariables(uiWidget) # Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's # "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's. # "setMRMLScene(vtkMRMLScene*)" slot. uiWidget.setMRMLScene(slicer.mrmlScene) # Create logic class. Logic implements all computations that should be possible to run # in batch mode, without a graphical user interface. self.logic = SlicerTumorSegmentatorLogic() self.logic.logCallback = self.addLog # Connections # These connections ensure that we update parameter node when scene is closed self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose) self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose) # These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene # (in the selected parameter node). self.ui.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.cet1Selector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.t2Selector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.flairSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.refSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) self.ui.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) # Buttons self.ui.applyButton.connect('clicked(bool)', self.onApplyButton) # Make sure parameter node is initialized (needed for module reload) self.initializeParameterNode() def addLog(self, text): """Append text to log window """ self.ui.statusLabel.appendPlainText(text) slicer.app.processEvents() # force update def cleanup(self): """ Called when the application closes and the module widget is destroyed. """ self.removeObservers() def enter(self): """ Called each time the user opens this module. """ # Make sure parameter node exists and observed self.initializeParameterNode() def exit(self): """ Called each time the user opens a different module. """ # Do not react to parameter node changes (GUI wlil be updated when the user enters into the module) self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) def onSceneStartClose(self, caller, event): """ Called just before the scene is closed. """ # Parameter node will be reset, do not use it anymore self.setParameterNode(None) def onSceneEndClose(self, caller, event): """ Called just after the scene is closed. """ # If this module is shown while the scene is closed then recreate a new parameter node immediately if self.parent.isEntered: self.initializeParameterNode() def initializeParameterNode(self): """ Ensure parameter node exists and observed. """ # Parameter node stores all user choices in parameter values, node selections, etc. # so that when the scene is saved and reloaded, these settings are restored. self.setParameterNode(self.logic.getParameterNode()) # Select default input nodes if nothing is selected yet to save a few clicks for the user if not self._parameterNode.GetNodeReference("InputVolumet1"): firstVolumeNode = slicer.mrmlScene.GetFirstNodeByClass("vtkMRMLScalarVolumeNode") if firstVolumeNode: self._parameterNode.SetNodeReferenceID("InputVolumet1", firstVolumeNode.GetID()) def setParameterNode(self, inputParameterNode): """ Set and observe parameter node. Observation is needed because when the parameter node is changed then the GUI must be updated immediately. """ if inputParameterNode: self.logic.setDefaultParameters(inputParameterNode) # Unobserve previously selected parameter node and add an observer to the newly selected. # Changes of parameter node are observed so that whenever parameters are changed by a script or any other module # those are reflected immediately in the GUI. if self._parameterNode is not None: self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) self._parameterNode = inputParameterNode if self._parameterNode is not None: self.addObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) # Initial GUI update self.updateGUIFromParameterNode() def updateGUIFromParameterNode(self, caller=None, event=None): """ This method is called whenever parameter node is changed. The module GUI is updated to show the current state of the parameter node. """ if self._parameterNode is None or self._updatingGUIFromParameterNode: return # Make sure GUI changes do not call updateParameterNodeFromGUI (it could cause infinite loop) self._updatingGUIFromParameterNode = True # Update node selectors and sliders self.ui.inputSelector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolumet1")) self.ui.cet1Selector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolumecet1")) self.ui.t2Selector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolumet2")) self.ui.flairSelector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolumeflair")) self.ui.refSelector.setCurrentNode(self._parameterNode.GetNodeReference("RefVolume")) self.ui.outputSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputVolume")) self.ui.checkCoregistered.checked = self._parameterNode.GetParameter("Coregistered") == "true" self.ui.checkSkullstripped.checked = self._parameterNode.GetParameter("Skullstripped") == "true" self.ui.checkDeleteProcessed.checked = self._parameterNode.GetParameter("DeleteProcessed") == "true" #self.ui.progressBar1.setCurrentNode(self._parameterNode.GetNodeReference("ProgressBar1")) # Update buttons states and tooltips if self._parameterNode.GetNodeReference("RefVolume") and self._parameterNode.GetNodeReference("OutputVolume"): self.ui.applyButton.toolTip = "Compute output volume" self.ui.applyButton.enabled = True else: self.ui.applyButton.toolTip = "Select input and output volume nodes" self.ui.applyButton.enabled = False # All the GUI updates are done self._updatingGUIFromParameterNode = False def updateParameterNodeFromGUI(self, caller=None, event=None): """ This method is called when the user makes any change in the GUI. The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded). """ if self._parameterNode is None or self._updatingGUIFromParameterNode: return wasModified = self._parameterNode.StartModify() # Modify all properties in a single batch self._parameterNode.SetNodeReferenceID("InputVolumet1", self.ui.inputSelector.currentNodeID) self._parameterNode.SetNodeReferenceID("InputVolumecet1", self.ui.cet1Selector.currentNodeID) self._parameterNode.SetNodeReferenceID("InputVolumet2", self.ui.t2Selector.currentNodeID) self._parameterNode.SetNodeReferenceID("InputVolumeflair", self.ui.flairSelector.currentNodeID) self._parameterNode.SetNodeReferenceID("RefVolume", self.ui.refSelector.currentNodeID) self._parameterNode.SetNodeReferenceID("OutputVolume", self.ui.outputSelector.currentNodeID) self._parameterNode.SetParameter("Coregistered", "true" if self.ui.checkCoregistered.checked else "false") self._parameterNode.SetParameter("Skullstripped", "true" if self.ui.checkSkullstripped.checked else "false") self._parameterNode.SetParameter("DeletePreprocessed", "true" if self.ui.checkDeleteProcessed.checked else "false") self._parameterNode.EndModify(wasModified) def onApplyButton(self): """ Run processing when user clicks "Apply" button. """ try: # Compute output self.logic.process( self.ui.refSelector.currentNode(), self.ui.inputSelector.currentNode(), self.ui.cet1Selector.currentNode(), self.ui.t2Selector.currentNode(), self.ui.flairSelector.currentNode(), self.ui.outputSelector.currentNode(), self.ui.checkCoregistered.checked, self.ui.checkSkullstripped.checked, self.ui.checkDeleteProcessed.checked) except Exception as e: slicer.util.errorDisplay("Failed to compute results: "+str(e)) import traceback traceback.print_exc() # # SlicerTumorSegmentatorLogic # class SlicerTumorSegmentatorLogic(ScriptedLoadableModuleLogic): """This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget. Uses ScriptedLoadableModuleLogic base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def __init__(self): """ Called when the logic class is instantiated. Can be used for initializing member variables. """ ScriptedLoadableModuleLogic.__init__(self) self.logCallback = None def log(self, text): logging.info(text) if self.logCallback: self.logCallback(text) def logProcessOutput(self, proc, returnOutput=False): # Wait for the process to end and forward output to the log output = "" from subprocess import CalledProcessError while True: try: line = proc.stdout.readline() if not line: break if returnOutput: output += line self.log(line.rstrip()) except UnicodeDecodeError as e: # Code page conversion happens because `universal_newlines=True` sets process output to text mode, # and it fails because probably system locale is not UTF8. We just ignore the error and discard the string, # as we only guarantee correct behavior if an UTF8 locale is used. pass proc.wait() retcode = proc.returncode if retcode != 0: raise CalledProcessError(retcode, proc.args, output=proc.stdout, stderr=proc.stderr) return output if returnOutput else None def setDefaultParameters(self, parameterNode): """ Initialize parameter node with default settings. """ pass def readSegmentationFolder(self, outputSegmentation, output_segmentation_dir, task="tumor"): """ The method is very slow, but this is the only option for some specialized tasks. """ import os outputSegmentation.GetSegmentation().RemoveAllSegments() # Get color node with random colors randomColorsNode = slicer.mrmlScene.GetNodeByID('vtkMRMLColorTableNodeRandom') rgba = [0, 0, 0, 0] # Get label descriptions # Get label descriptions if task is provided from tumorsegmentator.map_to_binary import class_map labelValueToSegmentName = class_map[task] if task else {} def import_labelmap_to_segmentation(labelmapVolumeNode, segmentId): updatedSegmentIds = vtk.vtkStringArray() updatedSegmentIds.InsertNextValue(segmentId) slicer.modules.segmentations.logic().ImportLabelmapToSegmentationNode(labelmapVolumeNode, outputSegmentation, updatedSegmentIds) slicer.mrmlScene.RemoveNode(labelmapVolumeNode) # Read each candidate file for labelValue, segmentName in labelValueToSegmentName.items(): self.log(f"Importing candidate {segmentName}") candidate = [k for k in os.listdir(output_segmentation_dir) if segmentName in k][0] labelVolumePath = os.path.join(output_segmentation_dir, candidate) if not os.path.exists(labelVolumePath): self.log(f"Path {segmentName} not exists.") continue labelmapVolumeNode = slicer.util.loadLabelVolume(labelVolumePath, {"name": segmentName}) randomColorsNode.GetColor(labelValue, rgba) segmentId = outputSegmentation.GetSegmentation().AddEmptySegment(segmentName, segmentName, rgba[0:3]) import_labelmap_to_segmentation(labelmapVolumeNode, segmentId) def readSegmentation(self, outputSegmentation, outputSegmentationFile, task='tumor'): # Get label descriptions from tumorsegmentator.map_to_binary import class_map labelValueToSegmentName = class_map[task] maxLabelValue = max(labelValueToSegmentName.keys()) if min(labelValueToSegmentName.keys()) < 0: raise RuntimeError("Label values in class_map must be positive") # Get color node with random colors randomColorsNode = slicer.mrmlScene.GetNodeByID('vtkMRMLColorTableNodeRandom') rgba = [0, 0, 0, 0] # Create color table for this segmentation task colorTableNode = slicer.vtkMRMLColorTableNode() colorTableNode.SetTypeToUser() colorTableNode.SetNumberOfColors(maxLabelValue+1) colorTableNode.SetName(task) for labelValue in labelValueToSegmentName: randomColorsNode.GetColor(labelValue,rgba) colorTableNode.SetColor(labelValue, rgba[0], rgba[1], rgba[2], rgba[3]) colorTableNode.SetColorName(labelValue, labelValueToSegmentName[labelValue]) slicer.mrmlScene.AddNode(colorTableNode) # Load the segmentation # outputSegmentation.SetLabelmapConversionColorTableNodeID(colorTableNode.GetID()) outputSegmentation.AddDefaultStorageNode() storageNode = outputSegmentation.GetStorageNode() storageNode.SetFileName(outputSegmentationFile) storageNode.ReadData(outputSegmentation) slicer.mrmlScene.RemoveNode(colorTableNode) def _apply_mask(self, input, output, mask): # Reorient in case HD-BET changed the orientation of the raw file input_img = sitk.ReadImage(input) mask = sitk.ReadImage(mask) masked_image = sitk.Mask(input_img, mask==1, outsideValue=0) sitk.WriteImage(masked_image, output) def process(self, refVolume, inputVolumet1, inputVolumecet1, inputVolumet2, inputVolumeflair, outputVolume, coregistered, skullstripped, deleteprocessed): """ Run the processing algorithm. Can be used without GUI widget. :param inputVolume: volume to be thresholded :param outputVolume: thresholding result """ if not inputVolumet1 or not outputVolume: raise ValueError("Input or output volume is invalid") import time startTime = time.time() self.log('Processing started') if torch.backends.cuda.is_built() and torch.cuda.is_available(): device = "gpu" else: device = "cpu" tempFolder = slicer.util.tempDirectory() import shutil pythonSlicerExecutablePath = shutil.which('PythonSlicer') if not pythonSlicerExecutablePath: raise RuntimeError("Python was not found") refFile = tempFolder+"/tumor-segmentator-ref.nii.gz" inputFilet1 = tempFolder+"/tumor-segmentator-t1.nii.gz" inputFilecet1 = tempFolder+"/tumor-segmentator-cet1.nii.gz" inputFilet2 = tempFolder+"/tumor-segmentator-t2.nii.gz" inputFileflair = tempFolder+"/tumor-segmentator-flair.nii.gz" # Write input volume to file # TumorSegmentator requires NIFTI self.log(f"Writing input file to {refFile}") volumeStorageNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLVolumeArchetypeStorageNode") volumeStorageNode.SetFileName(refFile) volumeStorageNode.UseCompressionOff() volumeStorageNode.WriteData(refVolume) volumeStorageNode.UnRegister(None) self.log(f"Writing input file to {inputFilet1}") volumeStorageNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLVolumeArchetypeStorageNode") volumeStorageNode.SetFileName(inputFilet1) volumeStorageNode.UseCompressionOff() volumeStorageNode.WriteData(inputVolumet1) volumeStorageNode.UnRegister(None) self.log(f"Writing input file to {inputFilecet1}") volumeStorageNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLVolumeArchetypeStorageNode") volumeStorageNode.SetFileName(inputFilecet1) volumeStorageNode.UseCompressionOff() volumeStorageNode.WriteData(inputVolumecet1) volumeStorageNode.UnRegister(None) options = ["-t1", inputFilet1, "-cet1", inputFilecet1, "-o", tempFolder] if not inputVolumet2 is None and not inputVolumeflair is None: self.log(f"Writing input file to {inputFilet2}") volumeStorageNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLVolumeArchetypeStorageNode") volumeStorageNode.SetFileName(inputFilet2) volumeStorageNode.UseCompressionOff() volumeStorageNode.WriteData(inputVolumet2) volumeStorageNode.UnRegister(None) options.append('-t2') options.append(inputFilet2) self.log(f"Writing input file to {inputFileflair}") volumeStorageNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLVolumeArchetypeStorageNode") volumeStorageNode.SetFileName(inputFileflair) volumeStorageNode.UseCompressionOff() volumeStorageNode.WriteData(inputVolumeflair) volumeStorageNode.UnRegister(None) options.append('-flair') options.append(inputFileflair) if not coregistered: self.log(f"Performing co-registration") list_files = [k for k in os.listdir(tempFolder) if 'nii' in k and not 'ref' in k] if refVolume.GetID()==inputVolumet1.GetID(): list_files = [k for k in list_files if not '-t1.' in k] elif refVolume.GetID()==inputVolumecet1.GetID(): list_files = [k for k in list_files if not '-cet1.' in k] elif refVolume.GetID()==inputVolumet2.GetID(): list_files = [k for k in list_files if not '-t2.' in k] elif refVolume.GetID()==inputVolumeflair.GetID(): list_files = [k for k in list_files if not '-flair.' in k] for file in list_files: inputFileTemp = os.path.join(tempFolder, file) self.log(f"Performing co-registered input file to {inputFileTemp}") BRAINSFITExecutablePath = shutil.which('Slicer') BRAINSFITCommand = [BRAINSFITExecutablePath, '--launch', 'BRAINSFit'] options_brainsfit = ['--fixedVolume', refFile, '--movingVolume', inputFileTemp, '--outputVolume', inputFileTemp] # self.log(' '.join([BRAINSFITExecutablePath] + options_brainsfit)) proc = slicer.util.launchConsoleProcess(BRAINSFITCommand + options_brainsfit + PARAMETERS_BRAINSFIT) self.logProcessOutput(proc) if not skullstripped: self.log(f"Performing skullstripping") mask_sk = tempFolder+"/tumor-segmentator-ref_masked_mask.nii.gz" output_sk = tempFolder+"/tumor-segmentator-ref_masked.nii.gz" HDBETExecutablePath = os.path.join(sysconfig.get_path('scripts'), "hd-bet") HDBETCommand = [ pythonSlicerExecutablePath, HDBETExecutablePath] device_hdbet = "0" if device=="gpu" else "cpu" options_hdbet = ['-i', refFile, '-o', output_sk, '-device', device_hdbet, '-mode', 'fast', '-tta', '0'] self.log(f"Tumor Segmentator arguments: {HDBETCommand + options_hdbet}") proc = slicer.util.launchConsoleProcess(HDBETCommand + options_hdbet) self.logProcessOutput(proc) # run_hd_bet(refFile, refFile, mode="fast", device=device, do_tta=False, ) list_files = [k for k in os.listdir(tempFolder) if 'nii' in k and not 'ref' in k] for file in list_files: inputFileTemp = os.path.join(tempFolder, file) self._apply_mask(input=inputFileTemp, output=inputFileTemp, mask=mask_sk) if not deleteprocessed: list_files = [os.path.join(tempFolder,k) for k in os.listdir(tempFolder) if 'nii' in k and not 'ref' in k] for file in list_files: slicer.util.loadVolume(file, returnNode=False) # Recommend the user to switch to fast mode if no GPU or not enough memory is available options.extend(["--device", device]) # Get TumorSegmentator launcher command # TumorSegmentator (.py file, without extension) is installed in Python Scripts folder if os.name == 'nt': TumorSegmentatorExecutablePath = os.path.join(sysconfig.get_path('scripts'), "TumorSegmentator.exe") else: TumorSegmentatorExecutablePath = os.path.join(sysconfig.get_path('scripts'), "TumorSegmentator") # TumorSegmentatorExecutablePath = "TumorSegmentator" # Get Python executable path TumorSegmentatorCommand = [ pythonSlicerExecutablePath, TumorSegmentatorExecutablePath] # Get options self.log('Creating segmentations with TumorSegmentator...') self.log(f"Tumor Segmentator arguments: {options}") proc = slicer.util.launchConsoleProcess(TumorSegmentatorCommand + options) self.logProcessOutput(proc) # Load result self.log('Importing segmentation results...') # Create output labelmap self.readSegmentationFolder(outputVolume, tempFolder) self.log("Cleaning up temporary folder...") if os.path.isdir(tempFolder): shutil.rmtree(tempFolder) # Set source volume - required for DICOM Segmentation export outputVolume.SetNodeReferenceID(outputVolume.GetReferenceImageGeometryReferenceRole(), refVolume.GetID()) outputVolume.SetReferenceImageGeometryParameterFromVolumeNode(refVolume) # Place segmentation node in the same place as the input volume shNode = slicer.vtkMRMLSubjectHierarchyNode.GetSubjectHierarchyNode(slicer.mrmlScene) inputVolumeShItem = shNode.GetItemByDataNode(refVolume) studyShItem = shNode.GetItemParent(inputVolumeShItem) segmentationShItem = shNode.GetItemByDataNode(outputVolume) shNode.SetItemParent(segmentationShItem, studyShItem) stopTime = time.time() self.log(f'Processing completed in {stopTime-startTime:.2f} seconds') # # SlicerTumorSegmentatorTest # class SlicerTumorSegmentatorTest(ScriptedLoadableModuleTest): """ This is the test case for your scripted module. Uses ScriptedLoadableModuleTest base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py """ def setUp(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear() def runTest(self): """Run as few or as many tests as needed here. """ self.setUp() self.test_SlicerSlicerTumorSegmentator1() def test_SlicerSlicerTumorSegmentator1(self): """ Ideally you should have several levels of tests. At the lowest level tests should exercise the functionality of the logic with different inputs (both valid and invalid). At higher levels your tests should emulate the way the user would interact with your code and confirm that it still works the way you intended. One of the most important features of the tests is that it should alert other developers when their changes will have an impact on the behavior of your module. For example, if a developer removes a feature that you depend on, your test should break so they know that the feature is needed. """ self.delayDisplay("Starting the test") # Get/create input data import SampleData # registerSampleData() inputVolume = SampleData.downloadSample('MRBrainTumor1') self.delayDisplay('Loaded test data set') outputVolume = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLSegmentationNode") # Test the module logic logic = SlicerTumorSegmentatorLogic() # Test algorithm logic.process(inputVolume, outputVolume) self.delayDisplay('Test passed')
// // ModelBootcamp.swift // SwiftUIBootcamp // // Created by Санжар Асанов on 17/3/23. // import SwiftUI struct UserModel: Identifiable { let id: String = UUID().uuidString let displayName: String let userName: String let followerCount: Int let isVerified: Bool } struct ModelBootcamp: View { @State var users: [UserModel] = [ // "Nick", "Emily", "Samantha", "Chris" UserModel(displayName: "Nick", userName: "nick123'", followerCount: 100, isVerified: true), UserModel(displayName: "Emily", userName: "emily1915", followerCount: 55, isVerified: false), UserModel(displayName: "Samantha", userName: "ninja", followerCount: 355, isVerified: true), UserModel(displayName: "Chris", userName: "Christian94", followerCount: 243, isVerified: false) ] var body: some View { NavigationView { List { ForEach(users) { user in HStack(spacing: 15.0) { Circle() .frame(width: 35, height: 35) VStack(alignment: .leading) { Text(user.displayName) .font(.headline) Text("@\(user.userName)") .foregroundColor(.gray) .font(.caption) } Spacer() if user.isVerified { Image(systemName: "checkmark.seal.fill") .foregroundColor(.blue) } VStack { Text("\(user.followerCount)") .font(.headline) Text("Followers") .foregroundColor(.gray) .font(.caption) } } .padding(.vertical, 5) } } .listStyle(InsetListStyle()) .navigationTitle("Users") } } } struct ModelBootcamp_Previews: PreviewProvider { static var previews: some View { ModelBootcamp() } }
### LISTS lista = ["a", "b", "c"] IO.puts("Lista: [#{Enum.join(lista, ", ")}]") a = Enum.at(lista, 0) IO.puts("This is the first character of the list '#{lista}': #{a}") # Pattern Matching IO.puts("\nPattern Matching:") [first, second, third] = lista IO.puts("First: #{first}") IO.puts("Second: #{second}") IO.puts("Third: #{third}") # Using underscores listb = ["a", "b", "c"] [_, _, third] = listb IO.puts("Using just the 3rd item: '#{third}'\n") # Convenience functions: hd() and tl() IO.puts("Using the convenience functions hd() and tl():") IO.puts("Printing the first item using hd() (head): '#{hd(listb)}'") IO.puts("Printing the remaining values using tl() (tail): '#{tl(listb)}'\n") # Using Cons operator listc = ["a", "b", "c", "d", "e", "f", "g"] [h | t] = listc IO.puts("Using the pipe/cons operator:") IO.puts("h will return the head: #{h}") IO.puts("t will return the remaining items: #{t}")
const { Model, DataTypes, Sequelize } = require('sequelize'); const { GENDER_TABLE } = require('./gender.model'); const CATEGORY_TABLE = 'categories'; const CategorySchema = { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: DataTypes.INTEGER }, name: { type: DataTypes.STRING, unique: true, allowNull: false, }, genderId: { field: 'gender_id', allowNull: false, type: DataTypes.INTEGER, references: { model: GENDER_TABLE, key: 'id' }, onUpdate: 'CASCADE', onDelete: 'SET NULL' }, } class Category extends Model { static associate(models) { this.belongsTo(models.Gender, { as: 'gender' }) this.hasMany(models.Product, { as: 'products', foreignKey: 'categoryId' }); } static config(sequelize) { return { sequelize, tableName: CATEGORY_TABLE, modelName: 'Category', timestamps: false } } } module.exports = { Category, CategorySchema, CATEGORY_TABLE };
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <title>Simple Calculator</title> </head> <body> <h1>Simple Calculator</h1> <div id="parent"> <div class="row"> <div class="col" id="disVal">0</div> </div> <div class="row"> <div class="but col" id="ac">AC</div> <div class="but col" id="back">&#8676;</div> <div class="but oper col" id="divide">&#247;</div> </div> <div class="row"> <div class="but num col" id="seven">7</div> <div class="but num col" id="eight">8</div> <div class="but num col" id="nine">9</div> <div class="but oper col" id="mut">x</div> </div> <div class="row"> <div class="but num col" id="four">4</div> <div class="but num col" id="five">5</div> <div class="but num col" id="six">6</div> <div class="but oper col" id="minus">-</div> </div> <div class="row"> <div class="but num col" id="one">1</div> <div class="but num col" id="two">2</div> <div class="but num col" id="three">3</div> <div class="but oper col" id="plus">+</div> </div> <div class="row"> <div class="but num col" id="zero">0</div> <div class="but col" id="dec">.</div> <div class="but oper col" id="equal">=</div> </div> </div> <script> var one = document.getElementById('one'); var two = document.getElementById('two'); var three = document.getElementById('three'); var four = document.getElementById('four'); var five = document.getElementById('five'); var six = document.getElementById('six'); var seven = document.getElementById('seven'); var eight = document.getElementById('eight'); var nine = document.getElementById('nine'); var zero = document.getElementById('zero'); var dec = document.getElementById('dec'); var ac = document.getElementById('ac'); var back = document.getElementById('back'); var displayValElement = document.getElementById('disVal'); var num = document.getElementsByClassName('num'); var oper = document.getElementsByClassName('oper'); var displayVal = '0'; var pendingVal ; var evalStringArray = []; var updateDisplayVal = (clickObj) => { var butText = clickObj.target.innerText; if(displayVal === '0'){ displayVal = ''; } displayVal += butText; displayValElement.innerText = displayVal; } var performOperation = (clickObj) => { var operator = clickObj.target.innerText; switch(operator){ case '+': pendingVal = displayVal; displayVal = '0'; displayValElement.innerText = displayVal; evalStringArray.push(pendingVal); evalStringArray.push('+'); break; case '-': pendingVal = displayVal; displayVal = '0'; displayValElement.innerText = displayVal; evalStringArray.push(pendingVal); evalStringArray.push('-'); break; case 'x': pendingVal = displayVal; displayVal = '0'; displayValElement.innerText = displayVal; evalStringArray.push(pendingVal); evalStringArray.push('*'); break; case '÷': pendingVal = displayVal; displayVal = '0'; displayValElement.innerText = displayVal; evalStringArray.push(pendingVal); evalStringArray.push('/'); break; case '=': evalStringArray.push(displayVal); var evalRes = eval(evalStringArray.join(' ')); displayVal = evalRes + ''; displayValElement.innerText = displayVal; evalStringArray = []; break; default: break; } } for(let i = 0 ; i<num.length ; i++){ num[i].addEventListener('click',updateDisplayVal, false); } for(let i = 0 ; i<oper.length ; i++){ oper[i].addEventListener('click',performOperation, false); } ac.onclick = () => { displayVal = '0'; pendingVal = undefined; evalStringArray = []; displayValElement.innerHTML = displayVal; } back.onclick = () => { let lenOfDisVal = displayVal.length; displayVal = displayVal.slice(0,lenOfDisVal - 1); if(displayVal === '') displayVal = '0'; displayValElement.innerText = displayVal; } dec.onclick = () => { if(!displayVal.includes('.')) displayVal += '.'; displayValElement.innerText = displayVal; } </script> </body> </html>
package net.gplatform.sudoor.server.jpa.autoconfig; /* * #%L * sudoor-server-lib * %% * Copyright (C) 2013 - 2015 Shark Xu * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 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 General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.gplatform.sudoor.server.jpa.autoconfig.EclipselinkJpaAutoConfiguration.EclipselinkEntityManagerCondition; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jta.JtaAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.AbstractJpaVendorAdapter; import org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.ClassUtils; /** * To avoid error "Cannot apply class transformer without LoadTimeWeaver specified" * Need to: * add spring.jpa.eclipselink.eclipselink.weaving=false to disable loadTimeWeaver * Or: * Config loadTimeWeaver * @author xufucheng * */ @Configuration @ConditionalOnClass({ LocalContainerEntityManagerFactoryBean.class, EnableTransactionManagement.class, EntityManager.class }) @Conditional(EclipselinkEntityManagerCondition.class) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, JtaAutoConfiguration.class }) @ConfigurationProperties(prefix = "spring.jpa") public class EclipselinkJpaAutoConfiguration extends JpaBaseConfiguration { private Map<String, String> eclipselink = new HashMap<String, String>(); public Map<String, String> getEclipselink() { return eclipselink; } public void setEclipselink(Map<String, String> eclipselink) { this.eclipselink = eclipselink; } @Autowired private JpaProperties properties; @Autowired private DataSource dataSource; @Override protected AbstractJpaVendorAdapter createJpaVendorAdapter() { EclipseLinkJpaVendorAdapter adapter = new EclipseLinkJpaVendorAdapter(); return adapter; } @Override protected Map<String, Object> getVendorProperties() { Map<String, Object> vendorProperties = new HashMap<String, Object>(); vendorProperties.putAll(eclipselink); return vendorProperties; } @Order(Ordered.HIGHEST_PRECEDENCE + 20) static class EclipselinkEntityManagerCondition extends SpringBootCondition { private static String[] CLASS_NAMES = { "org.eclipse.persistence.jpa.JpaEntityManager" }; @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { for (String className : CLASS_NAMES) { if (ClassUtils.isPresent(className, context.getClassLoader())) { return ConditionOutcome.match("found EclipselinkEntityManager class"); } } return ConditionOutcome.noMatch("did not find EclipselinkEntityManager class"); } } }
package controllers.reduction; import java.util.ArrayList; import dao.factory.DaoFactory; import dao.pojo.reduction.ReductionSurTotalDao; import exceptions.DataAccessException; import exceptions.ObjectAlreadyExistsException; import exceptions.ObjectConstraintException; import exceptions.ObjectNotExistsException; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.paint.Color; import pojo.reduction.ReductionSurTotal; public class ReductionSurTotalController { @FXML private TextField textRecherche; @FXML private TableView<ReductionSurTotal> tableReduction; @FXML private TableColumn<ReductionSurTotal, Integer> colId; @FXML private TableColumn<ReductionSurTotal, Integer> colTaux; @FXML private TableColumn<ReductionSurTotal, Double> colTotal; @FXML private TextField textTaux; @FXML private TextField textTotal; @FXML private Label lblMessage; private ObservableList<ReductionSurTotal> reductionObservableList = FXCollections.observableArrayList(); private ArrayList<ReductionSurTotal> reductions = new ArrayList<ReductionSurTotal>(); private ReductionSurTotalDao daoReduction = DaoFactory.getCurrentDao().getReductionSurTotalDao(); // Permet d'annuler la sélection dans la TableView si aucun item n'est sélectionné private int oldSelectedIndex = -1; @FXML public void initialize() { System.out.println("contrôleur réduction sur total appelé"); setupTable(); updateTable(); //rechercher(); } /** * * * * * * * * * * * * * * * Initialise la TableView * * * * * * * * * * * * * * */ private void setupTable() { // Affecte les données aux colonnes this.colId.setCellValueFactory(cellData -> cellData.getValue().idReductionProperty().asObject()); this.colTaux.setCellValueFactory(cellData -> cellData.getValue().tauxReductionProperty().asObject()); this.colTotal.setCellValueFactory(cellData -> cellData.getValue().totalFactureProperty().asObject()); // Fait interagir la sélection sur le tableau pour afficher les détails du client tableReduction.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> afficherDetailsReduction(newValue) ); // Gère le clic de la souris this.tableReduction.setOnMouseClicked( (event) -> { // On récupère l'index sélectionné par l'utilisateur int selectedIndex = tableReduction.getSelectionModel().getSelectedIndex(); // Si l'utilisateur clique sur un item if (oldSelectedIndex != selectedIndex) { oldSelectedIndex = selectedIndex ; tableReduction.getSelectionModel().select(selectedIndex); event.consume(); } // Si l'utilisateur ne clique sur aucun item else { oldSelectedIndex = -1; tableReduction.getSelectionModel().clearSelection(); event.consume(); } } ); } @FXML private void updateTable() { // Met à jour le label d'informations updateLblMessage(); this.reductionObservableList.clear(); try { // Récupère les réductions dans la solution de persistance this.reductions = this.daoReduction.getAll(); // Ajoute la liste de réductions à la liste observable this.reductionObservableList.addAll(this.reductions); // Fixe la table avec la liste observable this.tableReduction.setItems(this.reductionObservableList); } catch (IllegalArgumentException iae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText("La solution de persistance contient des erreurs, veuillez contacter l'administrateur"); } catch (DataAccessException dae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(dae.getMessage()); } } private void afficherDetailsReduction (ReductionSurTotal reduction) { // Met à jour le label d'informations updateLblMessage(); if (reduction != null) { this.textTotal.setText(Double.toString(reduction.getTotalFacture())); this.textTaux.setText(Integer.toString(reduction.getTauxReduction())); } // Réduction null else { this.textTotal.setText(""); this.textTaux.setText(""); } } private void updateLblMessage() { this.lblMessage.setText(null); } @FXML private void ajouter() { // Met à jour le label d'informations updateLblMessage(); try { if (this.textTaux.getText().trim().length() == 0) throw new IllegalArgumentException("Veuillez choisir un taux"); else if (this.textTotal.getText().trim().length() == 0) throw new IllegalArgumentException("Veuillez saisir un total"); ReductionSurTotal reduction = new ReductionSurTotal(Integer.parseInt(this.textTaux.getText()), Double.parseDouble(this.textTotal.getText())); // Ouvre une fenêtre d'alerte pour confirmer Alert alert = new Alert(AlertType.CONFIRMATION); alert.setHeaderText(null); alert.setContentText( "Ajouter la réduction ?"); // Permet l'utilisation native du composant Alert pour la validation // https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html alert.showAndWait().ifPresent(response -> { if (response == ButtonType.OK) { try { // On insère la réduction si les saisies sont correctes int idReduction = this.daoReduction.create(reduction); reduction.setIdReduction(idReduction); // On ajoute la réduction dans la TableView this.tableReduction.getItems().add(reduction); // Message de succès this.lblMessage.setTextFill(Color.GREEN); this.lblMessage.setText("Réduction ajoutée"); } catch (DataAccessException dae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(dae.getMessage()); } catch (ObjectAlreadyExistsException oaee) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(oaee.getMessage()); } } }); // Si les saisies de l'utilisateur sont incorrectes } catch (IllegalArgumentException iae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(iae.getMessage()); } } @FXML private void modifier() { // Met à jour le label d'informations updateLblMessage(); // On récupère l'index sélectionné par l'utilisateur int selectedIndex = tableReduction.getSelectionModel().getSelectedIndex(); try { // Si un item a été sélectionné if (selectedIndex >= 0) { if (this.textTaux.getText().trim().length() == 0) throw new IllegalArgumentException("Veuillez choisir un taux"); else if (this.textTotal.getText().trim().length() == 0) throw new IllegalArgumentException("Veuillez saisir un total"); // On teste les saisies de l'utilisateur new ReductionSurTotal(Integer.parseInt(this.textTaux.getText()), Double.parseDouble(this.textTotal.getText().replace(",","."))); // Ouvre une fenêtre d'alerte pour confirmer Alert alert = new Alert(AlertType.CONFIRMATION); alert.setHeaderText(null); alert.setContentText( "Valider les modifications sur la réduction ?"); // Permet l'utilisation native du composant Alert pour la validation // https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html alert.showAndWait().ifPresent(response -> { if (response == ButtonType.OK) { try { this.reductionObservableList.get(selectedIndex).setTauxReduction(Integer.parseInt(this.textTaux.getText())); this.reductionObservableList.get(selectedIndex).setTotalFacture(Double.parseDouble(this.textTotal.getText().replace(",","."))); // On modifie la réduction si les saisies sont correctes this.daoReduction.update(this.reductionObservableList.get(selectedIndex)); // On met à jour la TableView this.tableReduction.getItems().set(selectedIndex, this.reductionObservableList.get(selectedIndex)); // Message de succès this.lblMessage.setTextFill(Color.GREEN); this.lblMessage.setText("Réduction mise à jour"); } catch (DataAccessException dae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(dae.getMessage()); } catch (ObjectNotExistsException one) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(one.getMessage()); } catch (ObjectAlreadyExistsException oaee) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(oaee.getMessage()); } } }); } // Aucun item n'a été sélectionné else { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Erreur"); alert.setHeaderText(null); alert.setContentText("Veuillez sélectionner une réduction"); alert.showAndWait(); } // Si les saisies de l'utilisateur sont incorrectes } catch (IllegalArgumentException iae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(iae.getMessage()); } } @FXML private void supprimer() { // Met à jour le label d'informations updateLblMessage(); // On récupère l'index sélectionné par l'utilisateur int selectedIndex = this.tableReduction.getSelectionModel().getSelectedIndex(); // Si un item a été sélectionné if (selectedIndex >= 0) { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setHeaderText(null); alert.setContentText("Supprimer la réduction ?"); // Permet l'utilisation native du composant Alert pour la validation // https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html alert.showAndWait().ifPresent(response -> { if (response == ButtonType.OK) { try { this.daoReduction.delete(this.colId.getCellData(reductionObservableList.get(selectedIndex))); // On met à jour la TableView this.tableReduction.getItems().remove(selectedIndex); // Message de succès this.lblMessage.setTextFill(Color.GREEN); this.lblMessage.setText("Réduction supprimée"); } catch (DataAccessException dae) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(dae.getMessage()); } catch (ObjectNotExistsException onee) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(onee.getMessage()); } catch (ObjectConstraintException oce) { this.lblMessage.setTextFill(Color.RED); this.lblMessage.setText(oce.getMessage()); } } }); } // Aucun item n'a été sélectionné else { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Erreur"); alert.setHeaderText(null); alert.setContentText("Veuillez sélectionner une réduction"); alert.showAndWait(); } } }
const ObjectId = require("mongoose").Types.ObjectId; const LeaveTypeModel = require("../../models/LeaveType"); const {CreateError} = require("../../helpers/ErrorHandler"); const CheckAssociateService = require("../../services/Common/CheckAssociateService"); const CreateService = require("../../services/Common/CreateService"); const DropDownService = require("../../services/Common/DropDownService"); const ListService = require("../../services/Common/ListService"); const UpdateService = require("../../services/Common/UpdateService"); const DeleteService = require("../../services/Common/DeleteService"); const DetailsService = require("../../services/Common/DetailsService"); /** * @desc LeaveType Create * @access private * @route /api/v1/LeaveType/LeaveTypeCreate * @method POST */ const LeaveTypeCreate = async (req, res, next) => { try { const associal = await CheckAssociateService( { LeaveTypeName: req.body.LeaveTypeName }, LeaveTypeModel, ); if (associal) { throw CreateError("This LeaveType Already Created"); } const result = await CreateService(req, LeaveTypeModel); res.status(201).json(result); } catch (error) { next(error); } }; /** * @desc LeaveType List * @access private * @route /api/v1/LeaveType/LeaveTypeList * @method GET */ const LeaveTypeList = async (req, res, next) => { const searchKeyword = req.params.searchKeyword; let SearchRgx = { $regex: searchKeyword, $options: "i" }; let SearchArray = [ { LeaveTypeName: SearchRgx , LeaveTypeDetails: SearchRgx}]; try { const result = await ListService(req, LeaveTypeModel, { $or: SearchArray }); res.json(result); } catch (error) { next(error); } }; /** * @desc LeaveType Drop Down * @access private * @route /api/v1/LeaveType/LeaveTypeDropDown * @methud GET */ const LeaveTypeDropDown = async (req, res, next) => { try { const result = await DropDownService( req, LeaveTypeModel, { LeaveTypeStatus: true, }, { label: "$LeaveTypeName", value: "$_id", }, ); res.json(result); } catch (error) { next(error); } }; /** * @desc LeaveType Details * @access private * @route /api/v1/LeaveType/LeaveTypeDetails/:id * @methud GET */ const LeaveTypeDetails = async (req, res, next) => { try { const result = await DetailsService(req, LeaveTypeModel); const leaveTypeDetails = result ? result.LeaveTypeDetails : null; res.json(leaveTypeDetails); } catch (error) { next(error); } }; /** * @desc LeaveType Update * @access private * @route /api/v1/LeaveType/LeaveTypeUpdate/:id * @methud PATCH */ const LeaveTypeUpdate = async (req, res, next) => { try { const result = await UpdateService(req, LeaveTypeModel); res.json(result); } catch (error) { next(error); } }; /** * @desc LeaveType Delete * @access private * @route /api/v1/LeaveType/LeaveTypeDelete/:id * @method DELETE */ const LeaveTypeDelete = async (req, res, next) => { try { const result = await DeleteService(req, LeaveTypeModel); res.json(result); } catch (error) { next(error); } }; module.exports = { LeaveTypeCreate, LeaveTypeList, LeaveTypeDropDown, LeaveTypeDetails, LeaveTypeUpdate, LeaveTypeDelete, }
import { useEffect, useState } from "react" import Layout from "../../components/Layout/Layout" import { Row, Col, Menu, message } from 'antd' import Spinner from "../../components/Spinner" import { useNavigate } from "react-router-dom" import { useSelector } from "react-redux" import Statistical from "./Statistical" import History from "./History" import axios from "axios" import More from "./More" const menuItems = [ { label: 'Thống kê', key: 'statistical' }, { label: 'Lịch sử', key: 'history' }, { label: 'Hành động', key: 'action' } ] const StorageManage = () => { const navigate = useNavigate() const { user } = useSelector(state => state.user) const [loading, setLoading] = useState(false) const [currentMenu, setCurrentMenu] = useState(menuItems[0].key) const changeContent = (value) => { setCurrentMenu(value.key) } const [storage, setStorage] = useState({ total: 0, income: 0, outcome: 0, this_month: { total: 0, income: 0, outcome: 0, } }) const onChangeStorage = async (action, value) => { if (action === 'pop' && Number(value) > storage.total) { message.error('Lượng sữa trong kho không đủ') return } await axios.post('/api/v1/storage/action', { from: 'doctor', action: action, value: value }, { headers: { Authorization: "Bearer " + localStorage.getItem('token') }, }).then(res => { if (res.data.success) { setStorage(current => ( { total: Math.max(0, current.total + (action === 'push' ? (1) : (-1)) * value), income: action === 'push' ? current.income + Number(value) : current.income, outcome: action === 'pop' ? current.outcome + Number(value) : current.outcome, this_month: { total: Math.max(0, current.this_month.total + (action === 'push' ? (1) : (-1)) * value), income: action === 'push' ? current.this_month.income + Number(value) : current.this_month.income, outcome: action === 'pop' ? current.this_month.outcome + Number(value) : current.this_month.outcome, }, history: current.history } )) message.success(res.data.message) } else { message.error(res.data.message) } }).catch(err => { console.log(err) message.error(err.message) }) } const [chart, setChart] = useState({ labels: ['Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 5', 'Tháng 6', 'Tháng 7', 'Tháng 8', 'Tháng 9'], datasets: [ { label: 'Thu vào', data: [1, 2, 3, 4, 5, 6, 7, 8, 9], backgroundColor: '#cf1322', stack: '0' }, { label: 'Lấy ra', data: [9, 8, 7, 6, 5, 4, 3, 2, 1], backgroundColor: '#3f8600', stack: '1' }, ], }) const getStorage = async () => { setLoading(true) await axios.post('/api/v1/storage/get-storage', { }, { headers: { Authorization: "Bearer " + localStorage.getItem('token') }, }).then(res => { if(res.data.success) { setStorage(res.data.storage) } else { message.error(res.data.message) } }).catch(err => { console.log(err) message.error(err.message) }) setLoading(false) } const getChart = async () => { setLoading(true) await axios.post('/api/v1/storage/get-chart', { }, { headers: { Authorization: "Bearer " + localStorage.getItem('token') }, }).then(res => { if(res.data.success) { setChart(res.data.chart) } else { message.error(res.data.message) } }).catch(err => { console.log(err) message.error(err.message) }) setLoading(false) } useEffect(() => { getStorage() getChart() }, []) return ( <Layout> { loading ? <Spinner /> : <Row style={{ minHeight: '100vh', padding: 5 }}> <Col span={4}> <Menu style={{ height: '100vh' }} onClick={changeContent} selectedKeys={[currentMenu]} mode="vertical" items={menuItems} /> </Col> <Col span={20} style={{ padding: 10 }}> { currentMenu === menuItems[0].key ? <Statistical storage={storage} chart={chart} onChangeStorage={onChangeStorage} /> : currentMenu === menuItems[1].key ? <History storage={storage} /> : <More /> } </Col> </Row> } </Layout> ) } export default StorageManage
import { Action, AnyAction, AsyncThunkAction, createAsyncThunk, createSlice, Dispatch, PayloadAction, ThunkAction } from "@reduxjs/toolkit"; import { URLSearchParams } from "url"; import { AppDispatch, RootState } from "."; import { INote, ITrashNote } from "../interfaces"; export const getNoteList:any= (user:string)=> { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch(`/getNotes?user=${user}`) const body:any[] = await response.json(); const notes:INote[] = [] const trashNotes:ITrashNote[] = [] body.forEach(element => { //console.log(element.title+' '+element.body) if(!element.trashAt) notes.push({id:element._id,title:element.title, body:element.body, user:element.user, favourite:element.favourite}) else trashNotes.push({id:element._id,title:element.title, body:element.body, user:element.user, favourite:element.favourite, trashAt:element.trashAt}) }); console.log(notes) dispatch(loadAllNotes(notes)) dispatch(loadTrashNotes(trashNotes)) } } export const deleteNote:any= (noteId:string) => { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch('/deleteNote',{ method: 'POST', // or 'PUT' headers: {'Content-Type': 'application/json',}, body: JSON.stringify({id:noteId})} ); dispatch(selectNote(null)) dispatch(getNoteList(getState().auth.profile.email)); } } export const addNote:any= (note:INote) => { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch('/addNote',{ method: 'POST', // or 'PUT' headers: {'Content-Type': 'application/json',}, body: JSON.stringify({title:note.title, body:note.body, user:note.user, favourite:note.favourite})} ); const newNote = await response.json(); dispatch(selectNote(newNote)) dispatch(getNoteList(getState().auth.profile.email)); } } export const updateNote:any= (note:INote) => { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch('/updateNote',{ method: 'POST', // or 'PUT' headers: {'Content-Type': 'application/json',}, body: JSON.stringify({id:note.id,title:note.title, body:note.body, user:note.user, favourite:note.favourite})} ); dispatch(getNoteList(getState().auth.profile.email)); } } export const markFavourite:any= (noteId:string, favourite:boolean) => { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch('/markFavourite',{ method: 'POST', // or 'PUT' headers: {'Content-Type': 'application/json',}, body: JSON.stringify({id:noteId, favourite:favourite})} ); const favouriteResult = await response.json(); dispatch(markFavouriteNote(favouriteResult.favourite)) dispatch(getNoteList(getState().auth.profile.email)); } } export const moveToTrash:any= (noteId:string) => { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch('/moveToTrash',{ method: 'POST', // or 'PUT' headers: {'Content-Type': 'application/json',}, body: JSON.stringify({id:noteId})} ); dispatch(selectNote(null)) dispatch(getNoteList(getState().auth.profile.email)); } } export const restoreNote:any= (noteId:string) => { return async(dispatch:Dispatch, getState:RootState) => { const response = await fetch('/restoreNote',{ method: 'POST', // or 'PUT' headers: {'Content-Type': 'application/json',}, body: JSON.stringify({id:noteId})} ); dispatch(selectNote(null)) dispatch(getNoteList(getState().auth.profile.email)); } } export interface NoteState { selectedNote: INote | null, allNotes: INote[], trashNotes: ITrashNote[] } const initialState:NoteState = { selectedNote: null, allNotes: [ // { // id:"Note ID", // title:"Note Title", // body: 'Note Description', // user: 'user@gmail.com', // favourite: false, // trash: false // } ], trashNotes: [], } export const NoteSlice = createSlice({ name: 'notes', initialState, reducers: { loadAllNotes:(state, action:PayloadAction<INote[]>) => { state.allNotes=action.payload }, loadTrashNotes:(state, action:PayloadAction<ITrashNote[]>) => { state.trashNotes=action.payload }, selectNote:(state, action:PayloadAction<INote|null>) => { state.selectedNote=action.payload }, markFavouriteNote: (state, action:PayloadAction<boolean>) => { if(state.selectedNote) state.selectedNote.favourite=action.payload }, }, }) export const {loadAllNotes, selectNote, loadTrashNotes, markFavouriteNote} = NoteSlice.actions; export default NoteSlice.reducer;
package kr.or.ddit.basic; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class T11FileEncodingTest { public static void main(String[] args) throws IOException { /* * OutputStreamWriter => 바이트기반 출력용 객체를 문자기반 출력용 객체로 변환하는 보조 스트림 * => 이 객체도 출력할 때 '인코딩방식'을 지정해서 출력할 수 있다. */ // 키보드로 입력한 내용을 파일로 저장하는데, // out_utf8.txt파일은 'utf-8'인코딩 방식으로 // out_ansi.txt파일은 'ms949'인코딩 방식으로 저장하시오. InputStreamReader isr = new InputStreamReader(System.in); // 파일 출력용 FileOutputStream fos1 = new FileOutputStream("d:/D_Other/out_utf8.txt"); FileOutputStream fos2 = new FileOutputStream("d:/D_Other/out_ansi.txt"); OutputStreamWriter osw1 = new OutputStreamWriter(fos1, "UTF-8"); OutputStreamWriter osw2 = new OutputStreamWriter(fos2, "MS949"); int data = 0; while((data = isr.read()) != -1) { osw1.write(data); osw2.write(data); } System.out.println("작업 완료..."); isr.close(); // 보조 스트림을 닫으면 알아서 기반 스트림 먼저 닫음. osw1.close(); // 해줘도 상관은 없음 osw2.close(); } }
import type { DocumentInterface } from "@langchain/core/documents"; import { Document } from "@langchain/core/documents"; import { OpenAIEmbeddings } from "@langchain/openai"; import { PineconeStore } from "@langchain/pinecone"; import { Pinecone } from "@pinecone-database/pinecone"; import type { Note, NoteDigestSpan, NoteRevision } from "@brain2/db/edge"; import { env } from ".."; const pinecone = new Pinecone(); const index = pinecone.Index(env.PINECONE_INDEX); type PopulatedNote = Note & { revision: NoteRevision }; export interface NoteMetadata { id: string; type: "note"; span: NoteDigestSpan; owner: string; active: boolean; } /** * Get the vector store for retrieval */ export async function getVectorStore() { return PineconeStore.fromExistingIndex( new OpenAIEmbeddings({ modelName: "text-embedding-3-large", dimensions: 1024, }), { pineconeIndex: index, }, ); } function getDocumentFromNote(note: PopulatedNote) { return new Document({ metadata: { id: note.id, type: "note", span: note.digestSpan, owner: note.owner, active: note.active, }, pageContent: `${note.revision.title}\n${note.revision.content}`, }); } /** * Create an embedding for a note and save it to the vector store */ export async function embedNote(note: PopulatedNote) { const vectorStore = await getVectorStore(); await vectorStore.addDocuments([getDocumentFromNote(note)], { ids: [note.id], }); } export async function embedNotes(notes: PopulatedNote[]) { const vectorStore = await getVectorStore(); await vectorStore.addDocuments(notes.map(getDocumentFromNote), { ids: notes.map((note) => note.id), }); } /** * Get the k most similar notes to a given note */ export async function getSimilarNotes( query: string, owner: string, span: NoteDigestSpan, k: number, excludeIds: string[] = [], ): Promise<DocumentInterface<NoteMetadata>[]> { const vectorStore = await getVectorStore(); const results = await vectorStore.similaritySearch(query, k, { owner, type: "note", span, active: true, id: { $nin: excludeIds, }, }); return results as DocumentInterface<NoteMetadata>[]; }
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:pulizia_strade/Alerts/CustomAlerts.dart'; import 'package:pulizia_strade/Models/PositionInMap.dart'; import 'package:pulizia_strade/Providers/ParkProvider.dart'; class ParkButton extends StatelessWidget { final PositionInMap position; final double latitude; final double longitude; final bool positionFoundInDb; final String alertMessage = "Attenzione la posizione attuale non è comprese tra quelle monitorate dalla nostra app. Il parcheggio è stato salvato, ma non riceverai alcuna notifica su una eventuale pulizia delle strade."; ParkButton( this.position, this.latitude, this.longitude, this.positionFoundInDb); @override Widget build(BuildContext context) { ParkProvider parkProvider = Provider.of<ParkProvider>(context); double screenWidth = MediaQuery.of(context).size.width; return Container( child: ElevatedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all(Colors.blue[400]), shape: MaterialStateProperty.all<RoundedRectangleBorder>( RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ))), onPressed: () async { if (!positionFoundInDb) { await showAlertDialog(context, Text(alertMessage)); } parkProvider.addPark( position, latitude, longitude, positionFoundInDb); }, child: Padding( padding: EdgeInsets.all(screenWidth / 42), child: Text("Parcheggia qui", style: TextStyle( color: Colors.white, fontSize: screenWidth / 21, fontWeight: FontWeight.w500))))); } }
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include <doctest.h> #include <IceFloe.h> /********** * Testing the IceFloe Class */ TEST_CASE("Constructor sets the properties properlly") { auto screen_size = Coordinates(1000, 600); auto ice_floe = IceFloe(screen_size); // check size of icefloe not equal zero CHECK((ice_floe.GetSize().x != 0 && ice_floe.GetSize().y != 0)); // check icefloe initially is whithin screen CHECK((ice_floe.GetPosition().x >= 0 && ice_floe.GetPosition().y >= 0)); CHECK((ice_floe.GetPosition().x <= screen_size.x && ice_floe.GetPosition().y <= screen_size.y)); } TEST_CASE("Test adjusting the position of ice floe") { auto screen_size = Coordinates(1000, 600); auto ice_floe = IceFloe(screen_size); // adding zero doesnt change the current position of the ice floe auto current_pos = ice_floe.GetPosition(); ice_floe.AdjustPosition(Coordinates(0, 0)); auto new_position = ice_floe.GetPosition(); CHECK_EQ(current_pos.x, new_position.x); CHECK_EQ(current_pos.y, new_position.y); // adding a non zero position to the ice floe current_pos = ice_floe.GetPosition(); ice_floe.AdjustPosition(Coordinates(7, 4)); new_position = ice_floe.GetPosition(); CHECK_GT(new_position.x, current_pos.x); CHECK_GT(new_position.y, current_pos.y); // subtracting a non zero position to the ice floe current_pos = ice_floe.GetPosition(); ice_floe.AdjustPosition(Coordinates(-7, -4)); new_position = ice_floe.GetPosition(); CHECK_LT(new_position.x, current_pos.x); CHECK_LT(new_position.y, current_pos.y); } TEST_CASE("Test updating the position of ice floe") { auto screen_size = Coordinates(1000, 600); auto ice_floe = IceFloe(screen_size); // updating the ice floe doesnt affect the y coordnitates auto position = Coordinates(7, 6); auto current_pos = ice_floe.GetPosition(); ice_floe.UpdatePosition(position); auto new_position = ice_floe.GetPosition(); CHECK_EQ(new_position.y, current_pos.y); // the x coordinate becomes the new position CHECK_EQ(new_position.x, position.x); } TEST_CASE("Test flipping the color of ice floe") { auto screen_size = Coordinates(1000, 600); auto ice_floe = IceFloe(screen_size); auto original_color = ice_floe.IsOriginalColor(); ice_floe.FlipColor(); auto flipped_color = ice_floe.IsOriginalColor(); ice_floe.FlipColor(); auto new_color = ice_floe.IsOriginalColor(); CHECK_NE(original_color, flipped_color); CHECK_EQ(original_color, new_color); } /********** * Testing the IceFloeLayer Class */
import Toybox.Graphics; import Toybox.Lang; import Toybox.System; module Icons { function drawAlarmIcon( dc as Dc, x as Number, y as Number, scale as Float, options as Null ) as Void { dc.setPenWidth(5 * scale); dc.setColor(Graphics.COLOR_WHITE, Graphics.COLOR_TRANSPARENT); dc.drawCircle(x, y, 20 * scale); dc.drawLine(x, y - 10 * scale, x, y); dc.drawLine(x, y, x - 6 * scale, y + 8 * scale); dc.drawLine(x + 17 * scale, y - 23 * scale, x + 23 * scale, y - 17 * scale); dc.drawLine(x - 17 * scale, y - 23 * scale, x - 23 * scale, y - 17 * scale); } function drawBatteryIcon( dc as Dc, x as Number, y as Number, scale as Float, options as { :percentage as Number, :isCharging as Boolean, } ) as Void { var offset = 50 * (100 - options[:percentage] as Number) / 100; dc.setPenWidth(4 * scale); dc.setColor( options[:percentage] as Number > 15 ? Graphics.COLOR_GREEN : Graphics.COLOR_RED, Graphics.COLOR_TRANSPARENT ); dc.fillRoundedRectangle( x - 15 * scale, y - (20 - offset) * scale, 30 * scale, (50 - offset) * scale, 2 ); dc.setColor(Graphics.COLOR_WHITE, Graphics.COLOR_TRANSPARENT); dc.fillRectangle(x - 8 * scale, y - 26 * scale, 16 * scale, 6 * scale); dc.drawRoundedRectangle( x - 15 * scale, y - 20 * scale, 30 * scale, 50 * scale, 2 ); } function drawBluetoothIcon( dc as Dc, x as Number, y as Number, scale as Float, options as { :state as ConnectionState, } ) as Void { var isConnected = options[:state] == System.CONNECTION_STATE_CONNECTED; dc.setPenWidth(4 * scale); dc.setColor( isConnected ? Graphics.COLOR_BLUE : Graphics.COLOR_WHITE, Graphics.COLOR_TRANSPARENT ); dc.drawLine(x - 15 * scale, y - 15 * scale, x + 15 * scale, y + 15 * scale); dc.drawLine(x - 15 * scale, y + 15 * scale, x + 15 * scale, y - 15 * scale); dc.drawLine(x + 15 * scale, y + 15 * scale, x, y + 30 * scale); dc.drawLine(x + 15 * scale, y - 15 * scale, x, y - 30 * scale); dc.setPenWidth(5 * scale); dc.drawLine(x - 1 * scale, y - 30 * scale, x - 1 * scale, y + 30 * scale); if (!isConnected) { dc.setColor(Graphics.COLOR_RED, Graphics.COLOR_TRANSPARENT); dc.drawLine( x - 30 * scale, y - 10 * scale, x + 30 * scale, y + 10 * scale ); } } function drawHeartIcon( dc as Dc, x as Number, y as Number, scale as Float, options as Null ) as Void { dc.setColor(Graphics.COLOR_RED, Graphics.COLOR_TRANSPARENT); dc.fillCircle(x - 15 * scale, y - 10 * scale, 16 * scale); // x is off by two to make the circles overlap with only 1px of space // in between, aligning with the single pixel edge at the bottom. dc.fillCircle(x + 13 * scale, y - 10 * scale, 16 * scale); dc.fillPolygon([ [x - 28 * scale, y - 3 * scale] as Array<Numeric>, [x + 28 * scale, y - 3 * scale] as Array<Numeric>, [x + 1 * scale, y + 25 * scale] as Array<Numeric>, [x - 1 * scale, y + 25 * scale] as Array<Numeric>, ] as Array<ArrayOfNumeric>); } // Monkey C compiler doesn't understand Array<Array<T>> for some reason? typedef ArrayOfNumeric as Array<Numeric>; function drawNotificationIcon( dc as Dc, x as Number, y as Number, scale as Float, options as Null ) as Void { dc.setColor(Graphics.COLOR_WHITE, Graphics.COLOR_TRANSPARENT); dc.fillRoundedRectangle( x - 25 * scale, y - 20 * scale, 50 * scale, 35 * scale, 4 ); dc.fillPolygon([ [x - 15 * scale, y + 15 * scale] as Array<Numeric>, [x - 15 * scale, y + 25 * scale] as Array<Numeric>, [x, y + 15 * scale] as Array<Numeric>, ] as Array<ArrayOfNumeric>); } }
import React, { useEffect, useState } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image, Alert } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import * as ImagePicker from 'expo-image-picker'; const PerfilScreen = () => { const [user, setUser] = useState(null); useEffect(() => { const loadUser = async () => { const storedUser = await AsyncStorage.getItem('user'); if (storedUser) { const parsedUser = JSON.parse(storedUser); console.log("User loaded from AsyncStorage:", parsedUser); setUser(parsedUser); } }; loadUser(); }, []); const handleSelectImage = async () => { const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (!permissionResult.granted) { Alert.alert('Permissão negada', 'É necessário conceder permissão para acessar a galeria de fotos.'); return; } const pickerResult = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [1, 1], quality: 1, }); if (!pickerResult.cancelled) { console.log("Image selected:", pickerResult.uri); // Log the selected image URI const updatedUser = { ...user, profileImage: pickerResult.uri }; setUser(updatedUser); await AsyncStorage.setItem('user', JSON.stringify(updatedUser)); console.log("User updated with new profile image:", updatedUser); } }; return ( <View style={styles.container}> <TouchableOpacity onPress={handleSelectImage} style={styles.profileImageContainer}> {user && user.profileImage ? ( <Image source={{ uri: user.profileImage }} style={styles.profileImage} resizeMode="cover" /> ) : ( <Text style={styles.profileImageText}>Adicionar Foto</Text> )} </TouchableOpacity> <View style={styles.infoContainer}> <Text style={styles.title}>Perfil</Text> {user && <Text style={styles.text}>Email: {user.email}</Text>} {user && <Text style={styles.text}>Senha: {user.password}</Text>} {user && <Text style={styles.text}>Telefone: {user.phone}</Text>} {user && <Text style={styles.text}>Idade: {user.age}</Text>} {user && <Text style={styles.text}>Data de Nascimento: {user.birthDate}</Text>} </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 16, }, profileImageContainer: { width: 120, height: 120, borderRadius: 60, backgroundColor: '#ccc', justifyContent: 'center', alignItems: 'center', marginBottom: 32, // Increased margin to add space between image and info overflow: 'hidden', }, profileImage: { width: '100%', height: '100%', borderRadius: 60, }, profileImageText: { fontSize: 18, color: '#666', }, infoContainer: { backgroundColor: '#fff', padding: 16, borderRadius: 8, width: '90%', alignItems: 'flex-start', elevation: 3, // Add shadow for Android shadowColor: '#000', // Add shadow for iOS shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.8, shadowRadius: 2, borderColor: '#5C0D14', borderWidth: 1, }, title: { fontSize: 24, marginBottom: 24, color: '#5C0D14', textAlign: 'center', alignSelf: 'center', }, text: { fontSize: 18, marginBottom: 12, color: '#333', }, }); export default PerfilScreen;
import { useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import { signInFailure, signInStart, signInSuccess, } from "../reducer/features/users/userSlice"; // import SignIn from "./SignIn.jsx"; // import axios from "axios"; function SignIn() { const [formData, setFormData] = useState({}); const { loading, error } = useSelector((state) => state.user); const navigate = useNavigate(); const dispatch = useDispatch(); const handleChange = (e) => { setFormData({ ...formData, [e.target.id]: e.target.value, }); }; const handleSubmit = async (e) => { e.preventDefault(); dispatch(signInStart()); try { const response = await fetch("/api/auth/signin", { method: "POST", // or 'PUT' headers: { "Content-Type": "application/json", }, body: JSON.stringify(formData), }); const result = await response.json(); console.log("Success:", result); if (result.success === false) { dispatch(signInFailure(result.message)); } else { dispatch(signInSuccess(result)); navigate("/"); } } catch (error) { dispatch(signInFailure(error.message)); console.error("Error:", error); } }; console.log(formData); return ( <div className="max-w-lg mx-auto"> <h1 className="text-3xl font-minibold text-center my-7 ">Sign In</h1> <form className="flex flex-col text-center gap-4 "> <input type="email" className="p-3 border rounded-lg shadow-md" placeholder="email" onChange={handleChange} id="email" /> <input type="password" className="p-3 border rounded-lg shadow-md" placeholder="password" onChange={handleChange} id="password" /> <button disabled={loading} type="submit" className="bg-slate-700 text-white rounded-lg uppercase hover:opacity-80 p-3 disabled:opacity-80" onClick={handleSubmit} > {loading ? "Loading..." : "Sign In"} </button> </form> <div> <div className="flex mt-5 gap-2"> <p>create an account</p> <Link to={"/sign-up"}> {" "} <span className="text-blue-700">Sign In</span> </Link> </div> {error ? <p>{error}</p> : <p>i</p>} </div> </div> ); } export default SignIn;
<?php require_once './app/views/auth.view.php'; require_once './app/models/user.model.php'; require_once './app/helpers/auth.helper.php'; class AuthController { private $view; private $model; private $authHelper; function __construct() { $this->model = new UserModel(); $this->view = new AuthView(); $this->authHelper= new AuthHelper(); } public function showRegistro() { $this->view->showRegistro(); } //ACA ESTOY INTENTANDO USAR EL MISMO FORM DEPENDIENDO EL ACTION QUE SE HAGA /* if($_SERVER['REQUEST_METHOD'] === 'POST') { $email = $_POST['email']; $password = $_POST['password']; $action = $_POST['action']; if ($action === 'registrar') { // Lógica para registrar al usuario registro(); } elseif ($action === 'auth') { // Lógica para looguear al usuario auth(); } } */ public function registro(){ //guardo el usuario con la contraseña hasheada $email = $_POST['email']; $password = $_POST['password']; if(!empty($email) && !empty($password)){ $hash=password_hash($password, PASSWORD_BCRYPT); $this->model->saveUser($email,$hash); header('Location: ' . BASE_URL); } else{ $this->view->showLogin('Faltan completar datos'); return; } } public function showLogin() { $this->view->showLogin(); } public function auth() { $email = $_POST['email']; $password = $_POST['password']; // busco el usuario $user = $this->model->getByEmail($email); // encontró un user con el username que mandó, y tiene la misma contraseña if (!empty($user) && password_verify($password, $user->password)) { // ACA LO AUTENTIQUE AuthHelper::login($user); $this->view->showHeader(); header('Location: ' . BASE_URL . 'home'); } else { $this->view->showLogin('Usuario inválido'); } } public function logout() { $this->authHelper->logout(); //header('Location: ' . BASE_URL . '/home'); } }
import User from "../models/user.js"; import bcrypt from "bcrypt"; export const getAllUser = async (req, res) => { try { const users = await User.find(); if (!users) { return res.status(404).json({ message: "No Users Found", }); } return res.status(200).json({ users }); } catch (error) { console.log(error); res.status(500).json({ message: "Internal Server Error", }); } }; export const signup = async (req, res) => { try { const { name, email, password } = req.body; if (!name || !email || !password) { return res.status(400).json({ message: "All fields are required", }); } const existingUser = await User.findOne({ email }); if (existingUser) { return res.status(400).json({ message: "User already exists", }); } const salt = await bcrypt.genSalt(10); const hashedPassword = await bcrypt.hash(password, salt); const user = new User({ name, email, password: hashedPassword, blogs: [], }); await user.save(); res.status(200).json({ user }); } catch (error) { console.log(error); res.status(500).json({ message: "Internal Server Error", }); } }; export const login = async (req, res) => { try { const { email, password } = req.body; if (!email || !password) { return res.status(400).json({ message: "All fields are required", }); } const existingUser = await User.findOne({ email }); if (!existingUser) { return res.status(404).json({ message: "User dosen't exists", }); } const isPassword = bcrypt.compare(password, existingUser.password); if (!isPassword) { return res.status(404).json({ message: "Incorrect password", }); } res.status(200).json({ message: "Login successful" }); } catch (error) { console.log(error); res.status(500).json({ message: "Internal Server Error", }); } };
#include "Other/log.h" #include "Other/myraylib.h" #include "Object.h" #include "Event.h" class Services; class Player : public Object , public EventListener { private: // Ptr of global services Services* _services; // Velocity and rotation Vector2 _vel; float _speed; int _rot; int _acceleration; float _drag; // Maxes int _maxSpeed; int _rotSpeed; // Input flags bool _upPressed = false; bool _rightPressed = false; bool _leftPressed = false; // DeltaT float _deltaT; // Glags bool _atMaxSpeed = false; bool _canMove = true; void Init() override; void AddSelfAsListener() override; void OnEvent(std::shared_ptr<const Event>& event) override; void InputUpdate(); void PosUpdate(); public: Player(Services* servicesIn); ~Player(); void Update() override; void Draw() override; }; class PlayerPosEvent : public Event { public: Vector2 pos; float speed; int rot; PlayerPosEvent(Vector2 posIn, float speedIn, int rotIn) : pos(posIn), speed(speedIn), rot(rotIn) {} };
@extends('layouts.main_layout') @section('content') <div class="section-body"> <div class="row justify-content-center "> <div class="col-10"> <form method="post" action="{{ isset($role->id) ? route('roles.update',$role->id) : route('roles.store')}}"> @csrf @if (isset($role->id)) @method('PUT') @endif <div class="card card-primary"> <div class="card-header d-flex justify-content-between"> <h4>Création des rôles</h4> </div> <div class="card-body p-4 "> <div class="row"> <div class="form-group col-6"> <label for="name">Rôles</label> <input id="name" type="text" class="form-control" name="name" value="{{isset($role) ? $role->name : ''}}" > @error('name') <div class="text-danger" > {{ $message }} </div> @enderror </div> </div> <div class="row"> <div class="form-group col-10"> <label for="prenom">Permissions</label> <select class="form-control select2" multiple="" name="permission[]"> <option value="">....</option> @php $selectedPermission= collect(old('permission',isset($role) ? $role->permissions->pluck('id')->toArray() : [])) @endphp @foreach ($permissions as $permission) <option value="{{ $permission->name }}" {{ $selectedPermission->contains($permission->id) ? 'selected' : '' }} > {{$permission->name}} </option> @endforeach </select> </div> </div> </div> <div class="card-footer text-right"> <button class="btn btn-primary" type="submit">{{ isset($role->id) ? "Modifier" : "Ajouter"}}</button> <a href="{{route('roles.index')}}" class="btn btn-secondary">Annuler</a> </div> </div> </form> </div> </div> <div> @endsection
import { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import DefaultProfilePicture from './DefaultProfilePicture'; import Spinner from './Spinner'; import * as userAPI from '../api/userAPI'; const SearchBar = ({ chatMode, handleSetRecipient }) => { const [searchInput, setSearchInput] = useState(''); const [searchResult, setSearchResult] = useState([]); const [debounceTimeout, setDebounceTimeout] = useState(null); const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (debounceTimeout) { clearTimeout(debounceTimeout); } if (searchInput.trim() !== '') { const timeout = setTimeout(() => { setIsLoading(true); fetchSearchResults(searchInput) .then(() => setIsLoading(false)); }, 500); setDebounceTimeout(timeout); } else { setSearchResult([]); } }, [searchInput]); const fetchSearchResults = async (value) => { const res = await userAPI.searchUsers(value, 1,5); if (res.status === 'success') { if (res.data.length === 0) { setSearchResult([<div className='w-full text-center text-white p-1' key={'messageNoUsersFound'}>No Users Found</div>, <div className='w-full truncate text-center text-white cursor-pointer hover:underline p-1' key={"searchPostsKeyword"}>Search Posts with {searchInput}</div>]); return; } let users; chatMode ? users = res.data.map((user) => { return ( <div onClick={()=>handleSetRecipient(user)} className='w-[95%] h-[4rem] bg-[#60698459] my-2 p-2 rounded-md flex items-center' key={user.username}> {user.profilePicture ? <img className='w-12 h-12 rounded-full' src={user.profilePicture} alt='Profile Picture' /> : <DefaultProfilePicture size={12} />} <p className='pl-2 text-white'>{user.username}</p> </div> ); }) : users = res.data.map((user) => { return ( <Link to={'/profile/' + user.username} className='w-[90%] h-[4rem] bg-[#60698459] my-2 p-1 rounded-md flex items-center' key={user.username}> {user.profilePicture ? <img className='w-12 h-12 rounded-full' src={user.profilePicture} alt='Profile Picture' /> : <DefaultProfilePicture size={12} />} <p className='pl-2 text-white'>{user.username}</p> </Link> ); }); setSearchResult([...users]); } }; return ( <div className='w-full relative flex flex-col items-center justify-center mb-2 md:border-b-0'> <div className='w-full h-[85%] pl-2 text-[#9298a5] bg-[#282c37] outline-0 flex items-center rounded-md'> <input className='w-[90%] h-[85%] pl-2 p-4 text-[#9298a5] bg-[#282c37] outline-0 overflow-x-hidden' type="text" placeholder="Search" onChange={(e) => setSearchInput(e.target.value)} value={searchInput} /> <svg onClick={()=>setSearchInput('')} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" className="w-8 h-8 cursor-pointer pr-2"> <path fillRule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25zm-1.72 6.97a.75.75 0 10-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 101.06 1.06L12 13.06l1.72 1.72a.75.75 0 101.06-1.06L13.06 12l1.72-1.72a.75.75 0 10-1.06-1.06L12 10.94l-1.72-1.72z" clipRule="evenodd" /> </svg> </div> <div className='w-full max-h-[350%] absolute top-[80%] bg-[#3b4358] px-2 flex flex-col items-center flex-grow overflow-y-scroll scrollbar:bg-blue-500 rounded-b-lg scrollbar scrollbar-thumb-blue-500 scrollbar-track-gray-200'> {isLoading ? <Spinner size={12} /> : searchResult} </div> </div> ); }; export default SearchBar;
import web3 from "@solana/web3.js"; import { createContext } from "react"; import { ConnectedWallet } from "@saberhq/use-solana"; import { SwapProgramService } from "@/src/services/swap-program.service"; import { SwapProgramServiceV0 } from "@/src/services/swap-program-v0.service"; import { AugmentedProvider } from "@saberhq/solana-contrib"; /** @dev Define state for context. */ export interface WalletContextState { /** * @dev The function to sign message in Solana network. * */ signMessage(message: string): Promise<Uint8Array>; /** * @dev The function to disconnect walle & logout to Hamster server and Firebase. */ disconnect(): Promise<void>; /** * @dev The function to get sol balance of a specific wallet or signer. * @param {PublicKey} pub */ getSolBalance(pub?: web3.PublicKey): Promise<number>; /** * @dev Expose context frrom solana-adapter. */ solanaWallet: ConnectedWallet; provider: AugmentedProvider; /** * @dev Define Program service. */ programService: SwapProgramService | SwapProgramServiceV0; /** * @dev Sol balance of signer. */ solBalance: number; } /** @dev Initiize context. */ export const WalletContext = createContext<WalletContextState>(null);
const posts = [ { name: "Vincent van Gogh", username: "vincey1853", location: "Zundert, Netherlands", avatar: "images/avatar-vangogh.jpg", post: "images/post-vangogh.jpg", alt: "portrait of van Gogh", comment: "just took a few mushrooms lol", likes: 21 }, { name: "Gustave Courbet", username: "gus1819", location: "Ornans, France", avatar: "images/avatar-courbet.jpg", post: "images/post-courbet.jpg", comment: "i'm feelin a bit stressed tbh", likes: 4 }, { name: "Joseph Ducreux", username: "jd1735", location: "Paris, France", avatar: "images/avatar-ducreux.jpg", post: "images/post-ducreux.jpg", comment: "gm friends! which coin are YOU stacking up today?? post below and WAGMI!", likes: 152 } ] const likesArray = []; const postMain = document.getElementById("main-section") if(postMain) { posts.forEach((post,index) => { const postSection = document.createElement("section"); postSection.classList.add("info-post"); const postContainer = document.createElement("div"); //create the HTML main section postSection.innerHTML = ` <img class="small-img" src=${post.avatar}> <div class="text"> <p class="bold small-txt">${post.name}</p> <p class="small-txt">${post.location}</p> </div> <div id="post-el" class="post"> <img class="main-img" alt="portrait of VanGogh" src=${post.post}> </div> <div class="content"> <div class="icons"> <img class="small-icon like-el" src="images/icon-heart.png" alt="heart symbol"> <img class="small-icon" src="images/icon-comment.png" alt="comment symbol"> <img class="small-icon" src="images/icon-dm.png" alt="dm symbol"> </div> <p class="bold small-txt count-like-el">${post.likes}<span>likes</span></p> <p class="small-txt"><span class="bold">${post.username}</span> ${post.comment}</p> `; //append the section to the main element of HTML postMain.appendChild(postSection); //create the countLikes function const likeEl = postSection.querySelector(".like-el"); const countLikeEl = postSection.querySelector(".count-like-el"); likesArray[index] = post.likes; let isLiked = false; likeEl.addEventListener("click", function() { if (!isLiked) { likesArray[index] += 1; //change the color to red if liked likeEl.src = "images/red-heart.png"; isLiked = true; countLikeEl.textContent = `${likesArray[index]} likes` ; } }); }); }
import { Component, OnInit } from '@angular/core'; import { MessageService } from 'primeng/api'; import { MessagePageService } from 'src/app/shared/services/message.service'; @Component({ selector: 'app-main-layout', templateUrl: './main-layout.component.html', styleUrls: ['./main-layout.component.css'] }) export class MainLayoutComponent implements OnInit { menuList: any; showMessage: any; constructor(private messageService: MessageService, private messagePageService: MessagePageService) { console.log('Main layout constructor called'); } showMessages(title: string, body: string, type: string) { this.messageService.add({severity: type, summary: title, detail: body, life:3000}); } ngOnInit(): void { this.showMessage = this.messagePageService.messageObservable.subscribe((res: any) =>{ this.showMessages(res.title,res.body,res.type); }) this.menuList = [ { label: 'Contenedor', icon: 'pi pi-fw pi-file', items: [ { label: 'Nuevo', icon: 'pi pi-fw pi-plus', items: [ { label: 'Pagina', icon: 'pi pi-bookmark', routerLink: ['/main/page/create'] }, { label: 'Contenedor', icon: 'pi pi-fw pi-bookmark', routerLink: ['/main/conten/create'] }, ] }, { label: 'Buscar Contenedor', icon: 'pi pi-fw pi-search', routerLink: ['/main/conten/search'] }, { separator: true }, { label: 'Lista de Contenedores', icon: 'pi pi-fw pi-external-link' } ] }, { label: 'Reportes', icon: 'pi pi-fw pi-copy', items: [ { label: 'Reporte 01', icon: 'pi pi-fw pi-list' }, { label: 'Reporte 02', icon: 'pi pi-fw pi-list' }, { label: 'Reporte 03', icon: 'pi pi-fw pi-list' }, { label: 'Reporte 04', icon: 'pi pi-fw pi-list' }, ] } ]; // this.menuList = [ // { // label: 'File', // icon: 'pi pi-fw pi-file', // items: [ // { // label: 'New', // icon: 'pi pi-fw pi-plus', // items: [ // { // label: 'Bookmark', // icon: 'pi pi-fw pi-bookmark' // }, // { // label: 'Video', // icon: 'pi pi-fw pi-video' // }, // ] // }, // { // label: 'Delete', // icon: 'pi pi-fw pi-trash' // }, // { // separator: true // }, // { // label: 'Export', // icon: 'pi pi-fw pi-external-link' // } // ] // }, // { // label: 'Edit', // icon: 'pi pi-fw pi-pencil', // items: [ // { // label: 'Left', // icon: 'pi pi-fw pi-align-left' // }, // { // label: 'Right', // icon: 'pi pi-fw pi-align-right' // }, // { // label: 'Center', // icon: 'pi pi-fw pi-align-center' // }, // { // label: 'Justify', // icon: 'pi pi-fw pi-align-justify' // }, // ] // }, // { // label: 'Users', // icon: 'pi pi-fw pi-user', // items: [ // { // label: 'New', // icon: 'pi pi-fw pi-user-plus', // }, // { // label: 'Delete', // icon: 'pi pi-fw pi-user-minus', // }, // { // label: 'Search', // icon: 'pi pi-fw pi-users', // items: [ // { // label: 'Filter', // icon: 'pi pi-fw pi-filter', // items: [ // { // label: 'Print', // icon: 'pi pi-fw pi-print' // } // ] // }, // { // icon: 'pi pi-fw pi-bars', // label: 'List' // } // ] // } // ] // }, // { // label: 'Events', // icon: 'pi pi-fw pi-calendar', // items: [ // { // label: 'Edit', // icon: 'pi pi-fw pi-pencil', // items: [ // { // label: 'Save', // icon: 'pi pi-fw pi-calendar-plus' // }, // { // label: 'Delete', // icon: 'pi pi-fw pi-calendar-minus' // }, // ] // }, // { // label: 'Archieve', // icon: 'pi pi-fw pi-calendar-times', // items: [ // { // label: 'Remove', // icon: 'pi pi-fw pi-calendar-minus' // } // ] // } // ] // }, // { // label: 'Quit', // icon: 'pi pi-fw pi-power-off' // } // ]; } }
import { UserModel } from '@/domain/authentication/models' export interface CreateUserRepositoryContract { create: ( input: CreateUserRepositoryContract.Input, ) => Promise<CreateUserRepositoryContract.Output> } export namespace CreateUserRepositoryContract { export type Input = { email: string name: string last_name: string phone: string password: string role: 'admin' | 'client' } export type Output = UserModel } export interface FindUserByEmailRepositoryContract { findByEmail: ( input: FindUserByEmailRepositoryContract.Input, ) => Promise<FindUserByEmailRepositoryContract.Output> } export namespace FindUserByEmailRepositoryContract { export type Input = string export type Output = UserModel } export interface FindUserByIdRepositoryContract { findById: ( input: FindUserByIdRepositoryContract.Input, ) => Promise<FindUserByIdRepositoryContract.Output> } export namespace FindUserByIdRepositoryContract { export type Input = string export type Output = UserModel }
import '@/extensions/string'; import {CSSProperties, DetailedHTMLProps, HTMLAttributes, PointerEvent, useMemo, useRef, useState} from "react"; import styles from "./tilesGrid.module.scss"; import BoardTile from "@/components/BoardTile"; import BoardTileSelector, {HexadecimalColor} from "@/components/BoardTileSelector"; import Puzzle, {Answer, AnswerFound, Tile} from "@/models/Puzzle"; import ReactGA from 'react-ga4'; type BoardLetterGridProps = DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> & { enabled: boolean, puzzle: Puzzle, answersFound: AnswerFound[], onAnswerFound: (a: AnswerFound) => void; availableColors: HexadecimalColor[], }; export default function TilesGrid({ enabled, puzzle, answersFound, onAnswerFound, availableColors, ...props }: BoardLetterGridProps) { const [isSelecting, setSelecting] = useState<boolean>(false); const [selectedTiles, setSelectedTiles] = useState<Tile[]>([]); const gridRef = useRef<HTMLDivElement>(null); const tiles = useMemo(() => getSortedTiles(puzzle), [puzzle]); const color = availableColors[0]; const tileStyle: CSSProperties = { flexBasis: `${100 / puzzle.width}%`, pointerEvents: 'none' }; const startSelecting = (evt: PointerEvent<HTMLElement>) => { if (!enabled) { return; } if (!isSelecting) { const tile = getTileByOffset(evt.nativeEvent.offsetX, evt.nativeEvent.offsetY); ReactGA.event({ category: 'puzzle', action: 'select-tiles', label: 'start-selecting'}); setSelecting(true); setSelectedTiles([tile]); } }; const stopSelecting = () => { if (!isSelecting) { return; } const selectedWord = selectedTiles.map(t => t.letter).join(''); const matchedAnswer = puzzle.answers.find(a => a.word === selectedWord); if (matchedAnswer && answerIsValid(matchedAnswer)) { onAnswerFound({ answer: matchedAnswer, color: color }); ReactGA.event({ category: 'puzzle', action: 'select-tiles', label: 'answer-found', nonInteraction: false }); } setSelectedTiles([]); setSelecting(false); }; const answerIsValid = (matchedAnswer: Answer): boolean => { if (answersFound.find(a => a.answer.word === matchedAnswer.word) !== undefined) { return false; } const tilesMatch = (tiles: Tile[]) => { for (let i = 0; i < selectedTiles.length; i++) { const xMatch = selectedTiles[i].x === tiles[i].x; const yMatch = selectedTiles[i].y === tiles[i].y; if (!xMatch || !yMatch) { return false; } } return true; }; return tilesMatch(matchedAnswer.tiles) || isPalindrome(matchedAnswer.word) && tilesMatch([...matchedAnswer.tiles].reverse()); }; const handlePointerMove = (evt: PointerEvent<HTMLElement>) => { if (!isSelecting) { return; } const tile = getTileByOffset(evt.nativeEvent.offsetX, evt.nativeEvent.offsetY); if (!tile) { stopSelecting(); } else if (selectedTiles.includes(tile)) { setSelectedTiles(selectedTiles.slice(0, selectedTiles.indexOf(tile) + 1)); } else if (tilesAreSequential(selectedTiles[0], tile)) { setSelectedTiles([...getTilesInSequence(selectedTiles[0], tile)]); } }; const getTileByOffset = (offsetX: number, offsetY: number): Tile => { const gridElement = gridRef.current as HTMLDivElement; const gridWidth = Number.parseInt(window.getComputedStyle(gridElement).getPropertyValue('width').replace("px", '')); const cellSize = gridWidth / puzzle.width; const x = Math.floor(offsetX / cellSize); const y = Math.floor(offsetY / cellSize); return tiles.find(t => t.x === x && t.y === y) as Tile; }; const tilesAreSequential = (tile1: Tile, tile2: Tile): boolean => { if (tile2.x === tile1.x || tile2.y === tile1.y) { return true; } return Math.abs(tile2.x - tile1.x) === Math.abs(tile2.y - tile1.y); }; const getTilesInSequence = (firstTile: Tile, lastTile: Tile): Tile[] => { const dX = lastTile.x - firstTile.x; const dY = lastTile.y - firstTile.y; const amount = Math.max(Math.abs(dX), Math.abs(dY)) + 1; const tilesInSequence: Tile[] = [firstTile]; const nextX = () => dX > 0 ? firstTile.x + tilesInSequence.length : firstTile.x - tilesInSequence.length; const nextY = () => dY > 0 ? firstTile.y + tilesInSequence.length : firstTile.y - tilesInSequence.length; while (tilesInSequence.length < amount) { const x = dX === 0 ? firstTile.x : nextX(); const y = dY === 0 ? firstTile.y : nextY(); tilesInSequence.push(tiles.find(t => t.x === x && t.y === y) as Tile); } return tilesInSequence; }; const isPalindrome = (word: string) => word.reverse() === word; return ( <section ref={gridRef} className={styles.TilesGrid} style={{maxWidth: `calc(${puzzle.width} * var(--tile-max-size)`}} onPointerUp={() => stopSelecting()} onPointerLeave={() => stopSelecting()} onPointerDown={(e) => startSelecting(e)} onPointerMove={(e) => handlePointerMove(e)}> { tiles.map((t, i) => ( <BoardTile key={i} tabIndex={1} data-x={t.x} data-y={t.y} selectable={isSelecting} selected={selectedTiles.includes(t)} style={tileStyle}> {t.letter} </BoardTile> )) } { answersFound.map(({ answer, color }, i) => ( <BoardTileSelector key={i} puzzle={puzzle} color={color} firstTile={answer.tiles[0]} lastTile={answer.tiles[answer.tiles.length - 1]} /> )) } { isSelecting && <BoardTileSelector puzzle={puzzle} color={color} firstTile={selectedTiles[0]} lastTile={selectedTiles[selectedTiles.length - 1]} /> } </section> ); } function getSortedTiles(puzzle: Puzzle): Tile[] { const allTiles = [ ...puzzle.looseLetters, ...puzzle.answers.flatMap(a => a.tiles), ]; const uniqueTiles = allTiles.reduce((tiles, t) => { if (!tiles.find(tile => tile.x === t.x && tile.y === t.y)) { return [...tiles, t]; } return tiles; }, [] as Tile[]) return uniqueTiles.sort((a,b) => a.y === b.y ? a.x - b.x : a.y - b.y);; }
import { useNavigation } from "@react-navigation/native"; import React from "react"; import { View, Text, TouchableOpacity, StyleSheet, ScrollView, } from "react-native"; import { NavigatorParams } from "../App"; import { NativeStackNavigationProp } from "@react-navigation/native-stack"; interface ItemProps { title: string; onPress(): void; } const Menu = () => { const navigation = useNavigation<NativeStackNavigationProp<NavigatorParams>>(); const Item = (props: ItemProps) => { const { title, onPress } = props; return ( <TouchableOpacity onPress={onPress} style={styles.item}> <Text>{title}</Text> </TouchableOpacity> ); }; return ( <ScrollView showsVerticalScrollIndicator={false} style={styles.container}> <Item title="Introduction to reanimated 2" onPress={() => navigation.navigate("Introduction")} /> <Item title="Pan gesture handler basics" onPress={() => navigation.navigate("PanGestureHandlerBasics")} /> <Item title="Interpolate with ScrollView" onPress={() => navigation.navigate("InterpolateWithScrollView")} /> <Item title="Interpolate Colors" onPress={() => navigation.navigate("InterpolateColors")} /> </ScrollView> ); }; const styles = StyleSheet.create({ container: { backgroundColor: "#fff", }, item: { padding: 16, borderBottomWidth: 1, borderColor: "gray", }, }); export default Menu;
package registraAniversario.dao; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.List; import java.util.ArrayList; import java.util.Calendar; import registraAniversario.model.Pessoa; public class PessoaDAO { //put your link connection DB and name of your Schema like jdbc:mysql://localhost:3306/personDB String url = "jdbc:mysql://localhost:3306/your_schema"; //put your user from SQL String user = "user sql"; //put your password from SQL String password = "password sql"; private static final String INSERT_USER_SQL = "INSERT INTO aniversariantes (nome, data_nascimento, obs) VALUES (?,?,?);"; private static final String SELECT_USER_BY_ID = "SELECT * FROM aniversariantes WHERE id = ?;"; private static final String SELECT_ALL_USERS = "SELECT * FROM aniversariantes;"; private static final String DELETE_USER_SQL = "DELETE FROM aniversariantes WHERE id = ?;"; private static final String UPDATE_USER_SQL = "UPDATE aniversariantes SET nome=?, data_nascimento=?, obs=? WHERE id=?;"; // CREATE CONNECTION protected Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(url, user, password); } catch (SQLException exception) { exception.printStackTrace(); } catch (ClassNotFoundException exception) { exception.printStackTrace(); } return connection; } // CREATE USER public void criaPessoa(Pessoa pessoa) throws SQLException { Connection connection = null; try { connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USER_SQL); preparedStatement.setString(1, pessoa.getNome()); preparedStatement.setDate(2, pessoa.getDataNascimento()); preparedStatement.setString(3, pessoa.getObs()); preparedStatement.executeUpdate(); } catch (SQLException exception) { exception.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } } // READ USERS public List<Pessoa> listaPessoas(){ List<Pessoa> pessoas = new ArrayList<>(); try(Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS);) { System.out.println(preparedStatement); ResultSet resultSet = preparedStatement.executeQuery(); while(resultSet.next()) { int id = resultSet.getInt("id"); String nome = resultSet.getString("nome"); Date dataNascimento = resultSet.getDate("data_nascimento"); String obs = resultSet.getString("obs"); pessoas.add(new Pessoa(id, nome, dataNascimento, obs)); } } catch(SQLException exception) { exception.printStackTrace(); } return pessoas; } // SELECT USER BY ID public Pessoa selecionaPessoaPorId(int id) { Pessoa pessoa = null; try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID)) { preparedStatement.setInt(1, id); System.out.println(preparedStatement); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String nome = resultSet.getString("nome"); Date dataNascimento = resultSet.getDate("data_nascimento"); String obs = resultSet.getString("obs"); pessoa = new Pessoa(id, nome, dataNascimento, obs); } } catch (SQLException e) { e.printStackTrace(); } return pessoa; } // UPDATE USER public boolean atualizaPessoa(Pessoa pessoa) throws SQLException { boolean linhaAtualizada; try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(UPDATE_USER_SQL)) { statement.setString(1, pessoa.getNome()); statement.setDate(2, pessoa.getDataNascimento()); statement.setString(3, pessoa.getObs()); statement.setInt(4, pessoa.getId()); System.out.println("SQL de Atualização: " + statement); // Adicione esta linha para verificar o SQL gerado linhaAtualizada = statement.executeUpdate() > 0; System.out.println("Linhas atualizadas: " + (linhaAtualizada ? "1" : "0")); // Adicione esta linha para verificar o número de linhas atualizadas } catch (SQLException e) { e.printStackTrace(); linhaAtualizada = false; // Defina como falso em caso de erro } return linhaAtualizada; } // DELETE USERS public boolean deletaPessoa(int id) throws SQLException { boolean linhaDeletada; try(Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(DELETE_USER_SQL);){ statement.setInt(1, id); linhaDeletada = statement.executeUpdate() > 0; } return linhaDeletada; } public List<Pessoa> obterAniversariantesDoDia() { List<Pessoa> aniversariantesDoDia = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("MM-dd"); try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS)) { ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); String nome = resultSet.getString("nome"); Date dataNascimento = resultSet.getDate("data_nascimento"); String obs = resultSet.getString("obs"); // Verifique se a data de nascimento corresponde ao dia atual if (dataNascimento != null) { Calendar dataNascimentoCal = Calendar.getInstance(); dataNascimentoCal.setTime(dataNascimento); String dataNascimentoStr = sdf.format(dataNascimentoCal.getTime()); String dataAtualStr = sdf.format(Calendar.getInstance().getTime()); if (dataNascimentoStr.equals(dataAtualStr)) { aniversariantesDoDia.add(new Pessoa(id, nome, dataNascimento, obs)); } } } } catch (SQLException exception) { exception.printStackTrace(); } return aniversariantesDoDia; } }