text
stringlengths
184
4.48M
import 'package:flutter/material.dart'; import 'package:flutter_application_1/utils/my_images.dart'; import 'package:flutter_application_1/views/login/login_view.dart'; import 'register_validation.dart'; class RegisterPage extends StatefulWidget { const RegisterPage({Key? key}) : super(key: key); @override _RegisterPageState createState() => _RegisterPageState(); } class _RegisterPageState extends State<RegisterPage> { bool _isPasswordVisible = true; bool _isConfirmPasswordVisible = true; final TextEditingController _usernameController = TextEditingController(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); final TextEditingController _confirmPasswordController = TextEditingController(); final _formKey = GlobalKey<FormState>(); bool _areFormFieldsNotEmpty() { return _usernameController.text.isNotEmpty && _emailController.text.isNotEmpty && _passwordController.text.isNotEmpty && _confirmPasswordController.text.isNotEmpty; } _registerUser() async { String username = _usernameController.text; String email = _emailController.text; String password = _passwordController.text; String confirmPassword = _confirmPasswordController.text; // Wywołaj funkcję z pliku register_validation.dart registerValidation(context, username, email, password, confirmPassword); } @override Widget build(BuildContext context) { double statusBarHeight = MediaQuery.of(context).padding.top; double screenWidth = MediaQuery.of(context).size.width; return Scaffold( body: SingleChildScrollView( child: Stack( children: [ Positioned( width: 213, height: 183, top: statusBarHeight - 90, left: screenWidth - 166, child: Image.asset(MyImages.imageEllipse), ), Padding( padding: EdgeInsets.fromLTRB(16, statusBarHeight + 16, 16, 16), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextButton.icon( onPressed: () { Navigator.pop(context); }, icon: const Icon( Icons.arrow_back, color: Colors.purple, ), label: const Text( 'Go Back!', style: TextStyle( fontSize: 18, color: Colors.purple, decoration: TextDecoration.underline, ), ), ), const SizedBox(height: 20), _buildInputField( controller: _usernameController, label: 'Full Name', hint: 'Enter your full name', icon: Icons.person, ), const SizedBox(height: 20), _buildInputField( controller: _emailController, label: 'Email', hint: 'Enter your email', icon: Icons.email, ), const SizedBox(height: 20), _buildPasswordInput( controller: _passwordController, label: 'Password', hint: 'Enter your password', isVisible: _isPasswordVisible, toggleVisibility: () { setState(() { _isPasswordVisible = !_isPasswordVisible; }); }, ), const SizedBox(height: 20), _buildPasswordInput( controller: _confirmPasswordController, label: 'Confirm Password', hint: 'Confirm your password', isVisible: _isConfirmPasswordVisible, toggleVisibility: () { setState(() { _isConfirmPasswordVisible = !_isConfirmPasswordVisible; }); }, ), const SizedBox(height: 70), _buildRegisterButton(), const SizedBox(height: 8), _buildSignInText(), ], ), ), ) ], ), )); } Widget _buildInputField({ required TextEditingController controller, required String label, required String hint, required IconData icon, }) { return TextFormField( controller: controller, keyboardType: TextInputType.text, style: const TextStyle(color: Colors.purple), decoration: InputDecoration( labelText: label, hintText: hint, border: const OutlineInputBorder(), prefixIcon: Icon(icon, color: Colors.purple), ), ); } Widget _buildPasswordInput({ required TextEditingController controller, required String label, required String hint, required bool isVisible, required Function toggleVisibility, }) { return TextFormField( controller: controller, obscureText: isVisible, style: const TextStyle(color: Colors.purple), decoration: InputDecoration( labelText: label, hintText: hint, border: const OutlineInputBorder(), suffixIcon: IconButton( icon: Icon( isVisible ? Icons.visibility_off : Icons.visibility, color: Colors.purple, ), onPressed: () { toggleVisibility(); }, ), prefixIcon: const Icon(Icons.lock, color: Colors.purple), ), ); } Widget _buildRegisterButton() { return Container( width: 390, height: 50, margin: const EdgeInsets.only(top: 25, left: 0), child: ElevatedButton( onPressed: () { if (_areFormFieldsNotEmpty()) { _registerUser(); Navigator.push( context, MaterialPageRoute(builder: (context) => LoginPage()), ); } else { _showEmptyFieldsDialog(context); } }, style: ElevatedButton.styleFrom( backgroundColor: Colors.purple, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), ), child: const Text( 'Register', style: TextStyle(color: Colors.white), ), ), ); } Widget _buildSignInText() { return GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => LoginPage()), ); }, child: const Text( 'Already have an account? Sign In!', style: TextStyle( color: Colors.blue, decoration: TextDecoration.underline, ), ), ); } void _showEmptyFieldsDialog(BuildContext context) { showDialog( context: context, builder: (context) { return AlertDialog( title: const Text('Empty Fields'), content: const Text('Please fill in all the required fields.'), actions: <Widget>[ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: const Text('OK'), ), ], ); }, ); } }
<?php namespace App\Http\Controllers; use App\Models\BukuModel; use App\Models\DendaModel; use App\Models\TransaksiModel; use App\Models\UserModel; use DateTime; use Illuminate\Http\Request; use Yajra\DataTables\DataTables; class TransaksiController extends Controller { public function index(){ $breadcrumb = (object)[ 'title'=>'Daftar Transaksi', 'list' => ['Home', 'Transaksi'] ]; $page = (object)[ 'title' => 'Daftar transaksi yang terdaftar dalam sistem' ]; $activeMenu = 'transaksi'; //set saat menu aktif $transaksi = TransaksiModel::all(); $user = UserModel::all(); $buku = BukuModel::all(); return view('transaksi.index', [ 'breadcrumb' => $breadcrumb, 'page' => $page, 'transaksi' => $transaksi, 'user' => $user, 'buku' => $buku, 'activeMenu' => $activeMenu]); } // Ambil data barang dalam bentuk json untuk datatables public function list(Request $request) { $transaksis = TransaksiModel::select('transaksi_id', 'user_id', 'buku_id', 'transaksi_kode', 'tgl_peminjaman', 'tgl_pengembalian', 'denda') ->with('user')->with('buku'); //filter if($request->user_id){ $transaksis->where('user_id', $request->user_id); } if($request->buku_id){ $transaksis->where('buku_id', $request->buku_id); } return DataTables::of($transaksis) ->addIndexColumn() // menambahkan kolom index / no urut (default nama kolom: DT_RowIndex) ->addColumn('status', function ($transaksi) { // menambahkan kolom aksi if ($transaksi->tgl_pengembalian == null) { $status = '<span class="font-weight-bold text-warning">Pinjam</span>'; } else { $status = '<span class="font-weight-bold text-success">Kembali</span>'; } return $status; }) ->addColumn('aksi', function ($transaksi) { // menambahkan kolom aksi $btn = '<a href="'.url('/transaksi/' . $transaksi->transaksi_id).'" class="btn btn-info btn-sm">Detail</a> '; $btn .= '<a href="'.url('/transaksi/' . $transaksi->transaksi_id . '/edit').'" class="btn btn-warning btn-sm">Edit</a> '; // $btn .= '<form class="d-inline-block" method="POST" action="'. url('/transaksi/'.$transaksi->transaksi_id).'">' // . csrf_field() . method_field('DELETE') . // '<button type="submit" class="btn btn-danger btn-sm" // onclick="return confirm(\'Apakah Anda yakit menghapus data ini?\');">Hapus</button></form>'; return $btn; }) ->rawColumns(['status', 'aksi']) // memberitahu bahwa kolom aksi adalah html ->make(true); } public function create(){ $breadcrumb = (object)[ 'title' => 'Tambah Transaksi', 'list' => ['Home', 'Transaksi', 'Tambah'] ]; $page = (object)[ 'title' => 'Tambah Transaksi baru' ]; $user = UserModel::all(); $buku = BukuModel::all(); $activeMenu = 'Transaksi'; //set menu sedang aktif return view('Transaksi.create', [ 'breadcrumb' => $breadcrumb, 'page' => $page, 'user' => $user, 'buku' => $buku, 'activeMenu' => $activeMenu ]); } //UNTUK MENGHANDLE ATAU MENYIMPAN DATA BARU public function store(Request $request){ $request->validate([ //barang_kode harus diisi, berupa string, minimal 3 karakter dan bernilai unik di table m_barang kolom barang_kode 'transaksi_kode' => 'required|string|min:3|unique:t_transaksi,transaksi_kode', 'tgl_Peminjaman' => 'required|date', 'tgl_pengembalian' => 'required|date', 'denda' => 'required|integer', ]); TransaksiModel::create([ 'user_id' => $request -> user_id, 'buku_id' => $request -> buku_id, 'transaksi_kode'=> $request -> transaksi_kode, 'tgl_peminjaman'=> $request -> tgl_peminjaman, 'tgl_pengembalian' => $request -> tgl_pengembalian, 'denda' => $request -> denda, ]); return redirect('/transaksi')->with('success', 'Data transaksi berhasil disimpan'); } //MENAMPILKAN DETAIL BARANG public function show(string $id){ $transaksi = TransaksiModel::with('user')->with('buku')-> find($id); $breadcrumb = (object)[ 'title' => 'Detail Transaksi', 'list' => ['Home', 'Transaksi', 'Detail'] ]; $page = (object)[ 'title' => 'Detail Transaksi' ]; $activeMenu = 'transaksi'; // set menu yang aktif return view('transaksi.show', [ 'breadcrumb' => $breadcrumb, 'page' => $page, 'transaksi' => $transaksi, 'activeMenu' => $activeMenu]); } public function edit(string $id){ $transaksi = TransaksiModel::find($id); $user = UserModel::all(); $buku = BukuModel::all(); $breadcrumb = (object)[ 'title' => 'Edit Transaksi', 'list' => ['Home', 'Transaksi', 'Edit'] ]; $page = (object)[ 'title' => 'Edit Transaksi' ]; $activeMenu = 'transaksi'; return view('transaksi.edit',[ 'breadcrumb' => $breadcrumb, 'page' => $page, 'transaksi' => $transaksi, 'user' => $user, 'buku' => $buku, 'activeMenu' => $activeMenu ]); } public function update(Request $request, string $id){ $request->validate([ 'tgl_peminjaman' => 'required|date', 'tgl_pengembalian' => 'nullable|date', 'denda' => 'nullable|integer', ]); if (!$request->tgl_pengembalian == null) { $date1 = new DateTime($request->tgl_peminjaman); $date2 = new DateTime($request->tgl_pengembalian); $selisih = date_diff($date1, $date2); if ($selisih->days > 5) { $denda = $selisih->days - 5; } else { $denda = 0; } } else { $denda = 0; } TransaksiModel::find($id)->update([ 'transaksi_kode'=> $request -> transaksi_kode, 'tgl_peminjaman'=> $request -> tgl_peminjaman, 'tgl_pengembalian' => $request -> tgl_pengembalian, 'denda' => $denda, 'user_id' => $request -> user_id, 'buku_id' => $request -> buku_id, ]); return redirect('/transaksi')->with('success', 'Data berhasil diubah'); } public function destroy(string $id){ $check = TransaksiModel::find($id); if(!$check){ return redirect('/transaksi')->with('error', 'Data transaksi tidak ditemukan'); } try{ TransaksiModel::destroy($id); return redirect('/transaksi')->with('success', 'Data transaksi berhasil dihapus'); }catch(\Illuminate\Database\QueryException $e){ return redirect('/transaksi')->with('error', 'Data transaksi gagal dihapus karena terdapat tabel lain yang terkait dengan data ini'); } } }
<template> <v-dialog v-model="dialog_" persistent max-width="400px"> <v-card> <v-card-title> <span class="headline">找回密码</span> </v-card-title> <v-card-text> <v-text-field v-model="email" label="注册邮箱" name="email" prepend-icon="mdi-email" required hint="请输入注册时的邮箱" type="text" :rules="emailRules"></v-text-field> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="blue darken-1" text @click="dialog_=false">关闭</v-btn> <!-- <v-btn color="blue darken-1" text :disabled="!resetDisable" @click="reset">发送邮件</v-btn> --> <progress-button :text="true" progressColor="blue darken-1" color="blue darken-1" title="发送邮件" :disabled="!resetDisable" :loading="loading" @click="reset"> </progress-button> </v-card-actions> </v-card> </v-dialog> </template> <script> import userApi from '@/api/userApi.js' import ProgressButton from '../../components/common/ProgressButton.vue' export default { components: { ProgressButton }, props:{ dialog: { types: Boolean, default: false } }, data() { return { loading: false, email: null, emailRules: [ v => !!v || '必须输入邮箱字段', v => /^\w+([.-]?\w+)*@\w+([.-]\w+)*(\.\w{2,3})+$/.test(v) || '请输入正确格式的邮箱' ], } }, computed: { dialog_: { get() { return this.dialog; }, set(val) { //drawer_改变由父组件控制 this.$emit("on-change-reset-dialog", val); } }, resetDisable() { let email = /^\w+([.-]?\w+)*@\w+([.-]\w+)*(\.\w{2,3})+$/.test(this.email) return email && !this.loading } }, methods: { reset(){ let that = this this.loading = true userApi.sendResetEmail(this.email) .then(res => { that.loading = false if (res.code === 200){ this.$toast.success(res.data) this.dialog_ = false }else this.$toast.error(res.data) }) .catch(err => { console.log(err) that.loading = false }) } } } </script>
<script> import AxisX from "./bar_components/AxisX.svelte"; import AxisY from "./bar_components/AxisY.svelte"; import Tooltip from "./bar_components/Tooltip.svelte"; import data from "./data/data.js"; import { scaleLinear } from "d3-scale"; import { max } from "d3-array"; let width = 400, height = 400; const margin = { top: 25, right: 20, bottom: 30, left: 10 }; const radius = 10; $: innerWidth = width - margin.left - margin.right; let innerHeight = height - margin.top - margin.bottom; $: xScale = scaleLinear() .domain([0, 100]) .range([0, innerWidth]); let yScale = scaleLinear() .domain([0, max(data, d => d.hours)]) .range([innerHeight, 0]); let hoveredData; import { fly } from "svelte/transition"; </script> <main> <div class="chart-container" bind:clientWidth={width} > <svg {width} {height} on:mouseleave={() => hoveredData = null}> <g class="inner-chart" transform="translate({margin.left}, {margin.top})"> <AxisY width={innerWidth} {yScale} /> <AxisX height={innerHeight} width={innerWidth} {xScale} /> {#each data.sort((a, b) => a.grade - b.grade) as d, index} <circle in:fly={{ x: -10, opacity: 0, duration: 500 }} cx={xScale(d.grade)} cy={yScale(d.hours)} fill="purple" stroke="black" r={hoveredData == d ? radius * 2 : radius} opacity={hoveredData ? (hoveredData == d ? 1 : 0.45) : 0.85} on:mouseover={() => hoveredData = d} on:focus={() => hoveredData = d} tabindex="0" /> {/each} </g> </svg> {#if hoveredData} <Tooltip {xScale} {yScale} {width} data={hoveredData} /> {/if} </div> </main> <style> :global(.tick text, .axis-title) { font-weight: 400; /* How thick our text is */ font-size: 12px; /* How big our text is */ fill: hsla(212, 10%, 53%, 1); /* The color of our text */ } main { max-width: 768px; margin: auto; padding: 8px; } .chart-container { position: relative; /* background-color: whitesmoke(211, 206, 198); */ border: 1px solid black; border-radius: 6px; box-shadow: 1px 1px 30px rgba(252, 220, 252, 1); } circle { transition: r 300ms ease, opacity 500ms ease; cursor: pointer; } </style>
Part 1 - Segmentation Part 2 - Paging Part 3 - Interrupts Part 4 - Debugging, I/O, Misc fun on a bun IA32 IA-32 System-Level Registers and Data Structures ** CPUID ** CPU (feature) identification - Different processors support different features - CPUID is how we know if the chip we're running on supports newer features, such as hardware virtualisation, 64-bit mode, hyperthreading, thermal monitors, etc. - CPUID doesn't have operands. Rather it "takes input" as value preloaded into EAX (and possibly ECX). After it finishes the output is stored to EAX, EBX, ECX, and EDX. 0F A2 CPUID Returns processor identification and feature information to the EAX, EBX ECX, and EDX registers, as determined by input in EAX (in some cases, ECX as well). ** PUSHFD ** Push EFLAGS onto Stack 9C PUSHF Push lower 16 bits of EFLAGS 9C PUSHFD Push EFLAGS 9C PUSHFD Push RFLAGS - If you need to read the entire EFLAGS register, make sure you use PUSHFD, not just PUSHF (Visual Studio 2008 forces the 16 bit form if you don't have the D) ** POPFD ** Pop Stack into EFLAGS 9D POPF Pop top of stack into lower 16 bits of EFLAGS 9D POPFD Pop top of stack into EFLAGS REX.W + 9D POPFQ Pop top of stack and zero-extend into RFLAGS - There are some flags which will not be transferred from the stack to EFLAGS unless you're in ring 0 - If you need to set the entire EFLAGS register, make sure you use POPFD, not just POPF "" "" p. 17 intmx86 lecture slide one - Some Example CPUID Inputs and Outputs PROCESSOR MODES In the beginning, there was real mode, and it sucked. - Real-address mode "This mode implements the programming environment of the Intel 8086 processor with extensions (such as the ability to switch to protected or system management mode). The processor is placed in real-address mode following a power-up or reset. - DOS runs in real mode - No virtual memory, no privilege rings, 16 bit mode - Protected Mode - This mode is the native state of the processor. Among the capabilities of protected mode is the ability to directly execute 'Real-address mode' 8086 software in a protected, multi-tasking environment. This feature is called virtual-8086 mode although it is not actually a processor mode. Virtual-8086 mode is actually a protected mode attribute that can be enabled for any task - Virtual-8086 is just for backwards compatability, and I point it out only to say that Intel says it's not really its own mode - Protected mode adds support for virtual memory and privilege rings - Modern OSes operate in protected mode - System Management Mode - This mode provides an operating system or executive with a transparent mechanism for implementing platform-specific functions such as power management and system security. The processor enters SMM when the external SMM interrupt pin (SMI#) is activated or an SMI is received from the advanced programmable interrupt controller (APIC). - SMM has become a popular target for advanced rootkit discussions recently because access to SMM memory is locked so that neither ring 0 nor VMX hypervisors can access it. Thus is VMX is more privileged than ring 0 ("ring -1"), SMM is more privileged than VMX ("ring -2") because a hypervisor can't even read SMM memory. - Reserving discussion of VMX and SMM for Advanced x86 class Vol. 1, Sect 3.1 p. 23 lecture notes 1 Figure 1-6 Operating Modes of the AMD64 Architecture e.g. 64 bit mode, compatability mode (long mode) Protected Mode, Virutal 8086 Mode Real Mode, System Management Mode PRIVILEGE RINGS MULTICS was the first OS with support for privilege rings x86's rings are also enforced by hardware You often hear that normal programs execute in ring 3, (userspace/usermode), and the privileged code runs in ring 0 (kernelspace / kernelmode) The lower the ring number, the more privileged the code is In order to find the rings, we need to understand a capability called segmentation Vol 3a, Sect 5.5 (Level 0 - OS kernel, Level 1 - OS Services, Level 2 - OS Services, Level 3 - Applications) Paravirtualized Xen (Requires a modified guest OS) Figure 5: Execution mode level3 level2 level1 level0 Xen Guest OS Application (Newest Xen instead uses HW VMX to be more privileged than the OS kernel) Segmentation - "Segmentation provides a mechanism for dividing the processor's addressable memory space (called the linear address space) into smaller protected address spaces called segments.") Figure 3-4 - Multi-segment model Vol 3a, Sect 3.1 & 3.2.3 Segment registers, segment descriptors, linear address space (or physical memory) CS Access stack Limit code SS Base address data data DS data ES FS GS Segment addressing - "To locate a byte in a particular segment, a logical address (also called a far pointer) must be provided. A logical address consists of a segment selector and an offset." - "The physical address space is defined as the range of addresses that the processor can generate on its address bus." - Normally the physical address space is based on how much RAM you have installed, up to a maximum of 2^32 (4GB). But there is a mechanism (physical address extensions - PAE) which we will talk about later which allows systems to access a space up to 2^36 (64GB). - Basically a hack for more than 4GB of RAM but who aren't using a 64 bit OS. - Linear address space is a flat 32 bit space - If paging (talked about later) is disabled, linear address space is mapped 1:1 to physical address space Vol. 3a, Sect 3.1 Segmentation restated - Segmentation is not option - Segmentation translates logical addresses to linear addresses automatically in hardware by using table lookups - Logical address (also called a far pointer) = 16 bit selector + 32 bit offset - If paging (talked about later) is disabled, linear addresses map directly to physical addresses Figure 3-5. Logical to Linear Address Translation Logical Address, Segment Selector Descriptor Table, Segment Descriptor Base Address Linear Address, Offset (effective address) Figure 3-1. Segmentation and Paging Vol. 3a, Sect 3.1 Segment Selectors - A segment selector is a 16-bit value held in a segment register It is used to select an index for a segment descriptor from one of two tables - GDT (Global Descriptor Table), for use system-wide - LDT (Local Descriptor Table), intended to be a table per-process and switched when the kernel switches between process contexts - Note that the table index is actually 13 bits not 16, so the tables can each hold 2^13 = 8192 descriptors Figure 3-6. Segment Selector Table Indicator (0 = GDT, 1 = LDT), Requested Privilege Level The Six Segment Registers - CS, code segment - SS, stack segment - DS, data segment - ES/FS/GS, Extra (usually data) segment registers - The "hidden part" is like a cache so that segment descriptor information doesn't have to be looked up each time. Figure 3-7. Segment Registers Visible part, hidden part, segment selector, base address, limit, access information CS SS DS ES FS GS Implicit use of segment registers - When you're addressing the stack, you're implicitly using a logical address that is using the SS (stack segment) register as the segment selector, (i.e. ESP == SS:ESP) - Even if a disassembler doesn't show it, the use of segment registers is built into some of your favourite F3 A5 REP MOVS m32, m32 Move (E)CX doublewords from DS:[(E)SI] to ES:[(E)DI] Explicit use of segment registers - You can write assembly which explicitly specifies which segment register it wants to use. Just prefix the memory address with a segment register and colon - e.g. "mov eax, [ebx]", as opposed to "mov eax, fs:[ebx]" - The assembly just puts a prefix on the instruction to say "when this instruction is asking for memory, it's actually asking for memory in this segment." - In this way you're actually specifying a full logical address / far pointer Inferences - Windows maintains different CS, SS, & FS segment selectors for userspace processes vs kernel ones - The RPL field seems to correlate with the ring for kernel or userspace - Windows doesn't change DS or ES when moving between userspace and kernelspace (they were the exact same values) - Windows doesn't use GS One more time One of the segment registers (SS/CS/DS/ES/FS/GS), address used in some assembly instruction, GDT or LDT Figure 3-5. Logical Address to Linear Address Translation Logical address, seg. selector Descriptor table, seg. descriptor Base address Offset (effective address) Linear address + GDT & LDT Segment Selector, Global Descriptor Table (TI = 0), Local Descriptor Table (TI = 1) All entries in these tables are "Segment Descriptor" structures GDTR Register, LDTR Register Limit, Base Address; Limit, Base Address, Seg. Sel. Special registers point to the base of the tables and specify their size Fig. 3-1. Global and Local Descriptor Tables Global Descriptor Table Register (GDTR) Vol 3a. Figure 2-5 - The upper 32 bits ("base address") of the register specify the linear address where the GDT is stored - The lower 16 bits ("table limit") specify the size of the table in bytes - Special instructions used to load a value into the register or store the value out to memory - LGDT (load 6 bytes from memory into GDTR) - SGDT (store 6 bytes of GDTR to memory) Local Descriptor Table Register (LDTR) Vol 3a. Figure 2-5 - Like the segment registers, the LDT has a visible part, the segment selector, and a hidden part, the cached segment info. which specifies the size of the LDT - The selector's "Table Indicator" (T) bit must be set to 0 to specify that it's selecting from the GDT, not from itself ;) - Special instructions used to load a value into the register or store the value out to memory - LLDT (load 16 bit segment selector into LDTR) - SLDT (store 16 bit segment selector of LDTR to memory) Segment Descriptors
<?php namespace App\Listeners; use App\Events\CommentWritten; use App\Events\UnlockedEvent; use App\Models\User; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class CommentWrittenListener { /** * Create the event listener. */ public function __construct() { // } /** * Handle the event. */ public function handle(CommentWritten $event) { // Check and unlock comments written achievements $this->checkAndUnlockCommentsWrittenAchievements($event->comment->user); } private function checkAndUnlockCommentsWrittenAchievements(User $user) { $global_achievement_list = comment_written_achievement_list(); $commentsWrittenCount = $user->comments()->count(); // Define achievement unlocking conditions if ($commentsWrittenCount == 1) { $this->unlockAchievement($user, $global_achievement_list[0]); } elseif ($commentsWrittenCount == 3) { $this->unlockAchievement($user, $global_achievement_list[1]); } elseif ($commentsWrittenCount == 5) { $this->unlockAchievement($user, $global_achievement_list[2]); } elseif ($commentsWrittenCount == 10) { $this->unlockAchievement($user, $global_achievement_list[3]); } elseif ($commentsWrittenCount == 20) { $this->unlockAchievement($user, $global_achievement_list[4]); } } private function unlockAchievement(User $user, string $achievementName) { // Implement logic for unlocking achievements event(new UnlockedEvent($achievementName, $user)); } }
import { create } from "zustand"; import { StoreTypes } from "./utils/types"; const useStore = create<StoreTypes>((set) => ({ token: typeof window === "undefined" ? "" : localStorage.getItem("token") || "", setToken: (newToken: string) => set({ token: newToken }), balance: "", setBalance: (balance) => set({ balance }), isUnmounted: false, setIsUnmounted: (isUnmounted) => set({ isUnmounted }), dataLoading: false, setDataLoading: (dataLoading) => set({ dataLoading }), isModalUnmounted: false, setIsModalUnmounted: (isModalUnmounted) => set({ isModalUnmounted }), isOpenAddressBookModal: false, setIsOpenAddressBookModal: (isOpen) => set({ isOpenAddressBookModal: isOpen }), loading: false, setLoading: (isLoaded) => set({ loading: isLoaded }), copiedAddress: null, setCopiedAddress: (address: any) => set({ copiedAddress: address }), editData: null, setEditData: (data: any) => set({ editData: data }), searchResult: null, setSearchResult: (result: any) => set({ searchResult: result }), truncateAddress: (address: string) => { if (!address) { return ""; } const truncatedAddress = `${address.slice(0, 6)}...${address.slice(-6)}`; return truncatedAddress; }, })); export default useStore;
from project.toy_store import ToyStore from unittest import TestCase, main class TestToyStore(TestCase): def setUp(self): self.toy = ToyStore() self.toy_shelf ={ "A": None, "B": None, "C": None, "D": None, "E": None, "F": None, "G": None, } def test_correct_init(self): self.assertEqual({ "A": None, "B": None, "C": None, "D": None, "E": None, "F": None, "G": None, }, self.toy.toy_shelf) def test_add_toy_shelf_not_existing_raises_exception(self): with self.assertRaises(Exception) as ex: self.toy.add_toy("Z", "toyiiz") self.assertEqual("Shelf doesn't exist!", str(ex.exception)) def test_add_toy_already_exists_name_matches_raises_exception(self): self.toy.add_toy("A", "toyiiz") with self.assertRaises(Exception) as ex: self.toy.add_toy("A", "toyiiz") self.assertEqual("Toy is already in shelf!", str(ex.exception)) def test_add_toy_already_exists_name_miss_matches_raises_exception(self): self.toy.add_toy("A", "toyiiz") with self.assertRaises(Exception) as ex: self.toy.add_toy("A", "koyiiz") self.assertEqual("Shelf is already taken!", str(ex.exception)) def test_add_toy_with_success(self): self.toy_store = ToyStore() result = self.toy_store.add_toy("A", "ToyTestName") self.assertEqual(result, "Toy:ToyTestName placed successfully!") self.assertEqual(self.toy_store.toy_shelf, { "A": "ToyTestName", "B": None, "C": None, "D": None, "E": None, "F": None, "G": None, }) def test_remove_toy_method_shelf_is_already_taken(self): self.toy_store = ToyStore() with self.assertRaises(Exception) as ex: self.toy_store.remove_toy("K", "ToyTestName") self.assertEqual(str(ex.exception), "Shelf doesn't exist!") def test_remove_toy_method_toy_on_that_shelf_does_not_exist(self): self.toy_store = ToyStore() with self.assertRaises(Exception) as ex: self.toy_store.remove_toy("A", "ToyTestName") self.assertEqual(str(ex.exception), "Toy in that shelf doesn't exists!") self.toy_store.add_toy("A", "ToyTestNameOne") with self.assertRaises(Exception) as ex: self.toy_store.remove_toy("A", "ToyTestNameTwo") self.assertEqual(str(ex.exception), "Toy in that shelf doesn't exists!") def test_remove_toy_method_successfully_removed_toy_from_shelf(self): self.toy_store = ToyStore() self.toy_store.add_toy("A", "ToyTestName") result = self.toy_store.remove_toy("A", "ToyTestName") self.assertEqual(result, "Remove toy:ToyTestName successfully!") self.assertEqual(self.toy_store.toy_shelf, { "A": None, "B": None, "C": None, "D": None, "E": None, "F": None, "G": None, }) if __name__ == '__main__': main()
import React, {useState, useEffect} from "react"; import CharactersList from './CharactersList.js'; import './Characters.css'; function Characters() { const [characters, setCharacters] = useState([]); const fetchCharacters = () =>{ fetch('https://hp-api.onrender.com/api/characters') .then((response) => response.json()) .then(data => setCharacters(data)); } useEffect(() => { fetchCharacters() }, []); return ( <div className="text-center" id="characters"> <h2 className="characters-heading">List of Characters</h2> <div className="table-responsive"> <table className="table table-hover"> <thead> <tr className="border-bottom"> <th scope="col">Image</th> <th scope="col">Name</th> <th scope="col">Date of Birth</th> <th scope="col">Gender</th> <th scope="col">Species</th> <th scope="col">Ancestry</th> <th scope="col">Eye Colour</th> <th scope="col">Hair Colour</th> <th scope="col">Patronus</th> <th scope="col">Wand Details</th> </tr> </thead> <tbody> {characters.map((character) => <CharactersList name = {character.name} species = {character.species} gender = {character.gender} house = {character.house} dateOfBirth = {character.dateOfBirth} ancestry = {character.ancestry} eyeColour = {character.eyeColour} hairColour = {character.hairColour} patronus = {character.patronus} image = {character.image} wandWood = {character.wand.wood} wandCore = {character.wand.core} wandLength = {character.wand.length} /> )} </tbody> </table> </div> </div> ) } export default Characters;
/* Cleaning Data in SQL Queries */ SELECT * from Nashville_Housing ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Standardize Date Format SELECT SaleDate, convert(Date, SaleDate) from Nashville_Housing update Nashville_Housing SET SaleDate = convert(Date, SaleDate) -- Let's see if this works SELECT SaleDate, convert(Date, SaleDate) from Nashville_Housing -- This update method did not work on the SaleDate Column, lets try another method ALTER TABLE Nashville_Housing ADD SaleDateUpdated Date; UPDATE Nashville_Housing SET SaleDateUpdated = CONVERT(Date, SaleDate) --Let's see if this works SELECT SaleDateUpdated, CONVERT(Date, SaleDate) FROM Nashville_Housing ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --Populate empty property address data SELECT PropertyAddress FROM Nashville_Housing WHERE PropertyAddress is null --A check on the entire data show that parcelID that are thesame has same address SELECT * FROM Nashville_Housing WHERE PropertyAddress is null SELECT * FROM Nashville_Housing ORDER BY parcelid --We will use self join to replace empty property address with the propertyaddress of rows that has same parcelID SELECT a.ParcelID, a.PropertyAddress, b.ParcelID, b.PropertyAddress FROM Nashville_Housing a join Nashville_Housing b ON a.ParcelID = b.ParcelID AND a.UniqueID <> b.UniqueID WHERE a.PropertyAddress IS NULL -- use ISNULL() FUNCTION TO POPULATE IT SELECT a.ParcelID, a.PropertyAddress, b.ParcelID, b.PropertyAddress, ISNULL(a.PropertyAddress, b.PropertyAddress) FROM Nashville_Housing a JOIN Nashville_Housing b ON a.ParcelID = b.ParcelID AND a.UniqueID <> b.UniqueID WHERE a.PropertyAddress IS NULL -- Let now update it UPDATE a SET PropertyAddress = ISNULL(a.PropertyAddress, b.PropertyAddress) FROM Nashville_Housing a JOIN Nashville_Housing b ON a.ParcelID = b.ParcelID AND a.UniqueID <> b.UniqueID WHERE a.PropertyAddress IS NULL --Lets check again if there are still null values SELECT a.ParcelID, a.PropertyAddress, b.ParcelID, b.PropertyAddress, ISNULL(a.PropertyAddress, b.PropertyAddress) FROM Nashville_Housing a JOIN Nashville_Housing b ON a.ParcelID = b.ParcelID AND a.UniqueID <> b.UniqueID WHERE a.PropertyAddress IS NULL ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- --Breaking out Address into individual columns (Address, City, State) SELECT PropertyAddress FROM Nashville_Housing SELECT SUBSTRING(PropertyAddress, 1, CHARINDEX(',', PropertyAddress)) AS Address FROM Nashville_Housing -- since CHARINDEX(',', PropertyAddress) is a position remove 1 from it to get rid of the comma at the end of address SELECT SUBSTRING(PropertyAddress, 1, CHARINDEX(',', PropertyAddress)-1) AS Address FROM Nashville_Housing -- add the city SELECT SUBSTRING(PropertyAddress, 1, CHARINDEX(',', PropertyAddress)-1) AS Address, SUBSTRING(PropertyAddress, CHARINDEX(',', PropertyAddress)+1, LEN(PropertyAddress)) AS City FROM Nashville_Housing -- it is good to extract and add the column to the table ALTER TABLE Nashville_Housing ADD PropertySplitAddress nvarchar(255) UPDATE Nashville_Housing SET PropertySplitAddress = SUBSTRING(PropertyAddress, 1, CHARINDEX(',', PropertyAddress)-1) ALTER TABLE Nashville_Housing ADD PropertySplitCity nvarchar(255) UPDATE Nashville_Housing SET PropertySplitCity = SUBSTRING(PropertyAddress, CHARINDEX(',', PropertyAddress)+1, LEN(PropertyAddress)) -- see the result SELECT * FROM Nashville_Housing -- We will do thesame for owner address using a function called PARSENAME SELECT PARSENAME(REPLACE(OwnerAddress, ',', '.'), 3), PARSENAME(REPLACE(OwnerAddress, ',', '.'), 2), PARSENAME(REPLACE(OwnerAddress, ',', '.'), 1) FROM Nashville_Housing -- it is good to extract the owner address and add the column to the table ALTER TABLE Nashville_Housing ADD OwnerSplitAddress nvarchar(255) UPDATE Nashville_Housing SET OwnerSplitAddress = PARSENAME(REPLACE(OwnerAddress, ',', '.'), 3) ALTER TABLE Nashville_Housing ADD OwnerSplitCity nvarchar(255) UPDATE Nashville_Housing SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress, ',', '.'), 2) ALTER TABLE Nashville_Housing ADD OwnerSplitState nvarchar(255) UPDATE Nashville_Housing SET OwnerSplitState = PARSENAME(REPLACE(OwnerAddress, ',', '.'), 1) -- see the result SELECT * FROM Nashville_Housing ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Change Y and N to Yes and No in "Sold as Vacant" field SELECT DISTINCT(SoldAsVacant), COUNT(SoldAsVacant) FROM Nashville_Housing GROUP BY SoldAsVacant ORDER BY 2 SELECT SoldAsVacant, CASE WHEN SoldAsVacant = 'Y' THEN 'Yes' WHEN SoldAsVacant = 'N' THEN 'No' ELSE SoldAsVacant END FROM Nashville_Housing --Update SoldAsVacant field UPDATE Nashville_Housing SET SoldAsVacant = CASE WHEN SoldAsVacant = 'Y' THEN 'Yes' WHEN SoldAsVacant = 'N' THEN 'No' ELSE SoldAsVacant END -- let's see if it works SELECT DISTINCT(SoldAsVacant), COUNT(SoldAsVacant) FROM Nashville_Housing GROUP BY SoldAsVacant ORDER BY 2 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Remove Duplicates using CTE -- Using Partition by to know where there's duplicate SELECT *, ROW_NUMBER() OVER ( PARTITION BY ParcelID, PropertyAddress, SalePrice, SaleDate, LegalReference ORDER BY UniqueID ) row_num FROM Nashville_Housing ORDER BY ParcelID -- using CTE to see the duplicats WITH RowNumCTE AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY ParcelID, PropertyAddress, SalePrice, SaleDate, LegalReference ORDER BY UniqueID ) row_num FROM Nashville_Housing --ORDER BY ParcelID ) SELECT * FROM RowNumCTE WHERE row_num > 1 ORDER BY PropertyAddress -- Delete the duplicate WITH RowNumCTE AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY ParcelID, PropertyAddress, SalePrice, SaleDate, LegalReference ORDER BY UniqueID ) row_num FROM Nashville_Housing --ORDER BY ParcelID ) DELETE FROM RowNumCTE WHERE row_num > 1 -- Let's see if it works WITH RowNumCTE AS ( SELECT *, ROW_NUMBER() OVER ( PARTITION BY ParcelID, PropertyAddress, SalePrice, SaleDate, LegalReference ORDER BY UniqueID ) row_num FROM Nashville_Housing --ORDER BY ParcelID ) SELECT * FROM RowNumCTE WHERE row_num > 1 ORDER BY PropertyAddress ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Delete unused column like property and owner address because we have already created a split of it. This is often use in views SELECT * FROM Nashville_Housing ALTER TABLE Nashville_Housing DROP COLUMN OwnerAddress, PropertyAddress, SaleDate -- Let's see our table now SELECT * FROM Nashville_Housing
#ifndef FTDP_ITEM_H #define FTDP_ITEM_H #include <type_traits> // The common Visitor class class Visitor { public: // virtual destructor because we want the Visitor class to be polymorphic virtual ~Visitor() {} }; // Templated common Item class with a VisitorType which is also a template class // like for example: DynamicVisitor<Item> template <template<class> class VisitorType> class Item { public: // virtual accept function for any visitor of type Visitor virtual void accept(Visitor &visitor) noexcept = 0; // templated function for accepting a visitor for a specific type item template <class Type> void acceptVisitor(Type &item, Visitor &visitor) noexcept { // dynamic casting the visitor for this type so we get the right visit method using the accept method dynamic_cast<VisitorType<Type>&>(visitor).visit(item); // this is where the magic of dynamic polymorphism happens } }; // Dynamic visitor class interface that implement the common visitor // As we are going to implement this class multiple times for each specific type, in order to avoid the diamond death of multiple inheritance we need to make the inheritance virtual template <class Type> class DynamicVisitor : virtual public Visitor { // Let's make sure that the Type is subclass of Item<DynamicVisitor> such that it has an accept method that will call the visit method in this class static_assert(std::is_base_of<Item<DynamicVisitor>, Type>::value, "Type is not subclass of Item"); public: // The visit method for a generic Type // As this class will be implemented for each accepted Item type, it will provide virtual visit functions for all the accepted types virtual void visit(Type &item) noexcept = 0; }; // Primary template declaration of the visitor_traits // The specializations for this with the right accept method in it will be provided by the user for each accepted type template<class Type> struct visitor_traits { template<class VisitorType> // A dummy implementation of accept method static void accept(VisitorType &visitor, Type &item) noexcept { // Do nothing, because accept method is not implemented for this type // Could as well throw exception or terminate } }; // The static visitor class which implements the common Visitor interface class StaticVisitor : public Visitor { // Templated visit function for visiting any type of the accepted item types template <class Type> void visit(Type &item) noexcept { return Type::visit(&item); } }; #endif //FTDP_ITEM_H
// 순수 파이썬 사용 epsilon = 0.0000001 def perceptron(x1, x2): w1, w2, b = 1.0, 1.0, -1.5 sum = x1*w1+x2*w2+b if sum > epsilon : # 부동소수점 오차를 방지하기 위하여 return 1 else : return 0 print(perceptron(0, 0)) print(perceptron(1, 0)) print(perceptron(0, 1)) print(perceptron(1, 1)) // NUMPY 사용 import numpy as np epsilon = 0.0000001 def perceptron(x1, x2): X = np.array([x1, x2]) W = np.array([1.0, 1.0]) B = -1.5 sum = np.dot(W, X)+B if sum > epsilon : return 1 else : return 0 print(perceptron(0, 0)) print(perceptron(1, 0)) print(perceptron(0, 1)) print(perceptron(1, 1)) //퍼셉트론 학습 알고리즘 import numpy as np epsilon = 0.0000001 # 부동소수점 오차 방지 def step_func(t): # 퍼셉트론의 활성화 함수 if t > epsilon: return 1 else: return 0 X = np.array([ # 훈련 데이터 세트 [0, 0, 1], # 맨 끝의 1은 바이어스를 위한 입력 신호 1이다. [0, 1, 1], # 맨 끝의 1은 바이어스를 위한 입력 신호 1이다. [1, 0, 1], # 맨 끝의 1은 바이어스를 위한 입력 신호 1이다. [1, 1, 1] # 맨 끝의 1은 바이어스를 위한 입력 신호 1이다. ]) y = np.array([0, 0, 0, 1]) # 정답을 저장하는 넘파이 행렬 W = np.zeros(len(X[0])) # 가중치를 저장하는 넘파이 행렬 def perceptron_fit(X, Y, epochs=10): # 퍼셉트론 학습 알고리즘 구현 global W eta = 0.2 # 학습률 for t in range(epochs): for i in range(len(X)): predict = step_func(np.dot(X[i], W)) error = Y[i] - predict # 오차 계산 W += eta * error * X[i] # 가중치 업데이트 print("현재 처리 입력=",X[i],"정답=",Y[i],"출력=",predict,"변경된 가중치=", W) def perceptron_predict(X, Y): # 예측 global W for x in X: print(x[0], x[1], "->", step_func(np.dot(x, W))) perceptron_fit(X, y, 6) perceptron_predict(X, y) // sklean으로 퍼셉트론 실습하기 from sklearn.linear_model import Perceptron # 샘플과 레이블이다. X = [[0,0],[0,1],[1,0],[1,1]] y = [0, 0, 0, 1] # 퍼셉트론을 생성한다. tol는 종료 조건이다. random_state는 난수의 시드이다. clf = Perceptron(tol=1e-3, random_state=0) # 학습을 수행한다. clf.fit(X, y) # 테스트를 수행한다. print(clf.predict(X)) //퍼셉트론 시각화 from sklearn.metrics import accuracy_score print(accuracy_score(clf.predict(X), y)) # 데이터를 그래프 위에 표시한다. plt.scatter(X[:, 0], X[:, 1], c=y, s=100) plt.xlabel("x1") plt.ylabel("x2") # 데이터에서 최소 좌표와 최대 좌표를 계산한다. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 # 0.1 간격으로 메쉬 그리드 좌표를 만든다. xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) # 메쉬 그리드 데이터에 대하여 예측을 한다. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) # 컨투어를 그린다. countour vs. countourf plt.contourf(xx, yy, Z, alpha=0.4) plt.show()
from Graph_Algorithms.ConnectedComponents import ConnectedComponents from Graph import Graph from Station_Node import Station_Node from itertools import combinations ''' Given a subway graph, this class will return all the transportation islands present in the network and all the stations contained in the given transportation island. It also returns information on how the transportation islands are connected to each other. ''' ID = int Station = Station_Node class TransportationIslands: def __init__(self, graph: Graph): self.graph = graph self.island_graph = graph self.marked = {} for node in self.graph: self.marked[node.get_node_id()] = False self.start = node.get_node_id() self.deletion_edges = [] self.transport_islands = Graph() self.transport_list = [] self.transport_list_zones = [] # identifies edges that are interzone # adds them to a list for deletion def identify_interzone_edges(self, node_id: ID): self.marked[node_id] = True for adjacent in self.graph.get_node(node_id).get_adjacents(): if self.graph.get_node(node_id).zone != adjacent.zone and \ [adjacent.get_node_id(), node_id] not in \ self.deletion_edges: self.deletion_edges.append([node_id, adjacent.get_node_id()]) if self.marked[adjacent.get_node_id()] is False: self.identify_interzone_edges(adjacent.get_node_id()) # deletes interzone edges in the graph and stores as a new graph # connected components are collected using dfs def get_transportation_islands(self): self.identify_interzone_edges(self.start) for edge in self.deletion_edges: self.island_graph.delete_edge(edge[0], edge[1]) connected_comp = ConnectedComponents() trans_islands = connected_comp.\ get_connected_components(self.island_graph) for island in trans_islands: self.transport_list.append(island) self.transport_list_zones.append( self.graph.get_node(island[0]).zone) for island in combinations(trans_islands, 2): for edge in self.deletion_edges: if edge[0] in island[0]: if edge[1] in island[1]: self.transport_islands.add_edge( self.transport_list.index(island[0]), self.transport_list.index(island[1])) values = [self.transport_list, self.transport_islands, self.transport_list_zones] return values # prints summary of transportation islands def print_trans_island_summary(self): print('Transportation Islands and Zones:') for island in self.transport_list: print('\nIsland: '+str(island) + ': --> Zone: ' + str(self.transport_list_zones [self.transport_list.index(island)])) print('Connected to: ') temp = self.transport_list.index(island) list_node = self.transport_islands.get_node(temp) if list_node is None: print("This transportation island is not " "connected to other islands.") else: for adj in list_node.get_adjacents(): print(self.transport_list[adj.get_node_id()])
from functools import lru_cache from fastapi import FastAPI, UploadFile from pydantic import BaseModel from pdf2image import convert_from_bytes import io from openai import OpenAI import base64 from . import config import json app = FastAPI() client = OpenAI() with open("prompts.json", "r") as f: prompts = {} for key, value in json.load(f).items(): new_key = tuple([k == "True" for k in key[1:-1].split(", ")]) prompts[new_key] = value @lru_cache def get_settings(): return config.Settings() @app.get("/") def root(): return {"message": "Hello World"} @app.post("/parse") async def parse(file: UploadFile): try: # convert the pages to images pdf_bytes = file.file.read() images = convert_from_bytes(pdf_bytes) product_name_found, troubleshooting_page, page_offset = False, None, None troubleshooting_page = None def get_curr_prompt(): key = (product_name_found or troubleshooting_page is not None, troubleshooting_page is not None, page_offset is not None) return prompts[key] info = {'troubleshooting': {}} for i, image in enumerate(images): if (troubleshooting_page is not None) and (page_offset is not None): page = i - page_offset if page < troubleshooting_page: continue else: sections = [x for x in info['toc'].keys() if x > troubleshooting_page] sections.sort() if page >= sections[0] and page > troubleshooting_page: break image_bytes = io.BytesIO() image.save(image_bytes, format='JPEG') base64_image = base64.b64encode(image_bytes.getvalue()).decode('utf-8') response = client.chat.completions.create( model="gpt-4-turbo", response_format={ "type": "json_object" }, messages=[ { "role": "system", "content": "You are a helpful assistant designed to output JSON." }, { "role": "user", "content": [ { "type": "text", "text": get_curr_prompt() }, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" }, }, ], } ], max_tokens=1000, ) try: json_response = json.loads(response.choices[0].message.content) except: json_response = {} if 'page' in json_response: page_offset = i - int(json_response['page']) json_response.pop('page', None) if 'product' in json_response: product_name_found = True info['product'] = json_response['product'] if 'model' in json_response: info['model'] = json_response['model'] elif 'TROUBLESHOOTING_PAGE' in json_response: troubleshooting_page = int(json_response['TROUBLESHOOTING_PAGE']) info['toc'] = {int(k): v for k, v in json_response.items() if k.isnumeric()} elif 'troubleshooting' in json_response and json_response['troubleshooting'] != {}: if page_offset is not None: page = i - page_offset else: page = -1 info['troubleshooting'][page] = json_response['troubleshooting'] return info['troubleshooting'] except Exception as e: print(e) return {"filename": file.filename}
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ package org.opensearch.search.fetch.subphase.highlight; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.Term; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.TermQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.tests.index.RandomIndexWriter; import org.opensearch.Version; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.document.DocumentField; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.IndexService; import org.opensearch.index.IndexSettings; import org.opensearch.index.mapper.ContentPath; import org.opensearch.index.mapper.DefaultDerivedFieldResolver; import org.opensearch.index.mapper.DerivedField; import org.opensearch.index.mapper.DerivedFieldResolverFactory; import org.opensearch.index.mapper.DerivedFieldSupportedTypes; import org.opensearch.index.mapper.DerivedFieldType; import org.opensearch.index.mapper.Mapper; import org.opensearch.index.mapper.MapperService; import org.opensearch.index.mapper.SourceToParse; import org.opensearch.index.query.QueryShardContext; import org.opensearch.index.query.Rewriteable; import org.opensearch.script.MockScriptEngine; import org.opensearch.script.Script; import org.opensearch.script.ScriptEngine; import org.opensearch.script.ScriptModule; import org.opensearch.script.ScriptService; import org.opensearch.script.ScriptType; import org.opensearch.search.SearchHit; import org.opensearch.search.fetch.FetchContext; import org.opensearch.search.fetch.FetchSubPhase; import org.opensearch.search.fetch.FetchSubPhaseProcessor; import org.opensearch.search.fetch.subphase.FieldAndFormat; import org.opensearch.search.fetch.subphase.FieldFetcher; import org.opensearch.search.internal.ContextIndexSearcher; import org.opensearch.test.OpenSearchSingleNodeTestCase; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DerivedFieldFetchAndHighlightTests extends OpenSearchSingleNodeTestCase { private static String DERIVED_FIELD_SCRIPT_1 = "derived_field_script_1"; private static String DERIVED_FIELD_SCRIPT_2 = "derived_field_script_2"; private static String DERIVED_FIELD_SCRIPT_3 = "derived_field_script_3"; private static String DERIVED_FIELD_SCRIPT_4 = "derived_field_script_4"; private static String DERIVED_FIELD_1 = "derived_1"; private static String DERIVED_FIELD_2 = "derived_2"; private static String DERIVED_FIELD_3 = "derived_3"; private static String DERIVED_FIELD_4 = "derived_4"; private static String NESTED_FIELD = "field"; public void testDerivedFieldFromIndexMapping() throws IOException { // Create index and mapper service // Define mapping for derived fields, create 2 derived fields derived_1 and derived_2 XContentBuilder mapping = XContentFactory.jsonBuilder() .startObject() .startObject("derived") .startObject(DERIVED_FIELD_1) .field("type", "keyword") .startObject("script") .field("source", DERIVED_FIELD_SCRIPT_1) .field("lang", "mockscript") .endObject() .endObject() .startObject(DERIVED_FIELD_2) .field("type", "keyword") .startObject("script") .field("source", DERIVED_FIELD_SCRIPT_2) .field("lang", "mockscript") .endObject() .endObject() .startObject(DERIVED_FIELD_3) .field("type", "date") .field("format", "yyyy-MM-dd") .startObject("script") .field("source", DERIVED_FIELD_SCRIPT_3) .field("lang", "mockscript") .endObject() .endObject() .startObject(DERIVED_FIELD_4) .field("type", "object") .startObject("script") .field("source", DERIVED_FIELD_SCRIPT_4) .field("lang", "mockscript") .endObject() .endObject() .endObject() .endObject(); // Create source document with 2 fields field1 and field2. // derived_1 will act on field1 and derived_2 will act on derived_2. DERIVED_FIELD_SCRIPT_1 substitutes whitespaces with _ XContentBuilder source = XContentFactory.jsonBuilder() .startObject() .field("field1", "some_text_1") .field("field2", "some_text_2") .field("field3", 1710923445000L) .field("field4", "{ \"field\": \"foo bar baz\"}") .endObject(); int docId = 0; IndexService indexService = createIndex("test_index", Settings.EMPTY, MapperService.SINGLE_MAPPING_NAME, mapping); MapperService mapperService = indexService.mapperService(); try ( Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), dir, new IndexWriterConfig(mapperService.indexAnalyzer())); ) { iw.addDocument( mapperService.documentMapper() .parse(new SourceToParse("test_index", "0", BytesReference.bytes(source), MediaTypeRegistry.JSON)) .rootDoc() ); try (IndexReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); LeafReaderContext context = searcher.getIndexReader().leaves().get(0); QueryShardContext mockShardContext = createQueryShardContext(mapperService, searcher); mockShardContext.lookup().source().setSegmentAndDocument(context, docId); // mockShardContext.setDerivedFieldTypes(Map.of("derived_2", createDerivedFieldType("derived_1", "keyword"), "derived_1", // Assert the fetch phase works for both of the derived fields Map<String, DocumentField> fields = fetchFields(mockShardContext, context, "*"); Map<String, DocumentField> nestedFields = fetchFields(mockShardContext, context, DERIVED_FIELD_4 + "." + NESTED_FIELD); // Validate FetchPhase { assertEquals(fields.size(), 4); assertEquals(1, fields.get(DERIVED_FIELD_1).getValues().size()); assertEquals(1, fields.get(DERIVED_FIELD_2).getValues().size()); assertEquals(1, fields.get(DERIVED_FIELD_3).getValues().size()); assertEquals(1, fields.get(DERIVED_FIELD_4).getValues().size()); assertEquals("some_text_1", fields.get(DERIVED_FIELD_1).getValue()); assertEquals("some_text_2", fields.get(DERIVED_FIELD_2).getValue()); assertEquals("2024-03-20", fields.get(DERIVED_FIELD_3).getValue()); assertEquals("{ \"field\": \"foo bar baz\"}", fields.get(DERIVED_FIELD_4).getValue()); assertEquals(1, nestedFields.get(DERIVED_FIELD_4 + "." + NESTED_FIELD).getValues().size()); assertEquals("foo bar baz", nestedFields.get(DERIVED_FIELD_4 + "." + NESTED_FIELD).getValue()); } // Create a HighlightBuilder of type unified, set its fields as derived_1 and derived_2 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.highlighterType("unified"); highlightBuilder.field(DERIVED_FIELD_1); highlightBuilder.field(DERIVED_FIELD_2); highlightBuilder.field(DERIVED_FIELD_4 + "." + NESTED_FIELD); highlightBuilder = Rewriteable.rewrite(highlightBuilder, mockShardContext); SearchHighlightContext searchHighlightContext = highlightBuilder.build(mockShardContext); // Create a HighlightPhase with highlighter defined above HighlightPhase highlightPhase = new HighlightPhase(Collections.singletonMap("unified", new UnifiedHighlighter())); // create a fetch context to be used by HighlightPhase processor FetchContext fetchContext = mock(FetchContext.class); when(fetchContext.mapperService()).thenReturn(mapperService); when(fetchContext.getQueryShardContext()).thenReturn(mockShardContext); when(fetchContext.getIndexSettings()).thenReturn(indexService.getIndexSettings()); when(fetchContext.searcher()).thenReturn( new ContextIndexSearcher( reader, IndexSearcher.getDefaultSimilarity(), IndexSearcher.getDefaultQueryCache(), IndexSearcher.getDefaultQueryCachingPolicy(), true, null, null ) ); { // The query used by FetchSubPhaseProcessor to highlight is a term query on DERIVED_FIELD_1 FetchSubPhaseProcessor subPhaseProcessor = highlightPhase.getProcessor( fetchContext, searchHighlightContext, new TermQuery(new Term(DERIVED_FIELD_1, "some_text_1")) ); // Create a search hit using the derived fields fetched above in fetch phase SearchHit searchHit = new SearchHit(docId, "0", null, fields, null); // Create a HitContext of search hit FetchSubPhase.HitContext hitContext = new FetchSubPhase.HitContext( searchHit, context, docId, mockShardContext.lookup().source() ); hitContext.sourceLookup().loadSourceIfNeeded(); // process the HitContext using the highlightPhase subPhaseProcessor subPhaseProcessor.process(hitContext); // Validate that 1 highlight field is present assertEquals(hitContext.hit().getHighlightFields().size(), 1); } { // The query used by FetchSubPhaseProcessor to highlight is a term query on DERIVED_FIELD_1 FetchSubPhaseProcessor subPhaseProcessor = highlightPhase.getProcessor( fetchContext, searchHighlightContext, new TermQuery(new Term(DERIVED_FIELD_4 + "." + NESTED_FIELD, "foo")) ); // Create a search hit using the derived fields fetched above in fetch phase SearchHit searchHit = new SearchHit(docId, "0", null, nestedFields, null); // Create a HitContext of search hit FetchSubPhase.HitContext hitContext = new FetchSubPhase.HitContext( searchHit, context, docId, mockShardContext.lookup().source() ); hitContext.sourceLookup().loadSourceIfNeeded(); // process the HitContext using the highlightPhase subPhaseProcessor subPhaseProcessor.process(hitContext); // Validate that 1 highlight field is present assertEquals(hitContext.hit().getHighlightFields().size(), 1); } } } } public void testDerivedFieldFromSearchMapping() throws IOException { // Create source document with 2 fields field1 and field2. // derived_1 will act on field1 and derived_2 will act on derived_2. DERIVED_FIELD_SCRIPT_1 substitutes whitespaces with _ XContentBuilder source = XContentFactory.jsonBuilder() .startObject() .field("field1", "some_text_1") .field("field2", "some_text_2") .field("field3", 1710923445000L) .field("field4", "{ \"field\": \"foo bar baz\"}") .endObject(); int docId = 0; // Create index and mapper service // We are not defining derived fields in index mapping here XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().endObject(); IndexService indexService = createIndex("test_index", Settings.EMPTY, MapperService.SINGLE_MAPPING_NAME, mapping); MapperService mapperService = indexService.mapperService(); try ( Directory dir = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), dir, new IndexWriterConfig(mapperService.indexAnalyzer())); ) { iw.addDocument( mapperService.documentMapper() .parse(new SourceToParse("test_index", "0", BytesReference.bytes(source), MediaTypeRegistry.JSON)) .rootDoc() ); try (IndexReader reader = iw.getReader()) { IndexSearcher searcher = newSearcher(reader); LeafReaderContext context = searcher.getIndexReader().leaves().get(0); QueryShardContext mockShardContext = createQueryShardContext(mapperService, searcher); mockShardContext.lookup().source().setSegmentAndDocument(context, docId); DerivedField derivedField3 = new DerivedField( DERIVED_FIELD_3, "date", new Script(ScriptType.INLINE, "mockscript", DERIVED_FIELD_SCRIPT_3, emptyMap()) ); derivedField3.setFormat("dd-MM-yyyy"); // This mock behavior is similar to adding derived fields in search request mockShardContext.setDerivedFieldResolver( (DefaultDerivedFieldResolver) DerivedFieldResolverFactory.createResolver( mockShardContext, null, List.of( new DerivedField( DERIVED_FIELD_1, "keyword", new Script(ScriptType.INLINE, "mockscript", DERIVED_FIELD_SCRIPT_1, emptyMap()) ), new DerivedField( DERIVED_FIELD_2, "keyword", new Script(ScriptType.INLINE, "mockscript", DERIVED_FIELD_SCRIPT_2, emptyMap()) ), derivedField3, new DerivedField( DERIVED_FIELD_4, "object", new Script(ScriptType.INLINE, "mockscript", DERIVED_FIELD_SCRIPT_4, emptyMap()) ) ), true ) ); // Assert the fetch phase works for both of the derived fields Map<String, DocumentField> fields = fetchFields(mockShardContext, context, "derived_*"); Map<String, DocumentField> nestedFields = fetchFields(mockShardContext, context, DERIVED_FIELD_4 + "." + NESTED_FIELD); // Validate FetchPhase { assertEquals(fields.size(), 4); assertEquals(1, fields.get(DERIVED_FIELD_1).getValues().size()); assertEquals(1, fields.get(DERIVED_FIELD_2).getValues().size()); assertEquals(1, fields.get(DERIVED_FIELD_3).getValues().size()); assertEquals(1, fields.get(DERIVED_FIELD_4).getValues().size()); assertEquals("some_text_1", fields.get(DERIVED_FIELD_1).getValue()); assertEquals("some_text_2", fields.get(DERIVED_FIELD_2).getValue()); assertEquals("20-03-2024", fields.get(DERIVED_FIELD_3).getValue()); assertEquals("{ \"field\": \"foo bar baz\"}", fields.get(DERIVED_FIELD_4).getValue()); assertEquals(1, nestedFields.get(DERIVED_FIELD_4 + "." + NESTED_FIELD).getValues().size()); assertEquals("foo bar baz", nestedFields.get(DERIVED_FIELD_4 + "." + NESTED_FIELD).getValue()); } // Create a HighlightBuilder of type unified, set its fields as derived_1 and derived_2 HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.highlighterType("unified"); highlightBuilder.field(DERIVED_FIELD_1); highlightBuilder.field(DERIVED_FIELD_2); highlightBuilder.field(DERIVED_FIELD_4 + "." + NESTED_FIELD); highlightBuilder = Rewriteable.rewrite(highlightBuilder, mockShardContext); SearchHighlightContext searchHighlightContext = highlightBuilder.build(mockShardContext); // Create a HighlightPhase with highlighter defined above HighlightPhase highlightPhase = new HighlightPhase(Collections.singletonMap("unified", new UnifiedHighlighter())); // create a fetch context to be used by HighlightPhase processor FetchContext fetchContext = mock(FetchContext.class); when(fetchContext.mapperService()).thenReturn(mapperService); when(fetchContext.getQueryShardContext()).thenReturn(mockShardContext); when(fetchContext.getIndexSettings()).thenReturn(indexService.getIndexSettings()); when(fetchContext.searcher()).thenReturn( new ContextIndexSearcher( reader, IndexSearcher.getDefaultSimilarity(), IndexSearcher.getDefaultQueryCache(), IndexSearcher.getDefaultQueryCachingPolicy(), true, null, null ) ); { // The query used by FetchSubPhaseProcessor to highlight is a term query on DERIVED_FIELD_1 FetchSubPhaseProcessor subPhaseProcessor = highlightPhase.getProcessor( fetchContext, searchHighlightContext, new TermQuery(new Term(DERIVED_FIELD_1, "some_text_1")) ); // Create a search hit using the derived fields fetched above in fetch phase SearchHit searchHit = new SearchHit(docId, "0", null, fields, null); // Create a HitContext of search hit FetchSubPhase.HitContext hitContext = new FetchSubPhase.HitContext( searchHit, context, docId, mockShardContext.lookup().source() ); hitContext.sourceLookup().loadSourceIfNeeded(); // process the HitContext using the highlightPhase subPhaseProcessor subPhaseProcessor.process(hitContext); // Validate that 1 highlight field is present assertEquals(hitContext.hit().getHighlightFields().size(), 1); } { // test highlighting nested field DERIVED_FIELD_4 + "." + NESTED_FIELD FetchSubPhaseProcessor subPhaseProcessor = highlightPhase.getProcessor( fetchContext, searchHighlightContext, new TermQuery(new Term(DERIVED_FIELD_4 + "." + NESTED_FIELD, "foo")) ); // Create a search hit using the derived fields fetched above in fetch phase SearchHit searchHit = new SearchHit(docId, "0", null, nestedFields, null); // Create a HitContext of search hit FetchSubPhase.HitContext hitContext = new FetchSubPhase.HitContext( searchHit, context, docId, mockShardContext.lookup().source() ); hitContext.sourceLookup().loadSourceIfNeeded(); // process the HitContext using the highlightPhase subPhaseProcessor subPhaseProcessor.process(hitContext); // Validate that 1 highlight field is present assertEquals(hitContext.hit().getHighlightFields().size(), 1); } } } } public static Map<String, DocumentField> fetchFields( QueryShardContext queryShardContext, LeafReaderContext context, String fieldPattern ) throws IOException { List<FieldAndFormat> fields = List.of(new FieldAndFormat(fieldPattern, null)); FieldFetcher fieldFetcher = FieldFetcher.create(queryShardContext, queryShardContext.lookup(), fields); fieldFetcher.setNextReader(context); return fieldFetcher.fetch(queryShardContext.lookup().source(), Set.of()); } private static QueryShardContext createQueryShardContext(MapperService mapperService, IndexSearcher indexSearcher) { Settings settings = Settings.builder() .put("index.version.created", Version.CURRENT) .put("index.number_of_shards", 1) .put("index.number_of_replicas", 0) .put(IndexMetadata.SETTING_INDEX_UUID, "uuid") .build(); IndexMetadata indexMetadata = new IndexMetadata.Builder("index").settings(settings).build(); IndexSettings indexSettings = new IndexSettings(indexMetadata, settings); ScriptService scriptService = getScriptService(); return new QueryShardContext( 0, indexSettings, null, null, null, mapperService, null, scriptService, null, null, null, indexSearcher, null, null, null, () -> true, null ); } private static ScriptService getScriptService() { final MockScriptEngine engine = new MockScriptEngine( MockScriptEngine.NAME, Map.of( DERIVED_FIELD_SCRIPT_1, (script) -> ((String) ((Map<String, Object>) script.get("_source")).get("field1")).replace(" ", "_"), DERIVED_FIELD_SCRIPT_2, (script) -> ((String) ((Map<String, Object>) script.get("_source")).get("field2")).replace(" ", "_"), DERIVED_FIELD_SCRIPT_3, (script) -> ((Map<String, Object>) script.get("_source")).get("field3"), DERIVED_FIELD_SCRIPT_4, (script) -> ((Map<String, Object>) script.get("_source")).get("field4") ), Collections.emptyMap() ); final Map<String, ScriptEngine> engines = singletonMap(engine.getType(), engine); ScriptService scriptService = new ScriptService(Settings.EMPTY, engines, ScriptModule.CORE_CONTEXTS); return scriptService; } private DerivedFieldType createDerivedFieldType(String name, String type, String script) { Mapper.BuilderContext context = mock(Mapper.BuilderContext.class); when(context.path()).thenReturn(new ContentPath()); return new DerivedFieldType( new DerivedField(name, type, new Script(ScriptType.INLINE, "mockscript", script, emptyMap())), DerivedFieldSupportedTypes.getFieldMapperFromType(type, name, context, null), DerivedFieldSupportedTypes.getIndexableFieldGeneratorType(type, name), null ); } }
--- layout: about title: Reinforcement Learning has_children: true nav_order: 6 has_toc: false --- {: .no_toc} ## Table of contents {: .no_toc .text-delta } 1. TOC {:toc} # Overview We will start with example and applications of this field and give a general framework for decision making models under uncertainty. Then we will discuss 4 different scenarios -- with different state dynamics and known or unknown models. Later, we will focus on 2 scenarios of these 4, the stochastic optimization, which assumes fixed state and known model, and multi-arm bandit, which assumes fixed state but unknown model. The other scenarios will be covered in coming lectures. # Sequential Decision-making Problems (Under Uncertainty) ## Decion-making versus Supervised Learning For easier understanding of our problem, we first make a comparison between decision making and supervised learning. In supervised learning, we work with a set of features and a target and learn a function mapping from the features to the target. The decision making problem actually builds upon that. In this setting, we not only want the prediction of the target to be correct, but want to learn about the environment as well, so that we can make decisions and interact with the environment. As shown in the diagram in Figure \ref{diagram}, we do learn a model about uncertainty and that helps us to decide what to do, upon that, we can make a decision, interact with the environment and observe new data, and continue the iteration again. Eventually, we will end up with a sequence of decisions. ## Sub-categories of Decision Making - The four big types of sequential decision-making problems - Bandits - MDP - RL - Stochastic optimization ![](/reinforcement/figs/scenarios.png) and their connections and differences. The "under uncertainty" modifier is really what makes these problems interesting and practical. ### Stochastic optimization (Known model, fixed state) Suppose we are a retail store manager and we need to decide what to put on the shelf for an entire winter season. Let's assume people's demands and preferences are approximately unchanged every year, so that the model is known if we look at the historic data. Also, people's demand is not affected by what we put on the shelf, so there's no impact of the actions on the state. What we want is to decide what to stock in the market and the reward is how much money we make. As a summary, - State: customer demand - Action: how much inventory to stock subject to various constraints - Transition Kernel: no transition - Reward: revenue This scenario is called stochastic optimization. ### Bandits (Unknown model, fixed state) Suppose we are designing an online e-portal where we need to decide what contents should be shown to a new customer on the website. Depending on the customer's preference and what we show to him, the customer may or may not continue to engage with our website and we want the customer to engage. We can assume all the customers are from some unknown population, which is the state of the decision making problem. The population will not be affected by the actions we take, thus there's no transition between states. The reward is positive if people continue to engage, and negative vice versa. As a summary, - State: customer population - Action: which of the N pages to show to the arriving customer - Transition Kernel: no transition - Reward: conversion if right page, loss of opportunity if wrong page This scenario is called multi-arm bandit. ### MDP (Known model, dynamical state) Let's suppose we are designing an automatic chess player, but only to beat a specific player. This player is well known by us and can predict what he will do in any situations, which corresponds to the known transition kernel in our decision making problem. The board position, which is the state, constantly changes, and the actions is to decide is to play a move of the chess given a state. The reward will be positive if we win and negative if we loss. As a summary, - State: board position - Action: which of the feasible moves to play - Transition Kernel: change in board position due to play of opponent, which is \textbf{known} - Reward: win ($+l$) or loss ($-l$) This scenario is called Markov Decision Process, or MDP. ### RL (Unknown model, dynamical state) Suppose we are doing the same thing as the previous chess playing scenario and the only different thing is that we are now playing with a completely unknown player. Everything is as before, except that we do not know the transition kernel, i.e., we don't know what the player is going to do given the board position, and thus we need to learn as we play. As a summary, - State: board position - Action: which of the feasible moves to play - Transition Kernel: change in board position due to play of opponent, which is \textbf{unknown} - Reward: win ($+l$) or loss ($-l$) This scenario is known as reinforcement learning. ## Different fields that study these problems: - Control theory (especially robust control) - Operations research - Finance - Social sciences Some comments on each field's unique challenges. On one hand, good that a single framework has so many applications; on the other hand though, inevitable notational mess. # MDP - $S$: a state space which contains all possible states of the system - $A$: an action space which contains all possible actions an agent can take - $P(s'\|s,a)$ a stochastic transition kernel which gives the probability of transition from state $s$ to $s'$ if action $a$ is taken. This transition can be deterministic as well. Implies by this notation is that $s$ is the current state; $s'$ is the next state, or the state we ended in. - $R: S \times A \to \mathbb{R}$: a reward function that takes in the state and the action and gives back a real value reward. - $\gamma \in [0,1]$: a discount factor that re-weight long term and short term rewards Sometimes also horizon. Math is cleaner in infinite-horizon case. Why? well, because when things have been run for a long long time, things would have "settled down" or "converged" and the past history -- at whatever timestamp you slice it -- no longer matter. In the literature, sometimes finite-horizon problems are also called episodic; whereas infinite-horizon ones are called continuing task. As an aside, this is a general pattern. Asymptotic regime allows you to "cancel" out a lot of things, take limits, etc. (But not very practical; this intrinsic tension motivates lots of research in engineering) A couple of more comments: - States versus observation. - Rewards are what we immediately see but not our final goal. We're in the game for the long run, so it's the sum of rewards that we go after. These are the so-called value functions, which we'll define more precisely and need to comment with more details. For now, remember this intuitive punchline: rewards are short-term thing, values are long-term thing. We want to do good in the long run. - Fundamental to the long-term versus short-term performance is the tension between exploitation and exploration. Exploitation does well in the short-run; exploration may help us do well in the long-run (even if potentially losing out somewhat in the short-term). - Sometimes in the literature, the rewards model would be a mapping of (s, s', a) to (r). In other words, the reward you get not only depends on your current state, and your current action, but also the state you ends in (based on the generally stochastic transition). One such example would be, when you buy a lottery at a particular store, the (monetary) return/reward you get depends on if you actually win. Note, however, that such reward model distinction really do not matter at all in the infinite-horizon case -- again, coz convergence cancels that out. Even in the finite-horizon case, all the math works the same by thinking of the future-dependent reward as future-independent, but the horizon got shortened by 1. - In the infinite-horizon set up, the discount factor has to be strictly less than 1, for making sure the infinite-length rewards sequence converge and we end up with a finite summation of infinite terms. # Reinforcement Learning Set Up ## Agent and environment No longer have access to the transition model, and sometimes no access to the rewards model either. So there're the loss of two key components here; losing either makes the problem hard. Different applications might have different levels of lost access. For instance, often times in rigid-body robotics, we have at least the law of physics as a guiding principal and from that we get vague ideas of the transition.
from flask import Flask from markupsafe import escape from flask import url_for from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello(): return 'Welcome to My Watchlist!' @app.route('/hello_html') @app.route('/html') def html(): return '<h1>Hello Totoro!</h1><img src="http://helloflask.com/totoro.gif">' # 用户输入的数据会包含恶意代码,所以不能直接作为响应返回 # MarkupSafe(Flask 的依赖之一)提供的 escape() 函数对 name 变量进行转义处理,比如把 < 转换成 &lt;。这样在返回响应时浏览器就不会把它们当做代码执行 @app.route('/user/<name>') def user_page(name): return f'User: {escape(name)}' @app.route('/test') def test_url_for(): # 下面是一些调用示例(请访问 http://localhost:5000/test 后在命令行窗口查看输出的 URL): print(url_for('hello')) # 生成 hello 视图函数对应的 URL,将会输出:/ # 注意下面两个调用是如何生成包含 URL 变量的 URL 的 print(url_for('user_page', name='greyli')) # 输出:/user/greyli print(url_for('user_page', name='peter')) # 输出:/user/peter print(url_for('test_url_for')) # 输出:/test # 下面这个调用传入了多余的关键字参数,它们会被作为查询字符串附加到 URL 后面。 print(url_for('test_url_for', num=2)) # 输出:/test?num=2 return 'Test page' name = 'Grey Li' movies = [ {'title': 'My Neighbor Totoro', 'year': '1988'}, {'title': 'Dead Poets Society', 'year': '1989'}, {'title': 'A Perfect World', 'year': '1993'}, {'title': 'Leon', 'year': '1994'}, {'title': 'Mahjong', 'year': '1996'}, {'title': 'Swallowtail Butterfly', 'year': '1996'}, {'title': 'King of Comedy', 'year': '1999'}, {'title': 'Devils on the Doorstep', 'year': '1999'}, {'title': 'WALL-E', 'year': '2008'}, {'title': 'The Pork of Music', 'year': '2012'}, ] @app.route('/template') def index(): return render_template('index.html', name=name, movies=movies)
open Types open Misc open Core let grid_size (p : problem) : int * int = let w, h = (p.stage_width, p.stage_height) in if Float.(w < 20.0) || Float.(h < 20.0) then (0, 0) else ((w -. 10.0) /. 10.0 |> int_of_float, (h -. 10.0) /. 10.0 |> int_of_float) let place_row (x_start : float) (x_no : int) (y : float) : position list = List.range 0 (x_no - 1) |> List.map ~f:(fun i -> { x = x_start +. (float_of_int i *. 10.0); y }) let place_col (x : float) (y_start : float) (y_no : int) : position list = List.range 0 (y_no - 1) |> List.map ~f:(fun i -> { x; y = y_start +. (float_of_int i *. 10.0) }) (* Place a grid of points *) let place_grid (x_start : float) (y_start : float) (x_no : int) (y_no : int) (max_placed : int) : position list = let _remaining_placed, placed = List.fold (List.range 0 (y_no - 1)) ~init:(max_placed, []) ~f:(fun (remaining_placed, placed) i -> if remaining_placed = 0 then (0, placed) else let row = place_row x_start x_no (y_start +. (float_of_int i *. 10.0)) in (remaining_placed - List.length row, placed @ row)) in placed type edge = North | South | East | West [@@deriving sexp] type edges = edge list [@@deriving sexp] let parse_edges_flag edges : edges = match edges with | None -> [] | Some "" -> [] | Some e -> String.split_on_chars e ~on:[ ',' ] |> List.map ~f:(fun edge_str -> match edge_str with | "north" -> North | "south" -> South | "east" -> East | "west" -> West | _ -> failwith "Invalid edge placement") let place_edge (p : problem) (already_placed : position list) (e : edge) : position list = let w, h = grid_size p in let max_musicians = (p.musicians |> List.length) - (already_placed |> List.length) in let new_pos = match e with | North -> printf "Placing north edge\n"; place_row (p.stage_bottom_left.x +. 10.0) (min w max_musicians) (p.stage_bottom_left.y +. p.stage_height -. 10.0) | South -> printf "Placing south edge\n"; place_row (p.stage_bottom_left.x +. 10.0) (min w max_musicians) (p.stage_bottom_left.y +. 10.0) | East -> printf "Placing east edge\n"; place_col (p.stage_bottom_left.x +. p.stage_width -. 10.0) (p.stage_bottom_left.y +. 10.0) (min h max_musicians) | West -> printf "Placing west edge\n"; place_col (p.stage_bottom_left.x +. 10.0) (p.stage_bottom_left.y +. 10.0) (min h max_musicians) in (* Remove elements already in already_placed *) let already_placed_set = already_placed |> Set.Poly.of_list in let new_pos = List.filter new_pos ~f:(fun p -> not (Set.mem already_placed_set p)) in printf "\t%d new positions\n" (List.length new_pos); new_pos let place_edges (p : problem) (edges : edges) : position list = List.fold edges ~init:[] ~f:(fun acc e -> acc @ place_edge p acc e) (* CURVY TIME! *) let epsilon = 0.00001 let curvy_angle = 0.25 *. Float.pi let curvy_offset = (10.0 *. Float.sin curvy_angle) +. epsilon let curvy_grid_size (p : problem) : int * int = let w, h = (p.stage_width, p.stage_height) in if Float.(w < 20.0 + curvy_offset) || Float.(h < 20.0 + curvy_offset) then (0, 0) else ( 1.0 +. ((w -. 20.0) /. curvy_offset) |> int_of_float, 1.0 +. ((h -. 20.0) /. curvy_offset) |> int_of_float ) let place_curvy_row (x_start : float) (x_no : int) (y : float) (align : edge) : position list = let y_offset = match align with | North -> curvy_offset *. -1. | South -> curvy_offset | _ -> failwith "Can only align North or South" in List.range ~stop:`inclusive 0 (x_no - 1) |> List.map ~f:(fun i -> { x = x_start +. (float_of_int i *. curvy_offset); y = y +. (float_of_int (i % 2) *. y_offset); }) let place_curvy_col (x : float) (y_start : float) (y_no : int) (align : edge) : position list = let x_offset = match align with | East -> curvy_offset *. -1. | West -> curvy_offset | _ -> failwith "Can only align East or West" in List.range ~stop:`inclusive 0 (y_no - 1) |> List.map ~f:(fun i -> { x = x +. (float_of_int (i % 2) *. x_offset); y = y_start +. (float_of_int i *. curvy_offset); }) let place_curvy_edge (p : problem) (already_placed : position list) (e : edge) : position list = let w, h = curvy_grid_size p in let max_musicians = (p.musicians |> List.length) - (already_placed |> List.length) in let new_pos = match e with | North -> printf "Placing north curvy edge\n"; place_curvy_row (p.stage_bottom_left.x +. 10.0) (min w max_musicians) (p.stage_bottom_left.y +. p.stage_height -. 10.0) North | South -> printf "Placing south curvy edge\n"; place_curvy_row (p.stage_bottom_left.x +. 10.0) (min w max_musicians) (p.stage_bottom_left.y +. 10.0) South | East -> printf "Placing east curvy edge\n"; place_curvy_col (p.stage_bottom_left.x +. p.stage_width -. 10.0) (p.stage_bottom_left.y +. 10.0) (min h max_musicians) East | West -> printf "Placing west curvy edge\n"; place_curvy_col (p.stage_bottom_left.x +. 10.0) (p.stage_bottom_left.y +. 10.0) (min h max_musicians) West in (* Remove elements already in already_placed *) Printf.printf "\t%d already placed, %d new positions\n" (List.length already_placed) (List.length new_pos); let new_pos = List.filter new_pos ~f:(fun pos -> Random_solver.is_valid_placement p already_placed pos) in Printf.printf "\t%d new positions\n" (List.length new_pos); new_pos let place_curvy_edges (p : problem) (edges : edges) : position list = List.fold edges ~init:[] ~f:(fun acc e -> acc @ place_curvy_edge p acc e)
import { Member } from "@/types/member"; import RoleBadge from "./RoleBadge"; import { useQuery } from '@tanstack/react-query'; import { supabase } from "@/integrations/supabase/client"; interface MembershipDetailsProps { memberProfile: Member; userRole: string | null; } type AppRole = 'admin' | 'collector' | 'member'; const MembershipDetails = ({ memberProfile, userRole }: MembershipDetailsProps) => { const { data: userRoles } = useQuery({ queryKey: ['userRoles', memberProfile.auth_user_id], queryFn: async () => { if (!memberProfile.auth_user_id) return []; const { data, error } = await supabase .from('user_roles') .select('role') .eq('user_id', memberProfile.auth_user_id); if (error) { console.error('Error fetching roles:', error); return []; } return data.map(r => r.role) as AppRole[]; }, enabled: !!memberProfile.auth_user_id }); const getHighestRole = (roles: AppRole[]): AppRole | null => { if (roles?.includes('admin')) return 'admin'; if (roles?.includes('collector')) return 'collector'; if (roles?.includes('member')) return 'member'; return null; }; const displayRole = userRoles?.length ? getHighestRole(userRoles) : userRole; return ( <div className="space-y-2"> <p className="text-dashboard-muted text-sm">Membership Details</p> <div className="space-y-2"> <div className="text-dashboard-text flex items-center gap-2"> Status:{' '} <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium ${ memberProfile?.status === 'active' ? 'bg-dashboard-accent3/20 text-dashboard-accent3' : 'bg-dashboard-muted/20 text-dashboard-muted' }`}> {memberProfile?.status || 'Pending'} </span> </div> {memberProfile?.collector && ( <div className="text-dashboard-text flex items-center gap-2"> <span className="text-dashboard-muted">Collector:</span> <span className="text-dashboard-accent1">{memberProfile.collector}</span> </div> )} <div className="text-dashboard-text flex items-center gap-2"> <span className="text-dashboard-accent2">Type:</span> <span className="flex items-center gap-2"> {memberProfile?.membership_type || 'Standard'} <RoleBadge role={displayRole} /> </span> </div> </div> </div> ); }; export default MembershipDetails;
export class QNumber { constructor(num) { if (Number.isInteger(num)) this.number = num; else throw new Error(`${num} to nie jest właściwy numer polecenia.`); } } export class QType { constructor(t) { const accepted = ["J", "W", "P", "L", "O"]; if (accepted.includes(t)) this.type = t; else throw new Error(`Niezdefiniowany typ pytania: ${t}. Akceptowane: ["J", "W", "P", "L", "O"]`); } } export class Link { constructor(text) { this.text = text; } } export class Answer { constructor(id, text) { const accepted = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; if (id.length != 1 || !accepted.includes(id)) throw new Error(`Złe id odpowiedzi: ${id}`); else this.id = id; this.text = text; } } export class Good { constructor(id) { const accepted = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; if (id.length != 1 || !accepted.includes(id)) throw new Error(`Złe id odpowiedzi: ${id}`); else this.id = id; } } export class Question { constructor(number, text, type, links, answers, good) { this.number = number; this.text = text; this.type = type; this.links = links; this.answers = answers; this.good = good; this.answersIds = []; this.#validateAnswers(); this.#createHTMLElements(); } getAnswers() { const t = this.type.type; const answered = []; if (t === "J" || t === 'W' || t === "P") { this.answersIds.forEach(a => { const elem = document.getElementById(a); const checked = elem.checked; if (checked) { const label = document.getElementById(`${a}-label`); const text = label.innerText; answered.push(text); } }); } else if (t === "L" ){ this.answersIds.forEach(a => { const elem = document.getElementById(a); const text = elem.value; answered.push(text); }); } else { const elem = document.getElementById(`ans-${this.number.number}-a`); const value = elem.value; answered.push(value); } return answered; } showSolution() { this.correctContainer.style.display = 'block'; } #validateAnswers() { const all = []; const good = []; this.answers.forEach(e => { all.push(e.id); }); this.good.forEach(e => { good.push(e.id); }); good.forEach(g => { if (!all.includes(g)) { throw new Error("Dobre odpowiedzi zawierają nieistniejące."); } }); } #createHTMLElements() { this.mainContainer = document.createElement('div'); this.mainContainer.id = `question-${this.number.number}`; this.numberContainer = document.createElement('div'); this.numberContainer.className = 'question-number'; this.numberContainer.innerText = this.number.number; this.textContainer = document.createElement('div'); this.textContainer.className = 'question-text'; if (this.type.type === 'L') { let goodIndex = 0; let htmlText = ""; for (let i = 0; i < this.text.length; i++) { let check = this.text[i]; if (check === '_') { let id = `ans-${this.number.number}-${this.answers[goodIndex].id}`; goodIndex++; this.answersIds.push(id); const span = document.createElement('span'); span.innerText = htmlText; this.textContainer.appendChild(span); htmlText = ""; const elem = document.createElement('input'); elem.type = 'text'; elem.placeholder = 'uzupełnij...'; elem.id = id; elem.className = 'text-input'; this.textContainer.appendChild(elem); } else { htmlText += check; } } const span = document.createElement('span'); span.innerText = htmlText; this.textContainer.appendChild(span); } else if (this.type.type === "O") { const span = document.createElement('span'); span.innerText = this.text; const input = document.createElement('input'); input.type = 'text'; input.placeholder = 'odpowiedź...'; input.id = `ans-${this.number.number}-a`; input.className = 'long-text-input'; this.textContainer.appendChild(span); this.textContainer.appendChild(document.createElement('br')); this.textContainer.appendChild(input); } else { this.textContainer.innerHTML = this.text; } this.linksContainer = document.createElement('div'); this.links.forEach(l => { if (l.text !== '') { let element = document.createElement('img'); element.src = l.text; element.className = "link-image"; element.alt = 'obrazek'; this.linksContainer.appendChild(element); } }); this.answersContainer = document.createElement('div'); this.answersContainer.id = `question-${this.number.number}-ans`; if (this.type.type === "J" || this.type.type === "P" || this.type.type === "W") { this.answers.forEach(a => { let id = `ans-${this.number.number}-${a.id}`; this.answersIds.push(id); let label = document.createElement('label'); label.for = id; label.innerText = a.text; label.id = `${id}-label`; if (this.type.type === "J" || this.type.type === "P") { let radio = document.createElement('input'); radio.type = 'radio'; radio.name = `ans-${this.number.number}`; radio.id = id; this.answersContainer.appendChild(radio); } else if (this.type.type === "W") { let checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.id = id; this.answersContainer.appendChild(checkbox); } this.answersContainer.appendChild(label); this.answersContainer.appendChild(document.createElement('br')); }); } this.correctContainer = document.createElement('div'); this.correctContainer.style.display = 'none'; if (this.good.length === 0) this.correctContainer.innerText = "Poprawne: brak"; else if (this.good.length === 1) this.correctContainer.innerText = "Poprawna: "; else this.correctContainer.innerText = "Poprawne: "; if (this.type.type === "J" || this.type.type === "W" || this.type.type === "P") { this.answers.forEach(a => { const id = a.id; const goodIds = []; this.good.forEach(g => { goodIds.push(g.id); }); if (goodIds.includes(id)) this.correctContainer.innerText += `${a.id}, `; }); this.correctContainer.innerText = this.correctContainer.innerText .trim() .slice(0, -1); } else if (this.type.type === "L") { if (this.answers.length === 1) this.correctContainer.innerText = "Poprawna: "; else this.correctContainer.innerText = "Poprawne: "; this.answers.forEach(a => { this.correctContainer.innerText += `${a.text}, `; }); this.correctContainer.innerText = this.correctContainer.innerText .trim() .slice(0, -1); } else if (this.type.type === "O") { this.correctContainer.innerText += this.answers[0].text; } this.numberTextContainer = document.createElement('div'); this.numberTextContainer.appendChild(this.numberContainer); this.numberTextContainer.appendChild(this.textContainer); this.mainContainer.appendChild(this.numberTextContainer); this.mainContainer.appendChild(this.linksContainer); this.mainContainer.appendChild(this.answersContainer); this.mainContainer.appendChild(this.correctContainer); this.mainContainer.appendChild(document.createElement('hr')); } } export class Test { constructor(lines) { this.questions = []; this.allGood = []; this.submitButton = document.createElement('input'); this.submitButton.type = 'button'; this.submitButton.value = 'Sprawdź'; this.submitButton.onclick = (() => this.check()); this.reloadButton = document.createElement('input'); this.reloadButton.type = 'button'; this.reloadButton.value = 'Wyjdź'; this.reloadButton.onclick = (() => location.reload()); this.resultBox = document.createElement('div'); this.#parseLines(lines); } check() { const maxPoints = this.questions.length; let curPoints = 0; this.questions.forEach(q => { const ans = q.getAnswers(); // Działa const goodValues = []; // Nie działa q.answers.forEach(a => { const goodIds = []; q.good.forEach(g => { goodIds.push(g.id); }) if (goodIds.includes(a.id)) { goodValues.push(a.text); } }); let hasGood = false; let goodCount = 0; for (let i = 0; i < ans.length; i++) { const current = ans[i]; if (goodValues.includes(current)) { goodCount++; if (goodCount === goodValues.length || (['P', 'J'].includes(q.type.type) && goodCount === 1)) { hasGood = true; break; } } } if (hasGood) { curPoints++; q.textContainer.classList.add("correct"); q.textContainer.classList.remove("incorrect"); } else { q.textContainer.classList.add("incorrect"); q.textContainer.classList.remove("correct"); } }); this.resultBox.innerText = `Wynik: ${curPoints}/${maxPoints} (${curPoints / maxPoints * 100}%)` this.#showSolution(); } #showSolution() { this.questions.forEach(q => { q.showSolution(); }); } #parseLines(lines) { const firstLine = lines[0].trim(); let answers = []; let good = []; let links = []; let text = ""; let num = Number(firstLine.split('.')[0]); let type = firstLine.split('[')[1][0]; const questions = []; //TEGO NIE MODYFIKOWAĆ lines.forEach(l => { const line = l.trim(); if (isNewQuestion(line)) { // Tu sprawdzamy, czy jest nowe pytanie - jak tak, to dodajemy poprzednie do listy. if (line !== firstLine) { if (answers.length === 0 || (good.length === 0 && type !== 'L')) { throw new Error('Niewłaściwy format pliku.'); } questions.push(new Question( new QNumber(num), text, new QType(type), links, answers, good )); // Reset pól num = Number(line.split('.')[0]); // Parsowanie numeru type = line.split('[')[1][0]; // Parsowanie typu pytania answers = []; good = []; links = []; text = ""; } } else if (isNewLink(line)) { const trimmed = line.substring(1, line.length - 1); const linksSplitted = trimmed.split(' '); linksSplitted.forEach(link => { links.push(new Link(link)); }); } else if (isNewAnswer(line)) { const id = line .substring(1) // bez '(' .split(')')[0]; const text = line .split(')')[1] .trim(); const ans = new Answer(id, text); answers.push(ans); } else if (isNewGood(line)) { const trimmed = line.substring(1, line.length - 1); const ids = trimmed.split(' '); ids.forEach(id => { const g = new Good(id); good.push(g); }); } else if (isNewText(line)) { text += `${line} `; } }); if (answers.length === 0 || (good.length === 0 && type !== 'L')) { throw new Error('Niewłaściwy format pliku.'); } questions.push(new Question( new QNumber(num), text, new QType(type), links, answers, good )); if (questions.length === 0) throw new Error('Pusty lub niewłaściwy plik'); this.questions = questions; } } function isNewQuestion(line) { const accepted = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; for (let i = 0; i < accepted.length; i++) { var toCheck = accepted[i]; if (line[0] === toCheck) return true; } return false; } function isNewAnswer(line) { return (line[0] === '('); } function isNewGood(line) { return (line[0] === '{'); } function isNewLink(line) { return (line[0] === '<'); } function isNewText(line) { return (line.length > 0); }
from langchain.prompts.chat import ( ChatPromptTemplate, HumanMessagePromptTemplate, SystemMessagePromptTemplate) def create_test_generation_prompt(selected_testing_library, code_snippet): """ Create a chat prompt for a software tester generating test functions and test cases. Parameters: - selected_testing_library (str): The testing library to be used for generating tests. - code_snippet (str): The code snippet or functions for which test functions and cases are to be generated. Returns: langchain.chat_models.ChatPromptTemplate: The generated chat prompt template. """ # Define system and human message templates for the AI conversation system_template = f"""You are a software tester using {selected_testing_library}. Your task is to generate test functions and test cases for the given code snippet or functions.""" system_message_prompt = SystemMessagePromptTemplate.from_template(system_template) human_template = f"""Please generate test functions and test cases for the following code snippet using {selected_testing_library} {code_snippet}""" human_message_prompt = HumanMessagePromptTemplate.from_template(human_template) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) return chat_prompt
import { View, Text, ScrollView, TouchableOpacity, TextInput, Image, ActivityIndicator, Modal, Animated as RNAnimated } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useLocalSearchParams, router } from 'expo-router'; import { useState, useEffect, useRef } from 'react'; import { Ionicons } from '@expo/vector-icons'; import { accountService, type Account } from '@/services/account'; import { format } from 'date-fns'; import { vi } from 'date-fns/locale'; import Animated, { FadeIn, withRepeat, withSequence, withTiming, useAnimatedStyle } from 'react-native-reanimated'; import Toast from 'react-native-toast-message'; import { validateFullname, validatePhone, validateBirthDate } from '@/utils/validation'; import DateTimePicker from '@react-native-community/datetimepicker'; import { Platform, KeyboardAvoidingView, Keyboard } from 'react-native'; import * as ImagePicker from 'expo-image-picker'; import { useAuth } from '@/contexts/AuthContext'; // Thêm type cho trạng thái kết quả type ResultStatus = 'loading' | 'success' | 'error' | null; // Cập nhật component LoadingPopup const LoadingPopup = ({ visible, status = 'loading', errorMessage = '', successMessage = '' }: { visible: boolean; status?: ResultStatus; errorMessage?: string; successMessage?: string; }) => ( <Modal transparent visible={visible}> <View className="flex-1 bg-black/50 items-center justify-center"> <View className="bg-neutral-900 rounded-2xl p-6 items-center mx-4 w-[60%] max-w-[300px]"> {status === 'loading' && ( <> <ActivityIndicator size="large" color="#EAB308" className="mb-4" /> <Text className="text-white text-center font-medium"> Đang cập nhật thông tin... </Text> <Text className="text-white/60 text-center text-sm mt-2"> Vui lòng không tắt ứng dụng </Text> </> )} {status === 'success' && ( <> <View className="mb-4 bg-green-500/20 p-3 rounded-full"> <Ionicons name="checkmark-circle" size={32} color="#22C55E" /> </View> <Text className="text-white text-center font-medium"> Cập nhật thành công! </Text> <Text className="text-white/60 text-center text-sm mt-2"> {successMessage || 'Thông tin của bạn đã được cập nhật'} </Text> </> )} {status === 'error' && ( <> <View className="mb-4 bg-red-500/20 p-3 rounded-full"> <Ionicons name="close-circle" size={32} color="#EF4444" /> </View> <Text className="text-white text-center font-medium"> Cập nhật thất bại </Text> <Text className="text-white/60 text-center text-sm mt-2"> {errorMessage || 'Vui lòng thử lại sau'} </Text> </> )} </View> </View> </Modal> ); // Thêm component AvatarLoadingPopup const AvatarLoadingPopup = ({ visible, status = 'loading', errorMessage = '', successMessage = '' }: { visible: boolean; status?: ResultStatus; errorMessage?: string; successMessage?: string; }) => ( <Modal transparent visible={visible}> <View className="flex-1 bg-black/50 items-center justify-center"> <View className="bg-neutral-900 rounded-2xl p-6 items-center mx-4 w-[60%] max-w-[300px]"> {status === 'loading' && ( <> <ActivityIndicator size="large" color="#EAB308" className="mb-4" /> <Text className="text-white text-center font-medium"> Đang cập nhật ảnh đại diện... </Text> <Text className="text-white/60 text-center text-sm mt-2"> Vui lòng không tắt ứng dụng </Text> </> )} {status === 'success' && ( <> <View className="mb-4 bg-green-500/20 p-3 rounded-full"> <Ionicons name="checkmark-circle" size={32} color="#22C55E" /> </View> <Text className="text-white text-center font-medium"> Cập nhật ảnh thành công! </Text> <Text className="text-white/60 text-center text-sm mt-2"> {successMessage || 'Ảnh đại diện của bạn đã được cập nhật'} </Text> </> )} {status === 'error' && ( <> <View className="mb-4 bg-red-500/20 p-3 rounded-full"> <Ionicons name="close-circle" size={32} color="#EF4444" /> </View> <Text className="text-white text-center font-medium"> Cập nhật ảnh thất bại </Text> <Text className="text-white/60 text-center text-sm mt-2"> {errorMessage || 'Vui lòng thử lại sau'} </Text> </> )} </View> </View> </Modal> ); // Thêm component Skeleton const Skeleton = ({ className }: { className: string }) => { const animatedStyle = useAnimatedStyle(() => { return { opacity: withRepeat( withSequence( withTiming(0.5, { duration: 1000 }), withTiming(1, { duration: 1000 }) ), -1, true ) }; }); return ( <Animated.View style={animatedStyle} className={`bg-neutral-800 ${className}`} /> ); }; // Thêm hook để theo dõi trạng thái keyboard const useKeyboardStatus = () => { const [isKeyboardVisible, setKeyboardVisible] = useState(false); useEffect(() => { const keyboardDidShowListener = Keyboard.addListener( 'keyboardDidShow', () => { setKeyboardVisible(true); } ); const keyboardDidHideListener = Keyboard.addListener( 'keyboardDidHide', () => { setKeyboardVisible(false); } ); return () => { keyboardDidHideListener.remove(); keyboardDidShowListener.remove(); }; }, []); return isKeyboardVisible; }; export default function ProfileDetailScreen() { const { id } = useLocalSearchParams(); const [account, setAccount] = useState<Account | null>(null); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [isEditing, setIsEditing] = useState(false); const [editedData, setEditedData] = useState({ fullname: '', phone: '' }); const [errors, setErrors] = useState({ fullname: '', phone: '', dob: '' }); const [showDatePicker, setShowDatePicker] = useState(false); const [selectedDate, setSelectedDate] = useState<Date | null>(null); const [uploadingAvatar, setUploadingAvatar] = useState(false); const [imageError, setImageError] = useState(false); const { updateUserData } = useAuth(); const [showLoadingPopup, setShowLoadingPopup] = useState(false); const [loadingMessage, setLoadingMessage] = useState(''); const [popupStatus, setPopupStatus] = useState<ResultStatus>(null); const [imageLoading, setImageLoading] = useState(true); const [showDatePickerModal, setShowDatePickerModal] = useState(false); const [tempDate, setTempDate] = useState<Date | null>(null); const isKeyboardVisible = useKeyboardStatus(); const [showAvatarLoadingPopup, setShowAvatarLoadingPopup] = useState(false); const [avatarLoadingStatus, setAvatarLoadingStatus] = useState<ResultStatus>('loading'); const [avatarErrorMessage, setAvatarErrorMessage] = useState(''); const [successMessage, setSuccessMessage] = useState(''); const [avatarSuccessMessage, setAvatarSuccessMessage] = useState(''); useEffect(() => { fetchAccountDetail(); }, [id]); useEffect(() => { if (account?.dob) { setSelectedDate(new Date(account.dob)); } }, [account]); const fetchAccountDetail = async () => { try { const data = await accountService.getAccountInfo(id as string); setAccount(data); setEditedData({ fullname: data.fullname, phone: data.phone }); } catch (error) { Toast.show({ type: 'error', text1: 'Lỗi', text2: 'Không thể tải thông tin tài khoản', position: 'bottom' }); } finally { setLoading(false); } }; const validateForm = (): boolean => { const newErrors = { fullname: '', phone: '', dob: '' }; // Validate fullname const fullnameError = validateFullname(editedData.fullname); if (fullnameError) newErrors.fullname = fullnameError; // Validate phone const phoneError = validatePhone(editedData.phone); if (phoneError) newErrors.phone = phoneError; // Validate dob if (selectedDate) { const dateStr = format(selectedDate, 'dd/MM/yyyy'); const dobError = validateBirthDate(dateStr); if (dobError) newErrors.dob = dobError; } setErrors(newErrors); // Return true nếu không có lỗi return !Object.values(newErrors).some(error => error !== ''); }; const handleSave = async () => { if (!validateForm()) return; try { setLoadingMessage('Đang cập nhật thông tin...'); setPopupStatus('loading'); setShowLoadingPopup(true); const updateData = { fullname: editedData.fullname, phone: editedData.phone, dob: selectedDate ? format(selectedDate, "yyyy-MM-dd'T'HH:mm:ss.SSSxxx") : undefined }; const response = await accountService.updateAccountInfo(id as string, updateData); setAccount(response.data); await updateUserData({ fullname: response.data.fullname, phone: response.data.phone }); setIsEditing(false); setPopupStatus('success'); setSuccessMessage(response.message || 'Cập nhật thành công!'); // Tự động đóng sau 1 giây nếu thành công setTimeout(() => { setShowLoadingPopup(false); setPopupStatus(null); }, 1000); } catch (error) { let errorMessage = 'Không thể cập nhật thông tin'; if (error instanceof Error) { errorMessage = error.message; } setLoadingMessage(errorMessage); setPopupStatus('error'); // Tự động đóng sau 1.5 giây nếu lỗi setTimeout(() => { setShowLoadingPopup(false); setPopupStatus(null); }, 1500); } }; const handleDateChange = (event: any, date?: Date) => { if (Platform.OS === 'android') { setShowDatePicker(false); } if (date) { setSelectedDate(date); setEditedData(prev => ({ ...prev, dob: date.toISOString() })); setErrors(prev => ({ ...prev, dob: '' })); } }; const handleTempDateChange = (event: any, date?: Date) => { if (date) { setTempDate(date); } }; const handleConfirmDate = () => { if (tempDate) { setSelectedDate(tempDate); setErrors(prev => ({ ...prev, dob: '' })); } setShowDatePickerModal(false); }; const handleChangeAvatar = async () => { try { const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (status !== 'granted') { Toast.show({ type: 'error', text1: 'Cần cấp quyền', text2: 'Vui lòng cấp quyền truy cập thư viện ảnh để thay đổi ảnh đại diện', position: 'bottom' }); return; } const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [1, 1], quality: 0.8, base64: false, exif: false, allowsMultipleSelection: false }); if (!result.canceled && result.assets[0]) { setAvatarLoadingStatus('loading'); setShowAvatarLoadingPopup(true); try { const response = await accountService.uploadAvatar( id as string, result.assets[0].uri ); setAccount(prev => prev ? { ...prev, image: response.url } : null); await updateUserData({ image: response.url }); setAvatarLoadingStatus('success'); setAvatarSuccessMessage(response.message || 'Cập nhật ảnh thành công!'); // Tự động đóng sau 1.5s nếu thành công setTimeout(() => { setShowAvatarLoadingPopup(false); setAvatarLoadingStatus('loading'); }, 1500); } catch (error: any) { setAvatarLoadingStatus('error'); setAvatarErrorMessage(error.message || 'Không thể cập nhật ảnh đại diện'); // Tự động đóng sau 1.5s nếu lỗi setTimeout(() => { setShowAvatarLoadingPopup(false); setAvatarLoadingStatus('loading'); setAvatarErrorMessage(''); }, 1500); } } } catch (error) { setAvatarLoadingStatus('error'); setAvatarErrorMessage('Không thể mở thư viện ảnh'); } }; // Thêm hàm xử lý hủy const handleCancel = () => { // Reset lại các giá trị đã chỉnh sửa về ban đầu if (account) { setEditedData({ fullname: account.fullname, phone: account.phone }); setSelectedDate(account.dob ? new Date(account.dob) : null); } setErrors({ fullname: '', phone: '', dob: '' }); setIsEditing(false); }; // Thêm hàm đóng popup const handleClosePopup = () => { setShowLoadingPopup(false); setPopupStatus(null); }; if (loading) { return ( <View className="flex-1 bg-black"> <SafeAreaView className="flex-1"> {/* Header Skeleton - Bỏ border */} <View className="flex-row items-center justify-between px-6 py-4"> <View className="flex-row items-center"> <Skeleton className="w-6 h-6 rounded-full mr-4" /> <Skeleton className="w-40 h-6 rounded-lg" /> </View> <Skeleton className="w-20 h-6 rounded-lg" /> </View> <ScrollView className="flex-1 p-6"> {/* Avatar Skeleton */} <View className="items-center mb-8"> <Skeleton className="w-32 h-32 rounded-full" /> <Skeleton className="w-32 h-8 rounded-full mt-4" /> </View> <View className="space-y-6"> {/* Email Skeleton */} <View> <Skeleton className="w-12 h-4 rounded mb-2" /> <Skeleton className="w-full h-14 rounded-xl" /> </View> {/* Fullname Skeleton */} <View> <Skeleton className="w-16 h-4 rounded mb-2" /> <Skeleton className="w-full h-14 rounded-xl" /> </View> {/* Phone Skeleton */} <View> <Skeleton className="w-24 h-4 rounded mb-2" /> <Skeleton className="w-full h-14 rounded-xl" /> </View> {/* Birthday Skeleton */} <View> <Skeleton className="w-20 h-4 rounded mb-2" /> <Skeleton className="w-full h-14 rounded-xl" /> </View> </View> </ScrollView> </SafeAreaView> </View> ); } return ( <View className="flex-1 bg-black"> <SafeAreaView className="flex-1 mb-4" edges={['top']}> {/* Header */} <Animated.View entering={FadeIn.duration(300)} className="px-4 pt-1 mb-4" > <View className="flex-row items-center justify-between"> <View className="flex-row items-center space-x-3"> <TouchableOpacity onPress={() => router.back()} className="w-9 h-9 items-center justify-center" > <Ionicons name="arrow-back" size={24} color="white" /> </TouchableOpacity> <Text className="text-white text-xl font-bold"> Thông tin cá nhân </Text> </View> {!isEditing && ( <TouchableOpacity onPress={() => setIsEditing(true)} className="bg-yellow-500/10 px-4 py-2 rounded-full" > <Text className="text-yellow-500 font-medium"> Chỉnh sửa </Text> </TouchableOpacity> )} </View> </Animated.View> <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} className="flex-1" keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0} > <ScrollView className="flex-1 px-6" keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 20 }} > {/* Avatar Section */} <Animated.View entering={FadeIn} className="items-center mb-8"> <View className="relative w-32 h-32"> <Image source={ account?.image ? { uri: account.image } : require('@/assets/images/default-avatar.png') } className="w-32 h-32 rounded-full bg-neutral-800" onLoadStart={() => { setImageLoading(true); setImageError(false); }} onLoadEnd={() => setImageLoading(false)} onError={() => { setImageError(true); setImageLoading(false); }} defaultSource={require('@/assets/images/default-avatar.png')} /> {(imageLoading || uploadingAvatar) && ( <View className="absolute inset-0 bg-black/50 rounded-full items-center justify-center"> <ActivityIndicator color="#EAB308" /> </View> )} </View> <TouchableOpacity className={`bg-yellow-500/10 px-4 py-2 rounded-full mt-4 ${ isEditing || uploadingAvatar ? 'opacity-50' : '' }`} onPress={handleChangeAvatar} disabled={uploadingAvatar || isEditing} > <Text className={`text-yellow-500 font-medium ${ isEditing || uploadingAvatar ? 'opacity-50' : '' }`}> Đổi ảnh đại diện </Text> </TouchableOpacity> </Animated.View> {/* Form Fields */} <View className="space-y-6"> {/* Email */} <View> <Text className="text-white/60 mb-2">Email</Text> <View className="bg-neutral-900 p-4 rounded-xl"> <Text className="text-white">{account?.email}</Text> </View> </View> {/* Họ tên */} <View> <Text className="text-white/60 mb-2">Họ tên</Text> {isEditing ? ( <View> <TextInput value={editedData.fullname} onChangeText={(text) => { setEditedData(prev => ({ ...prev, fullname: text })); setErrors(prev => ({ ...prev, fullname: '' })); }} className={`bg-neutral-900 p-4 rounded-xl text-white ${ errors.fullname ? 'border border-red-500' : '' }`} placeholderTextColor="#9CA3AF" /> {errors.fullname ? ( <Text className="text-red-500 text-sm mt-1">{errors.fullname}</Text> ) : null} </View> ) : ( <View className="bg-neutral-900 p-4 rounded-xl"> <Text className="text-white">{account?.fullname}</Text> </View> )} </View> {/* Số điện thoại */} <View> <Text className="text-white/60 mb-2">Số điện thoại</Text> {isEditing ? ( <View> <TextInput value={editedData.phone} onChangeText={(text) => { setEditedData(prev => ({ ...prev, phone: text })); setErrors(prev => ({ ...prev, phone: '' })); }} className={`bg-neutral-900 p-4 rounded-xl text-white ${ errors.phone ? 'border border-red-500' : '' }`} keyboardType="phone-pad" placeholderTextColor="#9CA3AF" /> {errors.phone ? ( <Text className="text-red-500 text-sm mt-1">{errors.phone}</Text> ) : null} </View> ) : ( <View className="bg-neutral-900 p-4 rounded-xl"> <Text className="text-white">{account?.phone}</Text> </View> )} </View> {/* Ngày sinh */} <View> <Text className="text-white/60 mb-2">Ngày sinh</Text> {isEditing ? ( <View> <TouchableOpacity onPress={() => { if (Platform.OS === 'ios') { setTempDate(selectedDate || new Date()); setShowDatePickerModal(true); } else { setShowDatePicker(true); } }} className={`bg-neutral-900 p-4 rounded-xl flex-row items-center ${ errors.dob ? 'border border-red-500' : '' }`} > <Ionicons name="calendar-outline" size={20} color="#9CA3AF" style={{ marginRight: 12 }} /> <Text className="text-white flex-1"> {selectedDate ? format(selectedDate, 'dd/MM/yyyy', { locale: vi }) : 'Chọn ngày sinh'} </Text> <Ionicons name="chevron-down-outline" size={20} color="#9CA3AF" /> </TouchableOpacity> {errors.dob ? ( <Text className="text-red-500 text-sm mt-1">{errors.dob}</Text> ) : null} {Platform.OS === 'ios' ? ( <Modal visible={showDatePickerModal} transparent animationType="slide" > <View className="flex-1 justify-end bg-black/50"> <View className="bg-neutral-900 rounded-t-xl"> <View className="flex-row justify-between items-center p-4 border-b border-white/10"> <TouchableOpacity onPress={() => setShowDatePickerModal(false)} > <Text className="text-white font-medium">Huỷ</Text> </TouchableOpacity> <TouchableOpacity onPress={handleConfirmDate} > <Text className="text-yellow-500 font-medium">Xong</Text> </TouchableOpacity> </View> <DateTimePicker value={tempDate || selectedDate || new Date()} mode="date" display="spinner" onChange={handleTempDateChange} maximumDate={new Date()} minimumDate={new Date(1900, 0, 1)} textColor="white" themeVariant="dark" locale="vi-VN" /> </View> </View> </Modal> ) : ( showDatePicker && ( <DateTimePicker value={selectedDate || new Date()} mode="date" display="default" onChange={handleDateChange} maximumDate={new Date()} minimumDate={new Date(1900, 0, 1)} /> ) )} </View> ) : ( <View className="bg-neutral-900 p-4 rounded-xl flex-row items-center"> <Ionicons name="calendar-outline" size={20} color="#9CA3AF" style={{ marginRight: 12 }} /> <Text className="text-white"> {account?.dob ? format(new Date(account.dob), 'dd/MM/yyyy', { locale: vi }) : 'Chưa có ngày sinh'} </Text> </View> )} </View> </View> </ScrollView> </KeyboardAvoidingView> {/* Footer buttons */} {isEditing && !isKeyboardVisible && ( <Animated.View entering={FadeIn} className="px-6 py-3 border-t border-white/10 bg-black" > <View className="flex-row space-x-3"> <TouchableOpacity onPress={handleCancel} className="flex-1 bg-neutral-900 py-3 rounded-xl items-center" > <Text className="text-white font-medium"> Hủy </Text> </TouchableOpacity> <TouchableOpacity onPress={handleSave} className="flex-1 bg-yellow-500 py-3 rounded-xl items-center" > <Text className="text-black font-medium"> Lưu </Text> </TouchableOpacity> </View> </Animated.View> )} </SafeAreaView> <LoadingPopup visible={showLoadingPopup} status={popupStatus} errorMessage={loadingMessage} successMessage={successMessage} /> <AvatarLoadingPopup visible={showAvatarLoadingPopup} status={avatarLoadingStatus} errorMessage={avatarErrorMessage} successMessage={avatarSuccessMessage} /> </View> ); }
import { getBooks } from './api-books'; import refs from './refs'; import { errorMessage } from './messageError'; import { GetBook } from './modal'; import { homeCategory } from './selected'; document.addEventListener('DOMContentLoaded', async () => { let previousWidth = window.innerWidth; const data = await getBooks('top-books'); window.addEventListener('resize', onResize); async function onResize() { const currentWidth = window.innerWidth; if ( previousWidth > 768 || (previousWidth < 768 && currentWidth >= 768) || (previousWidth >= 768 && currentWidth <= 1440 && (previousWidth <= 768 || currentWidth >= 1439)) ) { try { render(data); } catch (error) { errorMessage(`Failed to render books:${error}`); } } previousWidth = currentWidth; } async function render(data) { try { refs.galleryBooks.innerHTML = ''; for (const el of data) { categoriesTemplate(el); if (el.books.length >= 1) { renderBooks(el); } else { errorMessage('Sorry, there are no items in this category'); } } addQuickViewListeners(); } catch (error) { errorMessage(`Failed to render books:${error}`); } } function addQuickViewListeners() { const quickViewTriggers = document.querySelectorAll('.book-image-overlay'); quickViewTriggers.forEach(trigger => { trigger.addEventListener('click', event => { const card = event.target.closest('.card'); if (card) { const data = card.dataset.id; GetBook(data); } }); }); } function categoriesTemplate(categories) { const markup = `<li id="${categories.list_name}" class="list-category-books"> <h2 class="list-category-title">${categories.list_name}</h2> <ul class="list-book"> </ul> <button type="button" class="btn-more" data-id="${categories.list_name}">See more</button>`; refs.galleryBooks.insertAdjacentHTML('beforeend', markup); } function bookTemplate(book) { const { book_image, author, title, _id, contributor, list_name } = book; if (list_name) return ` <li class="card book-item book-hover" data-id="${_id}"> <div class="wrapper-overlay"> <img class="book-img-home" src="${book_image}" alt="${contributor} ${title}"> <div class="book-image-overlay" aria-label="${title}"> <p class="book-image-overlay-text quick-view-trigger">Quick view</p> </div> </div> <h3 class="title-book">${title}</h3> <p class="author">${author}</p> </li> `; } function booksTemplate(books) { return books.map(bookTemplate).join(''); } function renderBooks(el) { const markup = onMediaScreenChange(el); const categoriesID = el.list_name; const listBook = document .getElementById(categoriesID) .querySelector('.list-book'); listBook.insertAdjacentHTML('afterbegin', markup); } function onMediaScreenChange(el) { let mediaMarkup; if (window.innerWidth >= 768 && window.innerWidth <= 1439) { mediaMarkup = booksTemplate(el.books.slice(0, 3)); } else if (window.innerWidth >= 1440) { mediaMarkup = booksTemplate(el.books); } else { mediaMarkup = booksTemplate(el.books.slice(0, 1)); } return mediaMarkup; } render(data); const openSeeMore = document.querySelectorAll('.btn-more'); openSeeMore.forEach(link => { link.addEventListener('click', categoryClick); }); function categoryClick(event) { const bestCategory = document.querySelector('.js-home-pg'); const categories = document.querySelector('.js-selected-page'); const listName = event.srcElement.dataset.id; bestCategory.style.display = 'none'; categories.style.display = 'block'; homeCategory(listName); } });
import { ReactNode } from "react"; import { redirect } from "next/navigation"; import { auth } from "@clerk/nextjs"; import { getUserByClerkId } from "@/lib/actions/user.actions"; import { NotificationProvider } from "../contexts/NotificationContext"; import Navbar from "@/components/navbar/Navbar"; import PodcastPlayer from "@/components/podcast-components/PodcastPlayer"; import { Toaster } from "@/components/ui/toaster"; import LiveChatWrapper from "@/components/live-chat/LiveChatWrapper"; export default async function RootLayout({ children, }: { children: ReactNode; }) { let user; const { userId } = auth(); if (userId) { user = await getUserByClerkId(userId); if (!user?.onboarding) redirect("/onboarding"); } return ( <main className="lg:h-[100vh]"> {/* NOTE - when a user is logged in, use NotificationProvider */} {user ? ( <NotificationProvider currentUserId={user.id} lastChecked={user.notificationLastChecked} > <Navbar /> {children} </NotificationProvider> ) : ( <> <Navbar /> {children} </> )} <LiveChatWrapper /> <PodcastPlayer /> <Toaster /> </main> ); }
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:project/screens/CRUD/controller/crud_controller.dart'; import 'package:project/screens/widgets/input_text.dart'; import '../../widgets/add_photo.dart'; class CreatePage extends StatelessWidget { CreatePage({super.key}); final controller = Get.put(CrudController()); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: const Text('Create Post'), ), body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(15.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ InputText( controller: controller.titleController, labale: 'Title', hintText: 'Title', icon: Icons.title, ), const SizedBox(height: 20), InputText( controller: controller.descriptonController, labale: 'Description', hintText: 'Enter Description', icon: Icons.description, textMinLines: 5, textMaxLines: 10, ), const SizedBox(height: 20), // ignore: unrelated_type_equality_checks Obx( // ignore: unrelated_type_equality_checks () => controller.createPostLoading == true ? const Center(child: CircularProgressIndicator()) : SizedBox( width: 160, height: 60, child: ElevatedButton( style: const ButtonStyle( backgroundColor: MaterialStatePropertyAll(Colors.green), elevation: MaterialStatePropertyAll(10), shadowColor: MaterialStatePropertyAll(Colors.red)), onPressed: () => controller.addPost(), child: const Text( 'Add Post', style: TextStyle(fontSize: 20), ), ), ), ), const SizedBox(height: 20), Obx(() { return AddPhoto( w: 200, h: 165, onTap: () => controller.uploadImg(), widget: Align( alignment: Alignment.center, child: controller.uploadImgLoading.value == true ? const Center(child: CircularProgressIndicator()) // ignore: unrelated_type_equality_checks : controller.imgUrl1.value == '' ? const Icon( Icons.upload_file, color: Colors.amber, size: 55, ) : AddPhoto( w: 160, h: 160, widget: ClipOval( child: Image.network( controller.imgUrl1.value, fit: BoxFit.fill, ), ), ), ), ); }), ], ), ), ), ); } }
//region 3rd Party Imports import React, {useState, useRef} from 'react'; import { View, StyleSheet, KeyboardAvoidingView, Keyboard, Image, Alert, TouchableOpacity, TouchableWithoutFeedback, Platform } from 'react-native'; import { dark_colors } from '../config'; import { Auth } from 'aws-amplify'; import NetInfo from "@react-native-community/netinfo"; //endregion //region 1st Party Imports import Screen from '../comps/Screen'; import SimpleInput from '../comps/SimpleInput'; import SimpleButton from '../comps/SimpleButton'; import Beam from '../comps/Beam'; import SubTitle from '../comps/SubTitle'; import * as logger from '../functions/logger'; import * as perms from '../functions/perms'; import BeamTitle from '../comps/BeamTitle'; //endregion export default function LoginPage({navigation}) { const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [passwordVisible, setPasswordVisible] = useState(false); const [submitButtonLoad, setSubmitButtonLoad] = useState(false); const usernameRef = useRef(); const passwordRef = useRef(); //region [FUNCTION] "clear = ()" = Clears all of the inputs const clear = () => { Keyboard.dismiss(); setUsername(""); setPassword(""); usernameRef.current.clear() passwordRef.current.clear(); } //endregion //region [FUNC ASYNC] "forgotPassword = async ()" = Navigates user to forgot password page const forgotPassword = async () => { navigation.navigate("ForgotPasswordPage1"); } //endregion const onSubmit = async () => { //Begin loading setSubmitButtonLoad(true); //Save the current username & password values. Clear the actual inputs. let user = username; let pass = password; clear(); try { //region Ensure the user is connected const netInfo = await NetInfo.fetch(); if (!netInfo.isConnected) { Alert.alert("No Connection", "You must be connected to the internet to login."); throw "No Connection"; } //endregion //Attempt to log the user in const response = await Auth.signIn(user, pass); //region [IF] the user successfully logged in via cognito [THEN] log the user in locally & update their dynamodb values to a logged in state if (response) { await perms.signIn(); logger.log("Login Successful") navigation.navigate("LoadingPage") //Actually navigate to loadingpage } //endregion } catch (error) { logger.log(error); //region [IF] the user is not confirmed [THEN] navigate to the confirmation page if (error.code === "UserNotConfirmedException") navigation.navigate("SignupPage3"); //endregion //region [ELSE IF] the username isn't found or the password isn't correct [THEN] alert the user else if (error.code === "NotAuthorizedException" || error.code === "UserNotFoundException") { Alert.alert("Incorrect Username or Password", "The username or password you entered was incorrect.", [ { text: "Try Again" }, ]) } //endregion } setSubmitButtonLoad(false); } return ( <Screen> <TouchableOpacity activeOpacity={1} onPress={()=>Keyboard.dismiss() }><> <KeyboardAvoidingView style={styles.page} behavior={Platform.OS === "android" ? "height" : "padding"} > <Image source={require('../../assets/Logo.png')} style={styles.logo} resizeMode="contain" /> <View height={6} /> <SimpleInput reference={usernameRef} placeholder="Username" autocorrect={false} icon="account" autoCapitalize="none" textContentType="username" maxLength={20} onChangeText={(text) => { setUsername(text); }} /> <SimpleInput reference={passwordRef} placeholder="Password" maxLength={20} textContentType="password" autoCapitalize="none" icon="lock" showRightButton={true} rightButtonProps={{ icon: passwordVisible ? "eye-off" : "eye", size: 24, onPress: () => setPasswordVisible(!passwordVisible) }} autocorrect={false} secureTextEntry={!passwordVisible} onChangeText={(text) => { setPassword(text); }} /> <View height={6} /> <SimpleButton title="Login" onPress={onSubmit} disabled={password.length < 8 || username.length < 1} loading={submitButtonLoad} /> <View style={styles.footer}> <TouchableOpacity onPress={forgotPassword}> <BeamTitle size={18}>Forgot Password?</BeamTitle> </TouchableOpacity> </View> </KeyboardAvoidingView> </></TouchableOpacity> <View style={styles.beamContainer}> <Beam style={styles.beam} /> <TouchableOpacity onPress={() => navigation.navigate("AuthPage")}> <SubTitle size={16} style={{ fontWeight: "400" }} color={dark_colors.text2}>Or Create Account</SubTitle> </TouchableOpacity> <Beam style={styles.beam} /> </View> </Screen> ); } const styles = StyleSheet.create({ //region text text: { color: dark_colors.text1 }, //endregion //region page page: { width: "100%", height: "100%", justifyContent: "center", }, //endregion //region logo logo: { height: 60, width: "100%" }, //endregion //region beamContainer beamContainer: { width: "100%", marginTop: -30, paddingHorizontal: 10, flexDirection: 'row', justifyContent: "space-between", alignItems: "center", }, //endregion //region beam beam: { width: "26%", borderRadius: 10 }, //endregion //region footer footer: { height: 70, alignItems: "flex-end", padding: 14, paddingRight: 20 } //endregion });
# File Attachments in ChatGenius ## Overview File attachments in ChatGenius are handled through a two-step process: 1. File upload to Convex storage 2. Message creation with attachment reference ## Key Components ### Frontend - `FileUpload.tsx`: Handles file upload UI and storage - `MessageAttachment.tsx`: Renders file previews and download buttons - `MessageItem.tsx`: Displays messages with attachments - `layout.tsx`: Manages attachment state and message sending ### Backend - `files.ts`: Handles file storage and retrieval - `messages.ts` & `direct_messages.ts`: Message creation with attachment references ## Critical Points ### Message Sending When sending messages with attachments, ALWAYS ensure: 1. The `attachmentId` is passed to both `sendChannelMessage` and `sendDirectMessage` mutations 2. The `attachmentId` is included in the message data structure 3. The attachment state is cleared after message sending ### Message Fetching When fetching messages, ALWAYS ensure: 1. Attachments are included in the query response 2. The attachment data is properly mapped to the message structure 3. Both channel messages and direct messages handle attachments consistently ### Code Example ```typescript // Correct way to send a message with attachment const handleMessageSubmit = async (content: string) => { if (!user) return; try { if (chatMode === 'channel' && selectedChannel) { await sendChannelMessage({ content, authorId: user._id, channelId: selectedChannel._id, isAvatarMessage: false, attachmentId: attachmentId || undefined, // Don't forget this! }); } else if (chatMode === 'direct' && selectedUser) { await sendDirectMessage({ content, senderId: user._id, receiverId: selectedUser._id, isAvatarMessage: false, attachmentId: attachmentId || undefined, // Don't forget this! }); } setMessageInput(''); setAttachmentId(null); // Clear attachment state after sending } catch (error) { console.error('Failed to send message:', error); } }; ``` ## Common Issues 1. **Missing Attachment ID**: Ensure `attachmentId` is passed in message mutations 2. **Attachment State**: Clear attachment state after message sending 3. **Query Inclusion**: Include attachments in message queries 4. **Type Safety**: Use proper typing for attachment data ## Testing Before making changes to file attachment functionality: 1. Test file upload in both channels and direct messages 2. Verify file preview and download in both contexts 3. Check attachment state management 4. Ensure proper cleanup of attachment references
import type { MonkeyTypes } from "../types/types"; export default { name: "awardChallenge", run: async (client, guild, discordUserID: string, challengeName: string) => { if (discordUserID === undefined || challengeName === undefined) { return { status: false, message: "Invalid parameters" }; } const member = await guild.members .fetch(discordUserID) .catch(() => undefined); if (member === undefined) { return { status: false, message: "Could not find user", member: discordUserID }; } const challengeRole = (await guild.roles.fetch( client.clientOptions.challenges[challengeName] ?? "" )) ?? undefined; if (challengeRole === undefined) { return { status: false, message: "Could not find challenge role", member }; } if (member.roles.cache.has(challengeRole.id)) { return { status: false, message: "User already has challenge role", member }; } await member.roles.add(challengeRole); const botCommandsChannel = await client.getChannel("botCommands"); if (botCommandsChannel !== undefined) { botCommandsChannel.send( `✅ Congratulations ${member} for passing the challenge. You have been awarded the ${challengeRole.name} role.` ); } return { status: true, message: "Successfully awarded challenge", member }; } } as MonkeyTypes.TaskFile;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Listagende pokemon</title> <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:wght@300;500;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./src/css/reset.css"> <link rel="stylesheet" href="./src/css/estilos.css"> <link rel="stylesheet" href="./src/css/scrollbar.css"> <!--alt + shift + f --- para identar responsive view -> extenção pra chome pra ver se o site presta pra celular --> </head> <body> <header> <a href="/"> <div class="pokemon-imagem"> <img src="./src/imagens/pokeball.png" alt="pokebola" class="logo"> </div> </a> <button id="botao-alterar-tema"> <div class="pokemon-imagem"> <img src="./src/imagens/sun.png" alt="imagen do sol" class="imagen-botao"> </div> </button> </header> <main> <ul class="listagen-pokemon"> <li class="cartao-pokemon"> <div class="informacoes"> <span>bulbasaur</span> <span>#001</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/bulbasaur.gif" alt="bulbasaur" class="gif"> </div> <ul class="tipos"> <li class="grama">Grama</li> <li class="Veneno">Veneno</li> </ul> <p class="descricao"> Há uma semente de planta em suas costas desde o dia que este Pókemon nasce. A semente crescelentamente. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Ivisaur</span> <span>#002</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/ivysaur.gif" alt="ivysaur" class="gif"> </div> <ul class="tipos"> <li class="grama">Grama</li> <li class="Veneno">Veneno</li> </ul> <p class="descricao">Quando o bulbo em suas costas cresce, parece perder a capacidade de ficar de pé em suas patas traseiras. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Venusaur</span> <span>#003</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/venusaur.gif" alt="venusaur" class="gif"> </div> <ul class="tipos"> <li class="grama">Grama</li> <li class="Veneno">Veneno</li> </ul> <p class="descricao">Sua planta florece quando está absorvendo energia solar> Ele permanece em movimento para buscar a luz solar. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Charmander</span> <span>#004</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/charmander.gif" alt="charmander" class="gif"> </div> <ul class="tipos"> <li class="tipo fogo">Fogo</li> </ul> <p class="descricao">Tem em preferencia por coisas quentes. Quando chove, diz-se que o vapor jorra da ponta de sua calda. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Charmeleon</span> <span>#005</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/charmeleon.gif" alt="charmeleon" class="gif"> </div> <ul class="tipos"> <li class="tipo fogo">Fogo</li> </ul> <p class="descricao">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium fuga rem at sequi quibusdam omnis voluptas impedit. Perspiciatis ipsa unde consequuntur minus nam atque distinctio placeat dolor veniam pariatur. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Charizard</span> <span>#006</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/charizard.gif" alt="charizard" class="gif"> </div> <ul class="tipos"> <li class="tipo fogo">Fogo</li> </ul> <p class="descricao">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium fuga rem at sequi quibusdam omnis voluptas impedit. Perspiciatis ipsa unde consequuntur minus nam atque distinctio placeat dolor veniam pariatur. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Squirtle</span> <span>#007</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/squirtle.gif" alt="squirtle" class="gif"> </div> <ul class="tipos"> <li class="tipo agua">Água</li> </ul> <p class="descricao">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium fuga rem at sequi quibusdam omnis voluptas impedit. Perspiciatis ipsa unde consequuntur minus nam atque distinctio placeat dolor veniam pariatur. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Wartortle</span> <span>#008</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/wartortle.gif" alt="wartortle" class="gif"> </div> <ul class="tipos"> <li class="tipo agua">Água</li> </ul> <p class="descricao">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium fuga rem at sequi quibusdam omnis voluptas impedit. Perspiciatis ipsa unde consequuntur minus nam atque distinctio placeat dolor veniam pariatur. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Blastoise</span> <span>#009</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/blastoise.gif" alt="blastoise" class="gif"> </div> <ul class="tipos"> <li class="tipo agua">Água</li> </ul> <p class="descricao">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium fuga rem at sequi quibusdam omnis voluptas impedit. Perspiciatis ipsa unde consequuntur minus nam atque distinctio placeat dolor veniam pariatur. </p> </li> <li class="cartao-pokemon"> <div class="informacoes"> <span>Caterpie</span> <span>#010</span> </div> <div class="pokemon-imagem"> <img src="./src/imagens/caterpie.gif" alt="caterpie" class="gif"> </div> <ul class="tipos"> <li class="tipo inseto">Inseto</li> </ul> <p class="descricao">Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium fuga rem at sequi quibusdam omnis voluptas impedit. Perspiciatis ipsa unde consequuntur minus nam atque distinctio placeat dolor veniam pariatur. </p> </li> </ul> </main> <script src="./src/js/index.js"></script> </body> </html>
#------------------------------------------------------------------------------# # Merge senate polls to bonica RF scores # Author: Sina Chen # Notes: # Source: # - rf_score: https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/7EWDRF # - dime: https://data.stanford.edu/dime#download-data #------------------------------------------------------------------------------# #### Libraries #### library(readr) library(dplyr) library(stringr) #### Data #### dime <- read_csv("dime_recipients_all_1979_2014.csv") rf_scores <- read_csv("rf_predicted_scores.csv") polls <- readRDS("senate_polls_fec_id.RDS") #------------------------------------------------------------------------------# #### Preprocessing #### # select relevant information from dime for merging dime_id <- dime %>% mutate(switcher = if_else(is.na(before.switch.ICPSR) == T, 0, 1)) %>% select(Cand.ID, bonica.rid, fecyear, switcher) %>% subset(str_detect(Cand.ID, '^[S]') == T) # select relevant information from rf scores rf_id <- rf_scores %>% subset(party == 100 & state != '00'| party == 200 & state != '00') %>% select(dwdime, dwnom1, rid, party, num_unq_donors) %>% mutate(party = recode(party, '100' = 'Dem', '200' = 'Rep')) #------------------------------------------------------------------------------# #### Merge #### # merge FEC candidate and committee id to rf scores based on bonica's rid rf_dime <- merge(rf_id, dime_id, by.x = 'rid', by.y = 'bonica.rid') %>% distinct() %>% mutate(party = recode(party, '100' = 'Dem', '200' = 'Rep')) rm(dime, dime_id, rf_scores, rf_id) # merge scores to Rep. candidates (not switching party) based on FEC id polls_score <- merge(polls, subset(rf_dime, switcher == 0, select = c('Cand.ID','dwdime', 'dwnom1', 'num_unq_donors')), by.x = c('fec_rep_cand_id'), by.y = c('Cand.ID'), all.x = T) %>% distinct() %>% rename(rf_score_rep = dwdime, dwnom_score_rep = dwnom1, n_donors_rep = num_unq_donors) # merge scores to Dem. candidates (not switching party) based on FEC id polls_score <- merge(polls_score, subset(rf_dime, switcher == 0, select = c('Cand.ID','dwdime', 'dwnom1', 'num_unq_donors')), by.x = c('fec_dem_cand_id'), by.y = c('Cand.ID'), all.x = T) %>% distinct() %>% rename(rf_score_dem = dwdime, dwnom_score_dem = dwnom1, n_donors_dem = num_unq_donors) # merge scores to Rep. candidates (switching party) based on FEC id and election year polls_score <- merge(polls_score, subset(rf_dime, switcher == 1, select = c('Cand.ID', 'fecyear', 'dwdime', 'dwnom1', 'num_unq_donors')), by.x = c('fec_rep_cand_id', 'election_year'), by.y = c('Cand.ID', 'fecyear'), all.x = T) %>% distinct() %>% mutate(rf_score_rep = if_else(is.na(rf_score_rep) ==T, dwdime, rf_score_rep), dwnom_score_rep = if_else(is.na(dwnom_score_rep)== T, dwnom1, dwnom_score_rep), n_donors_rep = if_else(is.na(n_donors_rep) == T, num_unq_donors, n_donors_rep)) %>% select(-c(dwdime, dwnom1, num_unq_donors)) # merge scores to Dem. candidates (switching party) based on FEC id and election year polls_score <- merge(polls_score, subset(rf_dime, switcher == 1, select = c('Cand.ID', 'fecyear', 'dwdime', 'dwnom1', 'num_unq_donors')), by.x = c('fec_dem_cand_id', 'election_year'), by.y = c('Cand.ID', 'fecyear'), all.x = T) %>% distinct() %>% mutate(rf_score_dem = if_else(is.na(rf_score_dem) == T, dwdime, rf_score_dem), dwnom_score_dem = if_else(is.na(dwnom_score_dem) == T, dwnom1, dwnom_score_dem), n_donors_dem = if_else(is.na(n_donors_dem) == T, num_unq_donors, n_donors_dem)) %>% select(-c(dwdime, dwnom1, num_unq_donors)) #saveRDS(polls_score, 'senate_polls1998_2018_score.RDS')
package iih.ci.sdk.cache; import java.util.Arrays; import java.util.List; import iih.bd.base.cache.ContextCache; import iih.ci.ord.ems.d.CiEnContextDTO; import iih.pi.reg.pat.d.PiPatBiolDO; import iih.pi.reg.pat.i.IPiPatBiolDORService; import xap.mw.core.data.BizException; import xap.mw.sf.core.util.ServiceFinder; /** * 患者血型缓存 * @author LiuXiaoying * */ public class BDPsnBloodInfoCache { public static String BDPsnBloodInfoCache_Key = "BDPsnBloodInfoCache_Key"; public static String DefaultContext_ID = "@@@@"; private static BDPsnBloodInfoCache ins = new BDPsnBloodInfoCache(); private BDPsnBloodInfoCache() { } private List<PiPatBiolDO> get(String[] szId_pat) throws BizException { PiPatBiolDO[] mmDispensCtrArr = ServiceFinder.find(IPiPatBiolDORService.class).findByAttrValStrings(PiPatBiolDO.ID_PAT, szId_pat); if(mmDispensCtrArr!= null && mmDispensCtrArr.length >=0){ return Arrays.asList(mmDispensCtrArr); } return null; } /** * 根据id_pat获取血型属性 * @param ctx * @param id_pat * @return * @throws BizException */ public static PiPatBiolDO GetPsnBloodInfo(CiEnContextDTO ctx) throws BizException { PiPatBiolDO psnBloodInfo = ContextCache.Get(BDPsnBloodInfoCache.class.getSimpleName(),null != ctx ? ctx.getId_grp() : DefaultContext_ID, null != ctx ? ctx.getId_org() : DefaultContext_ID, null != ctx ? String.format("%s||%s", BDPsnBloodInfoCache_Key, ctx.getCode_entp()) : BDPsnBloodInfoCache_Key, ctx.getId_pat()); if (null == psnBloodInfo) { List<PiPatBiolDO> infoList = (List<PiPatBiolDO>) ins.get(new String[] { ctx.getId_pat()}); if (null != infoList && infoList.size() > 0) { psnBloodInfo = infoList.get(0); ContextCache.Put(BDPsnBloodInfoCache.class.getSimpleName(),null != ctx ? ctx.getId_grp() : DefaultContext_ID, null != ctx ? ctx.getId_org() : DefaultContext_ID, null != ctx ? String.format("%s||%s", BDPsnBloodInfoCache_Key, ctx.getCode_entp()) : BDPsnBloodInfoCache_Key, ctx.getId_pat(), psnBloodInfo); } } return psnBloodInfo; } public static void Clear() { ContextCache.Clear(BDPsnBloodInfoCache.class.getSimpleName()); // 最后一个参数给空,则清空所有的BDPsnBloodInfoCache_Key 下的缓存 } }
import 'package:automated_bone_marrow_cell_classification_system/view/home_screen/home_main_screen.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart'; import '../../view/otp_screen.dart'; class LoginScreenController extends GetxController { final FirebaseAuth _auth = FirebaseAuth.instance; final GoogleSignIn _googleSignIn = GoogleSignIn(); Rx<User?> user = Rx<User?>(null); TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); FocusNode emailFocus = FocusNode(); FocusNode passwordFocus = FocusNode(); RxBool showPassword = false.obs; RxBool isLoading = false.obs; @override void onInit() { super.onInit(); user.bindStream(_auth.authStateChanges()); } Future<void> signInWithEmailAndPassword() async { final email = emailController.text.trim(); final password = passwordController.text.trim(); isLoading.value = true; if (email.isNotEmpty && password.isNotEmpty) { try { UserCredential userCredential = await _auth.signInWithEmailAndPassword( email: email, password: password, ); clearFields(); Get.to(() => HomeMainScreen()); } on FirebaseAuthException catch (e) { passwordController.clear(); Get.snackbar( 'Error', e.message ?? 'Login failed', backgroundColor: Colors.red, colorText: Colors.white, ); } catch (e) { Get.snackbar( 'Error', e.toString(), backgroundColor: Colors.red, colorText: Colors.white, ); } finally { isLoading.value = false; } } else { Get.snackbar( 'Error', 'Please enter both email and password', backgroundColor: Colors.red, colorText: Colors.white, duration: const Duration(seconds: 2), ); Future.delayed(const Duration(seconds: 2), () { isLoading.value = false; update(); // Prints after 1 second. }); } } Future<void> signInWithGoogle() async { try { final GoogleSignInAccount? googleSignInAccount = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount!.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleSignInAuthentication.accessToken, idToken: googleSignInAuthentication.idToken, ); await _auth.signInWithCredential(credential); Get.to(() => HomeMainScreen()); } catch (e) { Get.snackbar( 'Error', 'Something went wrong please try again later', backgroundColor: Colors.red, colorText: Colors.white, ); } finally { isLoading.value = false; } } void toggleShowPassword() { showPassword.value = !showPassword.value; update(); } void clearFields() { emailController.clear(); passwordController.clear(); } //Testing with phone number Future<UserCredential?> signInWithPhoneNumber( String phoneNumber, String otp) async { try { AuthCredential credential = PhoneAuthProvider.credential( verificationId: phoneNumber, // Assuming you already have the verificationId smsCode: otp, ); return await _auth.signInWithCredential(credential); } catch (e) { print('Error while signing in with phone number OTP: $e'); return null; } } // Method to send OTP to the user's phone number Future<void> sendOtp() async { try { await _auth.verifyPhoneNumber( phoneNumber: emailController.text.trim(), verificationCompleted: (PhoneAuthCredential credential) async { await _auth.signInWithCredential(credential); }, verificationFailed: (FirebaseAuthException e) { Get.snackbar('Error', e.message!.toString()); }, codeSent: (String verificationId, int? resendToken) { Get.to(() => const OtpScreen(), arguments: verificationId); }, codeAutoRetrievalTimeout: (String verificationId) { Get.snackbar('Code auto-retrieval timeout:', ' $verificationId'); }, ); } catch (e) { Get.snackbar('Error', ' $e'); } } // Method to sign out Future<void> signOut() async { await _auth.signOut(); } // Method to check if the user is signed in User? getCurrentUser() { return _auth.currentUser; } }
//leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDepth(TreeNode root) { if(root == null) return 0; //用来保存上一层的节点 List<TreeNode> queue = new LinkedList<>() { { add(root); } }; //保存下一层的节点 List<TreeNode> tmp; int res = 0; while(!queue.isEmpty()) { //用来存放新的一层的节点 tmp = new LinkedList<>(); //遍历上一层的每一个节点,把左右节点放入下一层的集合tmp中 for(TreeNode node : queue) { if(node.left != null) tmp.add(node.left); if(node.right != null) tmp.add(node.right); } queue = tmp; res++; } return res; } } //leetcode submit region end(Prohibit modification and deletion)
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_getfile_size.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aalvarez <aalvarez@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/08/20 20:40:29 by aalvarez #+# #+# */ /* Updated: 2022/08/21 18:19:41 by aalvarez ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include <unistd.h> /** * @brief checks the number of lines a valid file has, giving an invalid file * descriptor to this function may result in undefined behaviour. * * @param fd the file descriptor to evaluate. * @return int the number of lines the content of the file descriptor has. */ int ft_getfile_size(int fd) { char character; int size; size = 0; while (read(fd, &character, 1)) { if (character == '\n') size++; } return (size); }
/*M .SH NAME dippigt - distributive polynomial over polynomials over integers Groebner test .SH SYNOPSIS .nf #include<_pol2.h> list dippigt(r1, r2, s, PL, CONDS, OPL, pCGB1) single r1, r2, s; list PL, CONDS, OPL, *pCGB1; .SH DESCRIPTION .TP 4 .B r1, r2 are integer numbers, 0 <= r1,r2 < BASIS. .TP 4 .B s is either 0 or 1, for s = 0, .RS .TP 4 .B PL is a list of distributive polynomials in r1 variables over a ring of polynomials in r2 variables over the integer numbers. .TP 4 .B VL1 is a list, consisting of the r1 variables names used by the polynomials in PL. .TP 4 .B VL2 is a list, consisting of the r2 variables names used by the ring of polynomials over the integer numbers. .PP .RE For s = 1, .RS .PP .B PL is a parametric Groebnerbasis (s. dippicgb or dippircgb). .RE .TP 4 .B CONDS = {} or { V1 ... Vn } is a list, consisting of an even number (say n) of lists, say Vi, (i = 1,...,n), where Vi contains .IP the coefficient polynomials which are equal to zero (i odd), or the coefficient polynomials which are unequal to zero (i even). .PP (s.dippicgb) .TP 4 .B OPL is a list of length 3, every element (say e1,e2,e3) has value 0 or 1. .RS .TP 4 .B e1 turns the factorization of the coefficient polynomials on (e1=1) or off(e1=0). .TP 4 .B e2 determines the algorithm used to normalize the polynomials. .IP e2 = 0: 'Top reduction' will be used, i.e. only the leading monomials (with regard to the term order) unequal to zero will be eliminated. .IP e2 = 1: the 'common' algorithm to compute Groebner basis will be used. .TP 4 .B e3 is optional. .RE .PP dippigt verifies if PL is a parametric Groebenerbasis, and returns a list, containing the conditions, that PL is a parametric Groebnerbasis. *pCGB is a list, containing the conditions, that PL is not a parametric Groebnerbasis. .SH SEE ALSO dippicgb dippircgb V. Weispfenning, Comprehensive Groebner Bases, MIP 9003 E. Schoenfeld, Diplomarbeit: Parametrische Groebnerbasen im Computer Algebra System ALDES/SAC2 1991 (Passau) M*/ /*H Version 1 08.06.1993 Th. Weis DATE dippigt : 931130 H*/ #include <_pol2.h> static cgbigt(single,single,list,list,single,single,list*,list*); static cgbigth(single,single,list,list,list,single,single,list*,list*); static cgbnfs(single,single,list,list,list,list,list*,list*); list dippigt(r1,r2,s,PL,CONDS,OPL,pCGB1) single r1,r2,s; list PL,CONDS,OPL; list *pCGB1; { /* * Fall: PL == {} - Anfang */ if ( PL == _0 ) return(_0); /* * Fall: PL == {} - Ende * Fall: PL != {} */ { single fac,red; list CGB,CGB0; bind(PL,CONDS,OPL); init(CGB,CGB0); /* * Berechnungen vorbereiten - Anfang */ fac = lfirst(OPL); red = lsecond(OPL); if ( !s ) { CGB = lcopy(PL); CGB = diplpm(r1,CGB); CGB = linv(CGB); } else CGB = cgbfcb(r1,r2,PL); /* * Berechnungen vorbereiten - Ende * Groebner Test durchfuehren - Anfang */ cgbigt(r1,r2,CONDS,CGB,fac,red,&CGB0,pCGB1); /* * Groebner Test durchfuehren - Ende * Rueckgabe */ return(CGB0); } } /*c cgbigt( r1, r2, C, P, fac, red, pC0, pC1 ) (static) "comprehensive Groebner basis over integers, Groebner test" static cgbigt(r1,r2,C,P,fac,red,pC0,pC1) single r1,r2; list C,P; single fac,red; list *pC0,*pC1; cgbigt(r1,r2,C,P,fac,red,pC0,pC1); Dabei muss gelten: - 0 <= r1 < BASIS ist die Anzahl der Variablen; - 0 <= r2 < BASIS ist die Anzahl der Parameter; - C ist eine Bedingung; - P ist eine Liste von Polynomen; - fac ist ein Schalter fuer die Faktorisierung der Koef- fizienten; - red ist ein Schalter fuer den Reduktionstyp; fuer red = 0 wird cgbinorbtop, und fuer red = 1 wird cgbipanor benutzt. cgbigt verifiziert, ob P eine parametrische Groebnerbasis bzgl. C ist. *pC0 enthaelt die Bedingungen, so dass P eine Groebnerbasis ist. *pC1 enthaelt die Bedingungen, so dass P keine Groebnerbasis ist. c*/ static cgbigt(r1,r2,C,P,fac,red,pC0,pC1) single r1,r2; list C,P; single fac,red; list *pC0,*pC1; { /* * Fall: P oder lred(P) == {} - Anfang */ *pC0 = _0; *pC1 = _0; if ( P == _0 || lred(P) == _0 ) return; /* * Fall: P oder lred(P) == {} - Ende * Fall: P oder lred(P) != {} */ { single s; list CC0,CC1,COND,DEL,PAIRS,PCO,PELEM,PLIST,PPL,X; bind(C,P); init(CC0,CC1,COND,DEL,PAIRS,PCO,PELEM,PLIST,PPL,X); /* * Bestimmung von P - Anfang */ cgbidlop(r1,r2,C,P,fac,&DEL,&PPL); /* * Bestimmung von P - Ende * Test - Anfang */ while ( PPL != _0 ) { PELEM = lfirst(PPL); PPL = lred(PPL); COND = lfirst(PELEM); PLIST = lsecond(PELEM); PCO = cgbcdopl(r1,r2,PLIST); if ( PCO == _0 && lred(PLIST) != _0 ) { cgbmkpair(r1,r2,PLIST,&PAIRS); if ( PAIRS != _0 ) { cgbigth(r1,r2,COND,PAIRS,PLIST,fac,red,&CC0,&CC1); if ( CC0 != _0 ) { if ( *pC0 == _0 ) *pC0 = CC0; else { X = llast(*pC0); lsred(X,CC0); } } if ( CC1 != _0 ) { if ( *pC1 == _0 ) *pC1 = CC1; else { X = llast(*pC1); lsred(X,CC1); } } } else { s = lmemb(COND,*pC0); if ( s == 0 ) *pC0 = lcomp(COND,*pC0); } } else { s = lmemb(COND,*pC0); if ( s == 0 ) *pC0 = lcomp(COND,*pC0); } } /* * Test - Ende * Ruecksprung */ return; } } /*c cgbigth( r1, r2, COND, PPAIRS, P, fac, red, pC0, pC1 ) (static) "comprehensive Groebner basis over integers, Groebner test help" static cgbigth(r1,r2,COND,PPAIRS,P,fac,red,pC0,pC1) single r1,r2; list COND,PPAIRS,P; single fac,red; list *pC0,*pC1; cgbigth(r1,r2,COND,PPAIRS,P,fac,red,pC0,pC1); Dabei muss gelten: - 0 <= r1 < BASIS ist die Anzahl der Variablen; - 0 <= r2 < BASIS ist die Anzahl der Parameter; - COND ist eine Bedingung; - PPAIRS ist die Polynompaarliste von P; - P ist eine bzgl. COND bestimmte und gefaerbte Liste von Polynomen; - fac ist ein Schalter fuer die Faktorisierung der Koef- fizienten; - red ist ein Schalter fuer den Reduktionstyp; fuer red = 0 wird cgbinorbtop und fuer red = 1 wird cgbipanor benutzt. *pC0 enthaelt den Nachfolger der Bedingung COND, so dass P keine Groebnerbasis ist. *pC1 enthaelt den Nachfolger der Bedingung COND, so dass P eine Groebnerbasis ist. c*/ static cgbigth(r1,r2,COND,PPAIRS,P,fac,red,pC0,pC1) single r1,r2; list COND,PPAIRS,P; single fac,red; list *pC0,*pC1; { single s; list FCO,GCO,HCO,N0,N1,PAIR,PAIRS; bind(COND,PPAIRS,P); init(FCO,GCO,HCO,N0,N1,PAIR,PAIRS); /* * Vorbesetzen - Anfang */ PAIRS = PPAIRS; *pC0 = _0; *pC1 = _0; /* * Vorbesetzen - Ende * Konstruktion der S-Polynome - Anfang */ while ( PAIRS != _0 ) { PAIR = lfirst(PAIRS); PAIRS = lred(PAIRS); FCO = lsecond(PAIR); GCO = lthird(PAIR); cgbipaspol(r1,r2,COND,FCO,GCO,fac,&HCO); if ( HCO != _0 ) { if ( red == 0 ) cgbinorbtop(r1,r2,COND,HCO,P,fac,&N0,&N1); else cgbipanor(r1,r2,COND,HCO,P,fac,&N0,&N1); if ( N1 == _0 ) { s = lmemb(COND,*pC0); if ( s == 0 ) *pC0 = lcomp(COND,*pC0); } if ( N0 == _0 ) { s = lmemb(COND,*pC1); if ( s == 0 ) *pC1 = lcomp(COND,*pC1); } if ( N0 != _0 && N1 != _0 ) cgbnfs(r1,r2,N0,N1,*pC0,*pC1,pC0,pC1); } else *pC0 = lcomp(COND,*pC0); } /* * Konstruktion der S-Polynome - Ende * Ruecksprung */ return; } /*c cgbnfs( r1, r2, NN0, NN1, CC0, CC1, pC0, pC1 ) (static) "comprehensive Groebner basis, normalform set" static cgbnfs(r1,r2,NN0,NN1,CC0,CC1,pC0,pC1) single r1,r2; list NN0,NN1,CC0,CC1; list *pC0,*pC1; cgbnfs(r1,r2,NN0,NN1,CC0,CC1,pC0,pC1); Dabei muss gelten: - 0 <= r1 < BASIS ist die Anzahl der Variablen; - 0 <= r2 < BASIS ist die Anzahl der Parameter; - NN0 ist eine Liste von Tripel der Form: ( GA, PCO, C ), wobei - GA eine Bedingung ist, - *PCO eine Normalform ist, die durch GA bestimmt und komplett gruen gefaerbt wird, - C ein multiplikativer Faktor ist; - NN1 ist eine Liste von Tripel der Form: ( GA, PCO, C ), wobei - GA eine Bedingung ist, - *PCO eine Normalform ist, die durch GA bestimmt und NICHT komplett gruen gefaerbt wird, - C ein multiplikativer Faktor ist; - CC0 und CC1 sind Listen von Bedingungen. Die Bedingungen in NN0, die nicht in CC1 sind, werden zu CC0 (pC0) hinzugefuegt. Die Bedingungen in NN1 werden zu CC1 (pC1) hinzuge- fuegt. c*/ static cgbnfs(r1,r2,NN0,NN1,CC0,CC1,pC0,pC1) single r1,r2; list NN0,NN1,CC0,CC1; list *pC0,*pC1; { single s,t; list C,COND,N0,N1,PCO; bind(NN0,NN1,CC0,CC1); init(C,COND,N0,N1,PCO); /* * Vorbesetzen - Anfang */ *pC0 = CC0; *pC1 = CC1; N0 = NN0; N1 = NN1; /* * Vorbesetzen - Ende * Ueberpruefen und Zusammenstellen der Bedingungslisten - Anfang */ while ( N1 != _0 ) { COND = lfirst(N1); N1 = lred(N1); PCO = lfirst(N1); N1 = lred(N1); C = lfirst(N1); N1 = lred(N1); s = lmemb(COND,*pC1); if ( s == 0 ) *pC1 = lcomp(COND,*pC1); } while ( N0 != _0 ) { COND = lfirst(N0); N0 = lred(N0); PCO = lfirst(N0); N0 = lred(N0); C = lfirst(N0); N0 = lred(N0); s = lmemb(COND,*pC0); t = lmemb(COND,*pC1); if ( s == 0 && t == 0 ) *pC0 = lcomp(COND,*pC0); } /* * Ueberpruefen und Zusammenstellen der Bedingungslisten - Ende * Ruecksprung */ return; }
import { useId } from "react"; import { useFilters } from "../hooks/useFilters"; export const Filters = () => { const minPriceFilterId = useId(); const categoryFilterId = useId(); const { setFilters, filters } = useFilters(); const handleChangeMinPrice = (e) => { setFilters((prevState) => ({ ...prevState, minPrice: e.target.value })); }; const handleChangeCategory = (e) => { setFilters((prevState) => ({ ...prevState, category: e.target.value })); }; return ( <section className="flex justify-between p-4 text-base font-bold max-w-2xl m-auto flex-wrap gap-1"> <div className="flex gap-4"> <label htmlFor={minPriceFilterId}>Precio a partir de:</label> <input type="range" id={minPriceFilterId} min={0} max={1000} value={filters.minPrice} onChange={handleChangeMinPrice} /> <span>${filters.minPrice}</span> </div> <div className="flex gap-4"> <label htmlFor={categoryFilterId}>Categoría</label> <select id={categoryFilterId} className="bg-stone-600" onChange={handleChangeCategory} > <option value="all">Todas</option> <option value="laptops">Laptops</option> <option value="smartphones">Celulares</option> <option value="home-decoration">Decoraciones</option> </select> </div> </section> ); };
package fr.data; import java.util.ArrayList; import javax.swing.event.EventListenerList; import fr.data.event.DatabaseEvent; import fr.data.event.DatabaseListener; import fr.data.event.DatabaseSearchEvent; import fr.userinterface.event.MenuSelectedEvent; import fr.userinterface.event.MenuSelectedListener; public abstract class Database<T> { protected ArrayList<T> rows; private EventListenerList listeners = new EventListenerList(); protected void OnRowAdded(DatabaseEvent<T> event) { Object[] listeners = this.listeners.getListenerList(); for(int i = 0; i < listeners.length; i+=2) { if(listeners[i] == DatabaseListener.class) { ((DatabaseListener<T>)listeners[i+1]).OnRowAdded(event); ((DatabaseListener<T>)listeners[i+1]).OnDatabaseUpdate(event); } } } protected void OnRowRemoved(DatabaseEvent<T> event) { Object[] listeners = this.listeners.getListenerList(); for(int i = 0; i < listeners.length; i+=2) { if(listeners[i] == DatabaseListener.class) { ((DatabaseListener<T>)listeners[i+1]).OnRowRemove(event); ((DatabaseListener<T>)listeners[i+1]).OnDatabaseUpdate(event); } } } protected void OnRowUpdated(DatabaseEvent<T> event) { Object[] listeners = this.listeners.getListenerList(); for(int i = 0; i < listeners.length; i+=2) { if(listeners[i] == DatabaseListener.class) { ((DatabaseListener<T>)listeners[i+1]).OnRowUpdated(event); ((DatabaseListener<T>)listeners[i+1]).OnDatabaseUpdate(event); } } } protected void OnSearch(DatabaseSearchEvent event) { Object[] listeners = this.listeners.getListenerList(); for(int i = 0; i < listeners.length; i+=2) { if(listeners[i] == DatabaseListener.class) { ((DatabaseListener<T>)listeners[i+1]).OnDatabaseSearch(event); } } } public void AddDatabaseListener(DatabaseListener<T> listener) { listeners.add(DatabaseListener.class, listener); } public void removeDatabaseListener(DatabaseListener<T> listener) { listeners.remove(DatabaseListener.class, listener); } public ArrayList<T> GetRows(){ return rows; } public abstract void SearchRows(DatabaseSearchEvent event); }
package com.blooming.goaltracker import android.content.ContentValues.TAG import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.ImageButton import androidx.recyclerview.widget.RecyclerView import com.google.firebase.firestore.FirebaseFirestore class AnnouncementActivity : AppCompatActivity() { val db = FirebaseFirestore.getInstance() lateinit var announcementAdapter: AnnouncementAdapter lateinit var announcement_list: RecyclerView lateinit var backtomain: ImageButton override fun onCreate(savedInstanceState: Bundle?) { setTheme(MySharedPreferences.getTheme(this)) super.onCreate(savedInstanceState) setContentView(R.layout.activity_announcement) announcement_list = findViewById(R.id.announcement_list) backtomain = findViewById(R.id.backtomain) backtomain.setOnClickListener { finish() } announcementAdapter = AnnouncementAdapter(this) announcement_list.adapter = announcementAdapter db.collection("Announcement") .get() .addOnSuccessListener { announcements -> val announcementData = ArrayList<AnnouncementData>() for (announcement in announcements) { Log.d(TAG, "${announcement.id} => ${announcement.data}") val subject = announcement.data["subject"].toString() val content = announcement.data["content"].toString() val createDate = announcement.data["createDate"].toString() announcementData.add( AnnouncementData( subject = subject, content = content, createDate = createDate ) ) } announcementData.sortBy { it.createDate } announcementAdapter.announcementDatas = announcementData announcementAdapter.notifyDataSetChanged() } .addOnFailureListener { exception -> Log.d(TAG, "Error getting documents: ", exception) } } }
#pragma once #include "attributeEditor.h" #include "entityDisplay.h" #include "entityEditor.h" #include "imageViewer.h" #include "levelEditor.h" #include "musicPlayer.h" #include "palette.h" #include "profileEditor.h" #include "undoStack.h" #include "selection.h" #include "settings.h" #include "scriptEditor.h" #include "style.h" #include "styleEditor.h" #include "tilesetEditor.h" #include "toolbar.h" #include "tools/tools.h" #include "../px/profile.h" #include "../px/pxmap.h" #include "../px/tileset.h" #include "../rlImGui/focusData.h" #include "raylib.h" // The main editor. struct Editor { Settings settings; // Editor settings. EditorStyle style; // Style for the editor. Color fadeColor = { 255, 0, 0, 255 }; // Background color. Image icon; // Editor icon. bool enabled = false; // If the editor is enabled and ready to edit. bool doFullscreen = false; // If the editor is in fullscreen mode. FocusData focus; // For focusing subwindows. std::string rsc = ""; // Resource path. std::string level = ""; // Open level. Palette palette = Palette(this); // Palette viewer. EntityEditor entityEditor = EntityEditor(this); // Entity editor. LevelEditor levelEditor = LevelEditor(this); // Level editor. ProfileEditor profileEditor = ProfileEditor(this); // Profile editor. StyleEditor styleEditor = StyleEditor(this); // Style editor. MusicPlayer musicPlayer = MusicPlayer(this); // Music player. std::vector<ImageViewer> imageViewers = std::vector<ImageViewer>(); // Image viewers. std::vector<TilesetEditor> tilesetEditors = std::vector<TilesetEditor>(); // Tileset editors. std::vector<AttributeEditor> attrEditors = std::vector<AttributeEditor>(); // Attribute editors. std::vector<ScriptEditor> scriptEditors = std::vector<ScriptEditor>(); // Script editors. Selection tilesToPaint; // Tiles to paint to the canvas. Map map; // Currently loaded pxmap. Profile profile; // Player profile. std::map<std::string, Tileset> tilesets; // Loaded tilesets. Camera2D cam; // Camera for viewing the map. UndoStack undoStack; // Undo stack for undo/redo actions. bool levelClosed = false; // If a level was closed. bool quit = false; // If to quit the editor. float oldMouseX; // Old mouse X position. float oldMouseY; // Old mouse Y position. float mouseX; // Mouse X position. float mouseY; // Mouse Y position. Toolbar toolbar = Toolbar(this); // Toolbar for widgets. Tools tools; // Editor tool widgets. ToolItem currTool = ToolItem::Hand; // Current tool. int currentLayer = (int)MapLayer::FG; // Current layer to edit. int placeEntityId = 0; // The entity ID to place if an entity is being placed. bool isPlacingEntity = false; // If an entity is being placed. bool doingEntityMove = false; // If an entity is moving. // New level selection vars. std::string newFileName; // Name for the new file. bool closeNewLevel; // Close the new level popup. bool isNew; // If the level to select is new. // Level file select vars. int numLevelFiles; // How many level files there are to display. char** levelFiles = nullptr; // Actual level file names. // Zoom constants. static constexpr float MIN_ZOOM = 0.25f; static constexpr float MAX_ZOOM = 10.0f; // Initialize the editor. void Init(); // Main editor execution loop. int EditorLoop(); // Draw the main background. void Draw(); // Draw tile place preview. void DrawTilePlacePreview(); // Draw entity place preview. void DrawEntityPlacePreview(); // Draw the main UI. void DrawUI(); // Main update loop. void Update(); // Do the fade effect. void FadeEffect(); // Initialize the editor by loading everything needed. void InitEditor(); // Init sub-editors. void InitSubeditors(); // Load a tileset. void LoadTileset(std::string tilesetName); // Unload a tileset. void UnloadTileset(std::string tilesetName); // Load the fixed tilesets. void LoadFixedTilesets(); // Load a level from the current level name. void LoadLevel(); // Unload the current level. void UnloadLevel(); // Draw the grid. void DrawGrid(); // Detect if a keyboard shortcut is down. bool KeyboardShortcut(bool control, bool alt, bool shift, int key); // Draw the main menu at the top of the screen. void DrawMainMenu(); // Select a level name. void LevelNameSelect(bool saveAs); // Open a level name. void LevelNameOpen(); // Draw open level UI. void DrawSelectLevelUI(); // Draw the open level UI. void DrawOpenLevelUI(); // Draw about popup. void DrawAboutPopup(); // Open a level. void OpenLevel(std::string level); // Save the level. void SaveLevel(); // Close the level. void CloseLevel(); // Quit the editor. void Quit(); // Undo the last action. void Undo(); // Redo the last action. void Redo(); // Toggle fullscreen. void DoToggleFullscreen(); // Open about popup. void OpenAboutPopup(); // Open a tileset. void OpenTileset(std::string tilesetName, float tileSize); // Remove selections from all other tileset viewers. void RemoveAllOtherTilesetViewerSelections(TilesetEditor* exclude); // Resize all tileset editors. void ResizeAllTilesetViewers(std::string name); // Open an attribute editor. void OpenAttr(std::string name, float tileSize); // Open a script. void OpenScript(std::string scriptName); // Move the camera in the X direction. void MoveCamX(float amount, bool relative = true); // Move the camera in the Y direction. void MoveCamY(float amount, bool relative = true); // Get how much to speed the zoom by. float GetZoomSpeed(); // Zoom the camera in an out from a certain point with an amount. void Zoom(Vector2 origin, float amount, bool relative); // Get the tile at the X position with the current mouse and layer. -1 is out of bounds. int GetTileX(s8 layer = -1); // Get the tile at the Y position with the current mouse and layer. -1 is out of bounds. int GetTileY(s8 layer = -1); // Check for default tool applications. void DoDefaultToolRoutine(); // Check for default scrolling with shortcuts. void CheckScroll(); // Check for default zooming with mouse wheel. void CheckZoom(); // Check for entity deleting. void CheckEntityDelete(); // Take a screenshot. Note that it has to be unloaded later. RenderTexture2D Screenshot(); // Draw the save screenshot popup. void DrawSaveScreenshotPopup(); };
import React, { useRef, useState } from 'react' import Card from './card' import "../styles/cardSlider.css" import { AiOutlineLeft, AiOutlineRight } from 'react-icons/ai'; export default function CardSlider({data, title}) { const [sliderPosition, setSliderPosition] = useState(0); const [showControls, setShowControls] = useState(false); const listRef = useRef(); const handleDirection = (direction) => { let distance = listRef.current.getBoundingClientRect().x - 70; if (direction === "left" && sliderPosition > 0) { listRef.current.style.transform = `translateX(${230 + distance}px)`; setSliderPosition(sliderPosition - 1); } if (direction === "right" && sliderPosition < 3) { listRef.current.style.transform = `translateX(${-230 + distance}px)`; setSliderPosition(sliderPosition + 1); } }; return ( <div className='cardSlider-container' onMouseEnter={() =>setShowControls(true)} onMouseLeave={() =>setShowControls(false)} > <h1>{title}</h1> <div className='wrapper'> <div className={`slider-action left ${!showControls ? "none" : ""}`}> <AiOutlineLeft onClick={() => handleDirection("left")}/> </div> <div className='slider' ref={listRef}> {data.map((movie, index) => { return <Card movieData={movie} index={index} key={movie.id} />; })} </div> <div className={`slider-action right ${!showControls ? "none" : ""}`}> <AiOutlineRight onClick={() => handleDirection("right")}/> </div> </div> </div> ) }
--- id: bad87fee1348bd9aed908845 title: 텍스트 입력을 폼 컨트롤로 스타일링하기 challengeType: 0 forumTopicId: 18312 required: - link: >- https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css raw: true dashedName: style-text-inputs-as-form-controls --- # --description-- 제출 `button` 요소 내에 `<i class="fa fa-paper-plane"></i>`를 추가하여 `fa-paper-plane` Font Awesome 아이콘을 추가할 수 있습니다. 폼 글자 입력 필드에 `form-control`라는 클래스를 주세요. 폼 제출 버튼에 `btn btn-primary`라는 클래스를 주세요. 또한 이 버튼에 Font Awesome `fa-paper-plane` 아이콘을 주세요. `.form-control` 클래스를 가진 모든 글자 요소 `<input>`, `<textarea>` 그리고 `<select>`는 100% 너비를 가집니다. # --hints-- 폼에 있는 제출 버튼은 `btn btn-primary` 클래스를 가져야 합니다. ```js assert($('button[type="submit"]').hasClass('btn btn-primary')); ``` 제출 `button` 요소 내에 `<i class="fa fa-paper-plane"></i>`를 추가해야 합니다. ```js assert($('button[type="submit"]:has(i.fa.fa-paper-plane)').length > 0); ``` 폼에 있는 글자 `input`은 `form-control` 클래스를 가져야 합니다. ```js assert($('input[type="text"]').hasClass('form-control')); ``` 각각의 `i` 요소는 닫는 태그를 가져야 합니다. ```js assert(code.match(/<\/i>/g) && code.match(/<\/i/g).length > 3); ``` # --seed-- ## --seed-contents-- ```html <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> <style> h2 { font-family: Lobster, Monospace; } .thick-green-border { border-color: green; border-width: 10px; border-style: solid; border-radius: 50%; } </style> <div class="container-fluid"> <div class="row"> <div class="col-xs-8"> <h2 class="text-primary text-center">CatPhotoApp</h2> </div> <div class="col-xs-4"> <a href="#"><img class="img-responsive thick-green-border" src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a> </div> </div> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg" class="img-responsive" alt="Three kittens running towards the camera."> <div class="row"> <div class="col-xs-4"> <button class="btn btn-block btn-primary"><i class="fa fa-thumbs-up"></i> Like</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-info"><i class="fa fa-info-circle"></i> Info</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-danger"><i class="fa fa-trash"></i> Delete</button> </div> </div> <p>Things cats <span class="text-danger">love:</span></p> <ul> <li>cat nip</li> <li>laser pointers</li> <li>lasagna</li> </ul> <p>Top 3 things cats hate:</p> <ol> <li>flea treatment</li> <li>thunder</li> <li>other cats</li> </ol> <form action="https://freecatphotoapp.com/submit-cat-photo"> <div class="row"> <div class="col-xs-6"> <label><input type="radio" name="indoor-outdoor"> Indoor</label> </div> <div class="col-xs-6"> <label><input type="radio" name="indoor-outdoor"> Outdoor</label> </div> </div> <div class="row"> <div class="col-xs-4"> <label><input type="checkbox" name="personality"> Loving</label> </div> <div class="col-xs-4"> <label><input type="checkbox" name="personality"> Lazy</label> </div> <div class="col-xs-4"> <label><input type="checkbox" name="personality"> Crazy</label> </div> </div> <input type="text" placeholder="cat photo URL" required> <button type="submit">Submit</button> </form> </div> ``` # --solutions-- ```html <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"> <style> h2 { font-family: Lobster, Monospace; } .thick-green-border { border-color: green; border-width: 10px; border-style: solid; border-radius: 50%; } </style> <div class="container-fluid"> <div class="row"> <div class="col-xs-8"> <h2 class="text-primary text-center">CatPhotoApp</h2> </div> <div class="col-xs-4"> <a href="#"><img class="img-responsive thick-green-border" src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a> </div> </div> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/running-cats.jpg" class="img-responsive" alt="Three kittens running towards the camera."> <div class="row"> <div class="col-xs-4"> <button class="btn btn-block btn-primary"><i class="fa fa-thumbs-up"></i> Like</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-info"><i class="fa fa-info-circle"></i> Info</button> </div> <div class="col-xs-4"> <button class="btn btn-block btn-danger"><i class="fa fa-trash"></i> Delete</button> </div> </div> <p>Things cats <span class="text-danger">love:</span></p> <ul> <li>cat nip</li> <li>laser pointers</li> <li>lasagna</li> </ul> <p>Top 3 things cats hate:</p> <ol> <li>flea treatment</li> <li>thunder</li> <li>other cats</li> </ol> <form action="https://freecatphotoapp.com/submit-cat-photo"> <div class="row"> <div class="col-xs-6"> <label><input type="radio" name="indoor-outdoor"> Indoor</label> </div> <div class="col-xs-6"> <label><input type="radio" name="indoor-outdoor"> Outdoor</label> </div> </div> <div class="row"> <div class="col-xs-4"> <label><input type="checkbox" name="personality"> Loving</label> </div> <div class="col-xs-4"> <label><input type="checkbox" name="personality"> Lazy</label> </div> <div class="col-xs-4"> <label><input type="checkbox" name="personality"> Crazy</label> </div> </div> <input type="text" class="form-control" placeholder="cat photo URL" required> <button type="submit" class="btn btn-primary"><i class="fa fa-paper-plane"></i>Submit</button> </form> </div> ```
<?php namespace Src\shared\Domain\ValueObject; use http\Exception\InvalidArgumentException; use Ramsey\Uuid\Uuid as RamseyUuid; class Uuid { protected string $value; public function __construct(string $value) { $this->value = $value; } public static function random(): self { return new self(RamseyUuid::uuid4()->toString()); } public function value(): string { return $this->value; } private function ensureIsValidUuid($id): void { if(!RamseyUuid::isValid($id)) { throw new InvalidArgumentException(sprintf('<%s> does not allow the value <%s>.', static::class, $id)); } } public function equals(Uuid $other): bool { return $this->value() === $other->value(); } public function __toString() { return $this->value(); } }
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import { delay } from "awaiting"; import * as immutable from "immutable"; import { STUDENT_SUBDIR } from "@cocalc/frontend/course/assignments/consts"; import { close, path_split } from "@cocalc/util/misc"; import { JupyterActions } from "../browser-actions"; import { clear_hidden_tests } from "./clear-hidden-tests"; import { clear_mark_regions } from "./clear-mark-regions"; import clearSolution from "./clear-solutions"; import { set_checksum } from "./compute-checksums"; import { ImmutableMetadata, Metadata } from "./types"; export class NBGraderActions { private jupyter_actions: JupyterActions; private redux; constructor(jupyter_actions, redux) { this.jupyter_actions = jupyter_actions; this.redux = redux; } public close(): void { close(this); } // Ensure all nbgrader metadata is updated to the latest version we support. // The update is done as a single commit to the syncdb. public update_metadata(): void { const cells = this.jupyter_actions.store.get("cells"); let changed: boolean = false; // did something change. cells.forEach((cell, id: string): void => { if (cell == null) return; const nbgrader = cell.getIn(["metadata", "nbgrader"]) as any; if (nbgrader == null || nbgrader.get("schema_version") === 3) return; // Doing this set // make the actual change via the syncdb mechanism (NOT updating cells directly; instead // that is a side effect that happens at some point later). this.set_metadata(id, {}, false); changed = true; }); if (changed) { this.jupyter_actions._sync(); } } private get_metadata(id: string): ImmutableMetadata { return this.jupyter_actions.store.getIn( ["cells", id, "metadata", "nbgrader"], immutable.Map() ); } // Sets the metadata and also ensures the schema is properly updated. public set_metadata( id: string, metadata: Metadata | undefined = undefined, // if undefined, deletes the nbgrader metadata entirely save: boolean = true ): void { let nbgrader: Metadata | undefined = undefined; if (metadata != null) { nbgrader = this.get_metadata(id).toJS(); if (nbgrader == null) throw Error("must not be null"); // Merge in the requested changes. for (const k in metadata) { nbgrader[k] = metadata[k]; } // Update the schema, if necessary: if (nbgrader.schema_version == null || nbgrader.schema_version < 3) { // The docs of the schema history are at // https://nbgrader.readthedocs.io/en/stable/contributor_guide/metadata.html // They were not updated even after schema 3 came out, so I'm just guessing // based on reading source code and actual ipynb files. nbgrader.schema_version = 3; // nbgrader schema_version=3 requires that all these are set: // We only set "remove" if it is true. This violates the nbgrader schema, so *should* // break processing the ipynb file in nbgrader, which is *good* since instructors // won't silently push out content to students that students are not supposed to see. // We do NOT put nbgrader['remove']=false in explicitly, since no point in // breaking compatibility with official nbgrader if this cell type isn't being used. if (!nbgrader["remove"]) { delete nbgrader["remove"]; } for (const k of ["grade", "locked", "solution", "task"]) { if (nbgrader[k] == null) { nbgrader[k] = false; } } } } this.jupyter_actions.set_cell_metadata({ id, metadata: { nbgrader }, merge: true, save, }); } public async validate(frame_actions): Promise<void> { // Without confirmation: (1) restart, (2) run all -- without stopping for errors. // Validate button should be disabled while this happens. // As running happens number of failing tests and total score // gets updated at top. frame_actions?.set_all_md_cells_not_editing(); await this.jupyter_actions.restart(); this.jupyter_actions.run_all_cells(true); } public async confirm_validate(frame_actions): Promise<void> { const choice = await this.jupyter_actions.confirm_dialog({ title: "Validate notebook?", body: "Validating the notebook will restart the kernel and run all cells in order, even those with errors. This will ensure that all output is exactly what results from running all cells in order.", choices: [ { title: "Cancel" }, { title: "Validate", style: "danger", default: true }, ], }); if (choice === "Validate") { await this.validate(frame_actions); } } public async confirm_assign(): Promise<void> { const path = this.jupyter_actions.store.get("path"); let { head, tail } = path_split(path); if (head == "") { head = `${STUDENT_SUBDIR}/`; } else { head = `${head}/${STUDENT_SUBDIR}/`; } const target = head + tail; let minimal_stubs = this.jupyter_actions.store.getIn( ["metadata", "nbgrader", "cocalc_minimal_stubs"], false ); const MINIMAL_STUBS = "Generate with minimal stubs"; const choice = await this.jupyter_actions.confirm_dialog({ title: "Generate Student Version of Notebook", body: `Generating the student version of the notebook will create a new Jupyter notebook "${target}" that is ready to distribute to your students. This process locks cells and writes metadata so parts of the notebook can't be accidentally edited or deleted; it removes solutions, and replaces them with code or text stubs saying (for example) "YOUR ANSWER HERE"; and it clears all outputs. Once done, you can easily inspect the resulting notebook to make sure everything looks right. (This is analogous to 'nbgrader assign'.) The CoCalc course management system will *only* copy the ${STUDENT_SUBDIR} subdirectory that contains this generated notebook to students.`, choices: [ { title: "Cancel" }, { title: "Generate student version", style: !minimal_stubs ? "success" : undefined, default: !minimal_stubs, }, { title: MINIMAL_STUBS, style: minimal_stubs ? "success" : undefined, default: minimal_stubs, }, ], }); if (choice === "Cancel") return; minimal_stubs = choice == MINIMAL_STUBS; this.set_global_metadata({ cocalc_minimal_stubs: minimal_stubs }); this.ensure_grade_ids_are_unique(); // non-unique ids lead to pain later await this.assign(target, minimal_stubs); } public async assign( filename: string, minimal_stubs: boolean = false ): Promise<void> { // Create a copy of the current notebook at the location specified by // filename, and modify by applying the assign transformations. const project_id = this.jupyter_actions.store.get("project_id"); const project_actions = this.redux.getProjectActions(project_id); await project_actions.open_file({ path: filename, foreground: true }); let actions = this.redux.getEditorActions(project_id, filename); while (actions == null) { await delay(200); actions = this.redux.getEditorActions(project_id, filename); } await actions.jupyter_actions.wait_until_ready(); actions.jupyter_actions.syncdb.from_str( this.jupyter_actions.syncdb.to_str() ); // Important: we also have to fire a changes event with all // records, since otherwise the Jupyter store doesn't get // updated since we're using from_str. // The complicated map/filter thing below is just to grab // only the {type:?,id:?} parts of all the records. actions.jupyter_actions.syncdb.emit("change", "all"); await actions.jupyter_actions.save(); await actions.jupyter_actions.nbgrader_actions.apply_assign_transformations( minimal_stubs ); await actions.jupyter_actions.save(); } public apply_assign_transformations(minimal_stubs: boolean = false): void { /* see https://nbgrader.readthedocs.io/en/stable/command_line_tools/nbgrader-assign.html Of which, we do: 2. It locks certain cells so that they cannot be deleted by students accidentally (or on purpose!) 3. It removes solutions from the notebooks and replaces them with code or text stubs saying (for example) "YOUR ANSWER HERE", and similarly for hidden tests. 4. It clears all outputs from the cells of the notebooks. 5. It saves information about the cell contents so that we can warn students if they have changed the tests, or if they have failed to provide a response to a written answer. Specifically, this is done by computing a checksum of the cell contents and saving it into the cell metadata. */ //const log = (...args) => console.log("assign:", ...args); // log("unlock everything"); this.assign_unlock_all_cells(); // log("clear solutions"); this.assign_clear_solutions(minimal_stubs); // step 3a // log("clear hidden tests"); this.assign_clear_hidden_tests(); // step 3b // log("clear mark regions"); this.assign_clear_mark_regions(); // step 3c // this is a nonstandard extension to nbgrader in cocalc only. this.assign_delete_remove_cells(); // log("clear all outputs"); this.jupyter_actions.clear_all_outputs(false); // step 4 // log("assign save checksums"); this.assign_save_checksums(); // step 5 // log("lock readonly cells"); this.assign_lock_readonly_cells(); // step 2 -- needs to be last, since it stops cells from being editable! this.jupyter_actions.save_asap(); } // merge in metadata to the global (not local to a cell) nbgrader // metadata for this notebook. This is something I invented for // cocalc, and it is surely totally ignored by upstream nbgrader. set_global_metadata(metadata: object): void { const cur = this.jupyter_actions.store.getIn(["metadata", "nbgrader"]); if (cur) { metadata = { ...cur, ...metadata, }; } this.jupyter_actions.set_global_metadata({ nbgrader: metadata }); } private assign_clear_solutions(minimal_stubs: boolean = false): void { const store = this.jupyter_actions.store; const kernel_language = store.get_kernel_language(); this.jupyter_actions.store.get("cells").forEach((cell) => { if (!cell.getIn(["metadata", "nbgrader", "solution"])) return; // we keep the "answer" cell of a multiple_choice question as it is if (cell.getIn(["metadata", "nbgrader", "multiple_choice"]) == true) { return; } const cell2 = clearSolution(cell, kernel_language, minimal_stubs); if (cell !== cell2) { // set the input this.jupyter_actions.set_cell_input( cell.get("id"), cell2.get("input"), false ); } }); } private assign_clear_hidden_tests(): void { this.jupyter_actions.store.get("cells").forEach((cell) => { // only care about test cells, which have: grade=true and solution=false. if (!cell.getIn(["metadata", "nbgrader", "grade"])) return; if (cell.getIn(["metadata", "nbgrader", "solution"])) return; const cell2 = clear_hidden_tests(cell); if (cell !== cell2) { // set the input this.jupyter_actions.set_cell_input( cell.get("id"), cell2.get("input"), false ); } }); } private assign_clear_mark_regions(): void { this.jupyter_actions.store.get("cells").forEach((cell) => { if (!cell.getIn(["metadata", "nbgrader", "grade"])) { // We clear mark regions for any cell that is graded. // In the official nbgrader docs, it seems that mark // regions are only for **task** cells. However, // I've seen nbgrader use "in nature" that uses // the mark regions in other grading cells, and also // it just makes sense to be able to easily record // how you will grade things even for non-task cells! return; } const cell2 = clear_mark_regions(cell); if (cell !== cell2) { // set the input this.jupyter_actions.set_cell_input( cell.get("id"), cell2.get("input"), false ); } }); } private assign_delete_remove_cells(): void { const cells: string[] = []; this.jupyter_actions.store.get("cells").forEach((cell) => { if (!cell.getIn(["metadata", "nbgrader", "remove"])) { // we delete cells that have remote true and this one doesn't. return; } // delete the cell cells.push(cell.get("id")); }); if (cells.length == 0) return; this.jupyter_actions.delete_cells(cells, false); } private assign_save_checksums(): void { this.jupyter_actions.store.get("cells").forEach((cell) => { if (!cell.getIn(["metadata", "nbgrader", "solution"])) return; const cell2 = set_checksum(cell); if (cell !== cell2) { // set nbgrader metadata, which is all that should have changed this.jupyter_actions.set_cell_metadata({ id: cell.get("id"), metadata: { nbgrader: cell2.get("nbgrader") }, merge: true, save: false, }); } }); } private assign_unlock_all_cells(): void { this.jupyter_actions.store.get("cells").forEach((cell) => { if (cell == null || !cell.getIn(["metadata", "nbgrader", "locked"])) return; for (const key of ["editable", "deletable"]) { this.jupyter_actions.set_cell_metadata({ id: cell.get("id"), metadata: { [key]: true }, merge: true, save: false, }); } }); } private assign_lock_readonly_cells(): void { // For every cell for which the nbgrader metadata says it should be locked, set // the editable and deletable metadata to false. // "metadata":{"nbgrader":{"locked":true,... //console.log("assign_lock_readonly_cells"); this.jupyter_actions.store.get("cells").forEach((cell) => { const nbgrader = cell?.getIn(["metadata", "nbgrader"]) as any; if (!nbgrader) return; // We don't allow student to delete *any* cells with any // nbgrader metadata. this.jupyter_actions.set_cell_metadata({ id: cell.get("id"), metadata: { deletable: false }, merge: true, save: false, }); if (nbgrader.get("locked")) { // In addition, explicitly *locked* cells also can't be edited: this.jupyter_actions.set_cell_metadata({ id: cell.get("id"), metadata: { editable: false }, merge: true, save: false, }); } }); } public ensure_grade_ids_are_unique(): void { const grade_ids = new Set<string>(); const cells = this.jupyter_actions.store.get("cells"); let changed: boolean = false; // did something change. cells.forEach((cell, id: string): void => { if (cell == null) return; const nbgrader = cell.getIn(["metadata", "nbgrader"]) as any; if (nbgrader == null) return; let grade_id = nbgrader.get("grade_id"); if (grade_ids.has(grade_id)) { let n = 0; while (grade_ids.has(grade_id + `${n}`)) { n += 1; } grade_id = grade_id + `${n}`; this.set_metadata(id, { grade_id }, false); changed = true; } grade_ids.add(grade_id); }); if (changed) { this.jupyter_actions._sync(); } } }
import React from 'react'; import { useNavigate } from 'react-router-dom'; import { useWindowDimensions } from '../../../../hooks'; function CustomerListTable({ listData }) { const { width } = useWindowDimensions(); const navigate = useNavigate(); const isDesktop = width >= 768; return ( <div className="customers-table-wrap"> <table className="w-full"> <tr> <th>설치일</th> <th>고객명</th> <th>연락처</th> {isDesktop && <th>주소</th>} {isDesktop ? <th>모델명</th> : <th>설치 제품</th>} </tr> {listData?.length > 0 && listData.map(item => { // const { createdAt, id, name, contact, product, address } = item; const { createdAt, id, clientName, clientPhone, clientAddress, productModelName, } = item; const parts = createdAt?.split(' '); const datePart = parts[0]; return ( <tr className="cursor-pointer" key={id} onClick={() => { navigate(`/customers/${id}/edit`); }} > <td>{datePart}</td> <td>{clientName}</td> <td>{clientPhone}</td> {isDesktop && <td>{clientAddress}</td>} <td>{productModelName}</td> </tr> ); })} </table> </div> ); } export default CustomerListTable;
import { useEffect, useState } from "react"; const ENDPOINT = "https://api.ensideas.com/ens/resolve"; const cache = new Map<string, string>(); export function useEnsName(address?: string) { const [value, setValue] = useState<string | undefined>(); useEffect(() => { let isCancelled = false; async function main(address: string) { const cachedEnsName = cache.get(address); if (cachedEnsName && cachedEnsName !== value) { setValue(cachedEnsName); return; } const response = await fetch(`${ENDPOINT}/${address}`); const json = (await response.json()) as { name: string } | undefined; if (!isCancelled && json?.name) { cache.set(address, json.name); setValue(json.name); } } if ( address && address !== "0x0000000000000000000000000000000000000000" && !address.includes(".") ) { main(address); } return () => { isCancelled = true; }; // We don't want to re-compute if the value changes, only when the address changes // eslint-disable-next-line react-hooks/exhaustive-deps }, [address]); return value; }
/* eslint-disable @typescript-eslint/no-floating-promises */ import { renderHook } from "@testing-library/react-hooks"; import { useLogout } from "./useLogOut"; import { FlowType } from "../types"; import nock from "nock"; describe("useLogOutHook", () => { describe("with API FlowType", () => { it("#logout should not throw on a succesful logout", async () => { nock("https://kratos.local/") .delete("/self-service/logout/api") .reply(204); const { result } = renderHook(() => useLogout({ flowType: FlowType.API, kratos: { basePath: "https://kratos.local" }, }), ); expect(result.current.logout).toBeDefined(); expect( result.current.logout({ sessionToken: "valid-token" }), ).resolves.not.toThrow(); }); it("#logout should handle an invalid session", () => { nock("https://kratos.local/") .delete("/self-service/logout/api") .reply(403); const { result } = renderHook(() => useLogout({ flowType: FlowType.API, kratos: { basePath: "https://kratos.local" }, }), ); expect(result.current.logout).toBeDefined(); expect( result.current.logout({ sessionToken: "invalid-token" }), ).rejects.toThrowError(); }); }); });
/* Name, hw2.c, CS 24000, Spring 2023 * Last updated December 3, 2022 */ /* Add any includes here */ #include "hw2.h" #include <stddef.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <math.h> /* Define your functions here */ /* * This function calculates the average speed for a manufacturer * from a file containing information for different racing teams * and their cars. It takes the file which has the different cars' * information and the manufacturer we are trying to find the average * speed of their cars for. */ float average_speed_of_manufacturer(char *file_name, char *manufacturer) { FILE *fp = NULL; fp = fopen(file_name, "r"); if (!fp) { return FILE_READ_ERR; //return error if file doesn't exist } //declare vars for use in reading info from file char id_buffer[MAX_ID_LENGTH]; char manf_buffer[MAX_FIELD_LENGTH]; float test_distance = 0.0; float test_time = 0.0; int pitstops = 0; int distance = 0; float pitstop_time = 0.0; float cost = 0.0; double breakdown_rate = 0.0; float avg_speed = 0.0; int car_count = 0; int success = 0; while (1) { success = fscanf(fp, "%4[^,],%49[^,],%fkm,%fs,%d/%d/%f,$%f,%lf%%\n", id_buffer, manf_buffer, &test_distance, &test_time, &pitstops, &distance, &pitstop_time, &cost, &breakdown_rate); //read information from file if ((success < 9) && (success != -1)) { fclose(fp); fp = NULL; return BAD_RECORD; //return error if have corrupted data points in file } if (success == -1) { break; //break out of while loop if EOF } if (strcmp(manf_buffer, manufacturer) == 0) { car_count++; avg_speed += ((test_distance * 1000) / test_time); //compute average speed } } if (car_count == 0) { fclose(fp); fp = NULL; return NO_DATA_POINTS; //return error if no cars for given manufacturer } avg_speed = avg_speed / car_count; fclose(fp); fp = NULL; return avg_speed; } /* average_speed_of_manufacturer() */ /* * This function calculates the expected number of pitstops for the given id, * which is given as a parameter and corresponds to an entry in the file. It * is found by dividing the distance from the RACE LENGTH, and then * multiplying by the amount of pitstops per distance. It takes in the file * name and the id we are looking for as parameters. */ int expected_pitstops(char *file_name, char *id) { FILE *fp = NULL; fp = fopen(file_name, "r"); if (!fp) { return FILE_READ_ERR; //return error if file doesn't exist } //declare vars for use in reading info from file char id_buffer[MAX_ID_LENGTH]; char manf_buffer[MAX_FIELD_LENGTH]; float test_distance = 0.0; float test_time = 0.0; int pitstops = 0; int distance = 0; float pitstop_time = 0.0; float cost = 0.0; double breakdown_rate = 0.0; int success = 0; float expected_pitstops = 0.0; int id_count = 0; if (strlen(id) > MAX_ID_LENGTH) { fclose(fp); fp = NULL; return BAD_ID; } for (int i = 0; i < MAX_ID_LENGTH - 1; i++) { if (isdigit(id[i]) == 0) { fclose(fp); fp = NULL; return BAD_ID; } } while (1) { success = fscanf(fp, "%4[^,],%49[^,],%fkm,%fs,%d/%d/%f,$%f,%lf%%\n", id_buffer, manf_buffer, &test_distance, &test_time, &pitstops, &distance, &pitstop_time, &cost, &breakdown_rate); //read information from file if ((success < 9) && (success != -1)) { fclose(fp); fp = NULL; return BAD_RECORD; //return error if there are corrupted data points in file } if (success == -1) { break; //break out of while loop if EOF } if (strcmp(id_buffer, id) == 0) { id_count++; expected_pitstops = (RACE_LENGTH / (float)distance) * pitstops; expected_pitstops = ceil(expected_pitstops); } } if (id_count == 0) { fclose(fp); fp = NULL; return NO_DATA_POINTS; } fclose(fp); fp = NULL; return (int)expected_pitstops; } /* expected_pitstops() */ /* * This function finds the max total pitstop time for the given manufacturer * that is given as a parameter. It is found by traversing through the file, * calculating the total pitstop time for each entry corresponding to the * manufacturer, and then returning the max one. It takes the file name and * the manufacturer name as parameters. */ float find_max_total_pitstop(char *file_name, char *manufacturer) { FILE *fp = NULL; fp = fopen(file_name, "r"); if (!fp) { return FILE_READ_ERR; //return error if file doesn't exist } //declare vars for use in reading info from file char id_buffer[MAX_ID_LENGTH]; char manf_buffer[MAX_FIELD_LENGTH]; float test_distance = 0.0; float test_time = 0.0; int pitstops = 0; int distance = 0; float pitstop_time = 0.0; float cost = 0.0; double breakdown_rate = 0.0; int pitstop_count = 0; float total_time = 0.0; float temp_max = 0.0; int success = 0; while (1) { success = fscanf(fp, "%4[^,],%49[^,],%fkm,%fs,%d/%d/%f,$%f,%lf%%\n", id_buffer, manf_buffer, &test_distance, &test_time, &pitstops, &distance, &pitstop_time, &cost, &breakdown_rate); //read information from file if ((success < 9) && (success != -1)) { fclose(fp); fp = NULL; return BAD_RECORD; //return error if have corrupted data points in file } if (success == -1) { break; //break out of while loop if EOF } if (strcmp(manf_buffer, manufacturer) == 0) { pitstop_count++; total_time = (float)expected_pitstops(file_name, id_buffer) * pitstop_time; if (total_time > temp_max) { temp_max = total_time; } } } if (pitstop_count == 0) { fclose(fp); fp = NULL; return NO_DATA_POINTS; //return error if there are no data } fclose(fp); fp = NULL; total_time = temp_max; return total_time; } /* find_max_total_pitstop() */ /* * This function generates a cost report for a given file. What this means is * that for every entry in the in_file, There will be a expected cost report * generated that finds the expected breakdown cost for every entry. This is * done by multiplying the cost by the breakdown rate. This function takes in * the in_file we are reading from and the out_file we are writing to as * parameters. */ int generate_expected_cost_report(char *in_file, char *out_file) { FILE *fp_in = NULL; fp_in = fopen(in_file, "r"); if (!fp_in) { return FILE_READ_ERR; //return error if file doesn't exist } FILE *fp_out = NULL; fp_out = fopen(out_file, "w"); if (!fp_out) { fclose(fp_in); fp_in = NULL; return FILE_WRITE_ERR; } //declare vars for use in reading info from file char id_buffer[MAX_ID_LENGTH]; char manf_buffer[MAX_FIELD_LENGTH]; float test_distance = 0.0; float test_time = 0.0; int pitstops = 0; int distance = 0; float pitstop_time = 0.0; float cost = 0.0; double breakdown_rate = 0.0; int data_count = 0; float expected_br_cost = 0.0; int success = 0; while (1) { success = fscanf(fp_in, "%4[^,],%49[^,],%fkm,%fs,%d/%d/%f,$%f,%lf%%\n", id_buffer, manf_buffer, &test_distance, &test_time, &pitstops, &distance, &pitstop_time, &cost, &breakdown_rate); //read information from file if ((success < 9) && (success != -1)) { fclose(fp_in); fclose(fp_out); fp_in = NULL; fp_out = NULL; return BAD_RECORD; //return error if have corrupted data points in file } if (success == -1) { break; //break out of while loop if EOF } data_count++; expected_br_cost = cost * (breakdown_rate / 100.0); fprintf(fp_out, "Car number %s made by %s has a breakdown cost expectancy of $%.2f.\n", id_buffer, manf_buffer, expected_br_cost); } if (data_count == 0) { fclose(fp_in); fclose(fp_out); fp_in = NULL; fp_out = NULL; return NO_DATA_POINTS; } fclose(fp_in); fclose(fp_out); fp_in = NULL; fp_out = NULL; return OK; } /* generate_expected_cost_report() */ /* Remember, you don't need a main function! * It is provided by hw2_main.c or hw2_test.o /
/* eslint-disable no-unused-vars */ /* global $ */ console.log("Document ready"); $("#fact-button").on("click", function () { displayFact(); }); $("#name-input").on("keypress", function (e) { if (e.which === 13) { displayFact(); } }); /** * Calculates the length of the text entered in the name input field. * @returns {number} The length of the text entered, excluding spaces. Returns 0 if no text is entered. */ function getLen() { let text = $("#name-input").val(); if (text !== undefined) { let count = 0; for (let i = 0; i < text.length; i++) { if (text[i] !== " ") { count++; } } return count; } else { return 0; } } /** * Retrieves the spirit animal based on the input name. * @returns {string} The spirit animal. */ function getSpiritAnimal() { let text = $("#name-input").val(); if (text !== undefined) { let animals = [ "Cat", "Dog", "Elephant", "Lion", "Tiger", "Bear", "Wolf", "Fox", "Horse", "Eagle" ]; let index = text.length % animals.length; return animals[index]; } else { return "No name"; } } /** * Displays various facts about the user's name. */ function displayFact() { let text = $("#name-input").val(); text = sanitizeInput(); let fact = `${text} is ${getLen()} characters long.`; $("#length").hide().text(fact).fadeIn(); $("#fact").hide().text(`Random Fact: ${randomFacts()}`).fadeIn(); $("#fact").hide().text(`Random Fact: ${randomFacts()}`).fadeIn(); $("#animal") .hide() .text(`Your spirit animal is: ${getSpiritAnimal()}`) .fadeIn(); $("#first-letter") .hide() .text(`The first letter of your name is: ${text[0]}`) .fadeIn(); $("#last-letter") .hide() .text(`The last letter of your name is: ${text[text.length - 1]}`) .fadeIn(); $("#num-vowels") .hide() .text( getVowels() === 0 ? "Your name has no vowels" : getVowels() === 1 ? "Your name has 1 vowel" : `Your name has ${getVowels()} vowels` ) .fadeIn(); } /** * Generates a random fact from an array of facts. * @returns {string} A random fact. */ function randomFacts() { let facts = [ "Ants stretch when they wake up in the morning.", "Ostriches can run faster than horses.", "Olympic gold medals are actually made mostly of silver.", "You are born with 300 bones; by the time you are an adult you will have 206.", "It takes about 8 minutes for light from the Sun to reach Earth.", "Some bamboo plants can grow almost a meter in just one day.", "The state of Florida is bigger than England.", "Some penguins can leap 2-3 meters out of the water.", "On average, it takes 66 days to form a new habit.", "Mammoths still walked the Earth when the Great Pyramid was being built.", "Rabbit's teeth never stop growing.", "The average person spends 6 months of their lifetime waiting on a red light to turn green." ]; let index = Math.floor(Math.random() * facts.length); return facts[index]; } // eslint-disable-next-line no-unused-vars function refreshPage() { window.location.reload(); } /** * Calculates the number of vowels in the input text. * * @returns {number} The count of vowels in the input text. */ function getVowels() { let text = $("#name-input").val(); if (text !== undefined) { let count = 0; for (let i = 0; i < text.length; i++) { if ( text[i].toLowerCase() === "a" || text[i].toLowerCase() === "e" || text[i].toLowerCase() === "i" || text[i].toLowerCase() === "o" || text[i].toLowerCase() === "u" ) { count++; } } return count; } else { return 0; } } // eslint-disable-next-line no-unused-vars function validate_input() { let data = $("#name-input").val().trim(); if (data.length === 0) { return null; } return data; } /** * Reverses a given string. * * @param {string} name - The string to be reversed. * @returns {string} - The reversed string. */ // eslint-disable-next-line no-unused-vars function reverseString(name) { return name.split("").reverse().join(""); } function sanitizeInput() { let data = $("#name-input").val().trim(); data = data.replace(/[^a-zA-Z\s]/g, ""); return data; }
### 异步任务DEMO #### 1.传统的显式的 new Thread实现 ```$xslt public class Mythread { public static void main(String[] args) { //使用匿名内部类的方式执行多线程 Thread th1= new Thread("custom"){ @Override public void run(){ for(int i=0;i<100;i++){ System.out.println(Thread.currentThread().getName()+"使用匿名内部类的方式创建多线程=>"+i); } } };//start调用了底层c++的方法,重写run方法,使用的是模板方法模式。 th1.start(); } } ``` #### 2、继承Thread类、实现Runnable接口、Callable接口 ```$xslt /** * 任务类 */ class Task implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + ":异步任务"); } } ``` #### 3.jdk1.8之后可以使用Lambda 表达式 本质和第一种是一样的。 ```$xslt //新建线程并执行任务类 new Thread(() -> { System.out.println(Thread.currentThread().getName() + ":异步任务"); }).start(); ``` #### 4.线程池 ```$xslt public static void main (String args[]) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); for(int i = 0 ; i < 10 ; i ++){ final int num = i; Thread.sleep(i*1000); executorService.execute(new Runnable() { @Override public void run() { System.out.println(num); } }); } } ``` 异步线程池 ```$xslt @Service public class AsyncTaskDemoService { @Autowired AsyncTaskExecutor asyncTaskExecutor;//注入线程池对象 public void asyncTask(){ //通过线程池对象提交异步任务 asyncTaskExecutor.submit(() -> { log.info("异步任务开始"); //省略异步任务业务逻辑... log.info("异步任务结束"); }); } } ```
package com.example.reflexionai.data.repository import android.util.Log import com.example.reflexionai.data.local.MovieDatabase import com.example.reflexionai.data.local.dao.MovieDao import com.example.reflexionai.model.MovieList import com.example.reflexionai.data.network.ApiService import com.example.reflexionai.model.Movie import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* class MovieRepository(private val movieDao: MovieDao) { fun getMoviesFromLocal(): Flow<List<Movie>> = movieDao.getAllMovies() fun getMovieList1(): Flow<MovieList> = flow { val response = ApiService .getApi() .getMovies1() saveToLocal(response) emit(response) }.flowOn(Dispatchers.IO) private suspend fun saveToLocal(response: MovieList) { movieDao.addMovies(response.movies) } fun getMovieList2(): Flow<MovieList> = flow { val response = ApiService .getApi() .getMovies2() saveToLocal(response) emit(response) }.flowOn(Dispatchers.IO) }
<?php namespace App\Http\Controllers; use App\Post; use Illuminate\Http\Request; use App\Http\Requests; use Mail; use Session; class PagesController extends Controller { public function getIndex(){ $posts = Post::orderBy('created_at','desc')->limit(4)->get(); return view('pages.welcome')->withPosts($posts); } public function getAbout(){ $first = 'Mihai'; $last = 'Cosinschi'; $fullname = $first. ' ' . $last; $email = 'micos7@gmail.com'; $data = []; $data['email'] = $email; $data['name'] = $fullname; return view('pages.about')->withData($data); } public function getContact(){ return view('pages.contact'); } public function postContact(Request $request){ $this->validate($request,[ 'email' => 'required|email', 'subject' => 'min:3', 'message' => 'min:10' ]); $data = array( 'email' => trim($request->email), 'subject' => $request->subject, 'bodyMessage' => $request->message ); Mail::send('emails.contact', $data, function($message) use ($data){ $message->from($data['email']); $message->to('micos7@gmail.com'); $message->subject($data['subject']); }); Session::flash('success', 'Your Email was Sent!'); return redirect('/'); } }
import { TicketCreatedEvent } from "@tixy/common"; import mongoose from "mongoose"; import { Ticket } from "../../../models/Ticket"; import { natsWrapper } from "../../../natsWrapper"; import { queueGroupName } from "../queueGroupName"; import { TicketCreatedListener } from "../ticketCreatedListener"; const setup = async () => { // Create an instance of the listener const listener = new TicketCreatedListener(natsWrapper.client); // Create a fake data event const data: TicketCreatedEvent["data"] = { version: 0, id: mongoose.Types.ObjectId().toHexString(), title: "concert", price: 10, userId: mongoose.Types.ObjectId().toHexString(), }; // Create a fake message object //@ts-ignore const msg: Message = { ack: jest.fn(), }; return { listener, data, msg }; }; it("creates and saves a ticket", async () => { const { listener, data, msg } = await setup(); //Call the onMessage function with the data object + message object await listener.onMessage(data, msg); // write assertions to make sure a ticket was created const ticket = await Ticket.findById(data.id); expect(ticket).toBeDefined(); expect(ticket!.title).toEqual(data.title); expect(ticket!.price).toEqual(data.price); }); it("acks message", async () => { const { listener, data, msg } = await setup(); //Call the onMessage function with the data object + message object await listener.onMessage(data, msg); expect(msg.ack).toHaveBeenCalled(); });
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #define MAXSTR 1000 int main(int argc, char *argv[]) { char line[MAXSTR]; int *page_table, *mem_map; unsigned int log_size, phy_size, page_size, d; unsigned int num_pages, num_frames; unsigned int offset, logical_addr, physical_addr, page_num, frame_num; /* Get the memory characteristics from the input file */ fgets(line, MAXSTR, stdin); if ((sscanf(line, "Logical address space size: %d^%d", &d, &log_size)) != 2) { fprintf(stderr, "Unexpected line 1. Abort.\n"); exit(-1); } fgets(line, MAXSTR, stdin); if ((sscanf(line, "Physical address space size: %d^%d", &d, &phy_size)) != 2) { fprintf(stderr, "Unexpected line 2. Abort.\n"); exit(-1); } fgets(line, MAXSTR, stdin); if ((sscanf(line, "Page size: %d^%d", &d, &page_size)) != 2) { fprintf(stderr, "Unexpected line 3. Abort.\n"); exit(-1); } num_pages = 1 << (log_size - page_size); num_frames = 1 << (phy_size - page_size); fprintf(stdout, "Number of Pages: %d, Number of Frames: %d\n\n", num_pages, num_frames); /* Allocate arrays to hold the page table and memory frames map */ page_table = (int *)malloc(num_pages * sizeof(int)); mem_map = (int *)malloc(num_frames * sizeof(int)); /* Initialize page table to indicate that no pages are currently mapped to physical memory */ memset(page_table, 0, num_pages * sizeof(int)); /* Initialize memory map table to indicate no valid frames */ memset(mem_map, 0, num_frames * sizeof(int)); unsigned temp = 0; frame_num = 0; /* Read each accessed address from input file. Map the logical address to corresponding physical address */ fgets(line, MAXSTR, stdin); while (!(feof(stdin))) { sscanf(line, "0x%x", &logical_addr); fprintf(stdout, "Logical Address: 0x%x\n", logical_addr); page_num = logical_addr >> page_size; offset = logical_addr & ((1 << page_size) - 1); fprintf(stdout, "Page Number: %d\n", page_num); if (page_table[page_num] == 0) { printf("Page Fault!\n"); printf("Frame Number: %d\n", temp); mem_map[temp] = offset; physical_addr = (temp << page_size) | offset; page_table[page_num] = temp + 1; temp++; } else { frame_num = page_table[page_num]; frame_num--; printf("Frame Number: %d\n", frame_num); physical_addr = (frame_num << page_size) | offset; } fprintf(stdout, "Physical Address: 0x%x\n\n", physical_addr); fgets(line, MAXSTR, stdin); } free(page_table); free(mem_map); return 0; }
<div class="component"> <h1>My phone book!</h1> <div class="component-input"> <input type="text" [(ngModel)]="field"> <button class="add" (click)="openForm()">add phone</button> </div> <div class="component-table"> <table> <tr> <th (click)="sort('firstName')" class="click">First name</th> <th (click)="sort('secondName')" class="click">Last name</th> <th (click)="sort('phone')" class="click">Number</th> <th>edit</th> <th>delete</th> </tr> <tr *ngFor="let contact of contactBook | search:field | sort:type:up; let i = index; "> <td>{{contact.firstName}}</td> <td>{{contact.secondName}}</td> <td>{{contact.phone}}</td> <td><button class="edit" (click)="editContact(i)">edit</button></td> <td><button class="delete" (click)="delContact(i)">delete</button></td> </tr> </table> </div> </div> <ng-container *ngIf="addPhone"> <div class="wrapper"> <div class="box"> <div class="box-head"> <span>Add phone</span> <div class="close" (click)="closeForm()">X</div> </div> <div class="box-main"> <input type="text" placeholder="first name goes here" [(ngModel)]="firstName"> <input type="text" placeholder="second name goes here" [(ngModel)]="secondName"> <input type="text" placeholder="number phone goes here" [(ngModel)]="phone"> </div> <div class="box-bottom"> <button class="save" (click)="addContact()">Save</button> </div> </div> </div> </ng-container>
import os import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.distributions import Beta, Categorical class ContinousActorNetwork(nn.Module): """ TLDR: This model is not a deterministic policy network, but a stochastic policy network. Even though it outputs a single action, it is actually a distribution of actions. The output is a Beta distribution, which is a distribution of probabilities. The Beta distribution is a continuous distribution, which is why it is used in this model. We are doing this since the PPO algorithm is a continuous action space algorithm. The Beta distribution is a continuous distribution Detailed: Implements the Proximal Policy Optimization (PPO) actor model for reinforcement learning in environments with continuous action spaces, utilizing stochastic policies. PPO is a policy gradient method designed to address the challenges of sample efficiency, stability, and reliable learning in deep reinforcement learning. By employing stochastic policies, PPO facilitates effective exploration and manages the complexity inherent in continuous action spaces. The algorithm's core features include: - Sample Efficiency: Optimizes the policy with an objective that encourages judicious updates, making efficient use of collected samples by limiting the magnitude of policy changes, thus maximizing learning from each interaction with the environment. - Stability and Reliability: Incorporates a clipping mechanism to prevent excessively large policy updates, ensuring gradual and stable learning progression. This feature is crucial in continuous action spaces where small adjustment can significantly impact performance. - Flexibility and Simplicity: PPO's straightforward implementation and its ability to perform well across a diverse set of environments make it a versatile tool for various applications, from robotics to game playing. - Exploration: The use of stochastic policies inherently promotes exploration by sampling actions from a probability distribution. This approach, coupled with entropy bonuses, helps the agent to explore the action space more thoroughly, aiding in the discovery of optimal strategies. PPO's implementation for continuous action spaces typically involves a policy network that outputs parameters of a distribution (e.g., Gaussian) from which actions are sampled. This design allows for both effective exploration and the nuanced control needed in continuous environments. Usage: Designed for use in environments with continuous action spaces where the agent's objective is to learn optimal or near-optimal policies through interaction and iterative improvement. PPO's combination of efficiency, stability, and exploration makes it particularly well-suited for complex tasks requiring continuous control decisions. """ def __init__(self, n_actions, input_dims, alpha, fc1_dims=128, fc2_dims=128, chkpt_dir='tmp/continous_actor', scenario=None): super().__init__() chkpt_dir += scenario if not os.path.exists(chkpt_dir): os.makedirs(chkpt_dir) self.checkpoint_file = os.path.join(chkpt_dir, 'actor_continuous_ppo') self.fc1 = nn.Linear(input_dims, fc1_dims) self.fc2 = nn.Linear(fc1_dims, fc2_dims) self.alpha = nn.Linear(fc2_dims, n_actions) self.beta = nn.Linear(fc2_dims, n_actions) self.optimizer = optim.Adam(self.parameters(), lr=alpha) self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu') self.to(self.device) def forward(self, state): """ The model outputs alpha and beta params of the Beta distribution. This is done to output a continuous value for each action between 0 and 1. The Beta distribution is a continuous distribution, which is why it is used in this model. Dosctring: Forward pass to predict the parameters of the Beta distribution for each action dimension. This model is designed for environments where actions are continuous and bounded within the [0, 1] interval. It outputs the alpha and beta parameters of the Beta distribution, which are used to model the policy's action selection mechanism. The Beta distribution is particularly suited for such tasks due to its flexibility in modeling behaviors ranging from deterministic to highly uncertain, all within the bounded [0, 1] range. :param self: The object instance. :param state: The input state tensor. :return: The Beta distribution with the predicted alpha and beta parameters. """ x = T.tanh(self.fc1(state)) x = T.tanh(self.fc2(x)) alpha = F.relu(self.alpha(x)) + 1.0 beta = F.relu(self.beta(x)) + 1.0 dist = Beta(alpha, beta) return dist def save_checkpoint(self): T.save(self.state_dict(), self.checkpoint_file) def load_checkpoint(self): self.load_state_dict(T.load(self.checkpoint_file)) class ContinuousCriticNetwork(nn.Module): def __init__(self, input_dims, alpha, fc1_dims=128, fc2_dims=128, chkpt_dir='models/', scenario=None): super(ContinuousCriticNetwork, self).__init__() chkpt_dir += scenario if not os.path.exists(chkpt_dir): os.makedirs(chkpt_dir) self.checkpoint_file = os.path.join(chkpt_dir, 'critic_continuous_ppo') self.fc1 = nn.Linear(input_dims, fc1_dims) self.fc2 = nn.Linear(fc1_dims, fc2_dims) self.v = nn.Linear(fc2_dims, 1) self.optimizer = optim.Adam(self.parameters(), lr=alpha) self.device = T.device('cuda:0' if T.cuda.is_available() else 'cpu') self.to(self.device) def forward(self, state): x = T.tanh(self.fc1(state)) x = T.tanh(self.fc2(x)) v = self.v(x) return v def save_checkpoint(self): T.save(self.state_dict(), self.checkpoint_file) def load_checkpoint(self): self.load_state_dict(T.load(self.checkpoint_file))
# Docs ## Overview The `docs` folder contains two subfolders - `user` and `contributor`. The `user` subfolder contains the end-user documentation, which is displayed on the [Kyma website](https://kyma-project.io/#/). Depending on your module needs, the subfolder must include overview, usage, or technical reference documents. To display the content on the website properly, create a `_sidebar.md` file in the `user` subfolder and list the documents it contains there. For more information on how to publish user documentation, follow [this guide](https://github.com/kyma-project/community/blob/main/docs/guidelines/content-guidelines/01-user-docs.md). The `contributor` subfolder includes any developer-related documentation to help them manually install, develop, and operate a module. To have a common structure across all modules, all documents must be properly numbered according to the following structure: > **NOTE:** It is suggested to use the following titles if you have the content that matches them; otherwise use your own, more suitable titles, or simply skip the ones you find irrelevant. - 00-xx-overview - 01-xx-tutorial/configuration - 02-xx-usage - 03-xx-troubleshooting where `xx` is the number of the given document. For example: ```bash 00-00-overview-telemetry-manager 00-10-overview-logs 00-20-overview-traces 00-30-overview-metrics 01-10-configure-logs 01-20-configure-traces 01-30-configure-metrics 02-10-use-logs 02-20-use-traces 02-30-use-metrics (...) ``` > **NOTE:** Before introducing [docsify](https://docsify.js.org/#/?id=docsify), we agreed to use the `10`, `20`, `30` numbering. It was to help maintain the proper order of docs if they were rendered automatically on the website. With docsify, you manually add the content to the `_sidebar.md` file, and docs are displayed in the order you add them. However, this numbering is still recommended to have the unified structure of the docs in the module repositories. If you have other content that does not fit into the above topics, create your own 04-10-module-specific document(s). You can divide your documentation into subfolders to avoid having too many documents in one `docs/user` or `docs/contributor` folder. For example, if you have many technical reference documents, you can create a `technical reference` subfolder in `docs/user` and keep relevant documentation there. Each subfolder in the `user` folder must have its own `_sidebar.md` file with the links to the main module page and the list of docs it contains.
import { Injectable } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model, Types } from 'mongoose'; import { IUser } from '@users/schemas/user.schema'; import { UserDto } from '@users/dtos/user.dto'; @Injectable() export class UsersService { public constructor( @InjectModel('Users') private readonly _userModel: Model<IUser>, ) {} public async create(user: UserDto): Promise<IUser> { try { const newUser = new this._userModel(user); return newUser.save(); } catch (e) { return null; } } public async findUserById(id: string): Promise<IUser> { try { return this._userModel .findById( { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore _id: Types.ObjectId(id), }, { __V: 0 }, ) .lean(); } catch (e) { return null; } } public async findUserByLogin(login: string): Promise<IUser> { try { return this._userModel .findOne( { login, }, { __V: 0 }, ) .lean(); } catch (e) { return null; } } public async findUsers(): Promise<IUser[]> { try { return this._userModel.find({}, { __V: 0 }).exec(); } catch (e) { return null; } } public async updateUser(id: string, user: UserDto): Promise<any> { try { return ( this._userModel // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore .findOneAndUpdate({ _id: Types.ObjectId(id) }, { $set: user }) .exec() ); } catch (e) { return null; } } public async removeUser(id: string): Promise<any> { try { return ( this._userModel // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore .findOneAndRemove({ _id: Types.ObjectId(id) }) .exec() ); } catch (e) { return null; } } }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300&display=swap" rel="stylesheet"> <title>Calculadora</title> </head> <body> <div> <input class="display"> <button class="gray-button" onclick="limpaTela()">AC</button> <button class="gray-button" onclick="inverterNumero()">+/-</button> <button class="blue-button" onclick="adicionarCaracter('/')">/</button> <button class="blue-button" onclick="adicionarCaracter('*')">*</button> <button class="black-button" onclick="adicionarCaracter('7')">7</button> <button class="black-button" onclick="adicionarCaracter('8')">8</button> <button class="black-button" onclick="adicionarCaracter('9')">9</button> <button class="blue-button" onclick="adicionarCaracter('-')">-</button> <button class="black-button" onclick="adicionarCaracter('4')">4</button> <button class="black-button" onclick="adicionarCaracter('5')">5</button> <button class="black-button" onclick="adicionarCaracter('6')">6</button> <button class="blue-button" onclick="adicionarCaracter('+')">+</button> <button class="black-button" onclick="adicionarCaracter('1')">1</button> <button class="black-button" onclick="adicionarCaracter('2')">2</button> <button class="black-button" onclick="adicionarCaracter('3')">3</button> <button class="equal-button equal" onclick="calcular()">=</button> <button class="black-button zero" onclick="adicionarCaracter('0')">0</button> <button class="black-button" onclick="adicionarCaracter()">.</button> </div> <script> function adicionarCaracter(caracter){ const display = document.querySelector(".display").value document.querySelector(".display").value = display + caracter } function limpaTela(){ document.querySelector(".display").value = "" } function calcular(){ const display = document.querySelector(".display").value document.querySelector(".display").value = eval(display) } function inverterNumero(){ const display = document.querySelector(".display").value document.querySelector(".display").value = display * -1 } </script> </body> </html>
# trilha-testes-manuais-funcionais Com esse desafio, foi realizada toda a documentação e preparação de testes para o desenvolvimento de uma loja virtual. Para maiores informações, consultar documento **Testes Manuais Funcionais.pdf** Para isso, foram realizadas as seguintes etapas: * Criação de um ambiente colaborativo **JIRA** ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/9ccae97c-cf55-44c4-975b-d18c11f837ea) * Definição dos tipos de Item que compõem o projeto: ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/9229ab28-da28-45f5-ad90-507403a3d2e4) ## Planos de Fluxo de Trabalho * Fluxo de trabalho ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/3f648c0c-03be-4cf5-89d8-d91dc944ecef) * Ciclo de vida do Bug ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/960c5873-3781-4c90-83f0-507ba9eb7f67) ## Criação de User stories 1. Como usuário, desejo acessar a página de login na loja virtual a fim de visualizar as opções de login, cadastro e redefinição de senha ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/55d88a16-2d97-41d6-8d8f-69cf45113805) ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/4a1dc45a-0a39-4e43-bbea-45c65fe1fd7e) 2. Como usuário, desejo preencher o formulário para criação de conta na loja virtual, a fim de criar o meu cadastro de acesso ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/f20822a6-6410-4dd1-8350-fe9218f6253c) ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/bacc95c5-0a8c-4f89-bc39-30ab6399d4b7) 3. Como usuário, desejo acessar a página de login na loja virtual a fim de efetuar meu login no sistema ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/7227d078-fff5-4778-a3c1-bce04fa836dc) ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/60d47f8a-c63b-48d9-a1c2-e6ec2e2be86b) ## Mind-Maps ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/c3d2a66d-16a4-43ae-8a5c-16da4fc6374e) ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/a68f9cc5-5f84-4ce2-8998-8d8f2870a424) ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/553487db-d8e3-4c92-ab13-ef0efbbf7813) ## Ciclo de Testes ![image](https://github.com/ViniciusBenevidesdaSilva/trilha-testes-manuais-funcionais/assets/105802950/a10c86f9-7c6d-4afe-b0f4-f77ad9cc682b) ### US_1 – Navegação Login 1. Cliente navega por entre as telas de login e cadastro **Given** que o cliente esteja na tela de login **And** não esteja cadastrado no sistema, **When** clicar em 'Sign Up', **Then** será redirecionado para uma tela de criação de nova conta 2. Cliente navega por entre as telas de login e Forgot your password **Given** que o cliente esteja na tela de login **And** não esteja cadastrado no sistema, **When** clicar em 'Forgot your password', **Then** será redirecionado para uma tela de recuperação de senha ### US_2 - Cadastro de usuário 1. Cliente deixa campos em branco no cadastro **Given** que o cliente esteja na tela de cadastro, **And** tenha deixado algum campo em branco, **When** clicar em 'Sign Up', **Then** receberá um alerta sobre o campo pendente 2. Cliente informa senha com menos de 3 caracteres **Given** que o cliente esteja na tela de cadastro, **And** tenha informado uma senha com menos de 3 caracteres, **When** clicar em 'Sign Up', **Then** receberá um alerta sobre a quantidade de caracteres da senha 3. Cliente informa um username ou e-mail já cadastrado **Given** que o cliente esteja na tela de cadastro, **And** tenha inserido um username ou e-mail já cadastrado, **When** clicar em 'Sign Up', **Then** receberá um alerta 4. Cliente informar data de nascimento inválida **Given** que o cliente esteja na tela de cadastro, **And** tenha preenchido uma senha posterior a data atual, **When** clicar em 'Sign Up', **Then** receberá um alerta 5. Cliente preenche os dados de cadastro corretamente **Given** que o cliente esteja na tela de cadastro, **And** tenha preenchido corretamente o formulário, **When** clicar em 'Sign Up', **Then** seu usuário será criado **And** ele será redirecionado para uma tela de login ### US_3 - Login usuário 1. Cliente com cadastro valido realiza login 1° Passo: Acessar url https://www.saucedemo.com/v1/index.html Resultado: Usuário deve visualizar tela de login 2° Passo: Usuário digita username no campo 'username' Dados de Teste: User_Test Resultado: Sistema aguarda próxima etapa 3° Passo: Usuário digita password no campo 'password' Dados de Teste: Password_Test Resultado: Sistema aguarda próxima etapa 4° Passo: Usuário clica no botão 'Login' Resultado: Sistema emite um alerta informando que o usuário é inválido 2. Cliente com senha inválida tenta fazer login 1° Passo: Acessar url https://www.saucedemo.com/v1/index.html Resultado: Usuário deve visualizar tela de login 2° asso: Usuário digita username no campo 'username' Dados de Teste: User_Test Resultado: Sistema aguarda próxima etapa 3° Passo: Usuário digita password no campo 'password' Dados de Teste: Password_Test Resultado: Sistema aguarda próxima etapa 4° Passo: Usuário clica no botão 'Login' Resultado: Sistema emite um alerta informando que a senha é inválida 3. Cliente sem cadastro tenta fazer login 1° Passo: Acessar url https://www.saucedemo.com/v1/index.html Resultado: Usuário deve visualizar tela de login 2° Passo: Usuário digita username no campo 'username' Dados de Teste: User_Test Resultado: Sistema aguarda próxima etapa 3° Passo: Usuário digita password no campo 'password' Dados de Teste: Password_Test Resultado: Sistema aguarda próxima etapa 4° Passo: Usuário clica no botão 'Login' Resultado: Direcionar usuário para url https://www.saucedemo.com/v1/inventory.html
import moment from 'moment'; import { useSocketContext } from '@context/socket'; import { roomService } from '@service/router'; import { GetUserRoomResponse } from '@service/user-room/types'; import { Button, List, Modal } from 'antd'; import { FC, Fragment, useState } from 'react'; import RequestModal from './request-modal'; type Props = { data: GetUserRoomResponse[]; open: boolean; onClose: () => void; }; const EventModal: FC<Props> = ({ data, open, onClose }) => { const { setOpenWaiting } = useSocketContext(); const [controlRoomId, setControlRoomId] = useState(''); const handleJoin = async (roomId: string) => { if (roomId) { const res = await roomService.joinRoomStudent({ room_id: roomId, }); if (res.data?.id) { onClose(); setControlRoomId(roomId); setOpenWaiting(true); } } }; return ( <Fragment> <Modal width="50vw" title={`Lịch thi ngày ${moment(data?.[0]?.tb_room?.start_date).format( 'DD/MM/YYYY' )}`} open={open} onCancel={onClose} footer={null} > <List itemLayout="horizontal" dataSource={data} renderItem={(item) => ( <List.Item actions={[ <Button key={item.id} type="primary" onClick={() => handleJoin(item?.room_id)} disabled={item?.status === '3' || item?.tb_room?.status === '2'} > Tham gia </Button>, ]} > {moment(item?.tb_room?.start_date).format('HH:mm DD/MM/YYYY')} -{' '} {item?.tb_room?.title} </List.Item> )} /> </Modal> <RequestModal roomId={controlRoomId} /> </Fragment> ); }; export default EventModal;
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import sys from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files if sys.version_info >= (3, 5): from typing import List, Any, Union class Lagportstaticlag(Base): """ The Lagportstaticlag class encapsulates a list of lagportstaticlag resources that are managed by the user. A list of resources can be retrieved from the server using the Lagportstaticlag.find() method. The list can be managed by using the Lagportstaticlag.add() and Lagportstaticlag.remove() methods. """ __slots__ = () _SDM_NAME = "lagportstaticlag" _SDM_ATT_MAP = { "Active": "active", "ConnectedVia": "connectedVia", "Count": "count", "DescriptiveName": "descriptiveName", "Errors": "errors", "LagId": "lagId", "Multiplier": "multiplier", "Name": "name", "SessionStatus": "sessionStatus", "StackedLayers": "stackedLayers", "StateCounts": "stateCounts", "Status": "status", } _SDM_ENUM_MAP = { "status": [ "configured", "error", "mixed", "notStarted", "started", "starting", "stopping", ], } def __init__(self, parent, list_op=False): super(Lagportstaticlag, self).__init__(parent, list_op) @property def Active(self): # type: () -> 'Multivalue' """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): Activate/Deactivate Configuration """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP["Active"])) @property def ConnectedVia(self): # type: () -> List[str] """DEPRECATED Returns ------- - list(str[None | /api/v1/sessions/1/ixnetwork/lag]): List of layers this layer is used to connect with to the wire. """ return self._get_attribute(self._SDM_ATT_MAP["ConnectedVia"]) @ConnectedVia.setter def ConnectedVia(self, value): # type: (List[str]) -> None self._set_attribute(self._SDM_ATT_MAP["ConnectedVia"], value) @property def Count(self): # type: () -> int """ Returns ------- - number: Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. """ return self._get_attribute(self._SDM_ATT_MAP["Count"]) @property def DescriptiveName(self): # type: () -> str """ Returns ------- - str: Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. """ return self._get_attribute(self._SDM_ATT_MAP["DescriptiveName"]) @property def Errors(self): """ Returns ------- - list(dict(arg1:str[None | /api/v1/sessions/1/ixnetwork/],arg2:list[str])): A list of errors that have occurred """ return self._get_attribute(self._SDM_ATT_MAP["Errors"]) @property def LagId(self): # type: () -> 'Multivalue' """ Returns ------- - obj(ixnetwork_restpy.multivalue.Multivalue): LAG ID """ from ixnetwork_restpy.multivalue import Multivalue return Multivalue(self, self._get_attribute(self._SDM_ATT_MAP["LagId"])) @property def Multiplier(self): # type: () -> int """ Returns ------- - number: Number of layer instances per parent instance (multiplier) """ return self._get_attribute(self._SDM_ATT_MAP["Multiplier"]) @Multiplier.setter def Multiplier(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP["Multiplier"], value) @property def Name(self): # type: () -> str """ Returns ------- - str: Name of NGPF element, guaranteed to be unique in Scenario """ return self._get_attribute(self._SDM_ATT_MAP["Name"]) @Name.setter def Name(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP["Name"], value) @property def SessionStatus(self): # type: () -> List[str] """ Returns ------- - list(str[down | notStarted | up]): Current state of protocol session: Not Started - session negotiation not started, the session is not active yet. Down - actively trying to bring up a protocol session, but negotiation is didn't successfully complete (yet). Up - session came up successfully. """ return self._get_attribute(self._SDM_ATT_MAP["SessionStatus"]) @property def StackedLayers(self): # type: () -> List[str] """ Returns ------- - list(str[None | /api/v1/sessions/1/ixnetwork/lag]): List of secondary (many to one) child layer protocols """ return self._get_attribute(self._SDM_ATT_MAP["StackedLayers"]) @StackedLayers.setter def StackedLayers(self, value): # type: (List[str]) -> None self._set_attribute(self._SDM_ATT_MAP["StackedLayers"], value) @property def StateCounts(self): """ Returns ------- - dict(total:number,notStarted:number,down:number,up:number): A list of values that indicates the total number of sessions, the number of sessions not started, the number of sessions down and the number of sessions that are up """ return self._get_attribute(self._SDM_ATT_MAP["StateCounts"]) @property def Status(self): # type: () -> str """ Returns ------- - str(configured | error | mixed | notStarted | started | starting | stopping): Running status of associated network element. Once in Started state, protocol sessions will begin to negotiate. """ return self._get_attribute(self._SDM_ATT_MAP["Status"]) def update(self, ConnectedVia=None, Multiplier=None, Name=None, StackedLayers=None): # type: (List[str], int, str, List[str]) -> Lagportstaticlag """Updates lagportstaticlag resource on the server. This method has some named parameters with a type: obj (Multivalue). The Multivalue class has documentation that details the possible values for those named parameters. Args ---- - ConnectedVia (list(str[None | /api/v1/sessions/1/ixnetwork/lag])): List of layers this layer is used to connect with to the wire. - Multiplier (number): Number of layer instances per parent instance (multiplier) - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - StackedLayers (list(str[None | /api/v1/sessions/1/ixnetwork/lag])): List of secondary (many to one) child layer protocols Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def add(self, ConnectedVia=None, Multiplier=None, Name=None, StackedLayers=None): # type: (List[str], int, str, List[str]) -> Lagportstaticlag """Adds a new lagportstaticlag resource on the server and adds it to the container. Args ---- - ConnectedVia (list(str[None | /api/v1/sessions/1/ixnetwork/lag])): List of layers this layer is used to connect with to the wire. - Multiplier (number): Number of layer instances per parent instance (multiplier) - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - StackedLayers (list(str[None | /api/v1/sessions/1/ixnetwork/lag])): List of secondary (many to one) child layer protocols Returns ------- - self: This instance with all currently retrieved lagportstaticlag resources using find and the newly added lagportstaticlag resources available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._create(self._map_locals(self._SDM_ATT_MAP, locals())) def remove(self): """Deletes all the contained lagportstaticlag resources in this instance from the server. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ self._delete() def find( self, ConnectedVia=None, Count=None, DescriptiveName=None, Errors=None, Multiplier=None, Name=None, SessionStatus=None, StackedLayers=None, StateCounts=None, Status=None, ): """Finds and retrieves lagportstaticlag resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve lagportstaticlag resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the find method takes no parameters and will retrieve all lagportstaticlag resources from the server. Args ---- - ConnectedVia (list(str[None | /api/v1/sessions/1/ixnetwork/lag])): List of layers this layer is used to connect with to the wire. - Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group. - DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed to be unique like -name-, but may offer more context. - Errors (list(dict(arg1:str[None | /api/v1/sessions/1/ixnetwork/],arg2:list[str]))): A list of errors that have occurred - Multiplier (number): Number of layer instances per parent instance (multiplier) - Name (str): Name of NGPF element, guaranteed to be unique in Scenario - SessionStatus (list(str[down | notStarted | up])): Current state of protocol session: Not Started - session negotiation not started, the session is not active yet. Down - actively trying to bring up a protocol session, but negotiation is didn't successfully complete (yet). Up - session came up successfully. - StackedLayers (list(str[None | /api/v1/sessions/1/ixnetwork/lag])): List of secondary (many to one) child layer protocols - StateCounts (dict(total:number,notStarted:number,down:number,up:number)): A list of values that indicates the total number of sessions, the number of sessions not started, the number of sessions down and the number of sessions that are up - Status (str(configured | error | mixed | notStarted | started | starting | stopping)): Running status of associated network element. Once in Started state, protocol sessions will begin to negotiate. Returns ------- - self: This instance with matching lagportstaticlag resources retrieved from the server available through an iterator or index Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._select(self._map_locals(self._SDM_ATT_MAP, locals())) def read(self, href): """Retrieves a single instance of lagportstaticlag data from the server. Args ---- - href (str): An href to the instance to be retrieved Returns ------- - self: This instance with the lagportstaticlag resources from the server available through an iterator or index Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ return self._read(href) def Abort(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the abort operation on the server. Abort CPF control plane (equals to demote to kUnconfigured state). The IxNetwork model allows for multiple method Signatures with the same name while python does not. abort(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. abort(SessionIndices=list, async_operation=bool) ------------------------------------------------ - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. abort(SessionIndices=string, async_operation=bool) -------------------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = {"Arg1": self} for i in range(len(args)): payload["Arg%s" % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute("abort", payload=payload, response_object=None) def RestartDown(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the restartDown operation on the server. Stop and start interfaces and sessions that are in Down state. The IxNetwork model allows for multiple method Signatures with the same name while python does not. restartDown(async_operation=bool) --------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. restartDown(SessionIndices=list, async_operation=bool) ------------------------------------------------------ - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. restartDown(SessionIndices=string, async_operation=bool) -------------------------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = {"Arg1": self} for i in range(len(args)): payload["Arg%s" % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute("restartDown", payload=payload, response_object=None) def Start(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the start operation on the server. Start CPF control plane (equals to promote to negotiated state). The IxNetwork model allows for multiple method Signatures with the same name while python does not. start(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. start(SessionIndices=list, async_operation=bool) ------------------------------------------------ - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. start(SessionIndices=string, async_operation=bool) -------------------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = {"Arg1": self} for i in range(len(args)): payload["Arg%s" % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute("start", payload=payload, response_object=None) def Stop(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the stop operation on the server. Stop CPF control plane (equals to demote to PreValidated-DoDDone state). The IxNetwork model allows for multiple method Signatures with the same name while python does not. stop(async_operation=bool) -------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. stop(SessionIndices=list, async_operation=bool) ----------------------------------------------- - SessionIndices (list(number)): This parameter requires an array of session numbers 1 2 3 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. stop(SessionIndices=string, async_operation=bool) ------------------------------------------------- - SessionIndices (str): This parameter requires a string of session numbers 1-4;6;7-12 - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = {"Arg1": self} for i in range(len(args)): payload["Arg%s" % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute("stop", payload=payload, response_object=None) def get_device_ids(self, PortNames=None, Active=None, LagId=None): """Base class infrastructure that gets a list of lagportstaticlag device ids encapsulated by this object. Use the optional regex parameters in the method to refine the list of device ids encapsulated by this object. Args ---- - PortNames (str): optional regex of port names - Active (str): optional regex of active - LagId (str): optional regex of lagId Returns ------- - list(int): A list of device ids that meets the regex criteria provided in the method parameters Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._get_ngpf_device_ids(locals())
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * datacenter-config.h * * Created on: Oct 19, 2015 * Author: ubaid */ #ifndef DATACENTER_CONFIG #define DATACENTER_CONFIG #include "ns3/nstime.h" #include "ns3/callback.h" #include "processing-power-util.h" #include "storage-util.h" #include "application-size-util.h" #include "nutshell-data-collector.h" namespace ns3 { /** * \brief The class defines generic properties of datacenter * to be configured by user. * * This class is an interface between the Architecture creating * classes and User requirement. The class define generic * configuration data structure to hold the user requirement. * The architecture creating classes use configuration * object of this or its child class to create the * datacenter architecture. */ class DatacenterConfig { public: /** * \brief ENUM to define the distribution */ enum Procedure_e { RANDOM }; /** * \brief Class constructor */ DatacenterConfig(); /** * \brief Configures Node with different minimum and maximum values * for resources * \param pmin The minimum processing power * \param pmax The maximum processing power * \param psmin The minimum primary storage * \param psmax The maximum primary storage * \param ssmin The minimum secondary storage * \param ssmax The maximum secondary storage */ void ConfigureNode(const std::string pmin, const std::string pmax, const std::string psmin, const std::string psmax, const std::string ssmin, const std::string ssmax); /** * \brief Configures Node with same resources i.e homogeneous resources * \param processing The processing power * \param primary The primary storage * \param secondary The secondary storage */ void ConfigureNode(const std::string processing, const std::string primary, const std::string secondary); /** * \brief Configures VM general properties with different minimum and maximum values * for resources and application size * \param vmNum The number of VM to create * \param pmin The minimum processing power * \param pmax The maximum processing power * \param psmin The minimum primary storage * \param psmax The maximum primary storage * \param ssmin The minimum secondary storage * \param ssmax The maximum secondary storage * \param appSizeMin The minimum application size * \param appSizeMax The maximum application size */ void ConfigureVmGeneral(const uint32_t vmNum, const std::string pmin, const std::string pmax, const std::string psmin, const std::string psmax, const std::string ssmin, const std::string ssmax, const std::string appSizeMin, const std::string appSizeMax); /** * \brief Configures the VM data requirement with different minimum and maximum values * \param require The flag to set if VMs require data * \param numOfVmWithServerDataSrc The number of VMs to have Server for data source * \param distribution The distribution * \param dAmountMin The minimum data amount * \param dAmountMax The maximum data amount * \param hddRwRateMin The minimum read/write rate of HDD * \param hddRwRateMax The maximum read/write rate of HDD * \param memRwRateMin The minimum read/write rate of RAM * \param memRwRateMax The maximum read/write rate of RAM * \param numOfProcAccessMin The minimum number of data access by processor * \param numOfProcAccessMax The maximum number of data access by processor * \param memPdfMin The minimum percentage of Memory for data fetching * \param memPdfMax The maximum percentage of Memory for data fetching * \param hddMinAccT The minimum HDD access time * \param hddMaxAccT The maximum HDD access time * \param memMinAccT The minimum memory access time * \param memMaxAccT The maximum memory access time */ void ConfigureVmDataReq(bool require, uint32_t numOfVmWithServerDataSrc, Procedure_e distribution, std::string dAmountMin, std::string dAmountMax, std::string hddRwRateMin, std::string hddRwRateMax, std::string memRwRateMin, std::string memRwRateMax, uint32_t numOfProcAccessMin, uint32_t numOfProcAccessMax, double memPdfMin, double memPdfMax, Time hddMinAccT, Time hddMaxAccT, Time memMinAccT, Time memMaxAccT); /** * \brief Configure VM split, to perform VM execution on different * Nodes in case not enough resources are available. * * \param enable The flag to enable VM splitting * \param ratio The ratio at which the VM is supposed to be split. */ void ConfigureVmSplits(bool enable, std::string ratio); /** * \brief Configure VM arrival time with different values * \param min The minimum time of VM arrival * \param max The maximum time of VM arrival * */ void ConfigureVmArrivals(Time min, Time max); /** * \brief Configure VM Network properties with different values * \param mtu The Maximum Transmission Unit * \param protocolType The protocol to use for communication e.g ns3::TcpSocketFactory * \param vmTransRateMin The minimum transmission rate at which the VM transmit/receive data * \param vmTransRateMax The maximum transmission rate at which the VM transmit/receive data */ void ConfigureVmNetwork (uint32_t mtu, std::string protocolType, std::string vmTransRateMin, std::string vmTransRateMax); /** * \brief Configure VM general properties with similar resource requirement * \param vmNum The number of VM to create * \param processing The processing power requirement * \param primary The primary storage requirement * \param secondary The secondary storage requirement * \param appSize The application size of VM */ void ConfigureVmGeneral(const uint32_t vmNum, const std::string processing, const std::string primary, const std::string secondary, const std::string appSize); /** * \brief Configures the VM data requirement with similar values * \param require The flag to set if VMs require data * \param numOfVmWithServerDataSrc The number of VMs to have Server for data source * \param distribution The distribution * \param dAmount The data amount * \param hddRwRate The read/write rate of HDD * \param memRwRate The read/write rate of RAM * \param numOfProcAccess The number of data access by processor * \param memPdf The percentage of Memory for data fetching * \param hddAccT The HDD access time * \param memAccT The memory access time */ void ConfigureVmDataReq(bool require, uint32_t numOfVmWithServerDataSrc, Procedure_e distribution, std::string dAmount, std::string hddRwRate, std::string memRwRate, uint32_t numOfProcAccess, double memPdf, Time hddAccT, Time memAccT); /** * \brief Configure VM arrival time with similar values * \param t The time of VM arrival * */ void ConfigureVmArrivals(Time t); /** * \brief Configure VM Network properties with similar values * \param mtu The Maximum Transmission Unit * \param protocolType The protocol to use for communication e.g ns3::TcpSocketFactory * \param vmTransRate The transmission rate at which the VM transmit/receive data */ void ConfigureVmNetwork (uint32_t mtu, std::string protocolType, std::string vmTransRate); /** * \brief Configure the number of Storage server * \param numOfServ Then number of storage server to create. */ void ConfigureStorageServer(uint32_t numOfServ); /** * \brief Enable tracing to capture network data * \param collector The data collector object containing list of sub collector. */ void EnableTracing( NutshellDataCollector& collector); /** * \brief Get the node minimum processing resource value * \return The processing string value */ std::string GetNodeMinProcessing() const; /** * \brief Get the node maximum processing resource value * \return The processing power string value */ std::string GetNodeMaxProcessing() const; /** * \brief Get the node minimum primary storage resource value * \return The primary storage string value */ std::string GetNodeMinPrimaryStorage() const; /** * \brief Get the node maximum primary storage resource value * \return The primary storage string value */ std::string GetNodeMaxPrimaryStorage() const; /** * \brief Get the node minimum secondary storage resource value * \return The secondary storage string value */ std::string GetNodeMinSecondaryStorage() const; /** * \brief Get the node maximum secondary storage resource value * \return The secondary storage string value */ std::string GetNodeMaxSecondaryStorage() const; /** * \brief Get VM minimum processing requirement * \return The processing requirement string value */ std::string GetVmMinProcessing() const; /** * \brief Get VM maximum processing requirement * \return The processing requirement string value */ std::string GetVmMaxProcessing() const; /** * \brief Get VM minimum primary storage requirement * \return The primary storage requirement string value */ std::string GetVmMinPrimaryStorage() const; /** * \brief Get VM maximum primary storage requirement * \return The primary storage requirement string value */ std::string GetVmMaxPrimaryStorage() const; /** * \brief Get VM minimum secondary storage requirement * \return The secondary storage requirement string value */ std::string GetVmMinSecondaryStorage() const; /** * \brief Get VM maximum secondary storage requirement * \return The secondary storage requirement string value */ std::string GetVmMaxSecondaryStorage() const; /** * \brief Get VM minimum application size * \return The application size string value */ std::string GetVmMinAppSize() const; /** * \brief Get VM maximum application size * \return The application size string value */ std::string GetVmMaxAppSize() const; /** * \brief Get the number of VMs to create * \return The number of VM */ uint32_t GetNumOfVmToCreate() const; /** * \brief Check if VM required data * \return The boolean value of VM required data flag */ bool IsVmRequiredData() const; /** * \brief Get minimum VM data amount * \return The data amount string value */ std::string GetVmDataAmountMin() const; /** * \brief Get maximum VM data amount * \return The data amount string value */ std::string GetVmDataAmountMax() const; /** * \brief Get minimum VM HDD read/write rate * \return The HDD read/write rate string value */ std::string GetVmHddRwRateMin() const; /** * \brief Get maximum VM HDD read/write rate * \return The HDD read/write rate string value */ std::string GetVmHddRwRateMax() const; /** * \brief Get minimum VM memory read/write rate * \return The memory read/write rate string value */ std::string GetVmMemRwRateMin() const; /** * \brief Get maximum VM memory read/write rate * \return The memory read/write rate string value */ std::string GetVmMemRwRateMax() const; /** * \brief Get minimum number of processor access to memory * \return The number of processor access */ uint32_t GetVmNumOfProcAccessMin() const; /** * \brief Get maximum number of processor access to memory * \return The number of processor access */ uint32_t GetVmNumOfProcAccessMax() const; /** * \brief Get minimum percentage of memory for data fetching * \return The percentage of memory */ double GetVmMemPdfMin() const; /** * \brief Get maximum percentage of memory for data fetching * \return The percentage of memory */ double GetVmMemPdfMax() const; /** * \brief Get minimum VM HDD access time * \return The access time */ Time GetVmHddMinAccessTime() const; /** * \brief Get maximum VM HDD access time * \return The access time */ Time GetVmHddMaxAccessTime() const; /** * \brief Get minimum VM memory access time * \return The access time */ Time GetVmMemMinAccessTime() const; /** * \brief Get maximum VM memory access time * \return The access time */ Time GetVmMemMaxAccessTime() const; /** * \brief Get the number of VMs with storage server as data source * \return The number of VMs */ uint32_t GetNumOfVmWithServerDataSrc() const; /** * \brief Get the distribution type * \return The distribution procedure type */ Procedure_e GetVmDistributionType() const; /** * \brief Check if VM split is allowed * \return The boolean value of split allowed flag */ bool IsVmSplitAllowed() const; /** * \brief Get the VM split ratio * \return The ratio string value */ std::string GetVmSplitRatio() const; /** * \brief Get the minimum VM arrival time * \return The arrival time */ Time GetVmArrivalTimeMin() const; /** * \brief Get the maximum VM arrival time * \return The arrival time */ Time GetVmArrivalTimeMax() const; /** * \brief Get the VM MTU size * \return The MTU size */ uint32_t GetVmMtu() const; /** * \brief Get minimum VM transmission rate * \return The transmission rate string value */ std::string GetVmTransmissionRateMin() const; /** * \brief Get maximum VM transmission rate * \return The transmission rate string value */ std::string GetVmTransmissionRateMax() const; /** * \brief Get the VM protocol type * \return The VM protocol type string value */ std::string GetVmProtocolType() const; /** * \brief Get the number of storage servers * \return the number of storage server. */ uint32_t GetNumOfStorageServer() const; /** * \brief Checks if tracing is enabled * \return The boolean value of tracing flag */ bool IsTracingEnabled() const; /** * \brief Get the data collector object * \return The Data collector object. */ NutshellDataCollector& GetDataCollector(); virtual ~DatacenterConfig(); protected: /** * \brief Structure for Node Configuration */ struct NodeConfig { std::string processingMin, processingMax; std::string primaryStorageMin, primaryStorageMax; std::string secondaryStorageMin, secondaryStorageMax; }; /** * \brief Structure for VM Configuration */ struct VmConfig { /* ------------ General ---------*/ std::string processingMin, processingMax; std::string primaryStorageMin, primaryStorageMax; std::string secondaryStorageMin, secondaryStorageMax; std::string appSizeMin, appSizeMax; uint32_t numOfVmsToCreate; /* ------------ Data ---------*/ bool requireData; std::string dataAmountMin, dataAmountMax; std::string hddRwRateMin, hddRwRateMax, memRwRateMin, memRwRateMax; uint32_t numOfProcAccessMin, numOfProcAccessMax; double memPDFMin, memPDFMax; Time hddMinAccessTime, hddMaxAccessTime, memMinAccessTime, memMaxAccessTime; uint32_t numOfVmWithServerDataSource; Procedure_e distribution; /* ------------ Split ---------*/ bool allowVmSplit; std::string splitRatio; /* ------------ Arrival ---------*/ Time arrivalTimeMin, arrivalTimeMax; /* ----------- Network --------- */ uint32_t mtu; std::string vmTransmissionRateMin, vmTransmissionRateMax; std::string tid; }; /** * \brief Structure for Storage Server Configuration */ struct StorageServerConfig { uint32_t numOfServers; }; NodeConfig m_nodeConfiguration; //!< The node configuration VmConfig m_vmConfiguration; //!< The VM configuration StorageServerConfig m_storageServer; //!< The storage server configuration bool m_enableTracing; //!< The tracing flag NutshellDataCollector m_dataCollector; //!< The data collector }; } /* namespace ns3 */ #endif /* DATACENTER_CONFIG */
import { createProduct } from "../../services/productServices.js"; import PRODUCT_MODEL from "../../model/PRODUCT_MODEL.js"; jest.mock('../../model/PRODUCT_MODEL.js') describe('createProduct function', () => { let res; beforeEach(() => { res = { status: jest.fn().mockReturnThis(), json: jest.fn() }; }) const req = { user:{id:'logginId'} } it('Should send status code 400 if field dont have value', async() => { const testCases =[ {product_name:"",product_description:"",product_price:"",product_tag:"" }, {product_name:"sample",product_description:"sample",product_price:"100",product_tag:"" }, {product_name:"sample",product_description:"sample",product_price:"",product_tag:"sample" }, {product_name:"sample",product_description:"",product_price:"sample",product_tag:"sample" } ] for(const testCase of testCases){ try { await createProduct(testCase, req, res) } catch (e) { expect(res.status).toHaveBeenCalledWith(400) expect(e.message).toBe('All Fields in creating product required') } } }) it('Should return data when creating product', async()=> { const requestBody = { product_name: "Sample Product", product_description: "This is a sample product", product_price: "100", product_tag: "sample" }; const mockCreatedProduct = { _id: 'product123', product_name: "Sample Product", product_description: "This is a sample product", product_price: "100", product_tag: "sample", user: req.user.id }; PRODUCT_MODEL.create.mockResolvedValue(mockCreatedProduct); await createProduct(requestBody, req, res); expect(res.status).toHaveBeenCalledWith(201); expect(res.json).toHaveBeenCalledWith(mockCreatedProduct); }) })
use std::collections::HashMap; use std::fs::{self, File}; use std::hint::black_box; use std::io::{self, BufRead, BufReader, Write}; use std::mem; use std::os::fd::{AsRawFd, FromRawFd}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Instant; use anyhow::Context; use async_trait::async_trait; use clap::{Parser, Subcommand, ValueEnum}; use fxhash::FxHashMap; use itertools::Itertools; use rayon::iter::Either; use rayon::prelude::*; use rustls::client::Resumption; use rustls::crypto::{aws_lc_rs, ring}; use rustls::server::{NoServerSessionStorage, ServerSessionMemoryCache, WebPkiClientVerifier}; use rustls::{ CipherSuite, ClientConfig, ClientConnection, ProtocolVersion, RootCertStore, ServerConfig, ServerConnection, }; use crate::benchmark::{ get_reported_instr_count, validate_benchmarks, Benchmark, BenchmarkKind, BenchmarkParams, ResumptionKind, }; use crate::cachegrind::CachegrindRunner; use crate::util::async_io::{self, AsyncRead, AsyncWrite}; use crate::util::transport::{ read_handshake_message, read_plaintext_to_end_bounded, send_handshake_message, write_all_plaintext_bounded, }; use crate::util::KeyType; mod benchmark; mod cachegrind; mod util; /// The size in bytes of the plaintext sent in the transfer benchmark const TRANSFER_PLAINTEXT_SIZE: usize = 1024 * 1024 * 10; // 10 MB /// The amount of times a resumed handshake should be executed during benchmarking. /// /// Handshakes with session resumption execute a very small amount of instructions (less than 200_000 /// for some parameters), so a small difference in instructions accounts for a high difference in /// percentage (making the benchmark more sensitive to noise, because differences as low as 500 /// instructions already raise a flag). Running the handshake multiple times gives additional weight /// to the instructions involved in the handshake, and less weight to noisy one-time setup code. /// /// More specifically, great part of the noise in resumed handshakes comes from the usage of /// [`rustls::client::ClientSessionMemoryCache`] and [`rustls::server::ServerSessionMemoryCache`], /// which rely on a randomized `HashMap` under the hood (you can check for yourself by that /// `HashMap` by a `FxHashMap`, which brings the noise down to acceptable levels in a single run). const RESUMED_HANDSHAKE_RUNS: usize = 30; /// The name of the file where the instruction counts are stored after a `run-all` run const ICOUNTS_FILENAME: &str = "icounts.csv"; /// Default size in bytes for internal buffers (256 KB) const DEFAULT_BUFFER_SIZE: usize = 262144; #[derive(Parser)] #[command(about)] pub struct Cli { #[command(subcommand)] pub command: Command, } #[derive(Subcommand)] pub enum Command { /// Run all benchmarks and print the measured CPU instruction counts in CSV format RunAll { #[arg(short, long, default_value = "target/ci-bench")] output_dir: PathBuf, }, /// Run a single benchmark at the provided index (used by the bench runner to start each benchmark in its own process) RunSingle { index: u32, side: Side }, /// Run all benchmarks in walltime mode and print the measured timings in CSV format Walltime { #[arg(short, long)] iterations_per_scenario: usize, }, /// Compare the results from two previous benchmark runs and print a user-friendly markdown overview Compare { /// Path to the directory with the results of a previous `run-all` execution baseline_dir: PathBuf, /// Path to the directory with the results of a previous `run-all` execution candidate_dir: PathBuf, }, } #[derive(Copy, Clone, ValueEnum)] pub enum Side { Server, Client, } impl Side { /// Returns the string representation of the side pub fn as_str(self) -> &'static str { match self { Side::Client => "client", Side::Server => "server", } } } fn main() -> anyhow::Result<()> { let benchmarks = all_benchmarks()?; let cli = Cli::parse(); match cli.command { Command::RunAll { output_dir } => { let executable = std::env::args().next().unwrap(); let results = run_all(executable, output_dir.clone(), &benchmarks)?; // Output results in CSV (note: not using a library here to avoid extra dependencies) let mut csv_file = File::create(output_dir.join(ICOUNTS_FILENAME)) .context("cannot create output csv file")?; for (name, instr_count) in results { writeln!(csv_file, "{name},{instr_count}")?; } } Command::RunSingle { index, side } => { // `u32::MAX` is used as a signal to do nothing and return. By "running" an empty // benchmark we can measure the startup overhead. if index == u32::MAX { return Ok(()); } let bench = benchmarks .get(index as usize) .ok_or(anyhow::anyhow!("Benchmark not found: {index}"))?; let stdin_lock = io::stdin().lock(); let stdout_lock = io::stdout().lock(); // `StdinLock` and `StdoutLock` are buffered, which makes the instruction counts less // deterministic (the growth of the internal buffers varies across runs, causing // differences of hundreds of instructions). To counter this, we do the actual io // operations through `File`, which is unbuffered. The `stdin_lock` and `stdout_lock` // variables are kept around to ensure exclusive access. // safety: the file descriptor is valid and we have exclusive access to it for the // duration of the lock let mut stdin = unsafe { File::from_raw_fd(stdin_lock.as_raw_fd()) }; let mut stdout = unsafe { File::from_raw_fd(stdout_lock.as_raw_fd()) }; let handshake_buf = &mut [0u8; DEFAULT_BUFFER_SIZE]; let resumption_kind = bench.kind.resumption_kind(); let io = StepperIo { reader: &mut stdin, writer: &mut stdout, handshake_buf, }; async_io::block_on_single_poll(async { match side { Side::Server => { run_bench( ServerSideStepper { io, config: ServerSideStepper::make_config( &bench.params, resumption_kind, ), }, bench.kind, ) .await } Side::Client => { run_bench( ClientSideStepper { io, resumption_kind, config: ClientSideStepper::make_config( &bench.params, resumption_kind, ), }, bench.kind, ) .await } } }) .with_context(|| format!("{} crashed for {} side", bench.name(), side.as_str()))?; // Prevent stdin / stdout from being closed mem::forget(stdin); mem::forget(stdout); } Command::Walltime { iterations_per_scenario, } => { let mut timings = vec![Vec::with_capacity(iterations_per_scenario); benchmarks.len()]; for _ in 0..iterations_per_scenario { for (i, bench) in benchmarks.iter().enumerate() { let start = Instant::now(); // The variables below are used to initialize the client and server configs. We // let them go through `black_box` to ensure the optimizer doesn't take // advantage of knowing both the client and the server side of the // configuration. let resumption_kind = black_box(bench.kind.resumption_kind()); let params = black_box(&bench.params); let (mut client_writer, mut server_reader) = async_io::async_pipe(DEFAULT_BUFFER_SIZE); let (mut server_writer, mut client_reader) = async_io::async_pipe(DEFAULT_BUFFER_SIZE); let server_side = async move { let handshake_buf = &mut [0u8; DEFAULT_BUFFER_SIZE]; run_bench( ServerSideStepper { io: StepperIo { reader: &mut server_reader, writer: &mut server_writer, handshake_buf, }, config: ServerSideStepper::make_config(params, resumption_kind), }, bench.kind, ) .await }; let client_side = async move { let handshake_buf = &mut [0u8; DEFAULT_BUFFER_SIZE]; run_bench( ClientSideStepper { io: StepperIo { reader: &mut client_reader, writer: &mut client_writer, handshake_buf, }, resumption_kind, config: ClientSideStepper::make_config(params, resumption_kind), }, bench.kind, ) .await }; let (client_result, server_result) = async_io::block_on_concurrent(client_side, server_side); client_result .with_context(|| format!("client side of {} crashed", bench.name()))?; server_result .with_context(|| format!("server side of {} crashed", bench.name()))?; timings[i].push(start.elapsed()); } } // Output the results for (i, bench_timings) in timings.into_iter().enumerate() { print!("{}", benchmarks[i].name()); for timing in bench_timings { print!(",{}", timing.as_nanos()) } println!(); } } Command::Compare { baseline_dir, candidate_dir, } => { let baseline = read_results(&baseline_dir.join(ICOUNTS_FILENAME))?; let candidate = read_results(&candidate_dir.join(ICOUNTS_FILENAME))?; let result = compare_results(&baseline_dir, &candidate_dir, &baseline, &candidate)?; print_report(&result); } } Ok(()) } /// Returns all benchmarks fn all_benchmarks() -> anyhow::Result<Vec<Benchmark>> { let mut benchmarks = Vec::new(); for param in all_benchmarks_params() { add_benchmark_group(&mut benchmarks, param); } validate_benchmarks(&benchmarks)?; Ok(benchmarks) } /// The benchmark params to use for each group of benchmarks fn all_benchmarks_params() -> Vec<BenchmarkParams> { let mut all = Vec::new(); for (provider, suites, ticketer, provider_name) in [ ( ring::default_provider(), ring::ALL_CIPHER_SUITES, &(ring_ticketer as fn() -> Arc<dyn rustls::server::ProducesTickets>), "ring", ), ( aws_lc_rs::default_provider(), aws_lc_rs::ALL_CIPHER_SUITES, &(aws_lc_rs_ticketer as fn() -> Arc<dyn rustls::server::ProducesTickets>), "aws_lc_rs", ), ] { for (key_type, suite_name, version, name) in [ ( KeyType::Rsa, CipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, &rustls::version::TLS12, "1.2_rsa_aes", ), ( KeyType::Rsa, CipherSuite::TLS13_AES_128_GCM_SHA256, &rustls::version::TLS13, "1.3_rsa_aes", ), ( KeyType::EcdsaP256, CipherSuite::TLS13_AES_128_GCM_SHA256, &rustls::version::TLS13, "1.3_ecdsap256_aes", ), ( KeyType::EcdsaP384, CipherSuite::TLS13_AES_128_GCM_SHA256, &rustls::version::TLS13, "1.3_ecdsap384_aes", ), ( KeyType::Rsa, CipherSuite::TLS13_CHACHA20_POLY1305_SHA256, &rustls::version::TLS13, "1.3_rsa_chacha", ), ( KeyType::EcdsaP256, CipherSuite::TLS13_CHACHA20_POLY1305_SHA256, &rustls::version::TLS13, "1.3_ecdsap256_chacha", ), ( KeyType::EcdsaP384, CipherSuite::TLS13_CHACHA20_POLY1305_SHA256, &rustls::version::TLS13, "1.3_ecdsap384_chacha", ), ] { all.push(BenchmarkParams::new( provider.clone(), ticketer, key_type, find_suite(suites, suite_name), version, format!("{provider_name}_{name}"), )); } } all } fn find_suite( all: &[rustls::SupportedCipherSuite], name: CipherSuite, ) -> rustls::SupportedCipherSuite { *all.iter() .find(|suite| suite.suite() == name) .unwrap_or_else(|| panic!("cannot find cipher suite {name:?}")) } fn ring_ticketer() -> Arc<dyn rustls::server::ProducesTickets> { ring::Ticketer::new().unwrap() } fn aws_lc_rs_ticketer() -> Arc<dyn rustls::server::ProducesTickets> { aws_lc_rs::Ticketer::new().unwrap() } /// Adds a group of benchmarks for the specified parameters /// /// The benchmarks in the group are: /// /// - Handshake without resumption /// - Handshake with session id resumption /// - Handshake with ticket resumption /// - Transfer a 1MB data stream from the server to the client fn add_benchmark_group(benchmarks: &mut Vec<Benchmark>, params: BenchmarkParams) { let params_label = params.label.clone(); // Create handshake benchmarks for all resumption kinds for &resumption_param in ResumptionKind::ALL { let handshake_bench = Benchmark::new( format!("handshake_{}_{params_label}", resumption_param.label()), BenchmarkKind::Handshake(resumption_param), params.clone(), ); let handshake_bench = if resumption_param != ResumptionKind::No { // Since resumed handshakes include a first non-resumed handshake, we need to subtract // the non-resumed handshake's instructions handshake_bench .exclude_setup_instructions(format!("handshake_no_resume_{params_label}")) } else { handshake_bench }; benchmarks.push(handshake_bench); } // Benchmark data transfer benchmarks.push( Benchmark::new( format!("transfer_no_resume_{params_label}"), BenchmarkKind::Transfer, params.clone(), ) .exclude_setup_instructions(format!("handshake_no_resume_{params_label}")), ); } /// Run all the provided benches under cachegrind to retrieve their instruction count pub fn run_all( executable: String, output_dir: PathBuf, benches: &[Benchmark], ) -> anyhow::Result<Vec<(String, u64)>> { // Run the benchmarks in parallel let cachegrind = CachegrindRunner::new(executable, output_dir)?; let results: Vec<_> = benches .par_iter() .enumerate() .map(|(i, bench)| (bench, cachegrind.run_bench(i as u32, bench))) .collect(); // Report possible errors let (errors, results): (Vec<_>, FxHashMap<_, _>) = results .into_iter() .partition_map(|(bench, result)| match result { Err(_) => Either::Left(()), Ok(instr_counts) => Either::Right((bench.name(), instr_counts)), }); if !errors.is_empty() { // Note: there is no need to explicitly report the names of each crashed benchmark, because // names and other details are automatically printed to stderr by the child process upon // crashing anyhow::bail!("One or more benchmarks crashed"); } // Gather results keeping the original order of the benchmarks let mut measurements = Vec::new(); for bench in benches { let instr_counts = get_reported_instr_count(bench, &results); measurements.push((bench.name_with_side(Side::Server), instr_counts.server)); measurements.push((bench.name_with_side(Side::Client), instr_counts.client)); } Ok(measurements) } /// Drives the different steps in a benchmark. /// /// See [`run_bench`] for specific details on how it is used. #[async_trait(?Send)] trait BenchStepper { type Endpoint; async fn handshake(&mut self) -> anyhow::Result<Self::Endpoint>; async fn sync_before_resumed_handshake(&mut self) -> anyhow::Result<()>; async fn transmit_data(&mut self, endpoint: &mut Self::Endpoint) -> anyhow::Result<()>; } /// Stepper fields necessary for IO struct StepperIo<'a> { reader: &'a mut dyn AsyncRead, writer: &'a mut dyn AsyncWrite, handshake_buf: &'a mut [u8], } /// A benchmark stepper for the client-side of the connection struct ClientSideStepper<'a> { io: StepperIo<'a>, resumption_kind: ResumptionKind, config: Arc<ClientConfig>, } impl ClientSideStepper<'_> { fn make_config(params: &BenchmarkParams, resume: ResumptionKind) -> Arc<ClientConfig> { assert_eq!(params.ciphersuite.version(), params.version); let mut root_store = RootCertStore::empty(); let mut rootbuf = io::BufReader::new(fs::File::open(params.key_type.path_for("ca.cert")).unwrap()); root_store.add_parsable_certificates( rustls_pemfile::certs(&mut rootbuf).map(|result| result.unwrap()), ); let mut cfg = ClientConfig::builder_with_provider( rustls::crypto::CryptoProvider { cipher_suites: vec![params.ciphersuite], ..params.provider.clone() } .into(), ) .with_protocol_versions(&[params.version]) .unwrap() .with_root_certificates(root_store) .with_no_client_auth(); if resume != ResumptionKind::No { cfg.resumption = Resumption::in_memory_sessions(128); } else { cfg.resumption = Resumption::disabled(); } Arc::new(cfg) } } #[async_trait(?Send)] impl BenchStepper for ClientSideStepper<'_> { type Endpoint = ClientConnection; async fn handshake(&mut self) -> anyhow::Result<Self::Endpoint> { let server_name = "localhost".try_into().unwrap(); let mut client = ClientConnection::new(self.config.clone(), server_name).unwrap(); client.set_buffer_limit(None); loop { send_handshake_message(&mut client, self.io.writer, self.io.handshake_buf).await?; if !client.is_handshaking() && !client.wants_write() { break; } read_handshake_message(&mut client, self.io.reader, self.io.handshake_buf).await?; } // Session ids and tickets are no longer part of the handshake in TLS 1.3, so we need to // explicitly receive them from the server if self.resumption_kind != ResumptionKind::No && client.protocol_version().unwrap() == ProtocolVersion::TLSv1_3 { read_handshake_message(&mut client, self.io.reader, self.io.handshake_buf).await?; } Ok(client) } async fn sync_before_resumed_handshake(&mut self) -> anyhow::Result<()> { // The client syncs by receiving a single byte (we assert that it matches the `42` byte sent // by the server, just to be sure) let buf = &mut [0]; self.io.reader.read_exact(buf).await?; assert_eq!(buf[0], 42); Ok(()) } async fn transmit_data(&mut self, endpoint: &mut Self::Endpoint) -> anyhow::Result<()> { let total_plaintext_read = read_plaintext_to_end_bounded(endpoint, self.io.reader).await?; assert_eq!(total_plaintext_read, TRANSFER_PLAINTEXT_SIZE); Ok(()) } } /// A benchmark stepper for the server-side of the connection struct ServerSideStepper<'a> { io: StepperIo<'a>, config: Arc<ServerConfig>, } impl ServerSideStepper<'_> { fn make_config(params: &BenchmarkParams, resume: ResumptionKind) -> Arc<ServerConfig> { assert_eq!(params.ciphersuite.version(), params.version); let mut cfg = ServerConfig::builder_with_provider(params.provider.clone().into()) .with_protocol_versions(&[params.version]) .unwrap() .with_client_cert_verifier(WebPkiClientVerifier::no_client_auth()) .with_single_cert(params.key_type.get_chain(), params.key_type.get_key()) .expect("bad certs/private key?"); if resume == ResumptionKind::SessionId { cfg.session_storage = ServerSessionMemoryCache::new(128); } else if resume == ResumptionKind::Tickets { cfg.ticketer = (params.ticketer)(); } else { cfg.session_storage = Arc::new(NoServerSessionStorage {}); } Arc::new(cfg) } } #[async_trait(?Send)] impl BenchStepper for ServerSideStepper<'_> { type Endpoint = ServerConnection; async fn handshake(&mut self) -> anyhow::Result<Self::Endpoint> { let mut server = ServerConnection::new(self.config.clone()).unwrap(); server.set_buffer_limit(None); while server.is_handshaking() { read_handshake_message(&mut server, self.io.reader, self.io.handshake_buf).await?; send_handshake_message(&mut server, self.io.writer, self.io.handshake_buf).await?; } Ok(server) } async fn sync_before_resumed_handshake(&mut self) -> anyhow::Result<()> { // The server syncs by sending a single byte self.io.writer.write_all(&[42]).await?; self.io.writer.flush().await?; Ok(()) } async fn transmit_data(&mut self, endpoint: &mut Self::Endpoint) -> anyhow::Result<()> { write_all_plaintext_bounded(endpoint, self.io.writer, TRANSFER_PLAINTEXT_SIZE).await?; Ok(()) } } /// Runs the benchmark using the provided stepper async fn run_bench<T: BenchStepper>(mut stepper: T, kind: BenchmarkKind) -> anyhow::Result<()> { let mut endpoint = stepper.handshake().await?; match kind { BenchmarkKind::Handshake(ResumptionKind::No) => { // Nothing else to do here, since the handshake already happened black_box(endpoint); } BenchmarkKind::Handshake(_) => { // The handshake performed above was non-resumed, because the client didn't have a // session ID / ticket; from now on we can perform resumed handshakes. We do it multiple // times, for reasons explained in the comments to `RESUMED_HANDSHAKE_RUNS`. for _ in 0..RESUMED_HANDSHAKE_RUNS { // Wait for the endpoints to sync (i.e. the server must have discarded the previous // connection and be ready for a new handshake, otherwise the client will start a // handshake before the server is ready and the bytes will be fed to the old // connection!) stepper .sync_before_resumed_handshake() .await?; stepper.handshake().await?; } } BenchmarkKind::Transfer => { stepper .transmit_data(&mut endpoint) .await?; } } Ok(()) } /// The results of a comparison between two `run-all` executions struct CompareResult { /// Results for benchmark scenarios we know are fairly deterministic. /// /// The string is a detailed diff between the instruction counts obtained from cachegrind. diffs: Vec<(Diff, String)>, /// Results for benchmark scenarios we know are extremely non-deterministic known_noisy: Vec<Diff>, /// Benchmark scenarios present in the candidate but missing in the baseline missing_in_baseline: Vec<String>, } /// Contains information about instruction counts and their difference for a specific scenario #[derive(Clone)] struct Diff { scenario: String, baseline: u64, candidate: u64, diff: i64, diff_ratio: f64, } /// Reads the (benchmark, instruction count) pairs from previous CSV output fn read_results(path: &Path) -> anyhow::Result<HashMap<String, u64>> { let file = File::open(path).context(format!( "CSV file for comparison not found: {}", path.display() ))?; let mut measurements = HashMap::new(); for line in BufReader::new(file).lines() { let line = line.context("Unable to read results from CSV file")?; let line = line.trim(); let mut parts = line.split(','); measurements.insert( parts .next() .ok_or(anyhow::anyhow!("CSV is wrongly formatted"))? .to_string(), parts .next() .ok_or(anyhow::anyhow!("CSV is wrongly formatted"))? .parse() .context("Unable to parse instruction count from CSV")?, ); } Ok(measurements) } /// Returns an internal representation of the comparison between the baseline and the candidate /// measurements fn compare_results( baseline_dir: &Path, candidate_dir: &Path, baseline: &HashMap<String, u64>, candidate: &HashMap<String, u64>, ) -> anyhow::Result<CompareResult> { let mut diffs = Vec::new(); let mut missing = Vec::new(); let mut known_noisy = Vec::new(); for (scenario, &instr_count) in candidate { let Some(&baseline_instr_count) = baseline.get(scenario) else { missing.push(scenario.clone()); continue; }; let diff = instr_count as i64 - baseline_instr_count as i64; let diff_ratio = diff as f64 / baseline_instr_count as f64; let diff = Diff { scenario: scenario.clone(), baseline: baseline_instr_count, candidate: instr_count, diff, diff_ratio, }; match is_known_noisy(scenario) { true => known_noisy.push(diff), false => diffs.push(diff), }; } diffs.sort_by(|diff1, diff2| { diff2 .diff_ratio .abs() .total_cmp(&diff1.diff_ratio.abs()) }); let mut diffs_with_cachegrind_diff = Vec::new(); for diff in diffs { let detailed_diff = cachegrind::diff(baseline_dir, candidate_dir, &diff.scenario)?; diffs_with_cachegrind_diff.push((diff, detailed_diff)); } Ok(CompareResult { diffs: diffs_with_cachegrind_diff, missing_in_baseline: missing, known_noisy, }) } fn is_known_noisy(scenario_name: &str) -> bool { // aws-lc-rs RSA key validation is non-deterministic, and expensive in relative terms for // "cheaper" tests, and only done for server-side tests. Exclude these tests // from comparison. // // Better solutions for this include: // - https://github.com/rustls/rustls/issues/1494: exclude key validation in these tests. // Key validation is benchmarked separately elsewhere, and mostly amortised into // insignificance in real-world scenarios. // - Find a way to make aws-lc-rs deterministic, such as by replacing its RNG with a // test-only one. scenario_name.contains("_aws_lc_rs_") && scenario_name.contains("_rsa_") && scenario_name.ends_with("_server") } /// Prints a report of the comparison to stdout, using GitHub-flavored markdown fn print_report(result: &CompareResult) { println!("# Benchmark results"); if !result.missing_in_baseline.is_empty() { println!("### ⚠️ Warning: missing benchmarks"); println!(); println!("The following benchmark scenarios are present in the candidate but not in the baseline:"); println!(); for scenario in &result.missing_in_baseline { println!("* {scenario}"); } } println!("## Instruction count differences"); if result.diffs.is_empty() { println!("_There are no instruction count differences_"); } else { table( result .diffs .iter() .map(|(diff, _)| diff), true, ); println!("<details>"); println!("<summary>Details per scenario</summary>\n"); for (diff, detailed_diff) in &result.diffs { println!("#### {}", diff.scenario); println!("```"); println!("{detailed_diff}"); println!("```"); } println!("</details>\n") } if !result.known_noisy.is_empty() { println!("### ‼️ Caution: ignored noisy benchmarks"); println!("<details>"); println!("<summary>Click to expand</summary>\n"); table(result.known_noisy.iter(), false); println!("</details>\n") } } /// Renders the diffs as a markdown table fn table<'a>(diffs: impl Iterator<Item = &'a Diff>, emoji_feedback: bool) { println!("| Scenario | Baseline | Candidate | Diff |"); println!("| --- | ---: | ---: | ---: |"); for diff in diffs { let emoji = match emoji_feedback { true if diff.diff > 0 => "⚠️ ", true if diff.diff < 0 => "✅ ", _ => "", }; println!( "| {} | {} | {} | {}{} ({:.2}%) |", diff.scenario, diff.baseline, diff.candidate, emoji, diff.diff, diff.diff_ratio * 100.0 ) } }
import React from 'react'; import styles from './styles.module.scss'; import { useCurrentSidebarCategory } from '@docusaurus/theme-common'; // @ts-ignore import { useDocsSidebar } from '@docusaurus/theme-common/internal'; import Feature from '../Feature'; import { useLocation } from '@docusaurus/router'; // https://github.com/facebook/docusaurus/blob/main/packages/docusaurus-theme-common/src/contexts/docsSidebar.tsx import type { PropSidebar } from '@docusaurus/plugin-content-docs'; export type ContextValue = { name: string; items: PropSidebar }; function MyFeature(): JSX.Element { const sidebar = useCurrentSidebarCategory(); return ( <div className={styles.features}> {sidebar.items.map((item, idx) => { if (item.type === 'link' || item.type === 'category') { return ( <Feature icon={item.customProps?.icon as string} name={item.label} route={item.href} pages={item.type === 'category' ? item.items.length : 1} key={idx} /> ); } else { return null; } })} </div> ); } const getCurrent = (sidebarItems: PropSidebar, pathname: string) => { for (const item of sidebarItems) { if (item.type !== 'html' && item.href === pathname) { return item; } if (item.type === 'category') { const current = getCurrent(item.items, pathname); if (current) { return current; } } } return undefined; } export default function Features(): JSX.Element { const docsSidebar: ContextValue = useDocsSidebar(); const { pathname } = useLocation(); const current = getCurrent(docsSidebar?.items, pathname); if (!current || current.type !== 'category') { return ( <div className={styles.features}> <Feature icon="mdi-heart-broken" name="Keine Unterseite Gefunden 😢" route={(docsSidebar?.items.find((it) => it.type !== 'html') as {href: string})?.href || '/'} /> </div> ); } return <MyFeature />; }
from typing import Union import pandas as pd import numpy as np import os from pathlib import Path import MDAnalysis as _mda def assign_conserved_numbers(alignment_df: pd.DataFrame) -> pd.DataFrame: assert ( type(alignment_df) == pd.DataFrame ), "alignment_df, the argument of assign_conserved_numbers() has to be a Pandas DataFrame" # assign helix numbers struct = [col for col in alignment_df.columns] helix_numbers = {} is_block = False block = 0 block_number = 0 window = 4 for i, s in enumerate(struct): if s.startswith("H"): non_helix = [ part for part in struct[i : i + window] if part.startswith("-") ] if is_block and len(non_helix) >= 3: is_block = False block_number += 1 helix = [part for part in struct[i : i + window] if part.startswith("H")] if len(helix) >= 3: is_block = True block = block_number block += 1 helix_numbers.update({s: block}) else: helix_numbers.update({s: None}) # calculate most frequent values and conservation most_frequent_amino_acid = alignment_df.mode(axis=0).iloc[0, :].to_frame() occurrence = alignment_df.apply(lambda x: x.value_counts().max(), axis=0).to_frame() conservation = alignment_df.apply( lambda x: x.value_counts().max() / x.value_counts().sum(), axis=0 ).to_frame() variability = alignment_df.replace({"-": None}).nunique(axis=0).to_frame() alignment_df = alignment_df.append( pd.DataFrame(data=helix_numbers, index=[0]), ignore_index=True ) sequence_conserv = pd.concat( [ alignment_df, variability.T, most_frequent_amino_acid.T, occurrence.T, conservation.T, ], axis=0, ) sequence_conserv.iloc[-1, 0] = "conservation" sequence_conserv.iloc[-2, 0] = "occurrence" sequence_conserv.iloc[-3, 0] = "most_frequent_amino_acid" sequence_conserv.iloc[-4, 0] = "amino_acid_variability" sequence_conserv.iloc[-5, 0] = "helix_number" # transpose and re-index table --> PDB structures as columns, amino acid sequence as rows sequence_conserv.set_index("TM_helix", inplace=True) sequence_conserv.index.name = None sequence_conserv_tr = sequence_conserv.transpose().rename_axis("col") sequence_conserv_tr.reset_index(inplace=True) sequence_conserv_tr = sequence_conserv_tr.drop("col", axis=1) sequence_conserv_tr.loc[ sequence_conserv_tr["helix_number"] == 0, "helix_number" ] = None sequence_conserv_tr["IDs"] = sequence_conserv_tr.index # If there are multiple residues with the same conservation on the helix, # select the one which index is closest to the middle of the helix middle_ids = ( sequence_conserv_tr.groupby("helix_number")["IDs"] .apply(lambda x: x.iloc[(len(x) + 1) // 2]) .to_frame() ) for i, mid_id in middle_ids.iterrows(): sequence_conserv_tr.loc[ sequence_conserv_tr["helix_number"] == i, "middle_id" ] = mid_id["IDs"] idx = ( sequence_conserv_tr.groupby("helix_number")["conservation"].transform(max) == sequence_conserv_tr["conservation"] ) max_values_idx = sequence_conserv_tr[idx].index def select_most_conserved_closer_to_helix_middle(helix_group): distance_to_middle = list( abs(helix_group.index - helix_group["middle_id"].values[0]) ) return helix_group.iloc[distance_to_middle.index(min(distance_to_middle))] middle_most_conserved = ( sequence_conserv_tr.iloc[max_values_idx] .groupby("helix_number") .apply(select_most_conserved_closer_to_helix_middle) ) sequence_conserv_tr["location_id"] = 0 # assign number 50 to the most conserved amino acid sequence_conserv_tr.loc[middle_most_conserved["IDs"], "location_id"] = 50 reference_row_indexes = sequence_conserv_tr.groupby("helix_number")[ "location_id" ].idxmax() def add_value(group): group["location_id"] = list( 50 + group.index - reference_row_indexes[group["helix_number"].values[0]] ) return group assigned_groups = sequence_conserv_tr.groupby("helix_number")[ [ "helix_number", "amino_acid_variability", "most_frequent_amino_acid", "occurrence", "conservation", "location_id", ] ].apply(add_value) sequence_conserv_tr = sequence_conserv_tr.iloc[:, :-8].join(assigned_groups) sequence_conserv_tr["NS_number"] = sequence_conserv_tr.apply( lambda row: f"{int(row['helix_number'])}.{int(row['location_id'])}" if row["helix_number"] > 0 and row["location_id"] > 0 else "", axis=1, ) return sequence_conserv_tr def _renumber_pdb( sequence_conservation: pd.DataFrame, pdb_file: Union[str, Path], pdb_id: str, protein_name_in_alignment: str, folder_to_save_results: Union[str, Path], ) -> pd.DataFrame: assert ( type(sequence_conservation) == pd.DataFrame ), "sequence_conservation has to be Pandas DataFrame" assert type(pdb_file) in [str, Path], "pdb_file has to be a string or Path" assert type(pdb_id) == str, "pdb_id has to be a string" assert ( type(protein_name_in_alignment) == str ), "protein_name_in_alignment has to be a string" assert type(folder_to_save_results) in [ str, Path, ], "folder_to_save_results has to be a string or Path" np.warnings.filterwarnings( "ignore", category=np.VisibleDeprecationWarning ) # the error is coming from MD Analysis, not form this script amino_dict = { "CYS": "C", "ASP": "D", "SER": "S", "GLN": "Q", "LYS": "K", "ILE": "I", "PRO": "P", "THR": "T", "PHE": "F", "ASN": "N", "GLY": "G", "HIS": "H", "LEU": "L", "ARG": "R", "TRP": "W", "ALA": "A", "VAL": "V", "GLU": "E", "TYR": "Y", "MET": "M", "HSD": "H", "HSE": "H", } df = sequence_conservation[ [ protein_name_in_alignment, "helix_number", "most_frequent_amino_acid", "location_id", ] ] protein_struct = _mda.Universe(pdb_file) res_dict = [] for res in protein_struct.atoms.residues: if res.resname in amino_dict.keys() and res.resid >= 1: res_code = amino_dict[res.resname] res_dict.append((res_code, res.resid)) res_range = list(range(res_dict[0][1], res_dict[-1][1])) # as rolling window is not supported on string in pandas, this is an alternative # method has to be improved but for testing ok seq_start_in_pdb = "".join([r[0] for r in res_dict[0:5]]) for i, row in df.iterrows(): if row[protein_name_in_alignment] != "-": start_row_index = i end_row_index = start_row_index + 120 seq_part = "".join( df[protein_name_in_alignment] .iloc[start_row_index:end_row_index] .apply(str) ).replace("-", "") if seq_part[0:5] == seq_start_in_pdb: start_row_id = i break def match_res_id_with_row(row, protein_name_in_alignment, res_range): if ( row[protein_name_in_alignment] != "-" and row[protein_name_in_alignment] != "1" and len(res_range) ): row["res_id"] = res_range.pop(0) else: row["res_id"] = "-" return row pdb_sequence_df = df.iloc[start_row_id:].apply( lambda r: match_res_id_with_row(r, protein_name_in_alignment, res_range), axis=1 ) pdb_sequence_df["NS_number"] = pdb_sequence_df.apply( lambda row: f"{int(row['helix_number'])}.{int(row['location_id'])}" if row["helix_number"] > 0 and row["location_id"] > 0 else "", axis=1, ) pdb_sequence_df.to_csv( os.path.join(folder_to_save_results, f"{pdb_id.lower()}_renumbered.csv") ) pdb_sequence_df["helix_number"] = ( pdb_sequence_df["helix_number"].fillna(0).astype(int) ) return pdb_sequence_df def renumber_pdb( sequence_conservation: pd.DataFrame, pdb_file: Union[str, Path], pdb_id: str, protein_name_in_alignment: str, folder_to_save_results: Union[str, Path], ) -> None: pdb_sequence_df = _renumber_pdb( sequence_conservation, pdb_file, pdb_id, protein_name_in_alignment, folder_to_save_results, ) protein_struct = _mda.Universe(pdb_file) og_struct = _mda.Universe(pdb_file) for i, res in enumerate(og_struct.atoms): row = pdb_sequence_df.loc[pdb_sequence_df["res_id"] == res.resid] if len(row) and row["helix_number"].values[0] in [1, 2, 3, 4, 5, 6, 7]: NS_number = f"{row['helix_number'].to_numpy()[0]}{int(row['location_id'].to_numpy()[0])}" protein_struct.atoms[i].residue.resid = int(NS_number) protein_struct.atoms[i].residue.resname = "BWX" protein_struct.atoms.write( os.path.join(folder_to_save_results, f"{pdb_id.lower()}_renum.pdb") ) def add_NS_numbers_to_pdb( sequence_conservation: pd.DataFrame, pdb_file: Union[str, Path], pdb_id: str, protein_name_in_alignment: str, folder_to_save_results: Union[str, Path], ) -> None: pdb_sequence_df = _renumber_pdb( sequence_conservation, pdb_file, pdb_id, protein_name_in_alignment, folder_to_save_results, ) protein_struct = _mda.Universe(pdb_file) for i, res in enumerate(protein_struct.atoms): row = pdb_sequence_df.loc[pdb_sequence_df["res_id"] == res.resid] if len(row) and row["helix_number"].values[0] in [1, 2, 3, 4, 5, 6, 7]: NS_number = f"{row['helix_number'].to_numpy()[0]}.{int(row['location_id'].to_numpy()[0])}" res.tempfactor = float(NS_number) else: res.tempfactor = 0 protein_struct.atoms.write( os.path.join(folder_to_save_results, f"{pdb_id.lower()}_with_NS.pdb") )
using Fuse8_ByteMinds.SummerSchool.InternalApi.Models; using Fuse8_ByteMinds.SummerSchool.InternalApi.Models.Settings; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Fuse8_ByteMinds.SummerSchool.InternalApi.Data.EntitiesConfigurations; /// <inheritdoc /> public class SettingsConfig : IEntityTypeConfiguration<CurrenciesSettings> { /// <inheritdoc /> public void Configure(EntityTypeBuilder<CurrenciesSettings> builder) { builder.Property(static settings => settings.BaseCurrency) .HasColumnName("base_currency") .HasColumnType("varchar") .HasDefaultValueSql("'USD'"); builder.Property(static settings => settings.MinAvailableYear) .HasColumnName("min_available_year") .HasDefaultValueSql("2000"); // Only one row allowed. builder.Property<int>("Id") .HasColumnName("id") .HasDefaultValueSql("0"); builder.HasKey("Id") .HasName("settings_row_pk"); builder.ToTable("settings", static tableBuilder => { tableBuilder.HasCheckConstraint("only_one_row_ch", "id = 0"); tableBuilder.HasCheckConstraint("currency_enum_range_ch", $"base_currency IN ('{CurrencyType.EUR}', '{CurrencyType.KZT}', '{CurrencyType.RUB}', '{CurrencyType.USD}')"); }); } }
// Get items const alert = document.querySelector('.alert'); const form = document.querySelector('.shopping-form'); const inputItem = document.getElementById('shopping-input-item'); const container = document.querySelector('.shopping-list-container'); const list = document.querySelector('.shopping-list'); const addBtn = document.querySelector('.add-btn'); const resetBtn = document.querySelector('.reset-btn'); // Editing variables let editingItem; let isEditing = false; let editID = ''; // Helper functions. const getRandomID = () => { return new Date().getTime().toString(); }; const displayAlert = (text, action) => { alert.textContent = text; alert.classList.add(`alert-${action}`); setTimeout(() => { alert.textContent = ''; alert.classList.remove(`alert-${action}`); }, 1500); }; const setToDefaultValue = () => { inputItem.value = ''; isEditing = false; editID = ''; addBtn.textContent = 'Add'; }; const getLocalStorage = () => { return localStorage.getItem('shopping-list') ? JSON.parse(localStorage.getItem('shopping-list')) : []; }; // Function for creating list items. const createListItem = (id, value) => { // Create new article element const item = document.createElement('article'); // Add class to the newly created element. item.classList.add('shopping-list-item'); // Initialize attribute to be added to the element // and set it to the randomly generated id. const attribute = document.createAttribute('data-id'); attribute.value = id; // Add atribute to the element. item.setAttributeNode(attribute); // Add HTML dynamically to the article element. item.innerHTML = ` <p class="title">${value}</p> <div class="btn-container"> <button type="button" class="edit-btn"> <i class="fa-solid fa-pen"></i> </button> <button type="button" class="delete-btn"> <i class="fa-solid fa-trash-can"></i> </button> </div> `; // Initialize buttons when the item is added to the DOM so we can actually use them. const deleteBtn = item.querySelector('.delete-btn'); const editBtn = item.querySelector('.edit-btn'); deleteBtn.addEventListener('click', deleteItem); editBtn.addEventListener('click', editItem); // Append the article to the list list.appendChild(item); // Dynamically add class that changes visibility of the list container.classList.add('show-container'); }; // Main functions. const addItem = (e) => { e.preventDefault(); const value = inputItem.value; const id = getRandomID(); // Adding an item. if (value && !isEditing) { createListItem(id, value); displayAlert('Item added to the list!', 'success'); // Add to local storage. addToLocalStorage(id, value); // Reset input to empty setToDefaultValue(); // Editing an item. } else if (value && isEditing) { // Set the value of the currently editing item to the newly inserted value from the input box. editingItem.innerHTML = value; displayAlert('Value changed!', 'success'); // Edit local storage editLocalStorage(editID, value); setToDefaultValue(); } else { displayAlert('Please enter a value.', 'danger'); } }; // Clear shopping list. const resetItems = () => { // Get all added items. const items = document.querySelectorAll('.shopping-list-item'); if (items.length > 0) { // Remove them all. items.forEach((item) => { list.removeChild(item); }); } // Hide the container. container.classList.remove('show-container'); displayAlert('List reseted!', 'danger'); setToDefaultValue(); localStorage.removeItem('shopping-list'); }; const deleteItem = (e) => { // Get an item's position in DOM. const element = e.currentTarget.parentElement.parentElement; // Get an item's id from its dataset. const id = element.dataset.id; // Add timeout to mimick API call. setTimeout(() => { // Remove it from the DOM. list.removeChild(element); // Check if the deleted item was the last item in the list remaining. // If it is, hide container. if (list.children.length === 0) { container.classList.remove('show-container'); } }, 600); displayAlert('Item removed!', 'success'); setToDefaultValue(); removeFromLocalStorage(id); }; const editItem = (e) => { // Get an item's position in DOM. const element = e.currentTarget.parentElement.parentElement; // Get element's id. editID = element.dataset.id; // Initialize the item that we want to change its value. // .parentElement = div'btn-container', .previousElementSibling = div'title'. editingItem = e.currentTarget.parentElement.previousElementSibling; // Get its value and initialize it to the form input value. inputItem.value = editingItem.innerHTML; // Set editing flag to true. isEditing = true; // Change button's text from 'Add' to 'Edit'. addBtn.textContent = 'Edit'; }; // Local storage. const addToLocalStorage = (id, value) => { const item = { id, value }; let items = getLocalStorage(); items.push(item); localStorage.setItem('shopping-list', JSON.stringify(items)); }; const removeFromLocalStorage = (id) => { let items = getLocalStorage(); items = items.filter((item) => item.id !== id); localStorage.setItem('shopping-list', JSON.stringify(items)); }; const editLocalStorage = (id, value) => { let items = getLocalStorage(); // Iterate through items in local storage array items = items.map((item) => { if (item.id === id) { // If found, edit its value to the new value item.value = value; } return item; }); localStorage.setItem('shopping-list', JSON.stringify(items)); }; // Load items from the local storage on refresh. const loadItems = () => { let items = getLocalStorage(); // If local storage entry exist, loop through and create items in the list from them. if (items.length > 0) { items.forEach((item) => { createListItem(item.id, item.value); }); } }; // Event handlers form.addEventListener('submit', addItem); resetBtn.addEventListener('click', resetItems); // On refresh window.addEventListener('DOMContentLoaded', loadItems);
import { View, Text, Image } from 'react-native' import React, { useState } from 'react' import { useActionSheet } from '@expo/react-native-action-sheet'; import { useDispatch } from 'react-redux'; import ImageActionSheet from './ImageActionSheet'; import { USER_IMAGE_URL } from '../../constants'; import styled from 'styled-components'; import { editUserData } from '../../store/actions/UserActions'; import Icon from 'react-native-vector-icons/Ionicons' import * as ImagePicker from 'expo-image-picker'; import * as FileSystem from 'expo-file-system'; const imgDir = FileSystem.documentDirectory + 'images/'; const UserImage = ({userImage}) => { const [isLoading, setIsLoading] = useState(false); const dispatch = useDispatch(); const chooseImage = async () => { const res = await ImagePicker.launchImageLibraryAsync({ quality: 0.3, allowsEditing: true, aspect: [200, 200] }) .then(data=> { if(!data.canceled){ saveImage(data.assets[0].uri) } }) .catch(error => console.log(error)); } const createImage = async () => { const res = await ImagePicker.launchCameraAsync({ quality: 1, allowsEditing: true, aspect: [200, 200] }) .then(data=> { if(!data.canceled){ saveImage(data.assets[0].uri); } }) .catch(e => alert(e)) } const saveImage = async (uri) => { const filename = new Date().getTime() + '.jpg'; const dest = imgDir + filename; await FileSystem.deleteAsync(imgDir); await FileSystem.copyAsync({from: uri, to: dest}) .then( ()=> { return FileSystem.readDirectoryAsync(imgDir) }) .then(data=> dispatch(editUserData('image', dest))) .catch(error => console.log(error)); } const deleteImage = () => { dispatch(editUserData('image', null)); } return ( <ImageActionSheet chooseImage={chooseImage} createImage={createImage} deleteImage={deleteImage}> {userImage !== null || isLoading ? <UserImageItem onLoadStart={e => { setIsLoading(true) }} onLoadEnd={e =>setIsLoading(false)} source={{uri: userImage}} /> : <Icon style={{margin: 10}} size={30} name='camera-outline'/> } </ImageActionSheet> ) }; const UserImageItem = styled.Image` border-radius: 25px; background-color: #eaeaea; width: 50px; height: 50px; object-fit: cover; ` export default UserImage
/* Run TLC9711 over SPI on PI PICO * using inline code * (Based on the Adafruit TLC59711 PWM/LED driver library, authors: Limor Fried & Ladyada). * MRD 19/03/2023 ver 01 */ //#include <SPI.h> #include <SPI.h> #include <Arduino.h> // General constants #define HIGHLIGHT_TIMEOUT 60000 // TLC9711 variables and constants #define DATAIN 16 // not used by TLC59711 breakout #define CHIPSELECT 17 // not used by TLC59711 breakout #define SPICLOCK 18 // ci on TLC59711 breakout #define DATAOUT 19 // di on TLC59711 breakout #define SPI_FREQ 14000000 // SPI frequency #define LED_BRIGHT 0x7F #define RAMP_UP 255 #define RAMP_DOWN -255 #define MIN_PWM 0 #define MAX_PWM 65535 const int8_t numdrivers = 1; // number of chained breakout boards const int8_t numChannels = 12 * numdrivers; uint8_t BCr = LED_BRIGHT; uint8_t BCg = LED_BRIGHT; uint8_t BCb = LED_BRIGHT; // Array of struct to hold current pwm and ramp direction for each channel struct channelState { long pwm; int ramp; } channelStates[numChannels]; // TLC9711 functions // Initialise SPI for PI PICO void setupSPI() { pinMode(SPICLOCK, OUTPUT); pinMode(DATAOUT, OUTPUT); SPI.setSCK(SPICLOCK); SPI.setTX(DATAOUT); delay(5); SPI.begin(); delay(5); } // Write channel pwm info to TLC59711 void tlcWrite() { uint32_t command; // Magic word for write command = 0x25; command <<= 5; // OUTTMG = 1, EXTGCK = 0, TMGRST = 1, DSPRPT = 1, BLANK = 0 -> 0x16 command |= 0x16; command <<= 7; command |= BCr; command <<= 7; command |= BCg; command <<= 7; command |= BCb; SPI.beginTransaction(SPISettings(SPI_FREQ, MSBFIRST, SPI_MODE0)); for (uint8_t n = 0; n < numdrivers; n++) { SPI.transfer(command >> 24); SPI.transfer(command >> 16); SPI.transfer(command >> 8); SPI.transfer(command); // 12 channels per TLC59711 for (int8_t c = 11; c >= 0; c--) { // 16 bits per channel, send MSB first SPI.transfer(channelStates[n * 12 + c].pwm >> 8); SPI.transfer(channelStates[n * 12 + c].pwm); } } delayMicroseconds(200); SPI.endTransaction(); } // Set all channels to same pwm and ramp setting. void setAllChannels(long pwm, int ramp) { for(int channel = 0; channel < numChannels; channel++){ channelStates[channel].pwm = pwm; channelStates[channel].ramp = ramp; } } // Fade lamps according to setting for each channel in the ramp buffer. void fadeLamps() { for(int iter = 0; iter < 258; iter++) { tlcWrite(); for(int channel = 0; channel < numChannels; channel++){ channelStates[channel].pwm = calculateNewPwm(channelStates[channel].pwm,channelStates[channel].ramp); } delay(10); } } // Identify a single channel to be faded up, mark others to be faded down. void highlightLamp(uint32_t highlitChannel){ for(int channel = 0; channel < numChannels; channel++){ channelStates[channel].ramp = RAMP_DOWN; } channelStates[highlitChannel].ramp = RAMP_UP; } // Calculate new pwm value based on current pwm and ramp values. long calculateNewPwm(long pwm, int ramp){ long newPwm = pwm + ramp; if(newPwm < MIN_PWM) { newPwm = MIN_PWM; } else if(newPwm > MAX_PWM){ newPwm = MAX_PWM; } return newPwm; } // Test that a channel number is within range of available channels. bool channelInRange(int chan) { return (chan > -1 && chan < numChannels); } // Print channle states void printChannelStates() { for(int channel = 0; channel < numChannels; channel++){ Serial.print(channel); Serial.print(" "); Serial.print(channelStates[channel].pwm); Serial.print(" "); Serial.println(channelStates[channel].ramp); } } int highlight = 0; void setup() { Serial.begin(9600); while(!Serial){} delay(100); } void loop() { uint32_t channelIn = 99; while(Serial.available()) { channelIn = Serial.read() - 'A'; if(channelInRange(channelIn)) { //Serial.printf("Sending to C2\n"); rp2040.fifo.push_nb(channelIn); } } delay(10); } void setup1() { pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); setupSPI(); delay(100); setAllChannels(MIN_PWM, RAMP_UP); fadeLamps(); } void loop1() { static long lastHighlightTS = 0; if(rp2040.fifo.available() > 0){ uint32_t highlight = rp2040.fifo.pop(); highlightLamp(highlight); fadeLamps(); lastHighlightTS = millis(); } else if(lastHighlightTS > 0 && millis() > (lastHighlightTS + HIGHLIGHT_TIMEOUT)) { setAllChannels(MIN_PWM, RAMP_UP); fadeLamps(); lastHighlightTS = 0; } delay(20); }
// dotenv should be first line executed require('dotenv').config(); import { ForbiddenError, UnauthorizedError } from '@overture-stack/ego-token-middleware'; import cors from 'cors'; import express, { NextFunction, Request, Response } from 'express'; import swaggerUi from 'swagger-ui-express'; import { ServiceError } from './common/errors'; import { GeneralErrorType } from './common/types'; import { SERVER_PORT } from './config'; import swaggerDocument from './resources/swagger-def.json'; import studiesRouter from './routes/studies'; // *** create and init app *** const app = express(); app.use(cors()); app.use(express.json()); // *** setup endpoints *** app.get('/', (_req: Request, res: Response) => { res.send({ endpoints: { healthCheck: '/health', swaggerUi: '/api-docs' } }); }); app.get('/health', (_req: Request, res: Response) => { res.send(true); }); app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); app.use('/studies', studiesRouter); // *** define error handler *** app.use(function ( err: ServiceError | UnauthorizedError | ForbiddenError | Error, _req: Request, res: Response, _next: NextFunction ) { console.error(err.message); console.error(err.stack); if (err instanceof ServiceError) { const { httpStatus, type, studyId, submitters } = err; res.status(httpStatus).json({ success: false, error: { type, studyId, submitters } }); } else if (err instanceof UnauthorizedError) { res.status(401).send({ success: false, error: { message: err.message, type: GeneralErrorType.UNAUTHORIZED }, }); } else if (err instanceof ForbiddenError) { res.status(403).send({ success: false, error: { message: err.message, type: GeneralErrorType.FORBIDDEN }, }); } else { res.status(500).send({ success: false, error: { message: 'Internal Server Error! Reason is unknown!', type: GeneralErrorType.UNKNOWN, }, }); } }); // *** listen on port *** app.listen(SERVER_PORT, () => console.log(`App should be running at ${SERVER_PORT}!`));
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, map } from 'rxjs/operators'; import { environment } from '../../environments/environment'; import { User } from '../../app/login/usuarioEntity'; @Injectable({ providedIn: 'root' }) export class AuthenticationService { private userSubject: BehaviorSubject<User>; public user: Observable<User>; constructor( private router: Router, private http: HttpClient ) { this.userSubject = new BehaviorSubject<User>({} as any); this.user = this.userSubject.asObservable(); } public get userValue(): User { if (localStorage.getItem('userToken') != null) { // let userToken = localStorage.getItem('userToken') || '{}'; let userToken = localStorage.getItem('userToken'); let jsonObj = JSON.parse(userToken!); let us = new User(); us = jsonObj as User; return us; } return this.userSubject.value; } login(username: string, password: string) { return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password }, { withCredentials: true }) .pipe(map(user => { if (user.sucesso === false) { this.handleError(user.mensagemRetorno); } this.userSubject.next(user); localStorage.setItem('userToken', JSON.stringify(user)); localStorage.setItem('refreshToken', user.jwtToken); //localStorage.setItem('refreshToken', JSON.stringify(user.jwtToken)); this.startRefreshTokenTimer(); return user; }), catchError(this.handleError)); } handleError(error: any) { //Limpar Token localStorage.removeItem('refreshToken'); localStorage.removeItem('userToken'); let errorMessage = ''; if (error.error instanceof ErrorEvent) { // client-side error errorMessage = `Error: ${error.error.message}`; } else { // server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } return throwError(() => { return errorMessage; }); } logout() { this.http.post<any>(`${environment.apiUrl}/users/revoke-token`, {}, { withCredentials: true }).subscribe(); this.stopRefreshTokenTimer(); this.userSubject.next({} as any); this.router.navigate(['/login']); } obterRefreshTokenCookies() { console.log('obterRefreshTokenCookies'); if (localStorage.getItem('refreshToken')) { //Verificar validade token return (localStorage.getItem('refreshToken')); } else return null; } refreshToken() { return this.http.post<any>(`${environment.apiUrl}/users/refresh-token`, {}, { withCredentials: true }) .pipe(map((user) => { this.userSubject.next(user); this.startRefreshTokenTimer(); return user; })); } // helper methods private refreshTokenTimeout: any; private startRefreshTokenTimer() { // // parse json object from base64 encoded jwt token // const to = atob(this.userValue.jwtToken?.split('.')[1]); // const jwtToken = JSON.parse(to); // // set a timeout to refresh the token a minute before it expires // const expires = new Date(jwtToken.exp * 1000); // const timeout = expires.getTime() - Date.now() - (60 * 1000); // this.refreshTokenTimeout = setTimeout(() => this.refreshToken().subscribe(), timeout); } private stopRefreshTokenTimer() { clearTimeout(this.refreshTokenTimeout); } setBaseUrlApi() { environment.apiUrl = `${environment.protocolo}://${window.location.hostname}:${environment.porta}`; } getNomeUsuarioLogado() { let user = this.userValue; if (user) return user.username; else return ''; } }
<div class="d-flex justify-content-center"> <div class="col-8"> <form name="editForm" role="form" novalidate (ngSubmit)="save()" [formGroup]="editForm"> <h2 id="jhi-company-heading" data-cy="CompanyCreateUpdateHeading" jhiTranslate="sefinaApp.company.home.createOrEditLabel"> Criar ou editar Company </h2> <div> <jhi-alert-error></jhi-alert-error> <div class="row mb-3" *ngIf="editForm.controls.id.value !== null"> <label class="form-label" jhiTranslate="global.field.id" for="field_id">ID</label> <input type="number" class="form-control" name="id" id="field_id" data-cy="id" formControlName="id" [readonly]="true" /> </div> <div class="row mb-3"> <label class="form-label" jhiTranslate="sefinaApp.company.name" for="field_name">Name</label> <input type="text" class="form-control" name="name" id="field_name" data-cy="name" formControlName="name" /> </div> <div class="row mb-3"> <label class="form-label" jhiTranslate="sefinaApp.company.cnpj" for="field_cnpj">Cnpj</label> <input type="text" class="form-control" name="cnpj" id="field_cnpj" data-cy="cnpj" formControlName="cnpj" /> <div *ngIf="editForm.get('cnpj')!.invalid && (editForm.get('cnpj')!.dirty || editForm.get('cnpj')!.touched)"> <small class="form-text text-danger" *ngIf="editForm.get('cnpj')?.errors?.required" jhiTranslate="entity.validation.required"> O campo é obrigatório. </small> </div> </div> <div class="row mb-3"> <label class="form-label" jhiTranslate="sefinaApp.company.address" for="field_address">Address</label> <input type="text" class="form-control" name="address" id="field_address" data-cy="address" formControlName="address" /> </div> <div class="row mb-3"> <label class="form-label" jhiTranslate="sefinaApp.company.createdAt" for="field_createdAt">Created At</label> <div class="input-group"> <input id="field_createdAt" data-cy="createdAt" type="text" class="form-control" name="createdAt" ngbDatepicker #createdAtDp="ngbDatepicker" formControlName="createdAt" /> <button type="button" class="btn btn-secondary" (click)="createdAtDp.toggle()"><fa-icon icon="calendar-alt"></fa-icon></button> </div> </div> <div class="row mb-3"> <label class="form-label" jhiTranslate="sefinaApp.company.updatedAt" for="field_updatedAt">Updated At</label> <div class="input-group"> <input id="field_updatedAt" data-cy="updatedAt" type="text" class="form-control" name="updatedAt" ngbDatepicker #updatedAtDp="ngbDatepicker" formControlName="updatedAt" /> <button type="button" class="btn btn-secondary" (click)="updatedAtDp.toggle()"><fa-icon icon="calendar-alt"></fa-icon></button> </div> </div> </div> <div> <button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" (click)="previousState()"> <fa-icon icon="ban"></fa-icon>&nbsp;<span jhiTranslate="entity.action.cancel">Cancelar</span> </button> <button type="submit" id="save-entity" data-cy="entityCreateSaveButton" [disabled]="editForm.invalid || isSaving" class="btn btn-primary" > <fa-icon icon="save"></fa-icon>&nbsp;<span jhiTranslate="entity.action.save">Salvar</span> </button> </div> </form> </div> </div>
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable import torchvision.datasets as dset class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): self.sum += val * n self.cnt += n self.avg = self.sum / self.cnt def accuracy(output, target): batch_size = target.size(0) _, pred = output.max(1) correct = pred.eq(target).sum().item() accu = 100* (correct / batch_size) return accu class Temperature_Scheduler(object): def __init__(self, total_epochs, curr_temp=1, base_temp=1, min_temp=0.03, last_epoch=-1): self.curr_temp = curr_temp self.base_temp = base_temp self.min_temp = min_temp self.last_epoch = last_epoch self.total_epochs = total_epochs self.step(last_epoch + 1) def step(self, epoch=None): if epoch is None: epoch = self.last_epoch + 1 self.last_epoch = epoch self.curr_temp = (1 - (self.last_epoch / self.total_epochs)) * (self.base_temp - self.min_temp) + self.min_temp self.curr_temp = self.min_temp if self.curr_temp < self.min_temp else self.curr_temp return self.curr_temp class Cutout(object): def __init__(self, length): self.length = length def __call__(self, img): h, w = img.size(1), img.size(2) mask = np.ones((h, w), np.float32) y = np.random.randint(h) x = np.random.randint(w) y1 = np.clip(y - self.length // 2, 0, h) y2 = np.clip(y + self.length // 2, 0, h) x1 = np.clip(x - self.length // 2, 0, w) x2 = np.clip(x + self.length // 2, 0, w) mask[y1: y2, x1: x2] = 0. mask = torch.from_numpy(mask) mask = mask.expand_as(img) img *= mask return img class RandomGaussianNoise(object): def __init__(self, prob=0.5): self.prob = prob def __call__(self, img): if np.random.random() <= self.prob: return img + torch.randn(img.size) return img def _data_transforms_cifar10_nabk_v1(args): CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124] CIFAR_STD = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomChoice([transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip()], ), transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), transforms.RandomErasing(scale=(0.02, 0.4), value='random'), # default, p=0.5, ratio=(0.3, 3.3) ]) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) return train_transform, valid_transform def _data_transforms_cifar10_nabk_v2(args): CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124] CIFAR_STD = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomChoice([transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip()], ), transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.2), transforms.ToTensor(), transforms.RandomErasing(scale=(0.02, 0.4), value='random'), # default, p=0.5, ratio=(0.3, 3.3) transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) return train_transform, valid_transform def _data_transforms_cifar10_ecoNAS(args): CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124] CIFAR_STD = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.Resize(args.resolution), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) return train_transform, valid_transform def _data_transforms_cifar10(args): CIFAR_MEAN = [0.49139968, 0.48215827, 0.44653124] CIFAR_STD = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose([ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(CIFAR_MEAN, CIFAR_STD), ]) return train_transform, valid_transform def _data_imagenet(args): traindir = os.path.join(args.data, 'train') # validdir = os.path.join(args.data, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_data = dset.ImageFolder( traindir, transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ])) return train_data def count_parameters_in_MB(model): return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if "auxiliary" not in name) / 1e6 def save_checkpoint(state, is_best, save): filename = os.path.join(save, 'checkpoint.pth.tar') torch.save(state, filename) if is_best: best_filename = os.path.join(save, 'model_best.pth.tar') shutil.copyfile(filename, best_filename) def save(model, model_path): torch.save(model.state_dict(), model_path) def load(model, model_path): model.load_state_dict(torch.load(model_path, map_location='cpu')) def drop_path(x, drop_prob): if drop_prob > 0.: keep_prob = 1. - drop_prob mask = Variable(torch.cuda.FloatTensor(x.size(0), 1, 1, 1).bernoulli_(keep_prob)) x.div_(keep_prob) x.mul_(mask) return x def create_exp_dir(path, scripts_to_save=None): if not os.path.exists(path): os.mkdir(path) print('Experiment dir : {}'.format(path)) if scripts_to_save is not None: os.mkdir(os.path.join(path, 'scripts')) for script in scripts_to_save: dst_file = os.path.join(path, 'scripts', os.path.basename(script)) shutil.copyfile(script, dst_file)
// Source: https://www.hackerrank.com/challenges/cut-the-sticks/problem?isFullScreen=true 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', function(inputStdin) { inputString += inputStdin; }); process.stdin.on('end', function() { inputString = inputString.split('\n'); main(); }); function readLine() { return inputString[currentLine++]; } function main() { const _SIZE = +readLine(); const ARRAY = readAnArray(); ARRAY.sort((a, b) => a - b); const OBJ = new CutTheSticks(ARRAY); const RESULT = OBJ.getRemainingSticksLengthArray(); printArray(RESULT); } function readAnArray() { return readLine().split(" ").map(Number); } function printArray(array) { array.forEach((element, _) => console.log(element)); } class CutTheSticks { #sticksLengthArray; #sizeSticksLengthArray; #remainingSticksLengthArray; constructor(array) { this.#sticksLengthArray = array; this.#sizeSticksLengthArray = array.length; this.#initializeRemainingSticksLengthArray(); this.#cutTheSticks(); } #initializeRemainingSticksLengthArray() { this.#remainingSticksLengthArray = [this.#sizeSticksLengthArray]; } #cutTheSticks() { for (let i = 0; i < this.#sizeSticksLengthArray; ) { const SHORTEST_STICK_LENGTH = this.#sticksLengthArray[i]; i = this.#findFirstElementIndexDifferentOfFirstCurrentShortestStickLengthIndex(i); const CURRENT_ITERATION_SIZE = this.#sizeSticksLengthArray - i; if (i === this.#sizeSticksLengthArray) break; this.#remainingSticksLengthArray.push(CURRENT_ITERATION_SIZE); this.#decreaseSticksLengthsHigherThanCurrentShortestStickLength(i, SHORTEST_STICK_LENGTH); } } #findFirstElementIndexDifferentOfFirstCurrentShortestStickLengthIndex(index) { const SHORTEST_STICK_LENGTH = this.#sticksLengthArray[index]; while (index < this.#sizeSticksLengthArray && this.#sticksLengthArray[index] === SHORTEST_STICK_LENGTH) index++; return index; } #decreaseSticksLengthsHigherThanCurrentShortestStickLength(index, shortestStickLength) { for (let i = index; i < this.#sizeSticksLengthArray; i++) this.#sticksLengthArray[i] -= shortestStickLength; } getRemainingSticksLengthArray() { return this.#remainingSticksLengthArray; } }
import React, { useState, useEffect } from 'react'; import { connect } from 'react-redux'; import ArticleClassic from '~/components/elements/articles/ArticleClassic'; import ViewAllPosts from '~/components/elements/ViewAllPosts'; import PostRepository from '~/repositories/PostRepository'; const HomeMinimalistPostItems = ({ collectionSlug }) => { const [loading, setLoading] = useState(true); const [posts, setPosts] = useState(null); async function getPosts() { let queries, APIPosts; if (collectionSlug !== undefined) { queries = { slug_eq: collectionSlug }; APIPosts = await PostRepository.SPGetPostItemOfCollectionBySlug(queries); } else { queries = { _limit: 6 }; APIPosts = await PostRepository.getPosts(queries); } if (APIPosts) { setTimeout(function() { setLoading(false); }, 200); setPosts(APIPosts); return APIPosts; } else { setPosts(null); return null; } } useEffect(() => { getPosts(); }, []); let viewPostItems; if (!loading && posts) { viewPostItems = posts.map((item) => <ArticleClassic post={item} key={item.id}/>); } return ( <section className="ps-section--home-timeline"> <div className="ps-section__content"> <div className="ps-post-items">{viewPostItems}</div> </div> <ViewAllPosts/> </section> ); }; export default connect((state) => state.collection)(HomeMinimalistPostItems);
// // Dagor Engine 6.5 // Copyright (C) 2023 Gaijin Games KFT. All rights reserved // (for conditions of use see prog/license.txt) // #pragma once #include "dag_bindump.h" #include <ioSys/dag_fileIo.h> #include <ioSys/dag_zstdIo.h> #include <generic/dag_span.h> #include <EASTL/string_view.h> #include <EASTL/string.h> #include <dag/dag_vector.h> namespace bindump { struct SizeMetter : IWriter { uint64_t mSize = 0; void begin() override { mSize = 0; } void end() override {} uint64_t append(uint64_t size) override { uint64_t offset = mSize; mSize += size; return offset; } void write(uint64_t, const void *, uint64_t) override {} }; template <typename Cont> struct MemoryWriterBase : IWriter { Cont mData; void begin() override { mData.clear(); } void end() override {} uint64_t append(uint64_t size) override { uint64_t offset = mData.size(); mData.resize(offset + size); return offset; } void write(uint64_t offset, const void *src_data, uint64_t src_size) override { G_ASSERT(offset + src_size <= mData.size()); const uint8_t *data_start = (const uint8_t *)src_data; eastl::copy(data_start, data_start + src_size, mData.begin() + offset); } }; // TODO: Should be removed as soon as we switch to `dag::Vector` in all places where the `MemoryWriter` is used using MemoryWriter = MemoryWriterBase<eastl::vector<uint8_t>>; using VectorWriter = MemoryWriterBase<dag::Vector<uint8_t>>; class FileWriter : public IWriter { FullFileSaveCB mSaver; public: FileWriter(const char *filename) : mSaver(filename) {} explicit operator bool() const { return mSaver.fileHandle != nullptr; } void begin() override { mSaver.seekto(0); } void end() override { mSaver.close(); } uint64_t append(uint64_t size) override { uint64_t offset = mSaver.tell(); eastl::vector<char> empty_data(size); mSaver.write(empty_data.data(), empty_data.size()); return offset; } void write(uint64_t offset, const void *src_data, uint64_t src_size) override { int size = mSaver.tell(); G_ASSERT(offset + src_size <= size); mSaver.seekto((int)offset); mSaver.write(src_data, (int)src_size); mSaver.seekto(size); } }; class MemoryReader : public IReader { const uint8_t *mData = nullptr; const uint64_t mSize; public: MemoryReader(const uint8_t *data, uint64_t size) : mData(data), mSize(size) {} void begin() override {} void end() override {} void read(uint64_t offset, void *dest_data, uint64_t dest_size) override { G_ASSERT(offset + dest_size <= mSize); eastl::copy(mData + offset, mData + offset + dest_size, (uint8_t *)dest_data); } }; class FileReader : public IReader { FullFileLoadCB mLoader; public: FileReader(const char *filename) : mLoader(filename) {} explicit operator bool() const { return mLoader.fileHandle != nullptr; } void begin() override { mLoader.seekto(0); } void end() override { mLoader.close(); } void read(uint64_t offset, void *dest_data, uint64_t dest_size) override { mLoader.seekto(offset); mLoader.read(dest_data, (int)dest_size); } }; template <typename LayoutType> bool writeToFileFast(const LayoutType &layout, const char *filename) { FullFileSaveCB saver(filename); if (!saver.fileHandle) return false; SizeMetter size_metter; streamWrite(layout, size_metter); MemoryWriter mem_writer; mem_writer.mData.reserve(size_metter.mSize); streamWrite(layout, mem_writer); saver.write(mem_writer.mData.data(), mem_writer.mData.size()); return true; } namespace detail { template <enum detail::Target target> struct StrHolderBase : public traits::List<char, 1, target> { bool empty() const { return this->size() == 0; } uint64_t length() const { return !empty() ? this->size() - 1 : 0; } const char *c_str() const { return !empty() ? this->getDataPtr() : ""; } operator eastl::string_view() const { return eastl::string_view(c_str(), length()); } explicit operator const char *() const { return c_str(); } }; template <typename UserDataType, uint64_t alignment, enum detail::Target target> struct VecHolderBase : public traits::List<UserDataType, alignment, target> { bool empty() const { return this->size() == 0; } operator dag::ConstSpan<UserDataType>() const { return {data(), (intptr_t)this->size()}; } operator dag::Span<UserDataType>() { return {data(), (intptr_t)this->size()}; } const UserDataType *begin() const { return this->getDataPtr(); } const UserDataType *end() const { return this->getDataPtr() + this->size(); } UserDataType *begin() { return this->getDataPtr(); } UserDataType *end() { return this->getDataPtr() + this->size(); } const UserDataType *data() const { return this->getDataPtr(); } UserDataType *data() { return this->getDataPtr(); } }; #pragma pack(push, 1) template <typename UserDataType, enum detail::Target target> class SpanBase : public traits::Address<UserDataType, target> { protected: uint32_t mCount = 0; public: uint32_t size() const { return mCount; } const UserDataType &operator[](uint64_t no) const { return *(data() + no); } UserDataType &operator[](uint64_t no) { return *(data() + no); } operator dag::ConstSpan<UserDataType>() const { return {data(), (intptr_t)size()}; } explicit operator const UserDataType *() const { return data(); } const UserDataType &back() const { return *(end() - 1); } const UserDataType *begin() const { return data(); } const UserDataType *end() const { return data() + size(); } const UserDataType *data() const { return size() ? this->getDataPtr() : nullptr; } UserDataType *begin() { return data(); } UserDataType *end() { return data() + size(); } UserDataType *data() { return size() ? this->getDataPtr() : nullptr; } UserDataType &get() = delete; const UserDataType &get() const = delete; }; #pragma pack(pop) } // namespace detail template <enum detail::Target target = detail::MASTER> struct StrHolder : public detail::StrHolderBase<target> { template <enum detail::Target t> using MyLayout = StrHolder<t>; }; template <> struct StrHolder<detail::MASTER> : public detail::StrHolderBase<detail::MASTER> { template <enum detail::Target t> using MyLayout = StrHolder<t>; StrHolder &operator=(eastl::string_view str) { this->resize(str.size() + 1); eastl::copy(str.begin(), str.end(), this->mData.begin()); this->mData[str.size()] = 0; return *this; } }; template <typename UserDataType, uint64_t alignment = 1, enum detail::Target target = detail::MASTER> struct VecHolder : public detail::VecHolderBase<detail::traits::RetargetType<UserDataType, target>, alignment, target> { template <enum detail::Target t> using MyLayout = VecHolder<UserDataType, alignment, t>; }; template <typename UserDataType, uint64_t alignment> struct VecHolder<UserDataType, alignment, detail::MASTER> : public detail::VecHolderBase<UserDataType, alignment, detail::MASTER> { template <enum detail::Target t> using MyLayout = VecHolder<UserDataType, alignment, t>; VecHolder() = default; VecHolder(const VecHolder &) = default; VecHolder &operator=(const VecHolder &) = default; VecHolder &operator=(VecHolder &&other) noexcept { this->mData = eastl::move(other.mData); this->mListOffset = eastl::move(other.mListOffset); return *this; } VecHolder(const detail::traits::List<UserDataType, alignment, detail::MASTER> &vec) { detail::traits::List<UserDataType, alignment, detail::MASTER>::operator=(vec); } VecHolder(const eastl::vector<UserDataType> &vec) { *this = vec; } VecHolder(dag::Span<UserDataType> slice) { *this = slice; } VecHolder &operator=(const eastl::vector<UserDataType> &vec) { this->mData = vec; return *this; } VecHolder &operator=(eastl::vector<UserDataType> &&vec) noexcept { this->mData = eastl::move(vec); return *this; } VecHolder &operator=(dag::Span<UserDataType> slice) { this->mData.assign(slice.begin(), slice.end()); return *this; } VecHolder &operator=(dag::ConstSpan<UserDataType> slice) { this->mData.assign(slice.begin(), slice.end()); return *this; } eastl::vector<UserDataType> &content() { return this->mData; } operator eastl::vector<UserDataType>() && { return eastl::move(this->mData); } }; template <typename UserDataType, enum detail::Target target = detail::MASTER> struct Span : public detail::SpanBase<detail::traits::RetargetType<UserDataType, target>, target> { template <enum detail::Target t> using MyLayout = Span<UserDataType, t>; }; template <typename UserDataType> struct Span<UserDataType, detail::MASTER> : public detail::SpanBase<UserDataType, detail::MASTER> { template <enum detail::Target t> using MyLayout = Span<UserDataType, t>; using detail::traits::Address<UserDataType, detail::MASTER>::operator=; void setCount(uint32_t count) { this->mCount = count; } bool operator!=(const Span &other) const { return !operator==(other); } bool operator==(const Span &other) const { return this->begin() == other.begin() && this->size() == other.size(); } }; enum class BehaviorOnUncompressed { Copy, Reference, }; namespace detail { #pragma pack(push, 1) template <typename DataType> struct Compressed { BINDUMP_BEGIN_LAYOUT(Type) private: uint32_t decompressedSize = 0; VecHolder<uint8_t, 1, target> compressedData; public: uint32_t getDecompressedSize() const { return decompressedSize; } uint32_t getCompressedSize() const { return compressedData.size(); } template <typename DataTypeEx = DataType> size_t compress(const DataTypeEx &data, int level, ZSTD_CCtx_s *ctx = nullptr, const ZSTD_CDict_s *dict = nullptr) { static_assert(eastl::is_base_of_v<DataType, DataTypeEx>, "DataTypeEx must be derived from DataType"); static_assert(target == MASTER, "Unable to call compress() method on Mapper side"); MemoryWriter writer; streamWriteLayout(data, writer); if (level < 0) { compressedData = eastl::move(writer.mData); return compressedData.size(); } compressedData.resize(zstd_compress_bound(writer.mData.size())); size_t compressed_size = 0; if (dict) compressed_size = zstd_compress_with_dict(ctx, compressedData.data(), compressedData.size(), writer.mData.data(), writer.mData.size(), dict); else compressed_size = zstd_compress(compressedData.data(), compressedData.size(), writer.mData.data(), writer.mData.size(), level); G_ASSERT(compressed_size <= compressedData.size()); decompressedSize = writer.mData.size(); compressedData.resize(compressed_size); return compressedData.size(); } template <typename Cont> DataType *decompress(Cont & out_data, BehaviorOnUncompressed bou, const ZSTD_DDict_s *dict = nullptr) const { static_assert(target == MAPPER, "Unable to call decompress() method on Master side"); static_assert(sizeof(typename Cont::value_type) == 1, "The container must consist of single-byte elements"); if (decompressedSize) { out_data.resize(decompressedSize); size_t decompressed_size = 0; if (EASTL_LIKELY(dict)) { ZSTD_DCtx_s *dctx = zstd_create_dctx(/*tmp*/ true); // tmp for framemem decompressed_size = zstd_decompress_with_dict(dctx, out_data.data(), out_data.size(), compressedData.data(), compressedData.size(), dict); zstd_destroy_dctx(dctx); } else // TODO: use tmp context too decompressed_size = zstd_decompress(out_data.data(), out_data.size(), compressedData.data(), compressedData.size()); if (decompressed_size != decompressedSize) return nullptr; } else if (bou == BehaviorOnUncompressed::Reference) { out_data.clear(); return map<DataType>((uint8_t *)compressedData.data()); } else { out_data.assign(compressedData.begin(), compressedData.end()); } return map<DataType>(out_data.data()); } BINDUMP_END_LAYOUT() }; #pragma pack(pop) } // namespace detail template <template <enum detail::Target> class LayoutClass> using CompressedLayout = typename detail::Compressed<detail::EnableHash<LayoutClass, detail::MASTER>>::template Type<detail::MASTER>; template <typename UserDataType> using Compressed = typename detail::Compressed<UserDataType>::template Type<detail::MASTER>; #define BINDUMP_USING_EXTENSION() \ template <typename UserDataType, uint64_t alignment = 1> \ using VecHolder = bindump::VecHolder<UserDataType, alignment, target>; \ template <typename UserDataType> \ using Span = bindump::Span<UserDataType, target>; \ using StrHolder = bindump::StrHolder<target>; \ template <template <enum bindump::detail::Target> class LayoutClass> \ using CompressedLayout = \ typename bindump::detail::Compressed<bindump::detail::EnableHash<LayoutClass, target>>::template Type<target>; \ template <typename UserDataType> \ using Compressed = typename bindump::detail::Compressed<UserDataType>::template Type<target>; template <typename Type> class vector : public eastl::vector<Type> { void serialize() const { uint32_t count = this->size(); stream::writeAux(count); stream::write(this->data(), count); } void deserialize() { uint32_t count = 0; stream::readAux(count); this->resize(count); stream::read(this->data(), count); } void hashialize() const { stream::hash<Type>(); } public: BINDUMP_ENABLE_STREAMING(vector, eastl::vector<Type>, vector); }; class string : public eastl::string { void serialize() const { uint32_t count = this->length(); stream::writeAux(count); stream::write(this->data(), count); } void deserialize() { uint32_t count = 0; stream::readAux(count); this->resize(count); stream::read(this->begin(), count); } void hashialize() const { stream::hash<char>(); } public: BINDUMP_ENABLE_STREAMING(string, eastl::string, string); }; template <typename Type> class Ptr { eastl::unique_ptr<Type> mData; void serialize() const { uint8_t exist = mData ? 1 : 0; stream::writeAux(exist); if (exist) stream::write(*mData); } void deserialize() { uint8_t exist = 0; stream::readAux(exist); if (!exist) return; create(); stream::read(*mData); } void hashialize() const { stream::hash<Type>(); } public: Ptr() = default; Ptr(Ptr &&) noexcept = default; Ptr &operator=(Ptr &&) = default; Ptr(const Ptr &other) { *this = other; } BINDUMP_DECLARE_ASSIGNMENT_OPERATOR(Ptr, mData.reset(); if (other.mData) create(*other.mData);); template <typename... Args> Type &create(Args &&...args) { mData = eastl::make_unique<Type>(eastl::forward<Args>(args)...); return *mData; } operator Type *() { return mData.get(); } operator const Type *() const { return mData.get(); } explicit operator bool() const { return mData != nullptr; } Type *operator->() { return mData.get(); } const Type *operator->() const { return mData.get(); } Type &operator*() { return *mData; } const Type &operator*() const { return *mData; } Type *get() { return mData.get(); } const Type *get() const { return mData.get(); } }; template <typename Type> class Address : public detail::master::DeferredAction { Type *mData = nullptr; mutable uint64_t mOffset = 0; void serialize() const { mOffset = detail::streamer::writer::context().worker->append(0); stream::writeAux(mOffset); detail::streamer::writer::context().deferred_actions.emplace_back(this); } void deserialize() { mData = nullptr; stream::readAux(mOffset); if (mOffset) detail::streamer::reader::context().deferred_actions.emplace_back(this); } void hashialize() const { stream::hash<uint64_t>(); } void deferredWrite() const override { uint64_t offset_to_data = mData ? detail::streamer::writer::context().translateAddressToOffset(mData) : 0; detail::streamer::writer::context().worker->write(mOffset, &offset_to_data, sizeof(offset_to_data)); } void deferredRead() override { mData = detail::streamer::reader::context().translateOffsetToAddress<Type>(mOffset); } public: Address() = default; Address(Type *address) : mData(address) {} BINDUMP_DECLARE_ASSIGNMENT_OPERATOR(Address, mData = other.mData); Address &operator=(Type *address) { mData = address; return *this; } operator Type *() { return mData; } operator const Type *() const { return mData; } explicit operator bool() const { return mData != nullptr; } Type *operator->() { return mData; } const Type *operator->() const { return mData; } Type &operator*() { return *mData; } const Type &operator*() const { return *mData; } Type *get() { return mData; } const Type *get() const { return mData; } }; template <typename Type> class EnableHash { struct EmptyReader : public IReader { void begin() override {} void end() override {} void read(uint64_t, void *, uint64_t) override {} }; uint64_t mIsLayoutValid = 1; void serialize() const { HashVal<64> hash = getHash<Type>(); stream::write(hash); } void deserialize() { HashVal<64> hash; stream::read(hash); mIsLayoutValid = hash == getHash<Type>(); if (!isLayoutValid()) { static EmptyReader empty_reader; detail::streamer::reader::context().worker = &empty_reader; } } void hashialize() const { stream::hash<HashVal<64>>(); } public: BINDUMP_DECLARE_ASSIGNMENT_OPERATOR(EnableHash, ;); bool isLayoutValid() const { return mIsLayoutValid != 0; } }; } // namespace bindump
"use client" import { Progress } from "@/components/ui/progress" import { FormEvent, useState } from 'react' import { Input } from './ui/input' import { Button } from './ui/button' import { useMutation } from 'convex/react' import { api } from '../../convex/_generated/api' import { useEdgeStore } from '@/lib/edgestore' import { SingleImageDropzone } from './SingleImage' import { SingleFileDropzone } from './Singlefile' import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group" const GENRES = ["Приключения", "Боевик", "Драма", "Комедия", "Триллер", "Хоррор"] export default function FilmAddForm() { const { edgestore } = useEdgeStore() const filmMutation = useMutation(api.films.createFilm) const [thumbnailFile, setThumbnailFile] = useState<File>() const [filmFile, setFilmFile] = useState<File>() const [thumbnailFileProgress, setThumbnailFileProgress] = useState(0) const [filmFileProgress, setFilmFileProgress] = useState(0) const [error, setError] = useState(false) const [disabled, setDisabled] = useState(false) const [thumbnailURL, setThumbnailURL] = useState("") const [fileURL, setFileURL] = useState("") const [toggleItems, setToggleItems] = useState<string[]>([]) function addToggleItem(category:string) { if (toggleItems.includes(category)) { setToggleItems((toggleItems) => toggleItems.filter(toggleItem => toggleItem != category)) } else { setToggleItems([...toggleItems, category]) } } const createFilm = async (e: FormEvent) => { e.preventDefault() const form = e.target as HTMLFormElement const formData = new FormData(form) const name = formData.get("name") as string const country = formData.get("country") as string const year = formData.get("year") as string const description = formData.get("description") as string const actors = formData.get("actors") as string const janres = formData.get("janres") as string if (thumbnailFile) { const resThumb = await edgestore.publicFiles.upload({ file: thumbnailFile, onProgressChange: (progress) => { setThumbnailFileProgress(progress) }, }); setThumbnailURL(resThumb.url) } else { setError(true) return } if (filmFile) { const resFile = await edgestore.publicFiles.upload({ file: filmFile, onProgressChange: (progress) => { setFilmFileProgress(progress) }, }); setFileURL(resFile.url) } else { setError(true) return } await filmMutation({ characters: actors ?? "", country: country, description: description, name: name, year: year, thumbnailUrl: thumbnailURL, fileUrl: fileURL, janres: toggleItems }) setDisabled(false) form.reset() setError(false) setFileURL("") setFilmFile(undefined) setFilmFileProgress(0) setThumbnailFile(undefined) setThumbnailFileProgress(0) setThumbnailURL("") setToggleItems([]) } return ( <div className="w-full flex flex-col text-text-main"> <form onSubmit={createFilm}> <div className="flex flex-col text-text-main"> <label htmlFor="name">Название</label> <Input disabled={disabled} type="text" name="name" className='bg-second-bg-color font-Alegreya font-medium'/> </div> <div className="flex flex-col text-text-main"> <label htmlFor="country">Страна</label> <Input disabled={disabled} type="text" name="country" className='bg-second-bg-color'/> </div> <div className="flex flex-col text-text-main"> <label htmlFor="year">Год</label> <Input disabled={disabled} type="text" name="year" className='bg-second-bg-color' /> </div> <div className="flex flex-col text-text-main"> <label htmlFor="description">Описание</label> <textarea disabled={disabled} name="description" className='bg-second-bg-color' /> </div> <div className="flex flex-col text-text-main"> <label htmlFor="actors">Актеры</label> <Input disabled={disabled} type="text" name="actors" className='bg-second-bg-color'/> </div> <div className="flex flex-col text-text-main"> <label htmlFor="janres">Жанры</label> <ToggleGroup type="multiple" className="flex flex-wrap justify-start"> {GENRES.map((category, index) => { return ( <ToggleGroupItem className="bg-second-bg-color hover:bg-accent p-[5px] lg:p-2" key={index} value={category} onClick={() => { addToggleItem(category) }}> <h1 className="text-sm lg:text-base">{category}</h1> </ToggleGroupItem>) })} </ToggleGroup> </div> <div className="flex flex-col lg:flex-row gap-10"> <div className="flex flex-col text-text-main"> <label htmlFor="thumbnail">Thumbnail</label> <SingleImageDropzone disabled={disabled} className='bg-second-bg-color' width={350} height={200} value={thumbnailFile} onChange={(file) => { setThumbnailFile(file); }}/> <Progress className="bg-transparent h-[5px]" value={thumbnailFileProgress}/> </div> <div className="flex flex-col text-text-main"> <label htmlFor="fileFile">Film file</label> <SingleFileDropzone disabled={disabled} className='bg-second-bg-color' width={350} height={200} value={filmFile} onChange={(file) => { setFilmFile(file); }} /> <Progress className="bg-transparent h-[5px]" value={filmFileProgress}/> </div> </div> <Button disabled={disabled}>Create</Button> </form> </div> ) }
<?php use App\Http\Controllers\CiggyController; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('/dashboard', function () { return redirect('/../ciggies'); })->middleware(['auth', 'verified'])->name('dashboard'); Route::resource('/ciggies', CiggyController::class)->middleware(['auth']); require __DIR__.'/auth.php';
import { Client, GroupMessage, MessageElem, PrivateMessage } from "oicq"; import fs, { PathOrFileDescriptor } from "fs"; /** * Write message to the history file when receive a new message. * @param {Number} uid Client uid. * @param {ociq.Message} message `oicq.Message` object contains the new message. */ export function receive(uid : number, message : GroupMessage | PrivateMessage) { let d = new Date(message.time * 1000); let date = getDate(d); let filepath = getHistoryFileUrl(uid, message, date) fs.readFile(filepath as PathOrFileDescriptor, "utf8", (err, data) => { let folderpath : string[] let logs : object[] // TODO: 搞清楚这里创建文件夹逻辑 目前先解决TS类型 if (err) { folderpath = filepath.split("/") folderpath.pop() folderpath.shift() let folder = folderpath.join("/") createFolder(folder); if (err.code == "ENOENT") { logs = []; } else { throw err; } } else { logs = (data == "") ? [] : JSON.parse(data); } //插入消息 logs.push(filter(message)); // 按时间排序 // `any` 指排序时前后项 logs.sort(function (a : any , b : any) { return a.time - b.time; }) //写入文件 fs.writeFile(filepath as PathOrFileDescriptor, JSON.stringify(logs, null, 2), { "encoding": "utf8", "flag": "w" }, (err) => { if (err) throw err; return; }); }); } function getDate(d : Date) : String { let month = (d.getMonth() + 1).toString() if (month.length == 1) month = "0" + month let date = d.getDate().toString(); if (date.length == 1) date = "0" + date return d.getFullYear().toString() + month + date } function getHistoryFileUrl( uid: String | Number, message: GroupMessage | PrivateMessage, date: String ): String { let result = "" if (message instanceof PrivateMessage) result = `./dist/data/${uid}/private/${message.user_id}/${date}.json` else if (message instanceof GroupMessage) result = `./dist/data/${uid}/group/${message.group_id}/${date}.json` return result } function createFolder(path : String) { var pwd = "."; for (let i of path.split("/")) { try { fs.mkdirSync(pwd + "/" + i); pwd += "/" + i; continue; } catch (err) { pwd += "/" + i; continue; } } } function filter(obj : PrivateMessage | GroupMessage) : object { // To fix index problem in TypeScript let a = obj as { [index: string]: any } let deleteList = [ "font", "rand", "auto_reply", "group", "member", "friend", "to_id", "from_id" ]; for (let i of deleteList) { delete a[i]; } return obj; } /** * Get a specific file. * @param {Number} uid User QQ ID. * @param {"group" | "private"} type Message type. * @param {String} target Chat target user needs. * @param {String} file File needs. * @param {Function} callback Callback * @returns */ export function get( uid : number, type : "group" | "private", target : string, file : string, callback : Function ) { let fileList : string[] fs.readdir(`./dist/data/${uid}/${type}/${target}`, (err, data) => { // 获取目标账号下目录 if (err) return fileList; fileList = data; if (file != undefined && file != "-1") { fileList = fileList.slice(0, fileList.indexOf(file)) } // Type Safety // Make sure the type of `file` is string. file = (fileList[fileList.length - 1] === undefined) ? "" : fileList.pop() as string fs.readFile(`./dist/data/${uid}/${type}/${target}/${file}`, "utf8", (err, data) => { if (err) throw err; callback({ "file": file, "content": JSON.parse(data) }) }) }) } /** * Pull history from Tencent. * @param {oicq.Client} client An object of `oicq.Client`. * @param {"friend" | "group"} type * @param {String} target * @param {String} time * @param {Function} callback * @returns */ export function pull( client: Client, type: "friend" | "group", target: string, time: string, callback: any) { //FIXME: The type of `callback` need to be fixed. if (typeof (callback) != "function") return; let uid = client.uin if (time == "latest") { // 获取最新消息 if (type == "friend") { let friend = client.pickFriend(parseInt(target)); friend.getChatHistory().then((result) => { callback(result) }, (e) => console.log(e)); } if (type == "group") { let group = client.pickGroup(parseInt(target)); group.getChatHistory().then((result) => { // for(i of result) { receive(uid, i) } callback(result); }, (e) => console.log(e)); } } else { if (type == "friend") { let friend = client.pickFriend(parseInt(target)) friend.getChatHistory(parseInt(time)).then(callback, (e) => console.log(e)) } if (type == "group") { let group = client.pickGroup(parseInt(target)) group.getChatHistory(parseInt(time)).then((result) => { // for(i of result) { receive(uid, i) } callback(result.toString()) }, (e) => console.log(e)) } } } /** * * @param {oicq.client} client A QQ Client * @param {"friend" | "group"} type Message Type. * @param {String} target Message target. * @param {String | MessageElem} message Message Content. */ export function send( client : Client, type : "friend" | "group", target : string, message : string | MessageElem, callback : any) { // FIXME: Type need to be fixed if (typeof(callback) != "function") return; if (type in ["friend", "Friend"]) { let friend = client.pickFriend(parseInt(target)) callback(friend.sendMsg(message)) } if (type in ["group", "Group"]) { let group = client.pickGroup(parseInt(target)) callback(group.sendMsg(message)) } }
package main; import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import com.formdev.flatlaf.FlatLightLaf; import java.util.Vector; public class stokekle extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JTextField dogalYemField; private JTextField hazirYemField; private JTable table; // Veritabanı bağlantı bilgileri private static final String URL = "jdbc:postgresql://localhost:5432/farm"; private static final String KULLANICI_ADI = "postgres"; private static final String SIFRE = "123"; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { stokekle frame = new stokekle(); UIManager.setLookAndFeel(new FlatLightLaf()); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public stokekle() { setIconImage(Toolkit.getDefaultToolkit().getImage(stokekle.class.getResource("/main/inek.jpg"))); setTitle("Stok Ekle"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 474, 345); contentPane = new JPanel() { private static final long serialVersionUID = 1L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); ImageIcon imageIcon = new ImageIcon(getClass().getResource("eray.jpg")); Image image = imageIcon.getImage(); g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this); } @Override public Dimension getPreferredSize() { return new Dimension(400, 400); // JPanel'in boyutunu ayarla } }; contentPane.setForeground(SystemColor.inactiveCaptionText); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("Doğal Yem :"); lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14)); lblNewLabel.setBounds(20, 36, 95, 13); contentPane.add(lblNewLabel); dogalYemField = new JTextField(); dogalYemField.setBounds(133, 35, 76, 19); contentPane.add(dogalYemField); dogalYemField.setColumns(10); JLabel lblNewLabel_1 = new JLabel("Hazır Yem:"); lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 14)); lblNewLabel_1.setBounds(20, 103, 82, 13); contentPane.add(lblNewLabel_1); hazirYemField = new JTextField(); hazirYemField.setBounds(133, 102, 76, 19); contentPane.add(hazirYemField); hazirYemField.setColumns(10); JButton azaltButton = new JButton("Stok Azalt"); azaltButton.setBounds(269, 34, 95, 21); contentPane.add(azaltButton); JButton eklebutton = new JButton("Stok Ekle"); eklebutton.setBounds(269, 101, 95, 21); contentPane.add(eklebutton); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(8, 175, 442, 113); contentPane.add(scrollPane); table = new JTable(); scrollPane.setViewportView(table); JMenuBar menuBar = new JMenuBar(); menuBar.setBounds(0, 0, 788, 22); contentPane.add(menuBar); eklebutton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { int dogalYem = Integer.parseInt(dogalYemField.getText()); int hazirYem = Integer.parseInt(hazirYemField.getText()); updateStock("dogalyem", dogalYem, true); updateStock("haziryem", hazirYem, true); JOptionPane.showMessageDialog(null, dogalYem + " kg doğal yem ve " + hazirYem + " kg hazır yem başarıyla eklendi.", "Başarılı", JOptionPane.INFORMATION_MESSAGE); } catch (SQLException | NumberFormatException ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Stok ekleme işlemi sırasında bir hata oluştu: " + ex.getMessage(), "Hata", JOptionPane.ERROR_MESSAGE); } } }); azaltButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { int dogalYem = Integer.parseInt(dogalYemField.getText()); int hazirYem = Integer.parseInt(hazirYemField.getText()); if (checkStock("dogalyem", dogalYem) && checkStock("haziryem", hazirYem)) { updateStock("dogalyem", dogalYem, false); updateStock("haziryem", hazirYem, false); JOptionPane.showMessageDialog(null, dogalYem + " kg doğal yem ve " + hazirYem + " kg hazır yem başarıyla azaltıldı.", "Başarılı", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Stok azaltma işlemi başarısız: Yeterli stok yok.", "Hata", JOptionPane.ERROR_MESSAGE); } } catch (SQLException ex) { ex.printStackTrace(); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, "Geçersiz giriş", "Hata", JOptionPane.ERROR_MESSAGE); } } }); refreshTable(); } private void updateStock(String yemType, int amount, boolean increase) throws SQLException { String query; if (increase) { query = "UPDATE stok SET " + yemType + " = " + yemType + " + ? WHERE id = 1"; } else { query = "UPDATE stok SET " + yemType + " = " + yemType + " - ? WHERE id = 1 AND " + yemType + " >= ?"; } try (Connection conn = DriverManager.getConnection(URL, KULLANICI_ADI, SIFRE); PreparedStatement pstmt = conn.prepareStatement(query)) { pstmt.setInt(1, amount); // Stok miktarını parametre olarak ekleyin if (!increase) { pstmt.setInt(2, amount); // Azaltma işlemi için ek bir parametre ekleyin } int affectedRows = pstmt.executeUpdate(); if (!increase && affectedRows == 0) { throw new SQLException("Stok azaltma işlemi başarısız: Yeterli stok yok."); } // stok mesaj göster dogalYemField.setText(""); hazirYemField.setText(""); } catch (SQLException ex) { ex.printStackTrace(); throw new SQLException("Stok güncelleme işlemi başarısız: " + ex.getMessage()); } finally { refreshTable(); } } private boolean checkStock(String yemType, int amount) throws SQLException { String query = "SELECT " + yemType + " FROM stok WHERE id = 1"; try (Connection conn = DriverManager.getConnection(URL, KULLANICI_ADI, SIFRE); PreparedStatement pstmt = conn.prepareStatement(query); ResultSet rs = pstmt.executeQuery()) { if (rs.next()) { int currentStock = rs.getInt(yemType); return currentStock >= amount; } else { return false; } } } private void refreshTable() { String query = "SELECT * FROM stok WHERE id = 1"; try (Connection conn = DriverManager.getConnection(URL, KULLANICI_ADI, SIFRE); PreparedStatement pstmt = conn.prepareStatement(query); ResultSet rs = pstmt.executeQuery()) { table.setModel(buildTableModel(rs)); } catch (SQLException e) { e.printStackTrace(); } } private static TableModel buildTableModel(ResultSet rs) throws SQLException { java.sql.ResultSetMetaData metaData = rs.getMetaData(); Vector<String> columnNames = new Vector<>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } Vector<Vector<Object>> data = new Vector<>(); while (rs.next()) { Vector<Object> vector = new Vector<>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); } }
<template> <div> <v-alert type="warning" v-show="isWarning" >{{ warningMsg }}</v-alert> <v-row> <div class="col-md-6"> <v-form ref="form" v-model="formModel" > <v-text-field v-model="name" label="Name" required style="max-width: 300px" :rules="fieldRules" ></v-text-field> <v-text-field v-model="email" label="Email" required type="email" :rules="emailRules" style="max-width: 300px" ></v-text-field> <v-text-field v-model="phone" label="Phone number" required style="max-width: 300px" :rules="phoneRules" ></v-text-field> <v-btn @click="saveCustomer" color="blue" dark>Save</v-btn> <v-btn style="margin-left: 20px" color="grey" @click="$router.push('/customers')" dark>Cancel </v-btn> </v-form> </div> </v-row> </div> </template> <script> import {api} from "@/api"; import VueCookies from "vue-cookies"; export default { name: "AddNewCustomer", data() { return { phone: '', name: '', email: '', formModel: '', emailRuleBool: false, phoneRuleBool: false, isWarning: false, warningMsg: "Name or email already exists" } }, computed: { emailRules() { let rules = [] if (this.emailRuleBool) { rules = [ v => !v || /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must be valid'] } else { rules = [] } return rules }, phoneRules() { let rules = [] if (this.phoneRuleBool) { rules = [ v => !v || /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/.test(v) || 'Phone number must be valid'] } else { rules = [] } return rules }, fieldRules() { const rules = [] const rule = v => !!v || 'This field is required' rules.push(rule) return rules }, }, watch: { emailRuleBool: 'validateField', }, methods: { validateField() { this.$refs.form.validate() }, saveCustomer() { this.emailRuleBool = true this.phoneRuleBool = true this.$refs.form.validate() if (this.validateEmail() && this.validatePhone()) { if (this.name && this.email) api.post('/customer/create', { name: this.name, email: this.email, phone: this.phone, }).then(r => { if (r.status == 200) { VueCookies.set("success", true, "5s"); this.$router.push("/customers") } }, err => { if (err.response.status == 409) { this.customerExists() setTimeout(() => this.$refs.form.validate(), 200) } }); } }, init() { }, customerExists() { this.isWarning = true; setTimeout(() => this.isWarning = false, 4000) }, validateEmail() { return this.email.match( /^(([^<>()[\]\\.,;:\s@\\"]+(\.[^<>()[\]\\.,;:\s@\\"]+)*)|(\\".+\\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }, validatePhone() { return this.phone.match( /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/ ) } }, mounted() { this.init() }, } </script> <style scoped> </style>
import { MessageType } from './MessageType'; export abstract class MessageListener { /* I am a message listener, which is given each message received by a MessageConsumer. I am also an adapter because I provide defaults for both handleMessage() behaviors. A typical subclass would override one or the other handleMessage() based on its type and leave the remaining handleMessage() defaulted since it will never be used by MessageConsumer. */ private _type: MessageType; constructor(aType: MessageType) { this.setType(aType); } type() { /* Answers my type. @return Type */ return this._type; } setType(aMessageType: MessageType) { /** * Sets my type. * * @param {Type} a_type - The type to set as my type. */ this._type = aMessageType; } abstract handleMessage( aType: string, aMessageId: string, aTimeStamp: Date, aMessage: Buffer, aDeliveryTag: number, isRedelivery: boolean, ): Promise<void>; /** * Handles a binary message. If any MessageException is thrown by * the implementor, its isRetry() method is examined, and if it returns * true, the message being handled will be nack'd and re-queued. Otherwise, * if its isRetry() method returns false, the message will be rejected/failed * (not re-queued). If any other Exception is thrown, the message will be * considered not handled and will be rejected/failed. * * @param {string|null} aType - The string type of the message if sent, or null. * @param {string|null} aMessageId - The string id of the message if sent, or null. * @param {Date|null} aTimestamp - The timestamp of the message if sent, or null. * @param {Buffer|string} aMessage - The byte array or text containing the binary message. * @param {number} aDeliveryTag - The tag delivered with the message. * @param {boolean} isRedelivery - A boolean indicating whether or not this message is a redelivery. * @throws {Exception} When any problem occurs and the message must not be acknowledged. */ }
:TITLE:Adding/Editing a Release :INC:index :SUB:When to add a release <p> A 'release' is a product - either physical or digital - containing (parts of) the visual novel. This excludes soundtracks, drama CDs, fandisks, and other products that do not contain the visual novel itself.<br /> All releases should be added seperately. For example, a limited and a regular edition shouldn't be combined into one release, even if they share the release date and contents. For commercial games, separate releases can be distinguished by their JAN/UPC/EAN number. </p> :SUB:General info <dl> <dt>Type</dt><dd> Is the release complete, partial or a trial version? Complete releases have everything. Partial releases have most of the game, but there are things still waiting to be released. Trial versions are heavily cut down and free releases so that you can experience a game before you buy it. Sometimes, trial versions are cut down for web transmission and do not completely represent the finished product.<br /> In the case of a translation patch, the type should indicate whether it translates the full game (Complete), or just parts of it (Partial). </dd><dt>Patch</dt><dd> Use this checkbox to indicate that the release is a (translation) patch, used to patch an other release. </dd><dt>Freeware</dt><dd> Check if this box if the game is downloadable (or otherwise distributed) at no cost. </dd><dt>Doujin</dt><dd> Published by a doujin circle, amateur group or individual, as opposed to a legal entity such as a company. This field is ignored when the release type is set to patch. </dd><dt>Title (romaji)</dt><dd> The name of the release, in the Latin character set (using Romanisation or translation) </dd><dt>Original title</dt><dd> If the name is officially under a different title (usually because of different character sets), put the original title here. </dd><dt>Language</dt><dd> What language is this release? Use the language that the majority of the game is in. </dd><dt>JAN/UPC/EAN</dt><dd> The <a href="http://en.wikipedia.org/wiki/Global_Trade_Item_Number">GTIN</a> code of the product. Often called "JAN" for Japanese releases, "UPC" for USA and Canada and "EAN" for Europe. The system will automatically detect the type from the code and use the appropriate term on the release page. </dd><dt>Catalog number</dt><dd> Catalog number as assigned by the producer. Often used to identify releases on webshops, and can usually be found somewhere on the packaging of the product. </dd><dt>Official website</dt><dd> URL of the official homepage for this product. Note that, even though VNDB does not support piracy, it is allowed to link to a homepage or forum that does in the case it is the only <b>official</b> source of information for this release. </dd><dt>Release date</dt><dd> For commercial games, the sale date. For all others, the date on which the release was first available. If it was posted on a website, the date on which the post was public. </dd><dt>Age rating</dt><dd> The minimum age rating for the release. On most releases, this is specified on the packaging or on product web pages. </dd><dt>Notes</dt><dd> Anything miscellaneous and useful. Generally, extras (but not preorder bonuses) and progress information go here. </dd> </dl> :SUB:Format <dl> <dt>Resolution</dt><dd> Primary/native screen resolution of the game. </dd><dt>Voiced</dt><dd> Indicates whether this release includes voice acting in the VN/ADV parts of the game. <i>Fully voiced</i> indicates that all characters (usually excluding the protagonist and some minor characters) are voiced in all scenes. <i>Only ero scenes voiced</i> speaks for itself, and <i>Partially voiced</i> should be used when there is some voice acting, but only for the main characters or only in some scenes. </dd><dt>Animation</dt><dd> Whether the game has any animation can be specified with two seperate options: one for the normal story mode and one for the ero scenes, if the game has any. With <i>Simple animations</i>, we refer to (usually looping) effects like falling leaves or snow in the background or animated facial expressions like blinking eyes and a moving mouth. <i>Fully animated scenes</i> refers to non-looping anime-like scenes. Some games are entirely like this, others only have a few scenes that are fully animated. Effects like moving sprites around the screen, basic zooming and shaking background images are not considered as "animations". Minigames or other gameplay elements are excluded as well, only the (ADV/VN-like) story parts and ero scenes should be considered. </dd> </dl> <p> <b>NOTE</b>: The resolution, voiced and animation fields have no meaning for patches, and should be left empty for those releases. <br /><br /> <b>Platform</b><br /> The platforms that the product was released for. Does not include emulated platforms (e.g. Playstation 2 games on Playstation 3) or WINE. DVD Player refers to games playable as a normal DVD Video (DVDPG) and should not be confused with the DVD as a medium. <br /><br /> <b>Media</b> </p> <dl> <dt>Blu-ray</dt><dd> Blu-ray Disk, typically 30-60GB+. Requires a Blu-ray Drive. Playstation 3 are normally Blu-ray. </dd><dt>CD</dt><dd> CD-ROM, typically 700MB. </dd><dt>DVD</dt><dd> DVD5, typically 4.5GB, or DVD9, typically 9GB. DVDPG games are DVD. </dd><dt>Floppy</dt><dd> 5 1/4" or 3 3/4", no greater than 1.44MB. </dd><dt>GD</dt><dd> Dreamcast games are normally GD disks. </dd><dt>Internet Download</dt><dd> Anything without a physical box, i.e. obtained by downloading it over a network. </dd><dt>Memory Card</dt><dd> Any SD (Secure Digital) Card variant or MMC variant, Compact Flash or "USB Sticks". The Main difference between this and Cartridge (below) is that Memory Cards are re-writable (RW). </dd><dt>Cartridge</dt><dd> Compare with Memory Cards (above). Read-only. Famicom (NES), Super Nintendo (SNES), Game Boy Advanced (GBA) and Nintendo DS use cartridges. </dd><dt>Nintendo Optical Disk</dt><dd> Non-CD or DVD optical disks used by various Nintendo consoles. </dd><dt>Other</dt><dd> Any format not considered to be any of these mentioned should take this media. However, it should not be used liberally, and it's inclusion may need to be justified. </dd><dt>UMD</dt><dd> Universal Media Disk, typically 2.2GB. Playstation Portable uses this format. </dd> </dl> :SUB:Producers <p> The companies/groups/individuals involved in the development or publishing of this release. Does not include distributors. The following roles can be selected: <dl> <dt>Developer</dt><dd> The producer involved in the creation of the game itself, not necessarily of this specific release. Keep in mind that producers that have made modifications to a game but have not made the game itself should NOT be listed as developers. </dd><dt>Publisher</dt><dd> The producer responsible for publishing this specific release. The publisher may have made modifications to the game (e.g. translating all text or porting to a different platform), but was not involved in the creation process. </dd><dt>Both</dt><dd> When the release is developed and published by the same producer. This is often true for doujin games and the first releases of commercial games. </dd> </dl> </p> :SUB:Visual novel relations <p> The visual novels that this release (either partially or fully) covers. </p>
import React, { useState } from "react"; import { useLogin } from "../hooks/useLogin"; const Login = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const { login, error, isLoading } = useLogin(); const handleSubmit = async (e) => { e.preventDefault(); await login(email, password); }; return ( <> <form className="login" onSubmit={handleSubmit}> <div className="form-group"> <input value={email} onChange={(e) => setEmail(e.target.value)} type="email" className="form-input" placeholder="" /> <label className="form-label">Email</label> </div> <div className="form-group"> <input value={password} onChange={(e) => setPassword(e.target.value)} type="password" className="form-input" placeholder="" /> <label className="form-label">Password</label> </div> <button disabled={isLoading} type="submit"> Login </button> {error && <div className="error">{error}</div>} </form> </> ); }; export default Login;
import { FC } from 'react'; import { StyledCustomWebChat, StyledHeaderCustomWebChat, WrapperWebChat, StyledAvatar, StyledBodyWebChat, } from './CustomWebAvatar.styled'; import { ICustomWebChat } from './CustomWebChat.interface'; import { Text } from '../../../../../../atoms/Text/Text'; import { SVGIcon } from '../../../../../../atoms/SVGIcon/SVGIcon'; export const CustomWebChat: FC<ICustomWebChat> = ({ title, primaryColor, secondaryColor, description, avatar, customizeMyAvatar, customIsColor, }) => { return ( <StyledCustomWebChat> <div> <WrapperWebChat primaryColor={primaryColor} customIsColor={customIsColor} secondaryColor={secondaryColor}> <div> <SVGIcon iconFile="/icons/chevron-square-down.svg" /> </div> <StyledHeaderCustomWebChat> <StyledAvatar> {!customizeMyAvatar ? ( <SVGIcon iconFile={`/avatars/${avatar}`} /> ) : ( <img src={avatar} alt={avatar} /> )} </StyledAvatar> <div> <Text>{title}</Text> <Text>{description}</Text> </div> </StyledHeaderCustomWebChat> <div> <svg className="waves waves-animated" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shapeRendering="auto"> <defs> <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z" /> </defs> <g className="parallax"> <use xlinkHref="#gentle-wave" x="24" y="0" fill="rgba(255,255,255,0.7)" /> <use xlinkHref="#gentle-wave" x="24" y="2" fill="rgba(255,255,255,0.5)" /> <use xlinkHref="#gentle-wave" x="24" y="3" fill="rgba(255,255,255,0.3)" /> <use xlinkHref="#gentle-wave" x="24" y="4" fill="#ffffff" /> </g> </svg> </div> <StyledBodyWebChat customIsColor={customIsColor} primaryColor={primaryColor} secondaryColor={secondaryColor}> <div> {!customizeMyAvatar ? ( <SVGIcon iconFile={`/avatars/${avatar}`} /> ) : ( <img src={avatar} alt={avatar} /> )} <div> <Text> Hola mi nombre es Elipse mi función es responder preguntas ¿En qué puedo ayudarte? </Text> </div> </div> <div> <div> <Text>Hola Buen día! Me gustaria hablar con un agente.</Text> </div> </div> <div> <div> <span> <SVGIcon iconFile="/icons/send_121135.svg" /> </span> <div> <Text>Enviar un mensaje...</Text> </div> <span> <SVGIcon iconFile="/icons/send_121135.svg" /> </span> </div> </div> </StyledBodyWebChat> <Text>Powered by Elipse</Text> </WrapperWebChat> </div> </StyledCustomWebChat> ); };
import { Subject } from "rxjs"; export enum AlertType { Error, Success } export interface Alert { text: string; type: AlertType } const alertSubject = new Subject<Alert | undefined>(); function onAlert() { return alertSubject.asObservable(); } function error(message: string) { alertSubject.next({ text: message, type: AlertType.Error }); } function success(message: string) { alertSubject.next({ text: message, type: AlertType.Success }); } function clear() { return alertSubject.next(undefined); } export const alertService = { onAlert, error, success, clear };
<?php declare(strict_types = 1); namespace LanguageServer; use Throwable; use InvalidArgumentException; use Sabre\Event\{Loop, Promise, EmitterInterface}; use Sabre\Uri; /** * Transforms an absolute file path into a URI as used by the language server protocol. * * @param string $filepath * @return string */ function pathToUri(string $filepath): string { $filepath = trim(str_replace('\\', '/', $filepath), '/'); $parts = explode('/', $filepath); // Don't %-encode the colon after a Windows drive letter $first = array_shift($parts); if (substr($first, -1) !== ':') { $first = rawurlencode($first); } $parts = array_map('rawurlencode', $parts); array_unshift($parts, $first); $filepath = implode('/', $parts); return 'file:///' . $filepath; } /** * Transforms URI into file path * * @param string $uri * @return string */ function uriToPath(string $uri) { $fragments = parse_url($uri); if ($fragments === null || !isset($fragments['scheme']) || $fragments['scheme'] !== 'file') { throw new InvalidArgumentException("Not a valid file URI: $uri"); } $filepath = urldecode($fragments['path']); if (strpos($filepath, ':') !== false) { if ($filepath[0] === '/') { $filepath = substr($filepath, 1); } $filepath = str_replace('/', '\\', $filepath); } return $filepath; } /** * Throws an exception on the next tick. * Useful for letting a promise crash the process on rejection. * * @param Throwable $err * @return void */ function crash(Throwable $err) { Loop\nextTick(function () use ($err) { throw $err; }); } /** * Returns a promise that is resolved after x seconds. * Useful for giving back control to the event loop inside a coroutine. * * @param int $seconds * @return Promise <void> */ function timeout($seconds = 0): Promise { $promise = new Promise; Loop\setTimeout([$promise, 'fulfill'], $seconds); return $promise; } /** * Returns a promise that is fulfilled once the passed event was triggered on the passed EventEmitter * * @param EmitterInterface $emitter * @param string $event * @return Promise */ function waitForEvent(EmitterInterface $emitter, string $event): Promise { $p = new Promise; $emitter->once($event, [$p, 'fulfill']); return $p; } /** * Returns the part of $b that is not overlapped by $a * Example: * * stripStringOverlap('whatever<?', '<?php') === 'php' * * @param string $a * @param string $b * @return string */ function stripStringOverlap(string $a, string $b): string { $aLen = strlen($a); $bLen = strlen($b); for ($i = 1; $i <= $bLen; $i++) { if (substr($b, 0, $i) === substr($a, $aLen - $i)) { return substr($b, $i); } } return $b; } /** * Use for sorting an array of URIs by number of segments * in ascending order. * * @param array $uriList * @return void */ function sortUrisLevelOrder(&$uriList) { usort($uriList, function ($a, $b) { return substr_count(Uri\parse($a)['path'], '/') - substr_count(Uri\parse($b)['path'], '/'); }); } /** * Checks a document against the composer.json to see if it * is a vendored document * * @param PhpDocument $document * @param \stdClass|null $composerJson * @return bool */ function isVendored(PhpDocument $document, \stdClass $composerJson = null): bool { $path = Uri\parse($document->getUri())['path']; $vendorDir = getVendorDir($composerJson); return strpos($path, "/$vendorDir/") !== false; } /** * Check a given URI against the composer.json to see if it * is a vendored URI * * @param string $uri * @param \stdClass|null $composerJson * @return string|null */ function getPackageName(string $uri, \stdClass $composerJson = null) { $vendorDir = str_replace('/', '\/', getVendorDir($composerJson)); preg_match("/\/$vendorDir\/([^\/]+\/[^\/]+)\//", $uri, $matches); return $matches[1] ?? null; } /** * Helper function to get the vendor directory from composer.json * or default to 'vendor' * * @param \stdClass|null $composerJson * @return string */ function getVendorDir(\stdClass $composerJson = null): string { return $composerJson->config->{'vendor-dir'} ?? 'vendor'; }
#include <iostream> #include <array> #include "math.h" #include <algorithm> #include "raylib.h" #include <random> // ruleset total neighbours 9 + 8 + 9 = 26 static const int rows = 100; static const std::array<bool, 27> alive = { false, false, false, false, false, true, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, }; static const std::array<bool, 27> dead = { false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, }; int count_neighbours(std::array<std::array<std::array<bool, rows>, rows>, rows>& copy_grid, int row, int col, int lay) { int total = 0; for (int row_offset = -1; row_offset <= 1; ++row_offset) { for (int col_offset = -1; col_offset <=1; ++col_offset) { for (int lay_offset = -1; lay_offset <= 1; ++ lay_offset) { if (row_offset == 0 && col_offset == 0 && lay_offset == 0) { continue; } // total += (copy_grid[(row + row_offset) % rows] // [(col + col_offset) % rows] // [(lay + lay_offset) % rows]) ? 1 : 0; if (row + row_offset < 0 || row + row_offset >= rows || col + col_offset < 0 || col + col_offset >= rows || lay + lay_offset < 0 || lay + lay_offset >= rows) { continue; } total += (copy_grid[(row + row_offset)] [(col + col_offset)] [(lay + lay_offset)]) ? 1 : 0; } } } return total; } bool apply_alive(std::array<std::array<std::array<bool, rows>, rows>, rows>& copy_grid, int row, int col, int lay) { return alive[count_neighbours(copy_grid, row, col, lay)]; } bool apply_dead(std::array<std::array<std::array<bool, rows>, rows>, rows>& copy_grid, int row, int col, int lay) { return dead[count_neighbours(copy_grid, row, col, lay)]; } void apply_ruleset(std::array<std::array<std::array<bool, rows>, rows>, rows>& grid) { std::array<std::array<std::array<bool, rows>, rows>, rows> copy_grid; std::copy(grid.begin(), grid.end(), copy_grid.begin()); for (int row = 0; row < rows; ++row) { for (int col = 0; col < rows; ++col) { for (int lay = 0; lay < rows; ++lay) { if (copy_grid[row][col][lay]) { grid[row][col][lay] = apply_alive(copy_grid, row, col, lay); } else { grid[row][col][lay] = apply_dead(copy_grid, row, col, lay); } } } } } int main() { std::array<std::array<std::array<bool, rows>, rows>, rows> grid{}; // for (int i = 4; i < 7; ++i) { // grid[4][4][i] = 1; // grid[4][6][i] = 1; // grid[6][4][i] = 1; // grid[6][6][i] = 1; // } // for (int i = 4; i < 7; ++i) { // for (int j = 4; j < 7; ++j) { // for (int k = 4; k < 7; ++k) { // grid[i][j][k] = 1; // } // } // } auto gen = std::bind(std::uniform_int_distribution<>(0,1),std::default_random_engine()); for (int row = 0; row < rows; ++row) { for (int col = 0; col < rows; ++col) { for (int lay = 0; lay < rows; ++lay) { grid[row][col][lay] = gen(); } } } const int width = 1000; const int height = 1000; const int block_size = 1; InitWindow(width, height, "3d-automata"); float pos = (float) rows * (float) block_size; Camera3D camera = { 0 }; camera.position = (Vector3){ pos * 1.5f, pos * 1.5f, pos * 1.5f }; camera.target = (Vector3){ pos / 2, pos / 2, pos / 2 }; camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; camera.fovy = 60.0f; camera.projection = CAMERA_PERSPECTIVE; SetTargetFPS(60); while (!WindowShouldClose()) { BeginDrawing(); BeginMode3D(camera); ClearBackground(RAYWHITE); for (int row = 0; row < rows; ++row) { for (int col = 0; col < rows; ++col) { for (int lay = 0; lay < rows; ++lay) { if (!grid[row][col][lay]) { continue; } Vector3 cube_pos = { (float) row * block_size, (float) col * block_size, (float) lay * block_size }; Color cube_colour = ColorFromHSV((float)((( row + col + lay) * 18) % 360), 0.75f, 0.9f); DrawCube(cube_pos, block_size, block_size, block_size, cube_colour); } } } EndMode3D(); DrawFPS(10, 10); EndDrawing(); apply_ruleset(grid); } CloseWindow(); return 0; }
# Code Style Medusa is written mostly in C++, and this document will outline some suggestions on how to style the code you write. First of all, put braces on the same line as what the braces are for. Write: ```c++ void example(int a) { printf("Hello, world!\n"); } ``` Instead of: ```c++ void example(int a) { printf("Hello, world!\n"); } ``` Put spaces after parenthesis (like function definitions) and builtin `if`-type keywords. Write: ```c++ void example(int a) { if (a == 0) { printf("abc\n"); } } ``` Instead of: ```c++ void example(int a){ if(a == 0){ printf ("abc\n"); } } ``` Use hard-tabs (\t), not soft-tabs. Set tab-stops at 4. An exception is made for documentation files, where soft-tabs (spaces) are to be used. The reason for this is that most web-based Git clients (GitHub, GitLab, etc) default tab-stops at 8, and sometimes do not have the ability to change said default. In a case like this, it's preferable to make the documentation display correctly in those circumstances. I'm (spv) more accepting of hard-tabs in actual source code, as not much editing is done within web-based Git clients, and you *can* change the tab stops usually. Since the *default* is 8, and not everyone changes it, making the documentation look correct matters more to me than source code in that case. Use snake_case for variables, class members, and such. Use PascalCase for class names. Write: ```c++ class ExampleClass { ... int this_is_a_variable; ... }; ``` Instead of: ```c++ class example_class { ... int thisIsAVariable; ... } ``` Indent access specifiers like `public`, `protected`, and `private` 1 tab-stop past `class`. Write: ```c++ namespace example { class ExampleClass { public: int variable; private: int a_second_variable; }; } ``` Instead of this, : ```c++ namespace example { class ExampleClass { public: ... }; } ``` Or this: ```c++ namespace example { class ExampleClass { public: ... } } ``` For comments, line up the `*`'s of `/*` and `*/`. Write this: ``` /* ... */ ``` Instead of this: ``` /* ... */ ``` As well, start each line of a multi-line comment with `[space]*`. Write this: ``` /* * */ ``` Instead of this: ``` /* */ ``` <!-- Finally with comments, keep lines under 80 chars whenever possible, and after each `*` to start a line, place 2 spaces. Write this: ``` /* * Hello, world! I see you're reading this document. Oh no this line is going * to wrap! Oh ok, we're fine. Goodbye! */ ``` Instead of this: ``` /* * Hello, world! I see you're reading this document. Oh no this line is going to * wrap! Oh ok, we're fine. Goodbye! */ ``` (i'd like to do it this way, but sadly clang-format doesn't support this from what i can tell) --> Generally, C++ code would look something like this: ```c++ #include <cstdint> #include <cstdlib> #include <cstdio> int main(int argc, char *argv[]) { char *buf = malloc(0x4000); int ival; uint32_t val; printf("%p %d 0x%08x\n", buf, ival, val); if (val == 0) { whatever(val); } else if (val == 1) { whatever2(val); } else if (val == 2) { whatever3(val); } else { whatever4(val); } libmedusa::ARMv7Machine armv7_machine; libmedusa::reg_t reg; reg.reg_description = "pc"; reg.reg_name = "pc"; reg.reg_id = 0xf; reg.reg_value = 0x1; // |1 means THUMB on ARMv7 armv7_machine.set_register(reg); return 0; } ``` ## File License This file is licensed under the terms of the CC BY-SA 4.0 license.
# :star: Liquibase Parent POM [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fliquibase%2Fliquibase-parent-pom.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fliquibase%2Fliquibase-parent-pom?ref=badge_shield) Simplifying Extension Dependency Management with Parent POM This repository helps craft a parent POM file that becomes the central parent for all extension repositories. ## :pushpin: Features - Centralized configuration for Liquibase extension projects. - Easy inheritance for common settings and plugins. - Simplifies project management and distribution. ## :wrench: Usage 1. Add the following to your Liquibase extension project's `pom.xml` to inherit from this parent POM: ```xml <parent> <groupId>org.liquibase</groupId> <artifactId>liquibase-parent-pom</artifactId> <version>0.1.0</version> <!-- Replace with the desired version --> </parent> ``` 2. Customize your extension project as needed. Your project inherits common properties, plugins, and distribution management settings from this parent POM. ## :rocket: Contributing Contributions are welcome! Please follow these steps: 1. Fork the repository. 2. Create a new branch for your feature or bug fix: ```bash git checkout -b feature/your-feature ``` 3. Make your changes and commit them: ```bash git commit -m 'Add new feature' ``` 4. Push to your branch: ```bash git push origin feature/your-feature ``` 5. Create a pull request to the `main` branch of this repository. ## License [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fliquibase%2Fliquibase-parent-pom.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fliquibase%2Fliquibase-parent-pom?ref=badge_large)
import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import './widgets/new_transaction.dart'; import './widgets/transaction_list.dart'; import './widgets/chart.dart'; import './models/transaction.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Personal Expenses', theme: ThemeData( primarySwatch: Colors.purple, accentColor: Colors.amber, fontFamily: 'Quicksand', textTheme: ThemeData.light().textTheme.copyWith( headline6: TextStyle( fontFamily: 'OpenSans', fontWeight: FontWeight.bold, fontSize: 18, ), button: TextStyle(color: Colors.white), ), appBarTheme: AppBarTheme( textTheme: ThemeData.light().textTheme.copyWith( headline6: TextStyle( fontFamily: 'OpenSans', fontWeight: FontWeight.bold, fontSize: 20, ), ), ), ), home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final List<Transaction> _userTransactions = []; bool _showChart = false; List<Transaction> get _recentTransactions { return _userTransactions.where((tx) { return tx.date.isAfter( DateTime.now().subtract( Duration(days: 7), ), ); }).toList(); } void _addNewTransaction( String txTitle, double txAmount, DateTime chosenDate, ) { setState(() { _userTransactions.add( Transaction( title: txTitle, amount: txAmount, date: chosenDate, id: DateTime.now().toString(), ), ); }); } void _startAddNewTransaction(BuildContext ctx) { showModalBottomSheet( context: ctx, // context는 Navigator, Theme같은거를 참고하기 위해 필요하다. // 위젯트리에 들어가고, 나가는 거니까, context가 있어야하지. builder: (_) { // builder는 showModalBottomSheet에 넣을 위젯을 리턴한다. return GestureDetector( onTap: () {}, child: NewTransaction(_addNewTransaction), behavior: HitTestBehavior.opaque, ); }, ); } void _deleteTransaction(String id) { setState(() { _userTransactions.removeWhere((tx) => tx.id == id); }); } // build내부에 정의되는 변수들은 Context를 이용하는 위짓들. // state에서 정의되는거랑, build에서 정의되는거랑 차이점. @override Widget build(BuildContext context) { final mediaQuery = MediaQuery.of(context); final isLandscape = mediaQuery.orientation == Orientation.landscape; final PreferredSizeWidget appBar = Platform.isIOS ? CupertinoNavigationBar( middle: Text( 'Personal Expenses', ), trailing: GestureDetector( // 여기에 원래는 Row가 있었는데 왜?? child: Icon(CupertinoIcons.add), onTap: () => _startAddNewTransaction(context), ), ) : AppBar( title: Text( 'Personal Expenses', ), actions: <Widget>[ IconButton( icon: Icon(Icons.add), onPressed: () => _startAddNewTransaction(context), ), ], ); final fullHeight = mediaQuery.size.height - appBar.preferredSize.height - mediaQuery.padding.top; final txListWidget = Container( height: fullHeight * 0.7, child: TransactionList(_userTransactions, _deleteTransaction), ); final pageBody = SafeArea( // 동그란 엣지에서 화면 안 짤리게 해줌. child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ if (isLandscape) Column( children: <Widget>[ Text( 'Show Chart', style: Theme.of(context).textTheme.headline6, ), Switch.adaptive( // 플랫폼에 맞는 스위치를 생성해서 adaptive activeColor: Theme.of(context).accentColor, value: _showChart, onChanged: (val) { setState(() { _showChart = val; }); }, ), ], ), if (isLandscape) _showChart ? Container( height: fullHeight * 0.7, child: Chart(_recentTransactions), ) : txListWidget, if (!isLandscape) Container( height: fullHeight * 0.3, child: Chart(_recentTransactions), ), if (!isLandscape) txListWidget, ], ), ), ); return Platform.isIOS ? CupertinoPageScaffold( child: pageBody, navigationBar: appBar, ) : Scaffold( appBar: appBar, body: pageBody, floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () => _startAddNewTransaction(context), ), ); } }
import { createContext, FC, ReactNode, useState } from "react"; import { servicesUser } from "../../services/users"; import { User } from "../../types"; type ContextType = { users: User[]; loadUsers: () => void; }; type ProviderType = { children: ReactNode }; const StoreContext = createContext<ContextType>({ users: [], loadUsers: () => undefined, }); const StoreProvider: FC<ProviderType> = ({ children }) => { const [users, setUsers] = useState<User[]>([]); const loadUsers = () => servicesUser.getAll().then((data) => setUsers(data)); return ( <StoreContext.Provider value={{ users, loadUsers }}> {children} </StoreContext.Provider> ); }; export { StoreContext, StoreProvider };
package com.pinalka.controller; import com.pinalka.domain.User; import com.pinalka.services.LocalizationService; import com.pinalka.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Controller for register page * * @author gman */ @Controller public class LoginController { private static final String LOGIN = "/login"; @Autowired private UserService userService; @Autowired private LocalizationService localizationService; /** * Populate model of the login page * * @param model is the model to populate * @return page template */ @RequestMapping(value = "/login") public String login(final Model model) { final User user = userService.getCurrentUser(); localizationService.fillCommon(model, user, "page.login"); fillCommonInLogin(model, false); return LOGIN; } /** * Populate model of the login page after error * * @param model is the model to populate * @return page template */ @RequestMapping(value = "/login/fail") public String loginFail(final Model model) { final User user = userService.getCurrentUser(); localizationService.fillCommon(model, user, "page.login"); fillCommonInLogin(model, true); return LOGIN; } /** * Fills common attributes in login page * * @param model is the model to populate * @param isFail indicator of previous logon fail */ private void fillCommonInLogin(final Model model, final boolean isFail) { model.addAttribute("isFail", isFail); model.addAttribute("profileErrorLogin", localizationService.getMessage("profile.error.login")); model.addAttribute("profileName", localizationService.getMessage("profile.name")); model.addAttribute("profilePassword", localizationService.getMessage("profile.password")); model.addAttribute("profileActionRemember", localizationService.getMessage("profile.action.remember")); model.addAttribute("profileActionLogin", localizationService.getMessage("profile.action.login")); } }
\section{Background Research} \subsection{Primary Reaction} \noindent This experiment will use the thiocyanatoiron complex reaction as a means to explore the relationship between the equilibrium constant and temperature. The complex formation reaction is described below \citep{buffalostateChemicalEquilibrium}. \begin{equation*} Fe^{3+} + SCN^- \rightleftharpoons FeSCN^{2+} \end{equation*} \subsection{Equilibrium Constant} The equilibrium constant (\(K_c\)) is a measure of the extent to which a chemical reaction proceeds to completion. It is defined as the ratio of the concentrations of the products to the concentrations of the reactants, each raised to the power of their respective stoichiometric coefficients. The equilibrium constant is a crucial parameter in understanding the position of equilibrium in a chemical reaction. If \(K_c < 1\), the equilibrium favors the creation of reactants. If \(K_c > 1\), the equilibrium favors the creation of products. \citep{hammett1935some} \noindent \newline For a reaction: \begin{equation*} aA + bB \rightleftharpoons cC + dD \end{equation*} \noindent The equilibrium constant can be calculated as follows: \begin{equation} K_c=\frac{[C]^c \times [D]^d}{[A]^a \times [B]^b} \end{equation} % \begin{figure}[H] % \centering % \includegraphics[width=130mm,height=\textheight,keepaspectratio]{images/ntc_ptc.png} % \caption{Resistance vs Temperature Graph for NTC and PTC Thermistors \citep{amethermptcntc}} % \label{fig:ntc_ptc} % \end{figure} \subsection{Colorimetry} Colorimetry is a technique to determine the concentration of a substance in a solution by measuring the absorbance of monochromatic light using a spectrophotometer. It is based on the principle that different substances absorb and transmit light at different wavelengths. By comparing the absorbance of a sample to that of a standard solution, the concentration of the substance in the sample can be determined using the Beer-Lambert Law described below. Colorimetry is widely used in various fields, including environmental analysis, clinical chemistry, and industrial quality control, due to its simplicity, speed, and accuracy \citep{clydesdale1978colorimetry}. \begin{equation} A=\epsilon \; b \; C \label{eq:beer_lambert_law} \end{equation} \noindent Where: \begin{itemize}[noitemsep,nolistsep] \item \(A\) is the absorbance (\(\%\)). \item \(\epsilon\) is the molar absorptivity (\(M^{-1} \; cm^{-1}\)). \item \(b\) is the path length (\(cm\)). \item \(C\) is the molar concentration of the colored sample (\(M\)). \end{itemize} \subsection{Importance of Knowing How Temperature Changes the Equilibrium Constant} Understanding how temperature changes the equilibrium constant of a reaction is crucial for predicting and controlling chemical reactions. The following reaction describes the synthesis of methanol from carbon monoxide and hydrogen gas. \begin{equation*} CO (g) + 2 \; H_2 (g) \rightleftharpoons CH_3OH (g) \end{equation*} The reaction is exothermic, meaning it releases heat (\(\Delta H < 0\)). According to Le Chatelier’s principle, for exothermic reactions, the equilibrium constant \(K_c\) decreases with increasing temperature. This means that at higher temperatures, the reaction will shift towards the reactants, producing less methanol. Conversely, at lower temperatures, the reaction will shift towards the products, producing more methanol. Therefore, in the industrial production of methanol, it would be more beneficial to run the process at a lower temperature to maximize the yield of methanol. However, it's important to note that while lower temperatures favor the production of methanol in terms of thermodynamics, reaction rates are typically slower at lower temperatures. Therefore, a compromise temperature of 250 degrees Celsius is often chosen in industry to balance the thermodynamic favorability with a reasonable reaction rate. Thus, knowledge of how temperature affects the equilibrium constant is essential for optimizing industrial processes and ensuring efficient production of desired products \citep{sciencedirectProductionMethanol}. % \begin{figure}[H] % \centering % \includegraphics[width=75mm,height=\textheight,keepaspectratio]{images/conductor_semiconductor_insulator.png} % \caption{Resistivity vs Temperature Graph for Conductors, Semiconductors, and Insulators \citep{mandal_2022}. This plot shows the positive TCR of conductors and the negative TCR for semiconductors and insulators.} % \label{fig:materials_RT_Plot} % \end{figure} \section{Hypothesis} If the temperature of the solution increases, then the equilibrium constant of the reaction will decrease exponentially. If the temperature of the solution decreases, then the equilibrium constant of the reaction will increase exponentially.
import { useState } from "react"; import { Link } from "react-router-dom"; import { InputGroup, Navbar, Nav, Form, FormControl, Button, Container, } from "react-bootstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faSearch } from "@fortawesome/free-solid-svg-icons"; import "./Header.css"; // Import your custom CSS file function Header() { const [searchText, setSearchText] = useState(""); const handleChange = (e) => { const { value, name } = e.target; setSearchText(value); }; const handleClick = () => { console.log("Search " + searchText); }; return ( <Navbar bg="transparent" variant="transparent" expand="lg" className="custom-navbar" style={{ color: "black" }} > <Container> {/* Logo on the left */} <Navbar.Brand> <Link to="/"> <img className="logo" src=".\img\logo-no-background.png"></img> </Link> </Navbar.Brand> {/* Menu links in the middle */} <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="mx-auto"> <Nav.Link> <Link className="link" to="/"> Home </Link> </Nav.Link> <Nav.Link> <Link className="link" to="/about"> About Us </Link> </Nav.Link> <Nav.Link> <Link className="link" to="/shop"> Shop </Link> </Nav.Link> <Nav.Link> <Link className="link" to="/contact"> Contact </Link> </Nav.Link> </Nav> </Navbar.Collapse> {/* Search box with search icon */} <Form inline> <InputGroup> <FormControl value={searchText ? searchText : ""} className="rounded-search" name="search" onChange={handleChange} type="text" placeholder="Search" variant="outline-primary" /> <InputGroup.Text> <Button onClick={() => handleClick} variant="outline-primary"> <FontAwesomeIcon icon={faSearch} /> </Button> </InputGroup.Text> </InputGroup> </Form> </Container> </Navbar> ); } export default Header;
package org.example.Visitadores; import org.example.Frecuencia.*; import java.time.DayOfWeek; import java.util.HashMap; public class VisitadorEventosFrecuencia implements VisitorFrecuencia { private String frecuenciaMensaje; private HashMap<String, String> dias; public String obtenerMensajeFrecuencia() { return this.frecuenciaMensaje; } public void obtenerTipoFrecuencia(FrecuenciaDiaria frecuencia) { this.frecuenciaMensaje = "Se repite cada " + frecuencia.obtenerValorRepeticion() + " día" + esPlural(frecuencia) + "."; } public void obtenerTipoFrecuencia(FrecuenciaSemanal frecuencia) { // ver hacerlo por cada semana seria sin s if (frecuencia.obtenerDiasSemana().size() == 7) { this.frecuenciaMensaje = "Se repite todos los días cada " + frecuencia.obtenerValorRepeticion() + " semana" + esPlural(frecuencia) + "."; } String resultado = "Se repite los "; this.crearMapDias(); for (DayOfWeek dia : frecuencia.obtenerDiasSemana()) { resultado += this.dias.get(dia.name()) + ", "; } this.frecuenciaMensaje = resultado + "cada " + frecuencia.obtenerValorRepeticion() + " semana" + esPlural(frecuencia) + "."; } public void obtenerTipoFrecuencia(FrecuenciaMensual frecuencia) { this.frecuenciaMensaje = "Se repite cada " + frecuencia.obtenerValorRepeticion() + " mes" + esPluralMeses(frecuencia) + "."; } public void obtenerTipoFrecuencia(FrecuenciaAnual frecuencia) { this.frecuenciaMensaje = "Se repite cada " + frecuencia.obtenerValorRepeticion() + " año" + esPlural(frecuencia) + "."; } private String esPlural(Frecuencia frecuencia) { return frecuencia.obtenerValorRepeticion() > 1 ? "s" : ""; } private String esPluralMeses(FrecuenciaMensual frecuencia) { return frecuencia.obtenerValorRepeticion() > 1 ? "es" : ""; } private void crearMapDias() { this.dias = new HashMap<>(); this.dias.put("MONDAY", "lunes"); this.dias.put("TUESDAY", "martes"); this.dias.put("WEDNESDAY", "miercoles"); this.dias.put("THURSDAY", "jueves"); this.dias.put("FRIDAY", "viernes"); this.dias.put("SATURDAY", "sabado"); this.dias.put("SUNDAY", "domingo"); } }
/***************************************************************************** * - Copyright (C) - 2020 - InfinyTech3D - * * * * This file is part of the InfinyToolkit plugin for the SOFA framework * * * * Commercial License Usage: * * Licensees holding valid commercial license from InfinyTech3D may use this * * file in accordance with the commercial license agreement provided with * * the Software or, alternatively, in accordance with the terms contained in * * a written agreement between you and InfinyTech3D. For further information * * on the licensing terms and conditions, contact: contact@infinytech3d.com * * * * GNU General Public License Usage: * * Alternatively, this file may be used under the terms of the GNU General * * Public License version 3. The licenses are as published by the Free * * Software Foundation and appearing in the file LICENSE.GPL3 included in * * the packaging of this file. Please review the following information to * * ensure the GNU General Public License requirements will be met: * * https://www.gnu.org/licenses/gpl-3.0.html. * * * * Authors: see Authors.txt * * Further information: https://infinytech3d.com * ****************************************************************************/ #pragma once #include <InfinyToolkit/config.h> #include <sofa/core/behavior/BaseController.h> #include <sofa/type/Vec.h> #include <sofa/component/statecontainer/MechanicalObject.h> namespace sofa::infinytoolkit { using namespace sofa::defaulttype; /** Will search for MechanicalObject with Tag "slice" as target meshes. * Use the position of the MechanicalObject Tag as "needle". * At each step: * - BB of each target mesh is updated (TODO: this can be optimised) * - Check if position of the needle is inside a BB: BroadPhase * - if position is inside the BB mesh (could have several), cast ray from needle position to first triangle. * if an odd number of triangle is intersected by the ray, needle is inside mesh otherwise outside. * If needle is inside a mesh, @sa d_sliceName contain the name of this mesh. If none, d_sliceName return "None". */ class SOFA_INFINYTOOLKIT_API NeedleTracker : public sofa::core::behavior::BaseController { public: typedef defaulttype::Vec3Types DataTypes; typedef DataTypes::Coord Coord; typedef DataTypes::Real Real; typedef sofa::component::statecontainer::MechanicalObject<sofa::defaulttype::Vec3Types> MechanicalObject3; NeedleTracker(); virtual ~NeedleTracker(); Data<bool> d_drawDebug; ///< if true, draw the Mesh BoundingBox, ray and triangle intersected Data<int> d_sliceID; /// id of the mesh (in @sa m_slices) where the needle is. -1 if none Data<std::string> d_sliceName; /// Name of the mesh where the needle is. "None" if needle is outside of all meshes. public: /// Sofa API methods virtual void init() override; virtual void bwdInit() override; virtual void handleEvent(sofa::core::objectmodel::Event* event) override; //display debug draw info void draw(const core::visual::VisualParams* vparams); /// Return the number of targeted meshes size_t numberOfSlice() { return m_slices.size(); } /// Return the name of the Slice where the needle is. "None"if needle is outside from all meshes. std::string getPositionInSlices(const Coord& tipPosition); protected: /// BroadPhase method, test needle position with slice BB bool testSliceBBIntersection(int sliceID, const Coord& tipPosition); /// NarrowPhase method, test needle position with slice mesh triangles bool testSliceDiscretIntersection(int sliceID, const Coord& tipPosition); /// Internal method to compute each slice BB void computeSlicesBB(); /// Internal method to test the intersection between a ray and a triangle bool RayIntersectsTriangle(const Coord& origin, const type::Vec3& rayDirection, const Coord& P0, const Coord& P1, const Coord& P2, Coord& outIntersection); protected: /// Vector storing pointer to each mechanicalObject of the target mesh sofa::type::vector<MechanicalObject3*> m_slices; /// Pointer to the MechanicalObject corresponding to the needle position MechanicalObject3* m_needle; /// Vector of min and max of the slice boudingboxes sofa::type::vector<Coord> m_min; sofa::type::vector<Coord> m_max; /// Origin and direction of the ray (for draw debug only) Coord m_rayDirection; Coord m_rayOrigin; /// vector of triangles positions intersected by narrow phase ray. sofa::type::vector <Coord> m_triPointInter; bool isInit; }; } // namespace sofa::infinytoolkit
import { useContext, useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { Link } from 'react-router-dom'; import { AuthContext } from "../../../contexts/AuthContext"; import * as authService from "../../../services/authService"; import { LanguageContext } from "../../../contexts/LanguageContext"; import {languages} from '../../../languages/languages'; import { useValidateForm } from "../../../hooks/useValidateForm"; import Notification from "../../common/notification/Notification"; import Backdrop from "../../common/backdrop/Backdrop"; import ModalError from "../../common/modal/ModalError"; import styles from './Register.module.css'; const Register = () => { const {language} = useContext(LanguageContext); const { userLogin } = useContext(AuthContext); const navigate = useNavigate(); const [showNotification, setShowNotification] = useState(true); const [showPassNotification, setShowPassNotification] = useState(false); const [showModalError, setShowModalError] = useState(false); const [errorMessage, setErrorMessage] = useState([]); const [values, setValues] = useState({ email: '', password: '', confirmPassword: '' }); useEffect(() => { if (values.email === '' || values.password === '' || values.confirmPassword === '') { setShowNotification(true); } else { setShowNotification(false); } }, [values.email, values.password, values.confirmPassword]) useEffect(() => { if (values.confirmPassword && values.password !== values.confirmPassword) { setShowPassNotification(true); } else { setShowPassNotification(false); } }, [values.password, values.confirmPassword]) const {minLength, isValidEmail, isFormValid, errors} = useValidateForm(values); const changeValueHandler = (e) => { setValues(state => ({ ...state, [e.target.name]: e.target.value })) }; const onClickOk = () => { setShowModalError(false); } const onSubmit = (e) => { e.preventDefault(); authService.register(values.email, values.password.trim()) .then(result => { const authData = { _id: result._id, email: result.email, accessToken: result.accessToken }; userLogin(authData); navigate('/'); }) .catch((err) => { setShowModalError(true); setErrorMessage(state => [...state, err.message]); setValues({ email: '', password: '', confirmPassword: '' }); }); }; return ( <section className={styles["register-page"]}> { showNotification && <Notification message={languages.allFieldsRequired[language]} />} { showPassNotification && <Notification message={languages.passwordsDontMatch[language]} />} {showModalError && <Backdrop onClick={onClickOk} />} {showModalError && <ModalError errorMessage={errorMessage} onClickOk={onClickOk} />} <div className={styles["register-wrapper"]}> <form className={styles["register-form"]} onSubmit={onSubmit}> <h1>{languages.register[language]}</h1> <label htmlFor="register-email">{languages.email[language]}</label> <input type="email" id="register-email" name="email" value={values.email} onChange={changeValueHandler} onBlur={isValidEmail} /> {errors.email && <p className="error"> {languages.emailErrorMessage[language]} </p> } <label htmlFor="register-password">{languages.password[language]}</label> <input type="password" name="password" id="register-password" value={values.password} onChange={changeValueHandler} onBlur={(e) => minLength(e, 5)} /> {errors.password && <p className="error"> {languages.passwordErrorMessage[language]} </p> } <label htmlFor="confirm-register-password">{languages.reEnterPassword[language]}</label> <input type="password" name="confirmPassword" id="confirm-register-password" value={values.confirmPassword} onChange={changeValueHandler} /> <div className={styles["btn-register"]}> <button type="submit" disabled={!isFormValid || showNotification || showPassNotification} className={`${!isFormValid || showNotification || showPassNotification ? 'button-disabled' : ''}`} > {languages.register[language]} </button> </div> <p className="account-message"> {languages.alreadyHaveAccount[language]}<Link to="/login">{languages.here[language]}</Link> </p> </form> </div> </section> ); } export default Register;
import streamlit as st import pandas as pd import numpy as np # URL untuk dataset Uber DATA_URL = 'https://s3-us-west-2.amazonaws.com/streamlit-demo-data/uber-raw-data-sep14.csv.gz' # Fungsi caching untuk memuat data @st.cache_data def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) data.rename(lambda x: str(x).lower(), axis='columns', inplace=True) data['date/time'] = pd.to_datetime(data['date/time']) return data # Menampilkan judul aplikasi st.title('Uber Pickups di NYC') # Menampilkan teks "Loading data..." data_load_state = st.text('Loading data...') data = load_data(10000) # Membatasi data yang diambil ke 10.000 baris data_load_state.text('Done! (data loaded using @st.cache)') # Menampilkan data mentah jika checkbox diaktifkan if st.checkbox('Tampilkan data mentah'): st.subheader('Data mentah') st.write(data) # Membuat histogram jumlah penjemputan berdasarkan jam st.subheader('Jumlah penjemputan per jam') hist_values = np.histogram(data['date/time'].dt.hour, bins=24, range=(0,24))[0] st.bar_chart(hist_values) # Membuat peta interaktif berdasarkan waktu pemilihan penjemputan st.subheader('Peta penjemputan Uber berdasarkan waktu') hour_to_filter = st.slider('Jam', 0, 23, 17) # Slider untuk memilih jam filtered_data = data[data['date/time'].dt.hour == hour_to_filter] st.map(filtered_data)