text
stringlengths
184
4.48M
import React, { useEffect, useState } from 'react' import { Link } from 'react-router-dom' export const Navigations = () => { const [isLoggedIn,setLoggedIn] = useState(false); const logout = ()=>{ sessionStorage.clear(); console.log("cleared"); } useEffect(() => { if (sessionStorage.getItem("emailId") != null){ setLoggedIn(true); } return () => { } }) return ( <div> <nav className="navbar navbar-expand-lg navbar-light bg-light"> <div className="container-fluid"> <a className="navbar-brand" href="#">Navbar</a> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link className="nav-link active" aria-current="page" to="/">Home</Link> </li> {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/demo">Demo Page</Link> </li>:""} {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/aboutus/:name">About us</Link> </li>:""} {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/contactus">Contact us</Link> </li>:""} {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/edit/:id">Edit Product</Link> </li>:""} {/* <td><Link className="nav-link" to="/addproduct">AddProduct_clickHere</Link></td> */} {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/addproduct">Add Product</Link> </li>:""} {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/getProduct/:id">Get Product Details</Link> </li>:""} {isLoggedIn?<li className="nav-item"> <Link className="nav-link" to="/" onClick={logout}>Logout</Link> </li>:""} </ul> </div> </div> </nav> </div> ) }
\documentclass[review]{elsarticle} %%% Le da el formato final -- una vez aceptado %\documentclass[final,authoryear,5p,times]{elsarticle} %\documentclass[final,authoryear,5p,times,twocolumn]{elsarticle} \usepackage{lineno,hyperref} \modulolinenumbers[5] \usepackage{amssymb} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{multirow} \usepackage{algorithm} \usepackage{algpseudocode} %PO \usepackage{color} % Use colors on text \usepackage[normalem]{ulem} % Strike through text \journal{Astronomy and Computing} %% Elsevier bibliography styles %%%%%%%%%%%%%%%%%%%%%%% %% To change the style, put a % in front of the second line of the current style and %% remove the % from the second line of the style you would like to use. %%%%%%%%%%%%%%%%%%%%%%% %% Harvard \bibliographystyle{model2-names.bst}\biboptions{authoryear} %%%%%%%%%%%%%%%%%%%%%%% \begin{document} \begin{frontmatter} %\title{Variational Autoencoders with Scale for Light-curves: Learning a Deep Interpretable Representation and a Denoising Model Together!} %\title{Learning Quality Deep Representations for Light Curves using Variational Autoencoders with Rescaling} \title{On the Quality of Deep Representations for Unevenly-Sampled Light-Curves using Variational AutoEncoders} %\tnotetext[mytitlenote]{Fully documented templates are available in the elsarticle package on \href{http://www.ctan.org/tex-archive/macros/latex/contrib/elsarticle}{CTAN}.} % On the Quality of Deep Representations for Light-Curves using Variantional Autoencoders \author[UTFSM_SJ]{Francisco Mena\corref{mycorrespondingauthor}} \cortext[mycorrespondingauthor]{Corresponding author} \ead{[email protected]} \author[UTFSM_CC]{Patricio Olivares} %\ead[url]{www.elsevier.com} \author[UTFSM_SJ]{Margarita Bugue\~no} %\ead[url]{www.elsevier.com} \author[UTFSM_SJ]{Gabriel Molina} %\ead[url]{www.elsevier.com} \author[UTFSM_CC]{Mauricio Araya} %\ead[url]{www.elsevier.com} \address[UTFSM_SJ]{Depto. Inform\'atica, Universidad T\'ecnica Federico Santa Mar\'ia, Santiago, Chile} \address[UTFSM_CC]{Depto. Electr\'onica, Universidad T\'ecnica Federico Santa Mar\'ia, Valpara\'iso, Chile} \begin{abstract} %motivation, problem, approach, result, concl Analyzing light curves nowadays usually involves processing large datasets. Therefore, finding a good representation for them is both, a key and a non trivial task. In this paper we show that variational (stochastic) autoencoder models (VRAE$_t$) can be applied to learn an effective, informative and robust deep representation of transit light curves. In addition, we introduce S-VRAE$_t$, which stands for \textit{re-Scaling Variational Recurrent Auto Encoder}, a technique that embeds the re-scaling preprocessing of a time series into the learning model in order to use the scale information in the detection of transit exoplanets. The objective is to achieve the most likely low dimensional output of unevenly-sampled time series that matches latent variables to reconstruct it. For assessing our approach we use the largest transit dataset obtained by the Kepler mission in the past four years, and compare our results with similar techniques used for light curves. Our results show that the stochastic models have an improvement on the quality of representation with respect to their deterministic counterparts. Moreover, the S-VRAE$_t$ model is at the same time a deep denoising model, generating light curves similar to the Mandel Agol fit. \end{abstract} \begin{keyword} Variational Autoencoder \sep Transit Model \sep Light-Curve \MSC[2010] 00-01\sep 99-00 \end{keyword} \end{frontmatter} \linenumbers \input{draft_Introduction.tex} \input{draft_SoA.tex} \input{draft_Proposal.tex} \input{draft_Experiments.tex} \input{draft_Results.tex} \input{draft_Conclusion.tex} \section*{Acknowledgments} This research was possible due to the funding of \textit{Programa de Iniciaci\'on Cient\'ifica} PIIC-DGIP of Universidad T\'ecnica Feder\'ico Santa Mar\'ia, ANID-Basal Project FB0008 (AC3E) and ANID PIA/APOYO AFB180002 (CCTVal). \bibliography{mybibfile} \end{document}
<template> <div class="line-echarts"> <ly-echarts :options="options" /> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import LyEcharts from '@/components/echarts' import * as echarts from 'echarts' export default defineComponent({ name: 'bar-echarts', props: { xLabels: { type: Array, require: true }, values: { type: Array, require: true } }, setup(props) { const options = { xAxis: { data: props.xLabels, axisLabel: { inside: true, color: '#fff' }, axisTick: { show: false }, axisLine: { show: false }, z: 10 }, yAxis: { axisLine: { show: false }, axisTick: { show: false }, axisLabel: { color: '#999' } }, dataZoom: [ { type: 'inside' } ], series: [ { type: 'bar', showBackground: true, itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#83bff6' }, { offset: 0.5, color: '#188df0' }, { offset: 1, color: '#188df0' } ]) }, emphasis: { itemStyle: { color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ { offset: 0, color: '#2378f7' }, { offset: 0.7, color: '#2378f7' }, { offset: 1, color: '#83bff6' } ]) } }, data: props.values } ] } return { options, LyEcharts } } }) </script> <style lang="less" scoped></style>
const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const errorController = require('./controllers/error'); const db = require('./util/database') const app = express(); app.set('view engine', 'ejs'); app.set('views', 'views'); const adminRoutes = require('./routes/admin'); const shopRoutes = require('./routes/shop'); // db.execute('SELECT * FROM products').then((result) => { // console.log(result) // }).catch((err) => { // console.log(err) // }); // we now get back promises when using execute, // this is from the module.exports = pool.promise() // line in database.js // PRomises have two methods, .then() and .catch() // And if we start up the server now, npm start we // see the item we added in MySQL logged to // the console: // [ // [ // { // id: 1, // title: 'Summa Theologica', // price: 19.99, // description: 'Thomas Aquinas', // imageURL: 'https://images.unsplash.com/photo-1654157925394-4b7809721149?ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1460&q=80' // } // ] // There's also a huge logging of meta data, the above is // equivalent to logging result[0] // The data we get back has the format of an array, // with a nested array, and since it's an array // we can access specific indexes, like: // result[0] or result[1] // db.execute('SELECT * FROM products').then((result) => { // console.log(result[0]) // }).catch((err) => { // console.log(err) // }); // result[0]: // [ // { // id: 1, // title: 'Summa Theologica', // price: 19.99, // description: 'Thomas Aquinas', // imageURL: 'https://images.unsplash.com/photo-1654157925394-4b7809721149?ixlib=rb-4.0.3&ixid=M3wxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1460&q=80' // } // ] app.use(bodyParser.urlencoded({ extended: false })); app.use(express.static(path.join(__dirname, 'public'))); app.use('/admin', adminRoutes); app.use(shopRoutes); app.use(errorController.get404); app.listen(3000);
""" :copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved. The source code contained or described here in and all documents related to the source code ("Material") are owned by Intel Corporation or its suppliers or licensors. Title to the Material remains with Intel Corporation or its suppliers and licensors. The Material contains trade secrets and proprietary and confidential information of Intel or its suppliers and licensors. The Material is protected by worldwide copyright and trade secret laws and treaty provisions. No part of the Material may be used, copied, reproduced, modified, published, uploaded, posted, transmitted, distributed, or disclosed in any way without Intel's prior express written permission. No license under any patent, copyright, trade secret or other intellectual property right is granted to or conferred upon you by disclosure or delivery of the Materials, either expressly, by implication, inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and approved by Intel in writing. :organization: INTEL MCG PSI :summary: implementation of Apx 585 audio analyzer :since:27/11/2012 :author: nprecigx """ import time import subprocess from threading import Thread from ctypes import * from ErrorHandling.TestEquipmentException import TestEquipmentException from acs_test_scripts.Equipment.IEquipment import ExeRunner from acs_test_scripts.Equipment.AudioAnalyzer.Interface.IAudioAnalyzer import IAudioAnalyzer from Device.DeviceManager import DeviceManager class APx585(IAudioAnalyzer, ExeRunner): """ Implementation of APx585 audio analyzer """ # Executable timeout TIMEOUT = 1200 PIPE_ACCESS_DUPLEX = 0x3 PIPE_TYPE_MESSAGE = 0x4 PIPE_READMODE_MESSAGE = 0x2 PIPE_WAIT = 0 PIPE_NOWAIT = 1 PIPE_UNLIMITED_INSTANCES = 255 BUFFERSIZE = 512 NMPWAIT_USE_DEFAULT_WAIT = 5000 INVALID_HANDLE_VALUE = -1 ERROR_PIPE_CONNECTED = 535 TIMEOUT_PIPE = 60 PIPENAME = "\\\\.\\pipe\\APxSync" def __init__(self, name, model, eqt_params, bench_params): """ Constructor :type name: str :param name: the bench configuration name of the equipment :type model: str :param model: the model of the equipment :type eqt_params: dict :param eqt_params: the dictionary containing equipment parameters :type bench_params: dict :param bench_params: the dictionary containing equipment bench parameters """ IAudioAnalyzer.__init__(self) ExeRunner.__init__(self, name, model, eqt_params) self.__bench_params = bench_params self._device = None self.__handle = None self.__pipeHandle = None self.__charBuffer = None self.__bNbrRead = None def __manage_apx585(self, execution_type, board_type=None, test_type=None, call_type=None, accessories_type=None, signal_tested_direction=None, dut_bt_address=None): """ launch a command to APx585. :type execution_type: str :param execution_type: Init, pair_bt, run or calibration :type board_type: str :param board_type: board_type from device_catalog :type test_type: str :param test_type: test executed on device :type call_type: str :param call_type: 2G, 3G, VOIP :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :type signal_tested_direction: str :param signal_tested_direction: UL, DL :type dut_bt_address: str :param dut_bt_address: dut mac bluetooth address :rtype: str :return: executable return code """ waitendprocess = True if execution_type == "init": if board_type is not None and test_type is not None: cmd_line = "%s %s %s" % (execution_type, board_type, test_type) else: raise TestEquipmentException(TestEquipmentException.INVALID_PARAMETER) elif execution_type == "run": if accessories_type is not None and call_type is not None \ and signal_tested_direction is not None: cmd_line = "%s %s %s %s" % (execution_type, call_type, accessories_type, signal_tested_direction) else: raise TestEquipmentException(TestEquipmentException.INVALID_PARAMETER) elif execution_type == "pairbt": if dut_bt_address is not None: cmd_line = "%s %s" % (execution_type, dut_bt_address) else: raise TestEquipmentException(TestEquipmentException.INVALID_PARAMETER) elif execution_type == "connectbt": if dut_bt_address is not None: cmd_line = "%s %s %s" % (execution_type, accessories_type, dut_bt_address) else: raise TestEquipmentException(TestEquipmentException.INVALID_PARAMETER) elif execution_type == "calibration": if dut_bt_address is not None: cmd_line = "%s %s %s %s %s %s" % (execution_type, board_type, call_type, accessories_type, signal_tested_direction, dut_bt_address) else: raise TestEquipmentException(TestEquipmentException.INVALID_PARAMETER) else: raise TestEquipmentException(TestEquipmentException.INVALID_PARAMETER) apx585_result = ExeRunner.start_exe(self, cmd_line, self.TIMEOUT, waitendprocess) if not waitendprocess: exec_return_code = apx585_result[2].wait() else: exec_return_code = apx585_result[1] # if exception occured during execution => kill AudioPrecision application if exec_return_code == ExeRunner.NOT_TERMINATED: self._logger.info("Apx executable timeout") subprocess.Popen("taskkill /F /IM AudioPrecision.APx500.exe /T", shell=True) return exec_return_code def initialization(self, board_type, test_type): """ Init Apx585. :type board_type: str :param board_type: board_type from device_catalog :type test_type: str :param test_type: test executed on device :rtype: str :return: executable return code """ exec_return_code = self.__manage_apx585("init", board_type, test_type) return exec_return_code def pair_bt(self, dut_bt_address): """ Pair Bluetooth between Apx585 and Dut :param dut_bt_address: dut mac bluetooth address :rtype: str :rtype: str :return: executable return code """ exec_return_code = self.__manage_apx585("pairbt", None, None, None, None, None, dut_bt_address) return exec_return_code def connect_bt(self, accessories_type, dut_bt_address): """ Connect Bluetooth between Apx585 and Dut :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :type accessories_type: str :param dut_bt_address: dut mac bluetooth address :rtype: str :return: executable return code """ exec_return_code = self.__manage_apx585("connectbt", None, None, None, accessories_type, None, dut_bt_address) return exec_return_code def run(self, call_type, accessories_type, signal_tested_direction): """ Run Apx585 test :type call_type: str :param call_type: 2G, 3G, VOIP :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :type signal_tested_direction: str :param signal_tested_direction: UL, DL :rtype: str :return: executable return code """ exec_return_code = self.__manage_apx585("run", None, None, call_type, accessories_type, signal_tested_direction) return exec_return_code def calibration(self, board_type, call_type, acc_type, signal_tested_direction, dut_bt_address): """ Run Apx585 calibration :type board_type: str :param board_type: board_type from device_catalog :type call_type: str :param call_type: 2G, 3G, VOIP :type acc_type: str :param acc_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :type signal_tested_direction: str :param signal_tested_direction: UL, DL :type dut_bt_address: str :param dut_bt_address: dut mac bluetooth address :rtype: str :return: executable return code """ exec_return_code = self.__manage_apx585("calibration", board_type, None, call_type, acc_type, signal_tested_direction, dut_bt_address) return exec_return_code def get_volume(self, call_type=None, accessories_type=None): """ launch a command to APx585 :type call_type: str :param call_type: 2G, 3G, VOIP :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :rtype: (str, str) :return: tuple of (executable return code, volume) """ waitendprocess = False # Pipe handle creation self.create_pipe() cmd_line = "%s %s %s" % ("getvolume", call_type, accessories_type) apx585_result = ExeRunner.start_exe(self, cmd_line, self.TIMEOUT, waitendprocess) # Waiting message from APx l_volume = self.read_pipe() if not waitendprocess: exec_return_code = apx585_result[2].wait() else: exec_return_code = apx585_result[1] # if exception occured during execution => kill AudioPrecision application if exec_return_code == 3: self._logger.info("Apx executable timeout") subprocess.Popen("taskkill /F /IM AudioPrecision.APx500.exe /T", shell=True) self.close_pipe() return exec_return_code, l_volume def ringtone_detection(self, accessories_type=None): """ launch a command to APx585 to detect ringtone :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :rtype: str :return: executable return code """ waitendprocess = True cmd_line = "%s %s " % ("ringtonedetection", accessories_type) apx585_result = ExeRunner.start_exe(self, cmd_line, self.TIMEOUT, waitendprocess) exec_return_code = apx585_result[1] # if exception occured during execution => kill AudioPrecision application if exec_return_code == 3: self._logger.info("Apx executable timeout") subprocess.Popen("taskkill /F /IM AudioPrecision.APx500.exe /T", shell=True) return exec_return_code def write_pipe(self, message="none"): """ Write a message in a pipe :type message: str :param message: message write in the pipe :rtype: None :raise UECommandException: if message superior at the buffer size or message is not write on the pipe """ if len(message) < self.BUFFERSIZE: bNbrWritten = c_ulong(0) fSuccess = windll.kernel32.WriteFile(self.__pipeHandle, c_char_p(message), len(message), byref(bNbrWritten), None) windll.kernel32.FlushFileBuffers(self.__pipeHandle) if fSuccess != 1 or bNbrWritten.value == 0: raise TestEquipmentException( TestEquipmentException.OPERATION_FAILED, "Message %s is not write in the pipe" % str(message)) else: raise TestEquipmentException( TestEquipmentException.INVALID_PARAMETER, "Size of message %s is superior at the buffer size" % str(message)) def read_pipe(self): """ Read a message in a pipe :rtype: str :return: the message read on the pipe :raise UECommandException: if timeout is reached """ self.__charBuffer = create_string_buffer(self.BUFFERSIZE) self.__bNbrRead = c_ulong(0) def target(): fSuccess = 0 while (fSuccess != 1) or (self.__bNbrRead.value == 0): fSuccess = windll.kernel32.ReadFile(self.__pipeHandle, self.__charBuffer, self.BUFFERSIZE, byref(self.__bNbrRead), None) time.sleep(0.2) # Execution threader => if executable don't respond before timeout, it is killed thread = Thread(target=target) thread.start() thread.join(self.TIMEOUT_PIPE) if thread.is_alive(): windll.kernel32.FlushFileBuffers(self.__pipeHandle) self.close_pipe() raise TestEquipmentException(TestEquipmentException.TIMEOUT_REACHED, "Read message failed") return self.__charBuffer.value def create_pipe(self): """ Create and connect pipe :rtype: None :raise UECommandException: if message superior at the buffer size """ # Pipe creation pipeHandle = windll.kernel32.CreateNamedPipeA(self.PIPENAME, self.PIPE_ACCESS_DUPLEX, self.PIPE_TYPE_MESSAGE | self.PIPE_READMODE_MESSAGE | self.PIPE_WAIT, self.PIPE_UNLIMITED_INSTANCES, self.BUFFERSIZE, self.BUFFERSIZE, self.NMPWAIT_USE_DEFAULT_WAIT, None) self.__pipeHandle = pipeHandle def connect_pipe(): """ connect pipe """ if self.__pipeHandle == self.INVALID_HANDLE_VALUE: raise TestEquipmentException(TestEquipmentException.CONNECTION_ERROR, "Invalid pipe handle") # Connecting pipe self._logger.info("Connect Pipe") pConnected = windll.kernel32.ConnectNamedPipe(self.__pipeHandle, None) if ((pConnected == 0 and windll.kernel32.GetLastError() == self.ERROR_PIPE_CONNECTED) or pConnected == 1): # self.__pipeHandle = pipeHandle self._logger.info("Pipe Connected => " + str(self.__pipeHandle)) # If the connection failed then the handle is closed else: self.__pipeHandle = pipeHandle windll.kernel32.CloseHandle(self.__pipeHandle) raise TestEquipmentException(TestEquipmentException.OPERATION_FAILED, "Pipe creation failed") self._logger.info("Dans Create pipe => " + str(self.__pipeHandle)) # Execution threader => if executable don't respond before timeout, it is killed thread = Thread(target=connect_pipe) thread.start() return self.__pipeHandle def close_pipe(self): """ Create and connect pipe :rtype: None :raise UECommandException: Pipe handle is None """ # Pipe Handle Closing if self.__pipeHandle is not None: windll.kernel32.FlushFileBuffers(self.__pipeHandle) windll.kernel32.DisconnectNamedPipe(self.__pipeHandle) windll.kernel32.CloseHandle(self.__pipeHandle) else: raise TestEquipmentException(TestEquipmentException.OPERATION_FAILED, "Pipe handle none close error") def get_dtmf(self, accessories_type=None, signal_tested_direction=None, key_touch=None): """ launch a command to APx585 :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :type signal_tested_direction: str :param signal_tested_direction: UL, DL :rtype: str :return: executable return code """ waitendprocess = False exec_return_code = 3 l_touch_press2 = -1 if signal_tested_direction == "UL": self._device = DeviceManager().get_device("PHONE1") else: self._device = DeviceManager().get_device("PHONE2") # Pipe handle creation l_create_pipe = self.create_pipe() time.sleep(0.5) self._logger.info("Create pipe => " + str(l_create_pipe)) cmd_line = "%s %s %s" % ("getdtmf", accessories_type, signal_tested_direction) apx585_result = ExeRunner.start_exe(self, cmd_line, self.TIMEOUT_PIPE, waitendprocess) self._logger.info("Create pipe => " + str(self.__pipeHandle)) # Waiting message from APx self._logger.info("Start read pipe") l_ready = self.read_pipe() self._logger.info("End read pipe => " + str(l_ready)) time.sleep(0.5) if l_ready == "READY": self.write_pipe("GO") time.sleep(1) # Key press self._logger.info("DTMF press touch " + key_touch) self._device.run_cmd("adb shell input text " + key_touch, 1) self._logger.info("End press touch") self._logger.info("Read pipe") l_touch_press = self.read_pipe() self._logger.info("End read pipe (touch press) => " + str(l_touch_press)) exec_return_code = apx585_result[2].wait() self._logger.info("End wait pipe (exec_return_code) => " + str(exec_return_code)) if l_touch_press != "READY": l_touch_press2 = int(l_touch_press) - 48 else: apx585_result[2].terminate() self._logger.info("Start close pipe") self.close_pipe() self._logger.info("End close pipe") # if exception occured during execution => kill AudioPrecision application if exec_return_code == 3: self._logger.info("Apx executable timeout") subprocess.Popen("taskkill /F /IM AudioPrecision.APx500.exe /T", shell=True) return exec_return_code, str(l_touch_press2) def glitch_detection_before_switch(self, test_type, board_type, call_type, accessories_type, signal_tested_direction): """ Run Apx585 glitch detection in call. :type test_type: str :param test_type: glitch detection type glitchdetectiononswitch or glitchdetectiononswap :type board_type: str :param board_type: board_type from device_catalog :type call_type: str :param call_type: 2G, 3G, VOIP :type accessories_type: str :param accessories_type: accessories type: earpiece, speaker, headset, bluetootha2dp, bluetoothhsp :type signal_tested_direction: str :param signal_tested_direction: UL, DL :rtype: tuple :return: A tuple containing :: - stdout as C{in}: 0 if ready -1 else - return code as C{Popen}: the executable process """ waitendprocess = False if signal_tested_direction == "UL": self._device = DeviceManager().get_device("PHONE1") else: self._device = DeviceManager().get_device("PHONE2") # Pipe handle creation l_create_pipe = self.create_pipe() time.sleep(0.5) self._logger.info("Create pipe => " + str(l_create_pipe)) cmd_line = "%s %s %s %s %s" % (test_type, board_type, call_type, accessories_type, signal_tested_direction) apx585_result = ExeRunner.start_exe(self, cmd_line, self.TIMEOUT_PIPE, waitendprocess) self._logger.info("Create pipe => " + str(self.__pipeHandle)) # Waiting message from APx self._logger.info("Start read pipe") l_ready = self.read_pipe() self._logger.info("End read pipe => " + str(l_ready)) time.sleep(0.5) if l_ready == "READY": self.write_pipe("GO") return 0, apx585_result[2] else: apx585_result[2].terminate() return -1, None def glitch_detection_after_switch(self, process): """ Run Apx585 glitch detection in call :type process: Popen :param process: Apx585 executable processus :rtype: str :return: executable return code """ exec_return_code = process.wait() self._logger.info("Start close pipe") self.close_pipe() self._logger.info("End close pipe") # if exception occured during execution => kill AudioPrecision application if exec_return_code == 3: self._logger.info("Apx executable timeout") subprocess.Popen("taskkill /F /IM AudioPrecision.APx500.exe /T", shell=True) return exec_return_code
import 'package:auto_route/auto_route.dart'; import 'package:builtop_admin_dashboard/constants/color.dart'; import 'package:builtop_admin_dashboard/constants/const.dart'; import 'package:builtop_admin_dashboard/constants/text.dart'; import 'package:builtop_admin_dashboard/modules/users/admin/admins.page.dart'; import 'package:builtop_admin_dashboard/modules/users/supervisors/supervisor.model.dart'; import 'package:builtop_admin_dashboard/modules/users/supervisors/supervisors.controller.dart'; import 'package:builtop_admin_dashboard/utils/responsive.dart'; import 'package:builtop_admin_dashboard/widgets/form_fields.widget.dart'; import 'package:builtop_admin_dashboard/widgets/users_menu_button.widget.dart'; import 'package:flutter/material.dart'; import 'package:flutterx/flutterx.dart'; import 'package:mahg_essential_package/mahg_essential_package.dart'; import 'package:intl/intl.dart' as intl; class SupervisorDetailsPage extends MahgStatefulWidget<SupervisorsController> { const SupervisorDetailsPage({SupervisorsController? controllerEx, Key? key}) : super(controllerEx, key: key); @override State<SupervisorDetailsPage> createState() => _SupervisorDetailsPageState(); } class _SupervisorDetailsPageState extends MahgState<SupervisorDetailsPage, SupervisorsController> { @override createController() { return SupervisorsController(); } bool get loadingPage => ((context.routeData.queryParams.get('id') != null && context.routeData.queryParams.get('id') != '') && (controller.supervisor == null)); bool get isUpdate => ((context.routeData.queryParams.get('id') != null && context.routeData.queryParams.get('id') != '')); @override Widget build(BuildContext context) { return Card( shadowColor: ColorConst.primary.withOpacity(0.5), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), child: Padding( padding: const EdgeInsets.all(10.0), child: loadingPage ? const CircularProgressIndicator.adaptive() : Form( key: controller.formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: Text( controller.supervisor != null ? 'Edit Supervisor' : 'New Supervisor', style: const TextStyle( fontSize: 17, fontWeight: FontWeight.w600), ), ), isUpdate ? UsersMenuButton( canChangePassword: true, contextEx: context, returnToIndex: 1, user: controller.supervisor!, ) : const SizedBox.shrink() ], ), FxBox.h24, FormFieldsWidget( isUpdate: isUpdate, controller: controller, ), Row( children: [ FxButton( borderRadius: 4, onPressed: controller.supervisor?.id == null ? () => controller.addSupervisorHandler() : () => controller.editSupervisorHandler(), text: controller.supervisor?.id == null ? 'Add New' : 'Update', ), ], ), ], ), ), ), ); } }
<!DOCTYPE html> <html> <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, user-scalable=no"/> <!--Meta Keywords and Description--> <meta name="keywords" content="Formateur php symfony BTS Angular VueJS"> <meta name="description" content=""> <!--Favicon--> <link rel="shortcut icon" href="/_assets/img/favicon.ico" title="Favicon"/> <link rel="stylesheet" href="/_assets/main.css" /> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Injection SQL - Supports de cours Nicolas C.</title> <link rel="stylesheet" href="/_markdown_plugin_assets/highlight.js/atom-one-light.css" /></head> <body> <div class="main"> <nav class="navigation"> <a href="/">Supports de cours Nicolas C.</a> </nav> <article> <header> <h1 class="article-title">Injection SQL</h1> <div class="article-info"> <div> <span >Créé le:<time datetime="1663835595574" >2022-09-22 10:33</time ></span > <span >Mis à jour:<time datetime="1664812659946" >2022-10-03 17:57</time ></span > </div> </div> </header> <div class="article-content markdown-body"><h1 id="injections-sql-sqli-principes-impacts-exploitations-et-bonnes-pratiques-de-sécurité">Injections SQL (SQLi) : principes, impacts, exploitations et bonnes pratiques de sécurité</h1> <p><img src="/_resources/92885ab2e5cc4469be7a01576dd43e8d.jpg" /></p> <nav class="table-of-contents"><ul><li><a href="#injections-sql-sqli-principes-impacts-exploitations-et-bonnes-pratiques-de-sécurité">Injections SQL (SQLi) : principes, impacts, exploitations et bonnes pratiques de sécurité</a><ul><li><a href="#en-quoi-consiste-une-injection-sql-sqli">En quoi consiste une injection SQL (SQLi) ?</a></li><li><a href="#cas-dutilisation-et-impacts-dune-injection-sql">Cas d’utilisation et impacts d’une injection SQL</a></li><li><a href="#liste-des-injections-sql-connues">Liste des injections SQL connues</a></li><li><a href="#comment-détourner-la-logique-dune-application-via-une-attaque-par-injection-sql">Comment détourner la logique d’une application via une attaque par injection SQL ?</a><ul><li><a href="#recherche-dun-paramètre-vulnérable-aux-sqli">Recherche d’un paramètre vulnérable aux SQLi</a></li><li><a href="#contournement-dauthentification-via-une-attaque-par-injection-sql">Contournement d’authentification via une attaque par injection SQL</a></li><li><a href="#attaque-par-injection-sql-avec-lopérateur-or">Attaque par injection SQL avec l’opérateur OR</a></li><li><a href="#contournement-de-lauthentification-avec-des-commentaires">Contournement de l’authentification avec des commentaires</a></li></ul></li><li><a href="#focus-sur-les-attaques-par-injection-sql-avec-union-union-based-sqli">Focus sur les attaques par injection SQL avec UNION (Union Based SQLi)</a><ul><li><a href="#identification-du-nombre-de-colonnes">Identification du nombre de colonnes</a></li><li><a href="#utilisation-de-order-by">Utilisation de ORDER BY</a></li><li><a href="#utilisation-de-union">Utilisation de UNION</a></li><li><a href="#localisation-de-linjection">Localisation de l’injection</a></li></ul></li><li><a href="#énumération-de-la-base-de-données-suite-à-un-sqli">Énumération de la base de données suite à un SQLi</a><ul><li><a href="#schema">Schema</a></li><li><a href="#tables">Tables</a></li><li><a href="#colonnes">Colonnes</a></li><li><a href="#données">Données</a></li></ul></li><li><a href="#lecture-de-fichiers-suite-à-une-sqli">Lecture de fichiers suite à une SQLi</a></li><li><a href="#écriture-dans-des-fichiers-suite-à-une-sqli">Écriture dans des fichiers suite à une SQLi</a></li></ul></li></ul></nav><hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <p>La plupart des applications web utilisent une ou plusieurs base(s) de données pour stocker et traiter les informations en temps réel.</p> <p>En effet, lorsqu’un utilisateur envoie des requêtes, l’application web interroge la base de données afin de construire la réponse. Cependant, lorsque les informations fournies par l’utilisateur sont utilisées pour forger la requête à la base de données, un attaquant peut altérer cette dernière en l’utilisant à d’autres fins que celles prévues par le développeur d’origine. Ainsi, cela permet à un attaquant d’interroger la base de données via une <strong>injection SQL, abrégé en SQLi</strong>.</p> <p>L’injection SQL fait référence aux attaques contre les bases de données relationnelles telles que MySQL, Oracle Database ou Microsoft SQL Server. En revanche, les injections contre les bases de données non relationnelles, telles que MongoDB ou CouchDB, sont des injections NoSQL.</p> <p>Principes, impacts, exploitations, nous vous présentons dans cet article une vue d’ensemble des injections SQL, ainsi que les bonnes pratiques sécurité et mesures à implémenter pour contrer les risques d’attaque.</p> <h2 id="en-quoi-consiste-une-injection-sql-sqli">En quoi consiste une injection SQL (SQLi) ?</h2> <p>Il existe de nombreux types de vulnérabilités par injection, comme les failles XSS, l’injection d’entête HTTP, l’injection de code ainsi que l’injection de commande. Cependant, la plus connue, l’une des plus redoutables et la favorite des attaquants est certainement l’injection SQL.</p> <p>Une injection SQL se produit lorsqu’un utilisateur malveillant communique une entrée qui modifie la requête SQL envoyée par l’application web à la base de données. Cela lui permet alors d’exécuter d’autres requêtes SQL non souhaitées directement sur la base de données.</p> <p>Pour ce faire, l’attaquant doit injecter du code en dehors des limites de l’entrée utilisateur attendue, afin qu’il ne soit pas exécuté comme une entrée standard. Dans le cas le plus simple, il suffit d’injecter un guillemet simple ou double pour échapper aux limites de la saisie utilisateur et ainsi insérer des données directement dans la requête SQL.</p> <p>En effet, si possibilités d’injection il y a, l’attaquant va chercher un moyen d’exécuter une requête SQL différente. Dans la plupart des cas, il va utiliser du code SQL pour créer une requête qui exécute à la fois la requête SQL prévue et la nouvelle requête SQL.</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="cas-dutilisation-et-impacts-dune-injection-sql">Cas d’utilisation et impacts d’une injection SQL</h2> <p>Une injection SQL peut avoir un impact énorme, surtout si les privilèges sur le serveur et sur la base de données sont trop permissifs.</p> <p>Tout d’abord, un attaquant peut récupérer des <strong>informations sensibles</strong>, comme les <strong>identifiants</strong> et <strong>mots de passe</strong> des utilisateurs ou les informations relatives aux <strong>cartes bancaires</strong>.<br /> En effet, les injections SQL sont à l’origine de nombreuses compromissions de mots de passe et de données de sites et d’applications web.</p> <p>Un autre cas d’utilisation de l’injection SQL consiste à <strong>détourner la logique prévue de l’application web</strong>. L’exemple le plus courant est le contournement d’une page d’authentification. Les attaquants peuvent également être en mesure de <strong>lire et d’écrire des fichiers directement sur le serveur</strong>, ce qui peut conduire à placer des backdoors (portes dérobées) sur le serveur, puis à prendre le contrôle de l’application.</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="liste-des-injections-sql-connues">Liste des injections SQL connues</h2> <p>Le dépôt GitHub suivant répertorie les injections SQL connues selon les différents serveurs</p> <p><a title="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection" href="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection">https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL Injection</a></p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="comment-détourner-la-logique-dune-application-via-une-attaque-par-injection-sql">Comment détourner la logique d’une application via une attaque par injection SQL ?</h2> <p>Avant de commencer à exécuter des requêtes SQL entières, nous allons d’abord étudier comment détourner la logique de la requête originale.</p> <h3 id="recherche-dun-paramètre-vulnérable-aux-sqli">Recherche d’un paramètre vulnérable aux SQLi</h3> <p>Avant de parvenir à nos fins, à savoir détourner la logique de l’application web et contourner l’authentification, nous devons dans un premier temps tester le formulaire de connexion, pour savoir s’il est vulnérable à l’injection SQL.</p> <p>Pour ce faire, nous pouvons ajouter l’une des payload ci-dessous après notre nom d’utilisateur et voir si cela provoque des erreurs ou modifie le comportement de la page :</p> <table> <thead> <tr> <th></th> <th></th> </tr> </thead> <tbody> <tr> <td>Payload</td> <td>URL Encoded</td> </tr> <tr> <td>‘</td> <td>%27</td> </tr> <tr> <td>«</td> <td>%22</td> </tr> <tr> <td>#</td> <td>%23</td> </tr> <tr> <td>;</td> <td>%3B</td> </tr> <tr> <td>)</td> <td>%29</td> </tr> </tbody> </table> <p>Lors de l’ajout d’un simple guillemet, une erreur SQL est affichée.</p> <img width="710" height="270" src="/_resources/d16ac8f0677640f0b9093d689b70cfb6.png" class="jop-noMdConv" /> <p>La requête SQL envoyée à la base de données est la suivante :</p> <img width="710" height="217" src="/_resources/ab0570d554ee4cd3a6cf8855a73c3118.png" class="jop-noMdConv" /> <p>Le guillemet que nous avons saisi a donné lieu à un <strong>nombre impair de guillemets</strong>, ce qui a provoqué une <strong>erreur de syntaxe</strong>.<br /> Une option serait de commenter et d’écrire le reste de la requête dans le cadre de notre injection pour forger une requête fonctionnelle.<br /> Une autre option consiste à utiliser un nombre pair de guillemets dans notre requête injectée, de sorte que la requête finale fonctionne toujours.</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="contournement-dauthentification-via-une-attaque-par-injection-sql">Contournement d’authentification via une attaque par injection SQL</h3> <p><img src="/_resources/00af5f361c774703b3d2f408814b04db.png" /></p> <p>Sur cette page d’authentification, nous pouvons nous connecter avec les informations d’identification de l’administrateur :</p> <div><pre class="hljs"><code>Identifiant : <span class="hljs-type">admin</span> Mot de passe : 7<span class="hljs-type">aPa55w0rd</span>! </code></pre></div> <p>La page affiche la requête SQL en cours d’exécution afin de mieux comprendre comment détourner la logique de la requête.</p> <p><img src="/_resources/efb78b49d5e54fa9893a5d921df31eb6.png" /></p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <p>La page prend en compte les informations d’identification, puis utilise l’opérateur <strong>AND</strong> pour sélectionner les enregistrements correspondants au nom d’utilisateur et au mot de passe renseignés.<br /> Si la base de données MySQL renvoie les enregistrements correspondants, les informations d’identification sont valides, et le code PHP évalue la condition de tentative de connexion comme vraie.</p> <p>Si la condition est « True », l’enregistrement de l’administrateur est renvoyé, et notre connexion est validée.</p> <p>Au contraire, lorsque de mauvaises informations de connexion sont renseignées, la connexion échoue et la base de données renvoie « False ».</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="attaque-par-injection-sql-avec-lopérateur-or">Attaque par injection SQL avec l’opérateur OR</h3> <p>Pour contourner l’authentification, il faudrait que la requête renvoie « True », quels que soient le nom d’utilisateur et le mot de passe saisis. Pour ce faire, nous pouvons abuser de l’opérateur OR dans notre injection SQL.</p> <p>La documentation MySQL indique que l’opérateur AND est évalué avant l’opérateur OR. Cela signifie que s’il y a au moins une condition « True » dans la requête avec un opérateur OR, la requête sera évaluée comme « True » puisque l’opérateur OR renvoie « True » si l’un de ses opérandes est vrai.</p> <p>Un exemple de condition qui renvoie toujours TRUE est 1=1. Toutefois, pour que la requête SQL continue de fonctionner et que le nombre de guillemets soit pair, au lieu d’utiliser (‘1’=’1’), nous supprimerons le dernier guillemet et utiliserons (‘1’=’1), de sorte que le guillemet unique restant de la requête originale sera à sa place.</p> <p><img src="/_resources/b795a5cb72064b90a280946bb1826615.png" /></p> <img width="710" height="185" src="/_resources/b8f80126a8d9443cbaada9433a50ddd1.png" class="jop-noMdConv" /> <img width="710" height="294" src="/_resources/98c0edb04fd74bb5963151265e67a0fb.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <p>L’opérateur AND sera évalué en premier, et il renverra « False ». Ensuite, l’opérateur OR sera évalué, et si l’une des déclarations est vraie, il renverra « True ». Puisque 1=1 renvoie toujours « True », cette requête renverra vrai et nous donnera l’accès.</p> <p><img src="/_resources/b98934bc14ba4f72b62046439a6ddd62.png" /></p> <p>Note : La payload que nous avons utilisé ci-dessus est l’<a title="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection" href="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection">une des nombreuses payloads de contournement d’authentification</a> que nous pouvons utiliser pour contourner la logique d’authentification.</p> <p>Si le nom d’utilisateur n’est pas valide, la connexion va échouer parce qu’il n’existe pas dans la table et a donné lieu à une fausse requête globale.</p> <p><img src="/_resources/52c11cea1449472f87dc9f031ec213da.png" /></p> <img width="710" height="293" src="/_resources/821b97eb7f35441398a0dfda1ceda89b.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="contournement-de-lauthentification-avec-des-commentaires">Contournement de l’authentification avec des commentaires</h3> <p>Comme tout autre langage, SQL permet également l’utilisation de commentaires.<br /> Les commentaires sont utilisés pour documenter les requêtes ou ignorer une certaine partie de la requête.<br /> Nous pouvons utiliser deux types de commentaires avec MySQL : <strong>—</strong> et <strong>#</strong>.</p> <img width="710" height="339" src="/_resources/7baea870844e4c93a80cbb6ccbf56f99.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <p>Comme nous pouvons le voir, le reste de la requête est maintenant ignoré et le mot de passe n’est plus vérifié.<br /> De cette façon, nous pouvons nous assurer que la requête ne présente aucun problème de syntaxe.</p> <img width="710" height="546" src="/_resources/482a737518464b829e0c0b8f77225227.png" class="jop-noMdConv" /> <img width="710" height="253" src="/_resources/bc182543969f4e209cbc328c2f07d22d.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="focus-sur-les-attaques-par-injection-sql-avec-union-union-based-sqli">Focus sur les attaques par injection SQL avec UNION (Union Based SQLi)</h2> <p>Un autre type d’injection SQL consiste à <strong>injecter des requêtes SQL entières</strong> exécutées en même temps que la requête originale.</p> <p>La clause <strong>UNION</strong> est utilisée pour combiner les résultats de plusieurs instructions SELECT. Cela signifie que grâce à une injection UNION, nous serons en mesure de sélectionner et d’extraire des données de l’ensemble de la base de données.</p> <img width="710" height="390" src="/_resources/d70009c2ff034bbdb7e7f169abaf2e8e.png" class="jop-noMdConv" /> <p>UNION a combiné la sortie des deux instructions SELECT en une seule, ainsi les entrées des tables ont été combinées en une seule sortie.</p> <p>Une instruction UNION ne peut fonctionner que sur des instructions SELECT comportant un nombre égal de colonnes. L’UNION de deux requêtes qui ont des résultats avec un nombre de colonnes différentes renverra une erreur.</p> <p>S’il y a plus de colonnes dans la table de la requête originale, il faut ajouter d’autres chiffres afin de créer les colonnes restantes requises.</p> <img width="710" height="360" src="/_resources/33ce1349f0ad4c3b9cf8ba7dd1ce5eeb.png" class="jop-noMdConv" /> <p>Comme nous pouvons le voir, le résultat souhaité de la requête se trouve dans la première colonne de la deuxième ligne, tandis que les chiffres remplissent les autres colonnes.</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="identification-du-nombre-de-colonnes">Identification du nombre de colonnes</h3> <p>Afin d’exploiter les requêtes basées sur la clause UNION, il faut trouver le nombre de colonnes sélectionnées par le serveur. Il existe deux méthodes pour détecter ce nombre :</p> <ul> <li>En utilisant ORDER BY</li> <li>En utilisant UNION</li> </ul> <h3 id="utilisation-de-order-by">Utilisation de ORDER BY</h3> <p>La première façon de détecter le nombre de colonnes est la clause ORDER BY. La requête injectée va trier les résultats par le nombre de colonne que nous avons spécifiée jusqu’à ce que nous obtenions une erreur indiquant que la colonne spécifiée n’existe pas. La dernière colonne par laquelle nous avons réussi à trier nous donne le nombre total de colonnes.</p> <p><img src="/_resources/c8e01414035548269f20dabbf8c0754b.png" /></p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="utilisation-de-union">Utilisation de UNION</h3> <p>L’autre méthode consiste à utiliser la clause UNION avec un nombre différent de colonnes jusqu’à ce que nous obtenions les résultats avec succès. Contrairement à la méthode précédente, celle-ci donne toujours une erreur jusqu’à ce que nous obtenions le bon nombre de colonnes.</p> <img width="710" height="327" src="/_resources/40288b15b25b4578a724415dd99a3ffe.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="localisation-de-linjection">Localisation de l’injection</h3> <p>Alors qu’une requête peut renvoyer plusieurs colonnes, l’application web peut n’en afficher que certaines. Ainsi, si nous injectons notre requête dans une colonne qui n’est pas affichée sur la page, nous n’obtiendrons pas son résultat. C’est pourquoi nous devons déterminer quelles colonnes sont présentes sur la page, afin de déterminer où placer notre injection.</p> <img width="710" height="358" src="/_resources/7b3e83da5c9e432d9498d374c2546470.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="énumération-de-la-base-de-données-suite-à-un-sqli">Énumération de la base de données suite à un SQLi</h2> <p>Avant d’énumérer la base de données, nous devons identifier le type de Système de Gestion de Base de Données (SGBD) afin de savoir quelles requêtes utiliser.</p> <p>Si le serveur web que nous voyons dans les réponses HTTP est Apache ou Nginx, il est probable que le serveur web soit sous Linux, et donc que le SGBD soit MySQL. Il en va de même pour le SGBD Microsoft si le serveur web est IIS, il s’agit donc probablement de MSSQL. Il existe donc différentes requêtes que nous pouvons tester pour déterminer le type de base de données.</p> <p>Maintenant, pour extraire des données des tables à l’aide de UNION SELECT, nous devons former correctement nos requêtes SELECT. Pour ce faire, nous devons disposer de :</p> <ul> <li>La liste des bases de données</li> <li>La liste des tables de chaque base de données</li> <li>La liste des colonnes de chaque table</li> </ul> <p>Avec les informations ci-dessus, nous pourrons formuler notre instruction SELECT pour extraire toutes les données.</p> <p>La base de données INFORMATION_SCHEMA contient des métadonnées sur les bases de données et les tables présentes sur le serveur. Cette base de données joue un rôle crucial dans l’exploitation des vulnérabilités par injection SQL.</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="schema">Schema</h3> <p>Pour trouver quelles bases de données sont disponibles sur le SGBD, nous pouvons utiliser INFORMATION_SCHEMA.SCHEMATA, qui contient des informations sur toutes les bases de données du serveur.</p> <img width="710" height="379" src="/_resources/6da5c7e68b9c4df2863324b07bfd1b3e.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="tables">Tables</h3> <p>Pour trouver toutes les tables d’une base de données, nous pouvons utiliser INFORMATION_SCHEMA.TABLES. Cette opération peut être effectuée de la même manière que celle qui a permis de trouver les noms des bases de données.</p> <img width="710" height="254" src="/_resources/840a5ac5181e46dcac2a974e24dabeec.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="colonnes">Colonnes</h3> <p>Pour trouver les noms des colonnes de la table, nous pouvons utiliser la table COLUMNS de la base de données INFORMATION_SCHEMA. Elle contient des informations sur toutes les colonnes présentes dans toutes les bases de données.</p> <img width="710" height="271" src="/_resources/b84e21bf5d3742a2aa7bd8f3cccc71f3.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h3 id="données">Données</h3> <p>Maintenant que toutes les informations sont réunies, nous pouvons former notre requête UNION pour extraire les données des de la base de données.</p> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="lecture-de-fichiers-suite-à-une-sqli">Lecture de fichiers suite à une SQLi</h2> <p>Une injection SQL peut également être utilisée pour effectuer de nombreuses autres opérations, telles que la lecture et l’écriture de fichiers sur le serveur et même l’exécution de code à distance sur le serveur.</p> <p>La lecture de données est beaucoup plus courante que l’écriture de données, qui est strictement réservée aux utilisateurs privilégiés dans les SGBD modernes, car elle peut conduire à l’exploitation du système. Dans MySQL, l’utilisateur de la base de données doit disposer du privilège FILE pour charger le contenu d’un fichier dans une table.</p> <p>Plusieurs requêtes SQL permettent de déterminer quel utilisateur exécute les requêtes.</p> <p>On peut désormais lister les privilèges des utilisateurs. Nous constatons que le privilège FILE est listé pour notre utilisateur, ce qui nous permet de lire des fichiers et même potentiellement d’en écrire.</p> <img width="710" height="666" src="/_resources/2a0df6c386864cd8af79032ad777e92b.png" class="jop-noMdConv" /> <p>Grâce à ce privilège FILE, un utilisateur est capable de lire les fichiers du serveur.</p> <img width="710" height="244" src="/_resources/5d4df4e3e7d74b54a7e38ac326fff54e.png" class="jop-noMdConv" /> <hr /> <div style="page-break-after:always" class="jop-noMdConv"></div> <h2 id="écriture-dans-des-fichiers-suite-à-une-sqli">Écriture dans des fichiers suite à une SQLi</h2> <p>L’écriture de fichiers sur le serveur peut être utilisé pour écrire un webshell sur le serveur distant, ce qui permettra d’exécuter du code et de prendre le contrôle du serveur.</p> <p>De la même manière que pour la lecture de fichiers, si l’utilisateur possède les privilèges suivants, il sera capable d’écrire sur le serveur :</p> <ul> <li>Privilège FILE activé</li> <li>Variable globale MySQL secure_file_priv n’étant pas activée.</li> <li>Un accès en écriture à l’emplacement où il veut écrire sur le serveur.</li> </ul> <p>L’instruction SELECT INTO OUTFILE peut être utilisée pour écrire des données dans des fichiers à partir de requêtes de sélection. Elle est généralement utilisée pour exporter des données depuis des tables.</p> <img width="710" height="381" src="/_resources/c91eb20b22604e7c89d635edf5ac29d5.png" class="jop-noMdConv" /> <p>Un attaquant peut ainsi uploader un webshell et ainsi accéder au serveur.</p> <img width="710" height="388" src="/_resources/3e2c2736a86547fa925d0b4cf56bf00d.png" class="jop-noMdConv" /> <img width="710" height="174" src="/_resources/04114d9c4edb49238449966dc79492aa.png" class="jop-noMdConv" /> </div> </article> </div> <div class="go-top"> <p class="go-top-text">Retour Haut de page</p> </div> <!-- JQuery --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script> <!-- Local --> <script src="/_assets/js/script.js" type="text/javascript"></script> </body> </html>
@page @inject IViewLocalizer Localizer @model WoWning.Areas.Landingpage.Pages.Specific.RecipesModel @{ ViewData["Title"] = Localizer["Set Recipes"]; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>@Localizer["Set Recipes"]</h1> <hr /> <form method="get"> <div class="form-group col-md-4"> <label class="control-label">@Localizer["Character"]</label> <select onchange="this.form.submit()" name="character" asp-for="Character" class="form-control" asp-items="Model.Options"> <option disabled selected>@Localizer["Select an option"]</option> </select> </div> @if (!string.IsNullOrEmpty(Model.Character)) { <div class="form-group col-md-4"> <label class="control-label">@Localizer["Profession"]</label> <select onchange="this.form.submit()" name="profession" asp-for="Profession" class="form-control" asp-items="Model.OptionsProfessions"> <option disabled selected>@Localizer["Select an option"]</option> </select> </div> @if (!string.IsNullOrEmpty(Model.Profession)) { <hr /> <div class="form-actions no-color"> <p> @Localizer["Find by name:"] <input type="text" name="SearchString" value="@Model.CurrentFilter" /> <input type="submit" value="@Localizer["Search"]" class="btn btn-default" /> | <a asp-page="./Recipes" asp-route-character="@Model.Character" asp-route-profession="@Model.Profession">@Localizer["Back to full List"]</a> </p> </div> } } </form> @if (!string.IsNullOrEmpty(Model.Character) && !string.IsNullOrEmpty(Model.Profession)) { <form method="post"> <div class="form-group"> <input type="submit" value="@Localizer["Save"]" class="btn btn-primary" /> </div> <table class="table"> <thead> <tr> <th></th> <th>@Localizer["Expected Tip"]</th> <th> <a asp-route-character="@Model.Character" asp-route-profession="@Model.Profession" asp-route-sortOrder="@Model.NameSort" asp-route-currentFilter="@Model.CurrentFilter"> @Html.DisplayNameFor(model => model.Recipes[0].Name) </a> </th> <th> <a asp-route-character="@Model.Character" asp-route-profession="@Model.Profession" asp-route-sortOrder="@Model.LevelSort" asp-route-currentFilter="@Model.CurrentFilter"> @Html.DisplayNameFor(model => model.Recipes[0].Level) </a> </th> </tr> </thead> <tbody> @for (var i = 0; i < Model.Recipes.Count(); i++) { var m = "https://" + Model.WoWHeadDomain + ".wowhead.com/spell=" + Model.Recipes[i].Id; <tr> <td> <input type="hidden" asp-for="Recipes[i].Id" /> <input asp-for="Recipes[i].IsSelected" /> </td> <td> <input asp-for="Recipes[i].Gold" min="0" class="col-md-3" style="max-width: 65px;padding-left:10px;padding-right: 10px;text-align: right;"/> <img src="~/img/gold.png" /> <input asp-for="Recipes[i].Copper" max="99" min="0" class="col-md-3" style="max-width: 65px;padding-left:10px;padding-right: 10px;text-align: right;"/> <img src="~/img/silver.png" /> <input asp-for="Recipes[i].Silver" max="99" min="0" class="col-md-3" style="max-width: 65px;padding-left:10px;padding-right: 10px;text-align: right;"/> <img src="~/img/copper.png" /> </td> <td> <a href="@m" target="_blank" data-wh-icon-size="small" data-wowhead="[email protected][i].Id&amp;[email protected]">@Model.Recipes[i].TransName</a> </td> <td> @Html.DisplayFor(modelItem => Model.Recipes[i].Level) </td> </tr> } </tbody> </table> </form> }
// ignore_for_file: avoid_print import 'package:dio/dio.dart'; import 'package:news_app/models/article_Model.dart'; class NewsService { final Dio dio ; NewsService(this.dio); Future<List<ArticleModel>> getNews() async { try { var response = await dio.get( 'https://newsapi.org/v2/top-headlines?country=us&apiKey=31eb1788051f4893ae7fa067e55c1763&category=general'); Map<String, dynamic> jsonData = response.data; List<dynamic> articles = jsonData['articles']; //we need to convert list of maps to list of objects to make it easy to deal with data //the next steps is doing that List<ArticleModel> articlesList = []; for (var article in articles) { ArticleModel articleModel = ArticleModel( image: article['urlToImage'], title: article['title'], subtitle: article['description'], ); articlesList.add(articleModel); } return articlesList; } catch (e) { return []; } } }
<template> <section class="text-center"> <h2 class="text-red-600 text-4xl my-8 font-bold italic tracking-wider text-shadow z-10 uppercase" data-aos="fade-up" > {{ $t("message.date.mainTitle") }} </h2> </section> <section class="w-full dark:bg-dark-mode bg-white flex justify-center items-center flex-col bg-cover bg-center bg-no-repeat relative py-5" lazy-background="/static/home/fond2.svg" > <!-- BAR --> <div class="bg-red-600 w-1 h-full rounded-md absolute" data-aos="zoom-in" ></div> <!-- CONTENT --> <div v-for="(item, index) of dateList" :key="item" data-aos="zoom-in" class="w-full z-10 dark:text-white flex" > <div class="w-1/2 flex items-center px-8 my-10" :class="index % 2 == 0 ? 'justify-end' : 'ml-auto'" > <Countdown :link="item.link" :date="item.date" :hour="item.hour" :title="item.title" ></Countdown> <div class="rounded-full bg-red-800 border border-red-600 w-4 h-4 ml-10 absolute right-1/2 transform translate-x-1/2" ></div> </div> </div> </section> </template> <script> import Countdown from "../Countdown/Countdown.vue"; import dateList from "./date"; export default { name: "Date", components: { Countdown }, data() { return { dateList: dateList.list.length > 0 ? dateList.list.sort((a, b) => (a.date + a.hour).localeCompare(b.date + b.hour) ) : dateList.list, }; }, mounted() { this.dateList = this.dateList.filter((e) => { const d = new Date(); d.setDate(d.getDate() + dateList.stopDisplayingAfterDays); const c = new Date(e.date + " " + e.hour); return c > d; }); }, }; </script>
<!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>squares</title> <style type="text/css"> div{ width: 100px; height: 100px; background: #173459; color: #f8f9f9; border: 5px solid #903C56; transition-duration: 2s; } #translate:hover{ transform: translate(30px,40px); } #rotate:hover{ transform: rotate(-90deg); } #scale:hover{ transform: scale(.5); } #skew:hover{ transform:skew(30deg, 30deg); } </style> </head> <body> <p>Tap elements to trigger the effects.</p> <div id="translate">translate me!</div> <br> <div id="rotate">Rotate me!</div> <br> <div id="scale">Scale me!</div> <br> <div id="skew">Skew me!</div> </body> </html>
import 'package:flutter/material.dart'; import 'package:camera/camera.dart'; import 'package:office_app/employee_list.dart'; import 'package:path/path.dart' show join; import 'package:path_provider/path_provider.dart'; void main() { runApp(const EmployeeLoginApp()); } class EmployeeLoginApp extends StatelessWidget { const EmployeeLoginApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Employee Login App', theme: ThemeData( primarySwatch: Colors.blueGrey, ), home: const LoginScreen(), ); } } class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; bool isLoading = true; TextEditingController _nameController = TextEditingController(); // Controller for the name TextField @override void initState() { super.initState(); _initializeCamera(); } Future<void> _initializeCamera() async { final cameras = await availableCameras(); final firstCamera = cameras.first; final frontCamera = cameras.firstWhere( (camera) => camera.lensDirection == CameraLensDirection.front); _controller = CameraController(frontCamera, ResolutionPreset.medium); _initializeControllerFuture = _controller.initialize(); isLoading = false; setState(() {}); } void _takePhoto() async { // try { // await _initializeControllerFuture; // Wait for camera initialization // final path = join( // (await getTemporaryDirectory()).path, // '${DateTime.now()}.png', // ); // await _controller.takePicture(); // // Process the captured photo (e.g., save to database, display on UI) // print('Photo saved at $path'); // } catch (e) { // print('Error taking photo: $e'); // } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( drawer: _drawer(context), appBar: AppBar( title: const Text('Employee Login'), ), body: Center( child: isLoading ? CircularProgressIndicator() : SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Container( // width: 300, height: 500, decoration: BoxDecoration( border: Border.all(color: Colors.grey), ), child: FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return CameraPreview(_controller); } else { return const Center( child: CircularProgressIndicator(), ); } }, ), ), const SizedBox(height: 20), Padding( padding: const EdgeInsets.all(20.0), child: TextField( controller: _nameController, decoration: InputDecoration( labelText: 'Enter your name', prefixIcon: Icon(Icons.person), ), ), ), const SizedBox(height: 20), ElevatedButton.icon( onPressed: _takePhoto, icon: Icon(Icons.camera), label: const Text('Take Photo'), ), ], ), ), ), ); } } Drawer _drawer(BuildContext context) { return Drawer( child: Container( color: Colors.blueGrey[900], // Background color of the drawer child: ListView( children: [ DrawerHeader( decoration: BoxDecoration( color: Colors.blueGrey[800], // Header background color ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.end, children: [ CircleAvatar( radius: 40, backgroundColor: Colors.white, // Replace with your logo or user icon child: Icon( Icons.person, color: Colors.blueGrey[900], size: 50, ), ), SizedBox(height: 10), Text( 'Admin', style: TextStyle( color: Colors.white, fontSize: 20, ), ), ], ), ), ListTile( leading: Icon(Icons.dashboard, color: Colors.white), title: Text('Admin Panel', style: TextStyle(color: Colors.white)), onTap: () { Navigator.pop(context); // Close the drawer Navigator.push( context, MaterialPageRoute(builder: (context) => EmployeeListScreen()), ); }, ), // Add more list tiles for additional drawer items ], ), ), ); }
import React from "react"; import { useEffect, useState } from "react"; import { useParams } from 'react-router-dom' import ItemList from "./ItemList"; import { collection, getDocs, getFirestore, query, where} from 'firebase/firestore'; function ItemListContainer({greeting}) { const [inventario, setInventario] = useState([]) const { id } = useParams() useEffect(() => { const db = getFirestore(); // obtenemos la base de datos const itemsCollection = collection(db, 'items'); // obtenemos la colección if (id) { const q = query(itemsCollection, where('categoria', '==', id)); // obtenemos el query getDocs(q).then(snapshot =>{ // obtenemos los documentos setInventario(snapshot.docs.map((doc) => ({...doc.data(), id: doc.id}))); // seteamos el estado }) } else { getDocs(itemsCollection).then(snapshot =>{ // obtenemos los documentos setInventario(snapshot.docs.map((doc) => ({...doc.data(), id: doc.id}))); // seteamos el estado }) } }, [id]); return ( <> <div className="divItem"> <h2 className="div-h2">Bienvenidos a Developers Books<span className="spaH1">{greeting}</span></h2> <ItemList inventario={inventario} /> <div className='fs-1 fw-bold'>{<svg xmlns="http://www.w3.org/2000/svg" width="45" height="45" fill="currentColor" className="text-white bi bi-arrow-clockwise" viewBox="0 0 16 16"> <path d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z" /> <path d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z" /></svg>} </div> </div> </> ); } export default ItemListContainer; // import React, { useEffect, useState } from 'react'; // import { useParams } from 'react-router-dom'; // import ItemDetailContainer from './ItemDetailContainer'; // import ItemList from './ItemList'; // import './itemlist.css'; // export default function ItemListContainer({ greeting }) { // const {id} = useParams() // const [svg, setSvg] = useState(true) // const [inventario, setInventario] = useState([]) // useEffect(() => { // setTimeout(() => { // fetch("../data.json") // .then(res => res.json()) // .then(res => {(!id) ? setInventario (res) : setInventario (res.filter(item => item.categoria === id))}) // .then(setSvg(false)) // .catch(error => console.log("Error:", error)) // }, 2000); // }, [id]) // return ( // <> // <div className="divItem"> // <h2 className="div-h2">Bienvenidos a Developers Books<span className="spaH1">{greeting}</span></h2> // <ItemList inventario={inventario} /> // <div className='fs-1 fw-bold'>{svg && <svg xmlns="http://www.w3.org/2000/svg" width="45" height="45" fill="currentColor" className="text-white bi bi-arrow-clockwise" viewBox="0 0 16 16"> // <path d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z" /> // <path d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z" /> // </svg>}</div> // </div> // <ItemDetailContainer/> // </> // ) // }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div th:switch="${idCards}"> <h2 th:case="null">No idCards found!</h2> <div th:case="*"> <h2>Id Cards</h2> <table> <thead> <tr> <th>Id</th> <th>Number</th> <th>Date expire</th> </tr> </thead> <tbody> <tr th:each="idCard : ${idCards}"> <td th:text="${idCard.getId()}"></td> <td th:text="${idCard.getNumber()}"></td> <td th:text="${#temporals.format(idCard.getDateExpire(), 'dd.MM.yyyy HH:mm')}"></td> <td><a th:href="@{id_cards/{id}/edit(id=${idCard.getId()})}">Edit</a></td> <td><form th:method="DELETE" th:action="@{id_cards/{id}/delete(id=${idCard.getId()})}"> <input type="submit" value="delete"/> </form> </td> </tr> </tbody> </table> </div> <p><a th:href="@{/id_cards/new}">Create new id card</a></p> <p><a th:href="@{/}">Back</a></p> </div> </body> </html>
import { randomBoolean, randomMix, isSumUnitsDigitZero, isDiffUnitsDigitZero, genRandomQuestions, shuffle, calculate, randomMixExclude1, randomBetween } from './commonUtils.js'; /** * 表以内3个数连乘 * @example 1 ✖️ 8 ✖️ 2 = */ function genTripleMulti(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 54)) { const num1 = randomMix(9); const num2 = randomMix(9 - num1); const num3 = randomMix(9); if (num1 * num2 > 9 || num2 === 1 || num1 === 1) { continue; } const question = `${num1} ✖️ ${num2} ✖️ ${num3} = `; questions.add(question); } return Array.from(questions); } // console.log(genTripleMulti(60)) /** * 表以内3个数连除 * @example 48 ➗️ 6 ➗️ 4 = */ function genTripleDiv(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 50)) { const num1 = randomMix(9); const num2 = randomMix(9); const num3 = randomMix(9); if (num1 === 1 || num2 === 1 || num3 === 1 || num1 * num2 * num3 > 81 || (num1 * num2 * num3) / num2 >= 10) { continue; } const question = `${num1 * num2 * num3} ➗️ ${num2} ➗️ ${num3} = `; questions.add(question); } return Array.from(questions); } // console.log(genTripleDiv(10)) /** * 表以内3个数连除(带括号) * @example ['12 ➗️ (30 ➗️ 5) = ', '18 ➗️ (36 ➗️ 2) = ', ...] */ function genTripleDivWithBracket(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 50)) { const num1 = randomMix(9); const num2 = randomMix(9); const num3 = randomMix(9); const num4 = randomMix(9); if (num2 === 1 || num1 === 1 || num3 === 1 || num4 === 1 || (num1 * num2) % (num3) !== 0) { continue; } const question = `${num1 * num2} ➗️ (${num3 * num4} ➗️ ${num4}) = `; questions.add(question); } return Array.from(questions); } // console.log(genTripleDivWithBracket(10)) /** * 表以内先乘后除 * @example ['1 ✖️ 8 ➗️ 2 = ', '3 ✖️ 2 ➗️ 1 = ', ...] */ function genMultiDiv(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 50)) { const num1 = randomMix(9); const num2 = randomMix(9 - num1); const num3 = randomMix(9); if (num2 === 1 || num1 === 1 || num3 === 1 || num3 === num2 || num3 === num1 || num1 * num2 / num3 > 10 || (num1 * num2) % num3 !== 0) { continue; } const question = `${num1} ✖️ ${num2} ➗️ ${num3} = `; questions.add(question); } return Array.from(questions); } /** * 表以内先乘后除(带括号) * @example ['1 ✖️ (8 ➗️ 2) = ', '3 ✖️ (2 ➗️ 1) = ', ...] */ function genMultiDivWithBracket(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 50)) { const num1 = randomMix(9); const num2 = randomMix(9); const num3 = randomMix(9); if (num2 === 1 || num1 === 1 || num3 === 1) { continue; } const question = `${num1} ✖️ (${num2 * num3} ➗️ ${num3}) = `; questions.add(question); } return Array.from(questions); } // console.log(genMultiDivWithBracket(10)) /** * 表以内先除后乘 * @example [' 8 ➗️ 2 ✖️ 1 = ', '2 ➗️ 1 ✖️ 3 = ', ...] */ function genDivMulti(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 50)) { const num1 = randomMix(9); const num2 = randomMix(9); const num3 = randomMix(9); if (num2 === 1 || num1 === 1 || num3 === 1) { continue; } const question = `${num1 * num2} ➗️ ${num1} ✖️ ${num3} = `; questions.add(question); } return Array.from(questions); } // console.log(genDivMulti(10)) /** * 表以内先除后乘(带括号) * @example [' 8 ➗️ (2 ✖️ 1) = ', '6 ➗️ (1 ✖️ 3) = ', ...] */ function genDivMultiWithBracket(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 50)) { const num1 = randomMix(9); const num2 = randomMix(9); const num3 = randomMix(9); const num4 = randomMix(9); if (num2 === 1 || num1 === 1 || num3 === 1 || (num1 * num2) % (num3 * num4) !== 0 || num3 * num4 > 9) { continue; } const question = `${num1 * num2} ➗️ (${num3} ✖️ ${num4}) = `; questions.add(question); } return Array.from(questions); } // console.log(genDivMultiWithBracket(10)) /** * 表内乘法与加减混合 * @example * 8 ✖️ 5 + 9 = * 8 ✖️ 5 - 9 = * 41 + 8 ✖️ 5 = * 41 - 8 ✖️ 5 = */ function genMultiAddSub(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 100)) { const num1 = randomMixExclude1(9); const num2 = randomMixExclude1(9); const num3 = randomMix(99); let question = ''; if (randomBoolean()) { if (num1 * num2 + num3 > 100) { continue; } if (randomBoolean()) { question = `${num1} ✖️ ${num2} + ${num3} = `; } else { question = `${num3} + ${num1} ✖️ ${num2} = `; } } else { if (randomBoolean()) { if (num1 * num2 - num3 < 0) { continue; } question = `${num1} ✖️ ${num2} - ${num3} = `; } else { if (num3 - num1 * num2 < 0) { continue; } question = `${num3} - ${num1} ✖️ ${num2} = `; } } questions.add(question); } return Array.from(questions); } // console.log(genMultiAddSub(10)) /** * 表内乘法与加减混合(带括号) * @example * 4 * (3 + 3) = * (3 + 3) * 4 = * 4 * (6 - 3) = * (6 - 3) * 4 = */ function genMultiAddSubWithBracket(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 100)) { const num1 = randomMixExclude1(9); let question = ''; if (randomBoolean()) { const num2 = randomMix(9); const num3 = randomMix(9 - num2); if (randomBoolean()) { question = `${num1} ✖️ (${num2} + ${num3}) = `; } else { question = `(${num2} + ${num3}) ✖️ ${num1} = `; } } else { const num2 = randomMix(90); const num3 = randomBetween(num2, num2 + 9); if (randomBoolean()) { question = `${num1} ✖️ (${num3} - ${num2}) = `; } else { question = `(${num3} - ${num2}) ✖️ ${num1} = `; } } questions.add(question); } return Array.from(questions); } // console.log(genMultiAddSubWithBracket(10)) /** * 表内除法与加减混合 * @example * 40 ➗ 5 + 9 = * 41 + 40 ➗ 5 = * 40 ➗ 5 - 9 = * 41 - 40 ➗ 5 = */ function genDevAddSub(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 100)) { const num1 = randomMixExclude1(9); const num2 = randomMixExclude1(9); const num3 = randomMix(99); let question = ''; if (randomBoolean()) { if (num1 + num3 > 100) { continue; } if (randomBoolean()) { question = `${num1 * num2} ➗ ${num2} + ${num3} = `; } else { question = `${num3} + ${num1 * num2} ➗ ${num2} = `; } } else { if (randomBoolean()) { if (num1 - num3 < 0) { continue; } question = `${num1 * num2} ➗ ${num2} - ${num3} = `; } else { if (num3 - num1 < 0) { continue; } question = `${num3} - ${num1 * num2} ➗ ${num2} = `; } } questions.add(question); } return Array.from(questions); } // console.log(genDevAddSub(10)) /** * 表内除法与加减混合 * @example * 81 ÷ (6 + 3) = * 81 ÷ (9 - 3) = * (40 + 41) ÷ 9 = * (82 - 1) ÷ 9 = */ function genDevAddSubWithBracket(questionCount) { const questions = new Set(); while (questions.size < Math.min(questionCount, 100)) { const num1 = randomMixExclude1(9); const num2 = randomMixExclude1(9); let question = ''; if (randomBoolean()) { const num3 = randomMix(num2); if (randomBoolean()) { question = `${num1 * num2} ➗ (${num3} + ${num2 - num3}) = `; } else { question = `${num1 * num2} ➗ (${num2 + num3} -️ ${num3}) = `; } } else { const num3 = randomMix(num1 * num2); if (randomBoolean()) { question = `(${num3} + ${num1 * num2 - num3}) ➗ ${num1} = `; } else { question = `(${num3 + num1 * num2} -️ ${num3}) ➗ ${num1} = `; } } questions.add(question); } return Array.from(questions); } // console.log(genDevAddSubWithBracket(10)) // 将所有的问题生成函数放入一个数组 const questionGenerators = [ genTripleMulti, genTripleDiv, genTripleDivWithBracket, genMultiDiv, genMultiDivWithBracket, genDivMulti, genDivMultiWithBracket, genMultiAddSub, genMultiAddSubWithBracket, genDevAddSub, genDevAddSubWithBracket ]; /** * @category 脱式计算 * @name 加减乘除混合 * @example 24 ➗️ 4 ➗️ 2 = * * @param {number} questionCount - 需要生成的题目数量 * @return {string[]} 返回一个包含生成的题目的数组 */ export function genMixQuestions(questionCount) { const questions = []; for (let i = 0; i < questionCount; i++) { // 随机选择一个问题生成函数 const randomIndex = randomMix(questionGenerators.length - 1); const questionGenerator = questionGenerators[randomIndex]; // 生成问题并添加到问题数组中 const question = questionGenerator(1); // 假设每个问题生成函数都接受一个参数,表示要生成的问题数量 questions.push(...question); } return questions; } // console.log(generateRandomQuestions(10))
package com.integration.project.adapter; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.integration.project.R; import com.integration.project.entity.UserContractIncomeEntity; import java.lang.ref.WeakReference; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import static androidx.recyclerview.widget.RecyclerView.Adapter; /** * Created by Wongerfeng on 2020/8/6. */ public class UnsignContractAdapter extends Adapter<UnsignContractAdapter.ItemHolder> { private List<UserContractIncomeEntity.ContractIncome> mList; private Activity mActivity; public UnsignContractAdapter(Activity activity, List<UserContractIncomeEntity.ContractIncome> branchBankList) { WeakReference<Activity> reference = new WeakReference<>(activity); Activity a = reference.get(); if (a != null) { mActivity = a; } mList = branchBankList; } @NonNull @Override public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { ItemHolder holder; View view= LayoutInflater.from(mActivity).inflate(R.layout.item_constract_name, parent, false); holder = new ItemHolder(view); return holder; } @Override public void onBindViewHolder(@NonNull ItemHolder itemHolder, final int position) { if (mList.get(position) != null) { UserContractIncomeEntity.ContractIncome contractIncome = mList.get(position); itemHolder.contractName.setText(String.format("%s%s%s", "·《", contractIncome.getFileName(), "》")); } } @Override public int getItemCount() { if (mList != null) { return Math.max(mList.size(), 0); } else { return 0; } } static class ItemHolder extends RecyclerView.ViewHolder { TextView contractName; public ItemHolder(@NonNull View itemView) { super(itemView); contractName = itemView.findViewById(R.id.tvContractName); } } }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">My Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Menu </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" aria-disabled="true">Disabled</a> </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> <button type="button" class="btn btn-primary" style="background-color: blueviolet;">Sum</button> <div class="alert alert-primary" role="alert"> this my website <a href="https://www.sistec.ac.in/" class="alert-link">sistec link</a>. Give it a click if you like. </div> <!-- ------------------------------------------------------------------------------ --> <h1>My New Laptop <span class="badge text-bg-secondary bg-success">New</span></h1> <!-- --------------------------------------------------------------------------------------- --> <div id="carouselExampleCaptions" class="carousel slide"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="/day9/audi.jpg" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>First slide label</h5> <p>Some representative placeholder content for the first slide.</p> </div> </div> <div class="carousel-item"> <img src="/day9/audi2.jpg" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>Second slide label</h5> <p>Some representative placeholder content for the second slide.</p> </div> </div> <div class="carousel-item"> <img src="/day9/audi3.jpg" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5>Third slide label</h5> <p>Some representative placeholder content for the third slide.</p> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <!------------------------------------------------------------------------------------------------------------> <div class="container text-center"> <div class="row"> <div class="col"> <div class="card" style="width: 18rem;"> <img src="/day9/iphone.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Iphone14</h5> <p class="card-text">80000</p> <a href="#" class="btn btn-primary">Buy Now</a> </div> </div> </div> <div class="col"> <div class="card" style="width: 18rem;"> <img src="/day9/iphone12.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Iphone12</h5> <p class="card-text">72000</p> <a href="#" class="btn btn-primary">Buy Now</a> </div> </div> </div> <div class="col"> <div class="card" style="width: 18rem;"> <img src="/day9/iphone15.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Iphone15</h5> <p class="card-text">1500000</p> <a href="#" class="btn btn-primary">Buy Now</a> </div> </div> </div> </div> </div> <!-- <div class="card" style="width: 18rem;"> <img src="/day9/iphone.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">Iphone</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Buy Now</a> </div> </div> --> <!-- ------------------------------------------------------------------------------------------------ --> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item active" aria-current="page">Home</li> </ol> </nav> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item active" aria-current="page">Library</li> </ol> </nav> <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item"><a href="#">Library</a></li> <li class="breadcrumb-item active" aria-current="page">Data</li> </ol> </nav> <!-- ------------------------------------------------------------------------------------- --> <p class="d-inline-flex gap-1"> <a class="btn btn-primary" data-bs-toggle="collapse" href="#multiCollapseExample1" role="button" aria-expanded="false" aria-controls="multiCollapseExample1">Sistec</a> <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#multiCollapseExample2" aria-expanded="false" aria-controls="multiCollapseExample2">MIT</button> <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target=".multi-collapse" aria-expanded="false" aria-controls="multiCollapseExample1 multiCollapseExample2">Toggle both elements</button> </p> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1"> <div class="card card-body"> Some placeholder content for the first collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger. </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2"> <div class="card card-body"> Some placeholder content for the second collapse component of this multi-collapse example. This panel is hidden by default but revealed when the user activates the relevant trigger. </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> </body> </html>
import React, { Suspense, useEffect, useState } from "react"; import "./homePage.styles.scss"; // import PreviewItem from "../../components/previewItem/previewItem.component"; import Slider from "../../components/slider/slider.component"; const PreviewItem = React.lazy(() => import("../../components/previewItem/previewItem.component")); function Home() { const removeListener = () => { window.removeEventListener("scroll", divLoading); }; const [view, setView] = useState({ action: null, adventure: null, comedy: null }); const divLoading = () => { // console.log(window.scrollY); if (window.scrollY > 380) { setView({ ...view, action: true }); } if (window.scrollY > 900) { setView({ ...view, adventure: true }); } if (window.scrollY > 1165) { setView({ ...view, comedy: true }); } }; useEffect(() => { window.addEventListener("scroll", divLoading); return () => { removeListener(); }; }, [view.action, view.adventure, view.comedy]); return ( <div id="home"> <Slider /> <div className="center"> <Suspense fallback="<div>is Loading</div>"> <PreviewItem title="Popular" order_by="popularity" min_score="8.5" /> {view.action ? <PreviewItem title="Action" genres="1" min_score="8" order_by="popularity" /> : null} {view.adventure ? <PreviewItem title="Adventure" genres="2" min_score="8" order_by="popularity" /> : null} {view.comedy ? <PreviewItem title="Comedy" genres="4" min_score="8.5" order_by="popularity" /> : null} </Suspense> </div> </div> ); } export default Home;
package main import ( "fmt" "github.com/stretchr/testify/assert" "sync" "testing" ) //Дана последовательность чисел: 2,4,6,8,10. Найти сумму их квадратов(22+32+42….) с использованием конкурентных вычислений. func Test3(t *testing.T) { sum := 0 mut := sync.Mutex{} arr := []int{2, 4, 6, 8, 10} // Исходные числа загоняются в массив channel := make(chan int, len(arr)) for i := 0; i < len(arr); i++ { channel <- arr[i] } close(channel) // Для предотвращения race condition блокируем мьютексом appendCounter := func(a int) { mut.Lock() defer mut.Unlock() sum += a } // Параллельное вычисление квадратов чисел wg := sync.WaitGroup{} wg.Add(len(arr)) for i := 0; i < len(arr); i++ { go func() { defer wg.Done() for i2 := range channel { appendCounter(i2 * i2) } }() } wg.Wait() assert.Equal(t, 220, sum) fmt.Println(sum) }
<!DOCTYPE html> <html> <head> <title>달력</title> <style type="text/css"> /* font 링크 */ @font-face { font-family: 'KBIZHanmaumGothic'; src: url('https://cdn.jsdelivr.net/gh/projectnoonnu/[email protected]/KBIZHanmaumGothic.woff')format('woff'); font-weight: normal; font-style: normal; } #calendar { border-radius: 8px; background-color: rgba(0, 0, 0, 0.4); } td{ width: 40px; height: 40px; text-align: center; font-size: 18px; font-family: 'KBIZHanmaumGothic'; border: none; border-color:rgb(43, 33, 33); border-radius: 8px; } .arrowBtn { cursor: pointer; } </style> <script> var today = new Date(); var date = new Date(); // 이전 달 function prevCalendar() { today = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate()); buildCalendar(); } // 다음 달 function nextCalendar() { today = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate()); //달력 cell 만들어 출력 buildCalendar(); } // 이번 달 function buildCalendar(){ // 이번 달의 첫째 날, // new를 쓰는 이유 : new를 쓰면 이번달의 로컬 월을 정확하게 받아온다. // new를 쓰지 않았을때 이번달을 받아오려면 +1을 해줘야한다. // 왜냐면 getMonth()는 0~11을 반환하기 때문 var doMonth = new Date(today.getFullYear(),today.getMonth(),1); // 이번 달의 마지막 날 // new를 써주면 정확한 월을 가져옴, getMonth()+1을 해주면 다음달로 넘어가는데 // day를 1부터 시작하는게 아니라 0부터 시작하기 때문에 // 대로 된 다음달 시작일(1일)은 못가져오고 1 전인 0, 즉 전달 마지막일 을 가져오게 된다 var lastDate = new Date(today.getFullYear(),today.getMonth()+1,0); var tbCalendar = document.getElementById("calendar"); // 날짜를 찍을 테이블 변수 만듬, 일 까지 다 찍힘 var tbCalendarYM = document.getElementById("tbCalendarYM"); // 테이블에 정확한 날짜 찍는 변수 // innerHTML : js 언어를 HTML의 권장 표준 언어로 바꾼다 // new를 찍지 않아서 month는 +1을 더해줘야 한다. tbCalendarYM.innerHTML = today.getFullYear() + "년 " + (today.getMonth() + 1) + "월"; // while은 이번달이 끝나면 다음달로 넘겨주는 역할*/ while (tbCalendar.rows.length > 2) { //열을 지워줌 //기본 열 크기는 body 부분에서 2로 고정되어 있다. tbCalendar.deleteRow(tbCalendar.rows.length-1); //테이블의 tr 갯수 만큼의 열 묶음은 -1칸 해줘야지 //30일 이후로 담을달에 순서대로 열이 계속 이어진다. } var row = null; //테이블에 새로운 열 삽입 즉, 초기화 row = tbCalendar.insertRow(); // count, 셀의 갯수를 세어주는 역할 var cnt = 0; // 1일이 시작되는 칸을 맞추어 줌 // 이번달의 day만큼 돌림 for (i=0; i<doMonth.getDay(); i++) { //열 한칸한칸 계속 만들어주는 역할 cell = row.insertCell(); cnt = cnt + 1;//열의 갯수를 계속 다음으로 위치하게 해주는 역할 } // 달력 출력 // 1일부터 마지막 일까지 돌림 for (i = 1; i <= lastDate.getDate(); i++) { //열 한칸한칸 계속 만들어주는 역할 cell = row.insertCell(); //셀을 1부터 마지막 day까지 HTML 문법에 넣어줌 cell.innerHTML = i; //열의 갯수를 계속 다음으로 위치하게 해주는 역할 cnt = cnt + 1; // 일요일 계산 if (cnt % 7 == 1) { //1주일이 7일 이므로 일요일 구하기 //월화수목금토일을 7로 나눴을때 나머지가 1이면 cnt가 1번째에 위치함을 의미한다 //1번째의 cell에만 색칠 cell.innerHTML = "<font color=#F79DC2>" + i } if (cnt%7 == 0){/* 1주일이 7일 이므로 토요일 구하기*/ //월화수목금토일을 7로 나눴을때 나머지가 0이면 cnt가 7번째에 위치함을 의미한다 cell.innerHTML = "<font color=skyblue>" + i //7번째의 cell에만 색칠 row = calendar.insertRow(); //토요일 다음에 올 셀을 추가 } // 오늘의 날짜에 색 칠하기 //달력에 있는 년,달과 내 컴퓨터의 로컬 년,달이 같고, 일이 오늘의 일과 같으면 if (today.getFullYear() == date.getFullYear() && today.getMonth() == date.getMonth() && i == date.getDate()) { // 오늘 날짜 색깔 셋팅 cell.bgColor = "orange"; } } } </script> </head> <body> <table id="calendar" border="3" align="center" style="border-color:rgb(43, 33, 33);"> <tr> <td> <label class="arrowBtn" onclick="prevCalendar()"><</label> </td> <td align="center" id="tbCalendarYM" colspan="5"> yyyy년 m월 </td> <td> <label class="arrowBtn" onclick="nextCalendar()">></label> </td> </tr> <tr> <td align="center"><font color ="#F79DC2">일</td> <td align="center">월</td> <td align="center">화</td> <td align="center">수</td> <td align="center">목</td> <td align="center">금</td> <td align="center"><font color ="skyblue">토</td> </tr> </table> <script language="javascript" type="text/javascript"> buildCalendar(); </script> </body> </html>
package com.langfeiyes.batch._02_params; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepScope; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.util.Map; //开启 spring batch 注解--可以让spring容器创建springbatch操作相关类对象 @EnableBatchProcessing //springboot 项目,启动注解, 保证当前为为启动类 @SpringBootApplication public class ParamJob { //作业启动器 @Autowired private JobLauncher jobLauncher; //job构造工厂---用于构建job对象 @Autowired private JobBuilderFactory jobBuilderFactory; //step 构造工厂--用于构造step对象 @Autowired private StepBuilderFactory stepBuilderFactory; //构造一个step对象执行的任务(逻辑对象) @StepScope @Bean public Tasklet tasklet(@Value("#{jobParameters['name']}")String name){ return new Tasklet() { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { //要执行逻辑--step步骤执行逻辑 //方案1: 使用chunkContext //Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters(); //System.out.println("params---name:" + jobParameters.get("name")); //方案2: 使用@Vlaue System.out.println("params---name:" + name); return RepeatStatus.FINISHED; //执行完了 } }; } //构造一个step对象 @Bean public Step step1(){ //tasklet 执行step逻辑, 类似 Thread()--->可以执行runable接口 return stepBuilderFactory .get("step1") .tasklet(tasklet(null)) .build(); } //构造一个job对象 /* @Bean public Job job(){ return jobBuilderFactory.get("param-job").start(step1()).build(); }*/ /*@Bean public Job job(){ return jobBuilderFactory.get("param-chunk-job").start(step1()).build(); }*/ @Bean public Job job(){ return jobBuilderFactory .get("param-value-job1") .start(step1()) .build(); } public static void main(String[] args) { SpringApplication.run(ParamJob.class, args); } }
# frozen_string_literal: true module Types class ImageAttributeType # Defines translated fields for an image attribute class ImageAttributeTranslationType < Types::BaseObject description 'Translated fields for an image attribute' field :locale, String, description: 'The locale for this translation', null: false field :name, String, description: 'The translated name of an image attribute', null: false end end end
import React, { useEffect } from 'react'; import { Box, Container, TabList, Tabs, Text, Tab, TabPanel, TabPanels, } from '@chakra-ui/react'; import { Login } from '../components/Authentication/Login'; import { Signup } from '../components/Authentication/Signup'; import { useHistory } from 'react-router-dom'; export const Homepage = () => { const history = useHistory(); useEffect(() => { const user = JSON.parse(localStorage.getItem('userInfo')); if (user) history.push('/chats'); }, [history]); // console.log('homepage render'); return ( <Container maxW='xl' centerContent> <Box d='flex' justifyContent='center' p={3} bg={'white'} w='100%' m='40px 0 15px 0' borderRadius='lg' borderWidth='1px'> <Text fontSize='4xl' fontFamily='Work sans' color='black'> Chat Time </Text> </Box> <Box bg={'white'} w='100%' p={4} borderRadius='lg' borderWidth='1px' color='black'> <Tabs variant='soft-rounded'> <TabList mb='1em'> <Tab width='50%'>Login</Tab> <Tab width='50%'>Sign Up</Tab> </TabList> <TabPanels> <TabPanel> <Login></Login> </TabPanel> <TabPanel> <Signup></Signup> </TabPanel> </TabPanels> </Tabs> </Box> </Container> ); };
#include "main.h" int check_pal(char *s, int i, int len); int _strlen_recursion(char *s); /** * @s: a string to revers * is_palindrome - to check if a string is a palindrome * @s: as string to reverse * * Return: 1 if it is, 0 it's not */ int is_palindrome(char *s) { if (*s == 0) return (1); return (check_pal(s, 0, _strlen_recursion(s))); } /** * _strlen_recursion - it returns the length of a string * @s: as string to calculate the length of * * Return: length of the string */ int _strlen_recursion(char *s) { if (*s == '\0') return (0); return (1 + _strlen_recursion(s + 1)); } /** * check_pal - it is used to check the characters recursively for palindrome * @s: this is string to check * @i: as iterator here * @len: length of the string * * Return: 1 if palindrome, 0 if not */ int check_pal(char *s, int i, int len) { if (*(s + i) != *(s + len - 1)) return (0); if (i >= len) return (1); return (check_pal(s, i + 1, len - 1)); }
import { storyblokEditable } from "@storyblok/react"; import { Link } from "react-router-dom"; import styled from "styled-components"; const ProductGrid = ({ blok }) => { const getSlug = (name) => { return name.toLowerCase().trim().replaceAll(" ", "-"); }; return ( <StyledDiv {...storyblokEditable(blok)}> <h1 className="text-5xl mb-6">Products</h1> <div className="flex flex-wrap"> {blok?.products?.items.map((item) => ( <div key={item?.name} className="img-wrapper mr-8 mb-8"> <Link to={`/product/${getSlug(item?.name)}`}> <img key={item?.id} src={item?.image} alt={item?.name} /> </Link> <h4 className="font-bold mt-1 mb-1">{item?.name}</h4> <p>{item?.description}</p> </div> ))} </div> </StyledDiv> ); }; const StyledDiv = styled.div` margin-top: 10rem; & .img-wrapper { width: 320px; & img { width: 100%; height: 240px; object-fit: cover; border-radius: 8px; } } `; export default ProductGrid;
import { inject, injectable } from 'tsyringe'; import _ from 'lodash'; import { Logger } from 'winston'; import { FileSystemUtils } from '../utils/file-system.utils'; import { Checker, CheckerResults } from './checker'; import { Config, LockfileConfig } from '../config'; export const defaultOptions: LockfileConfig = { path: `${process.cwd()}/package-lock.json`, version: 2, }; @injectable() export class LockfileVersionChecker implements Checker { constructor(@inject('FileSystemUtils') private fsUtils: FileSystemUtils, @inject('Logger') private logger: Logger) {} public async run(config: Config): Promise<CheckerResults> { this.logger.debug('Running LockfileVersionChecker'); const runOptions = _.defaults(config.lockfile, defaultOptions); if (!runOptions.path || !this.fsUtils.exists(runOptions.path)) { return { name: 'LockfileVersion', success: true }; } const contents = this.fsUtils.readFile(runOptions.path); let lockfile: { lockfileVersion: number }; try { lockfile = JSON.parse(contents); } catch { return { name: 'LockfileVersion', success: false, fails: ['Lockfile is in an invalid format'] }; } const valid = lockfile.lockfileVersion == runOptions['version']; this.logger.debug(`Lockfile is ${valid ? 'valid' : 'invalid'}`); return { name: 'LockfileVersion', success: valid, fails: valid ? undefined : [`LockfileVersion isn't "${runOptions['version']}"`], }; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device --> <link rel="icon" type="image/png" sizes="32x32" href="images/favicon.png"> <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=Barlow+Semi+Condensed:wght@500&display=swap" rel="stylesheet"> <link rel="stylesheet" href="css/styles.css"> <title>Frontend Mentor | [Testimonial-Grid-Challenge]</title> </head> <body> <div class="testimonial"> <div class="Daniel"> <img class="person-image" src="images/image-daniel.jpg" alt="Daniel Img"> <p class="person-name">Daniel Clifford</p> <p class="person-identity">Verified Graduate</p> <h2 class="person-comment">I received a job offer mid-course, and the subjects I learned were current, if not more so, in the company I joined. I honestly feel I got every penny’s worth.</h2> <p class="person-story">“ I was an EMT for many years before I joined the bootcamp. I’ve been looking to make a transition and have heard some people who had an amazing experience here. I signed up for the free intro course and found it incredibly fun! I enrolled shortly thereafter. The next 12 weeks was the best - and most grueling - time of my life. Since completing the course, I’ve successfully switched careers, working as a Software Engineer at a VR startup. ”</p> </div> <div class="Jonathan"> <img class="person-image" src="images/image-jonathan.jpg" alt="Jonathan Image"> <p class="person-name">Jonathan Walters</p> <p class="person-identity">Verified Graduate</p> <h2 class="person-comment">The team was very supportive and kept me motivated</h2> <p class="person-story">“ I started as a total newbie with virtually no coding skills. I now work as a mobile engineer for a big company. This was one of the best investments I’ve made in myself. ”</p> </div> <div class="Jeanette"> <img class="person-image" src="images/image-jeanette.jpg" alt="Jeanette Image"> <p class="person-name person-design-changes-name">Jeanette Harmon</p> <p class="person-identity person-design-changes-identity">Verified Graduate</p> <h2 class="person-comment person-design-changes-comment">An overall wonderful and rewarding experience</h2> <p class="person-story person-design-changes-story">“ Thank you for the wonderful experience! I now have a job I really enjoy, and make a good living while doing something I love. ”</p> </div> <div class="Patrick"> <img class="person-image" src="images/image-patrick.jpg" alt="Patrick Image"> <p class="person-name">Patrick Abrams</p> <p class="person-identity">Verified Graduate</p> <h2 class="person-comment">Awesome teaching support from TAs who did the bootcamp themselves. Getting guidance from them and learning from their experiences was easy.</h2> <p class="person-story">“ The staff seem genuinely concerned about my progress which I find really refreshing. The program gave me the confidence necessary to be able to go out in the world and present myself as a capable junior developer. The standard is above the rest. You will get the personal attention you need from an incredible community of smart and amazing people. ”</p> </div> <div class="Kira"> <img class="person-image" src="images/image-kira.jpg" alt="Kira Image"> <p class="person-name person-design-changes-name">Kira Whittle</p> <p class="person-identity person-design-changes-identity">Verified Graduate</p> <h2 class="person-comment person-design-changes-comment">Such a life-changing experience. Highly recommended!</h2> <p class="person-story person-design-changes-story">“ Before joining the bootcamp, I’ve never written a line of code. I needed some structure from professionals who can help me learn programming step by step. I was encouraged to enroll by a former student of theirs who can only say wonderful things about the program. The entire curriculum and staff did not disappoint. They were very hands-on and I never had to wait long for assistance. The agile team project, in particular, was outstanding. It took my learning to the next level in a way that no tutorial could ever have. In fact, I’ve often referred to it during interviews as an example of my developent experience. It certainly helped me land a job as a full-stack developer after receiving multiple offers. 100% recommend! ”</p> </div> </div> <div class="footer"> Challenge by <a href="https://www.frontendmentor.io?ref=challenge" target="_blank">Frontend Mentor</a>.<br> Coded by <a href="https://100rav5026.github.io/CV/">Sourav Mudaliar 2023</a>. </div> </body> </html>
import React from 'react' import './testimonials.scss' import Slider from "react-slick"; import Elon from "../../asset/Elon.png"; import Bill from "../../asset/Bill Gates.png"; import Bill1 from "../../asset/Bill Gates1.png"; import Galileo from "../../asset/Galileo Galilei.png"; import Galieo1 from "../../asset/Galileo Galilei1.png"; import Jeff from "../../asset/Jeff Bezos.png"; import Martindainguyen from "../../asset/Martindainguyen.png"; import Richard from "../../asset/Richard Branson.png"; import Sundar from "../../asset/Sundar Pichai.png"; import Sundar1 from "../../asset/Sundar Pichai1.png"; const data = [ { id: 1, img: Bill1, name: "Bill Gates", }, { id: 2, img:Elon, name: "Elon Musk", }, { id: 3, img: Bill, name: "Bill Gates", }, { id: 4, img: Sundar, name: "Sundar Pichai", }, { id: 5, img: Galieo1, name: "Galileo Galilei", }, { id: 6, img: Bill, name: "Bill Gates", }, { id: 7, img: Sundar1, name: "Sundar Pichai", }, { id: 8, img: Galileo, name: "Galileo Galilei", }, { id: 9, img: Jeff, name: "Jeff Bezos", }, { id: 10, img: Martindainguyen, name: "Martindainguyen", }, { id: 11, img: Richard, name: "Richard Branson", }, ]; export default function Testimonials() { const settings = { dots: false, infinite: true, slidesToShow: 4, slidesToScroll: 1, autoplay: true, autoplaySpeed: 2000, ltr: true, responsive: [ { breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, infinite: true, // dots: true } }, { breakpoint: 900, settings: { slidesToShow: 2, slidesToScroll: 1, infinite: true, // dots: true } }, { breakpoint: 600, settings: { slidesToShow: 1, slidesToScroll: 1, infinite: true, // dots: true } }, ] }; return ( <div id='testimonials'> <Slider {...settings}> {data.map((data) => ( <div className='testimonials-item ' key={data.id}> <img src={data.img} alt='imag' className='image' /> <h6>{data.name}</h6> </div> ))} </Slider> </div> ) }
pragma solidity ^0.4.24; import "./StandardToken.sol"; import "./ownership/Administrable.sol"; contract MintableToken is StandardToken, Administrable { event Mint(address indexed to, uint256 amount); event MintStarted(); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier cantMint() { require(mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint * @return A boolean that indicated if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwnerOrAdmin(ROLE_MINT) canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to start minting new tokens. * @return True if the operation was successful. */ function startMinting() onlyOwner cantMint public returns (bool) { mintingFinished = false; emit MintStarted(); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } }
@extends('layouts.app') @section('title') Payment @endsection @section('content') <div class="page-title"> <div class="container"> <div class="column"> <ul class="breadcrumbs"> <li><a href="/">Trang chủ</a> </li> <li class="separator"></li> <li>Xem lại đơn hàng của bạn và thanh toán</li> </ul> </div> </div> </div> <div class="container padding-bottom-3x mb-1 checkut-page"> <div class="row"> <!-- Payment Methode--> <div class="col-xl-9 col-lg-8"> @include('includes.steps') <div class="card"> <div class="card-body"> <h6 class="pb-2">Xem lại đơn hàng của bạn :</h6> <hr> <div class="row padding-top-1x mb-4"> <div class="col-sm-12"> <h6>Địa chỉ giao hàng :</h6> <ul class="list-unstyled"> <li><span class="text-muted">Tên: </span>{{ Auth::user()->name }}</li> <li><span class="text-muted">Điện thoại: </span>{{ $shipping_address->phone }}</li> <li><span class="text-muted">Địa chỉ 1: </span>{{ $shipping_address->address1 }}</li> <li><span class="text-muted">Địa chỉ 2: </span>{{ $shipping_address->address2 }}</li> <li><span class="text-muted">Thành phố: </span>{{ $shipping_address->city }}</li> </ul> </div> </div> <h6>Thanh toán bằng :</h6> <div class="row mt-4"> <div class="col-12"> <div class="payment-methods"> <div class="single-payment-method"> <a class="text-decoration-none " href="#" data-bs-toggle="modal" data-bs-target="#stripe"> <img class="" src="https://geniusdevs.com/codecanyon/omnimart40/assets/images/1601930611stripe-logo-blue.png" alt="Stripe" title="Stripe"> <p>Stripe</p> </a> </div> <div class="single-payment-method"> <a class="text-decoration-none " href="#" data-bs-toggle="modal" data-bs-target="#bank"> <img class="" src="https://geniusdevs.com/codecanyon/omnimart40/assets/images/1638530860pngwing.com (1).png" alt="Bank Transfer" title="Bank Transfer"> <p>Bank Transfer</p> </a> </div> <div class="single-payment-method"> <a class="text-decoration-none " href="#" data-bs-toggle="modal" data-bs-target="#cod"> <img class="" src="https://support.sitegiant.com/wp-content/uploads/2022/08/cash-on-delivery-banner.png" alt="Flutter Wave" title="Flutter Wave"> <p>Thanh toán khi giao hàng</p> </a> </div> </div> </div> </div> </div> </div> <!-- Modal Cash on Transfer--> <div class="modal fade" id="cod" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title">Giao dịch tiền mặt khi giao hàng</h6> <button class="close" type="button" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> </div> <form action="{{ route('user.checkout.cash.on.delivery') }}" method="POST"> @csrf <input type="hidden" name="payment_method" value="Cash On Delivery" id=""> <div class="card-body"> <p>Trả tiền khi giao hàng về cơ bản có nghĩa là bạn sẽ thanh toán số lượng sản phẩm trong khi nhận được hàng được giao cho bạn.</p> </div> <div class="modal-footer"> <button class="btn btn-primary btn-sm" type="button" data-bs-dismiss="modal"><span>Hủy bỏ</span></button> <button class="btn btn-primary btn-sm" type="submit"><span>Thanh toán khi giao hàng</span></button> </div> </form> </div> </div> </div> <!-- Modal Stripe --> <div class="modal fade" id="stripe" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title">Transactions via Stripe</h6> <button class="close" type="button" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> </div> <div class="modal-body"> <div class="card-body"> <div class="card-wrapper"></div> <form role="form" action="{{ route('user.checkout.stripe') }}" method="post" class="require-validation" data-cc-on-file="false" data-stripe-publishable-key="{{ env('STRIPE_KEY') }}" id="payment-form"> @csrf <div class="form-group col-sm-12"> <input class="form-control card-number" type="text" name="card" placeholder="Card Number" required=""> </div> <input type="hidden" name="payment_method" value="Stripe"> <div class="form-group col-sm-12"> <input class="form-control card-expiry-month" type="text" name="month" placeholder="Expitation Month" required=""> </div> <div class="form-group col-sm-12"> <input class="form-control card-expiry-year" type="text" name="year" placeholder="Expitation Year" required=""> </div> <div class="form-group col-sm-12"> <input class="form-control card-cvc " type="text" name="cvc" placeholder="CVV" required=""> </div> <p class="p-3">Stripe is the faster &amp; safer way to send money. Make an online payment via Stripe.</p> <div class="modal-footer"> <button class="btn btn-primary btn-sm" type="button" data-bs-dismiss="modal"><span>Cancel</span></button> <button class="btn btn-primary btn-sm" type="submit"><span>Chekout With Stripe</span></button> </div> </form> </div> </div> </div> </div> </div> <div class="modal fade" id="flutterwave" tabindex="-1" aria-hidden="true"> <form class="interactive-credit-card row" action="https://geniusdevs.com/codecanyon/omnimart40/flutterwave/submit" method="POST"> <input type="hidden" name="_token" value="sXahNV8HiLbT9glsyMxedbtDGJmeA8qZf5UfwM7k"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title">Transactions via Flutterwave</h6> <button class="close" type="button" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> </div> <div class="modal-body"> <div class="card-body"> <p>Flutterwave is the faster &amp; safer way to send money. Make an online payment via Flutterwave.</p> </div> </div> <input type="hidden" name="payment_method" value="Flutterwave"> <input type="hidden" name="state_id" value="" class="state_id_setup"> <div class="modal-footer"> <button class="btn btn-primary btn-sm" type="button" data-bs-dismiss="modal"><span>Cancel</span></button> <button class="btn btn-primary btn-sm" type="submit"><span>Checkout With Flutterwave</span></button> </div> </div> </div> </form> </div> <!-- Modal bank --> <div class="modal fade" id="bank" tabindex="-1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title">Transactions via Bank Transfer</h6> <button class="close" type="button" data-bs-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> </div> <form action="{{ route('user.checkout.bank.transfer') }}" method="POST"> <div class="modal-body"> <div class="col-lg-12 form-group"> <label for="transaction">Transaction Number</label> <input class="form-control" name="transaction" id="transaction" placeholder="Enter Your Transaction Number" required=""> </div> <p></p> <p>Account Number : 434 3434 3334</p> <p>Pay With Bank Transfer.</p> <p>Account Name : Jhon Due</p> <p>Account Email : [email protected]</p> <p></p> </div> <div class="modal-footer"> @csrf <input type="hidden" name="payment_method" value="Bank"> <button class="btn btn-primary btn-sm" type="button" data-bs-dismiss="modal">Cancel</button> <button class="btn btn-primary btn-sm" type="submit"><span>Checkout With Bank Transfer</span></button> </div> </form> </div> </div> </div> </div> @include('includes.order-summary') </div> </div> @endsection @section('footer') <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script> $(function() { var $form = $(".require-validation"); $('form.require-validation').bind('submit', function(e) { var $form = $(".require-validation"), inputSelector = ['input[type=email]', 'input[type=password]', 'input[type=text]', 'input[type=file]', 'textarea' ].join(', '), $inputs = $form.find('.required').find(inputSelector), $errorMessage = $form.find('div.error'), valid = true; $errorMessage.addClass('hide'); $('.has-error').removeClass('has-error'); $inputs.each(function(i, el) { var $input = $(el); if ($input.val() === '') { $input.parent().addClass('has-error'); $errorMessage.removeClass('hide'); } }); if (!$form.data('cc-on-file')) { Stripe.setPublishableKey($form.data('stripe-publishable-key')); Stripe.createToken({ number: $('.card-number').val(), cvc: $('.card-cvc').val(), exp_month: $('.card-expiry-month').val(), exp_year: $('.card-expiry-year').val() }, stripeResponseHandler); } }); /*------------------------------------------ -------------------------------------------- Stripe Response Handler -------------------------------------------- --------------------------------------------*/ function stripeResponseHandler(status, response) { if (response.error) { $('.error') .removeClass('hide') .find('.alert') .text(response.error.message); } else { /* token contains id, last4, and card type */ var token = response['id']; $form.find('input[type=text]').empty(); $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>"); $form.get(0).submit(); } } }); </script> @endsection
#include "bitset.h" #include <stdbool.h> #include <assert.h> #include <stdio.h> bitset bitset_create(unsigned maxValue) { assert (maxValue < 32); return (bitset) {0, maxValue}; } bool bitset_in(bitset set, unsigned int value) { return value <= set.maxValue && set.values & (1 << value); } bool bitset_isEqual(bitset set1, bitset set2) { return set1.values == set2.values && set1.maxValue == set2.maxValue; } bool bitset_isSubset(bitset subset, bitset set) { if (subset.values <= set.values && subset.maxValue <= set.maxValue) { for (int i = 0; i <= subset.maxValue; i++) if (bitset_in(subset, i) && !bitset_in(set, i)) return false; return true; } else return false; } void bitset_insert(bitset *set, unsigned int value) { assert(value <= set->maxValue); set->values |= (1 << value); } void bitset_deleteElement(bitset *set, unsigned int value) { if (bitset_in(*set, value)) set->values &= ~(1 << value); } bitset bitset_union(bitset set1, bitset set2) { assert(set1.maxValue == set2.maxValue); return (bitset) {set1.values | set2.values, set1.maxValue}; } bitset bitset_intersection(bitset set1, bitset set2) { assert(set1.maxValue == set2.maxValue); return (bitset) {set1.values & set2.values, set1.maxValue}; } bitset bitset_difference(bitset set1, bitset set2) { assert(set1.maxValue == set2.maxValue); return (bitset) {set1.values & ~set2.values, set1.maxValue}; } bitset bitset_symmetricDifference(bitset set1, bitset set2) { assert(set1.maxValue == set2.maxValue); return (bitset) {set1.values ^ set2.values, set1.maxValue}; } bitset bitset_complement(bitset set) { return (bitset) {~set.values, set.maxValue}; } void bitset_print(bitset set) { printf("{"); int is_empty = true; for (int i = 0; i <= set.maxValue; i++) { if (bitset_in(set, i)) { printf("%d, ", i); is_empty = false; } } if (is_empty) { printf("}\n"); } else { printf("\b\b}\n"); } }
import { useDispatch, useSelector } from "react-redux"; import TotalSalesChart from "../charts/TotalSalesChart"; import InventoryChart from "../charts/InventoryChart"; import MonthlyCompareChart from "../charts/MonthlyCompareChart"; import BestSeller from "./BestSeller"; import { useEffect } from "react"; import { getBoss } from "../../app/features/bossSlice"; import { RiAlignVertically, RiNumbersLine } from "react-icons/ri"; const MainBoss = () => { const dashboard = useSelector((state) => state.boss.bossDashboard); const User = useSelector((state) => state.auth.User); const dispatch = useDispatch(); useEffect(() => { if (User?.id) dispatch(getBoss(User.id)); }, [User.id, dispatch]); const todayFormated = () => { const dateToday = new Date(); const nameMounth = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const day = dateToday.getDate(); const mounth = nameMounth[dateToday.getMonth()]; const year = dateToday.getFullYear(); return `Hoy, ${day} ${mounth} ${year}`; }; return ( <section className="py-6 px-12 z-20 grid gird-cols-1 lg:grid-cols-6 "> <section className="col-span-4 flex flex-col gap-y-6 lg:pr-6 pr-0 mb-4 lg:mb-0"> <section className="flex flex-col gap-y-3.5"> <h2 className="text-3xl font-medium text-light"> Welcome Back,{" "} <span className="bg-gradient-to-r from-primary to-secondary text-transparent bg-clip-text font-bold"> {User?.name} </span> </h2> <p className="text-light/80 text-sm">{todayFormated()}</p> <p className="text-sm text-light/90"> Here&apos;s your summary of the day </p> </section> <section className="bg-base-light/30 px-2 py-4 rounded-md"> <h5 className="text-light font-bold mb-4 text-xl flex gap-x-2 items-center uppercase"> Total Sales <RiNumbersLine /> </h5> <TotalSalesChart annual_sales={dashboard?.annual_sales} /> </section> <section className="bg-base-light/30 px-2 py-4 rounded-md"> <h5 className="text-light text-xl font-bold mb-4 flex gap-x-2 items-center uppercase"> Monthly Sales <RiAlignVertically /> </h5> <MonthlyCompareChart annual_sales={dashboard?.annual_sales} /> </section> </section> <section className="col-span-2 w-full flex flex-col gap-y-7 justify-center mb-10"> <BestSeller best_salesman={dashboard?.best_salesman} /> <section className="flex flex-col items-center gap-y-4 bg-base-light/30 py-4 rounded-md shadow-md"> <h5 className="text-light uppercase font-bold text-xl"> 10 Products with Low Stock </h5> <InventoryChart /> </section> </section> </section> ); }; export default MainBoss;
from django import forms from .models import ModelFile from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import UserCreationForm # 追加 from django.contrib.auth.models import User # 追加 # モデルからフォームを作成 class FormAnimal(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control-file' field.widget.attrs['id'] = 'image-input' class Meta: model = ModelFile # 画像ファイル送信用 フォームモデル fields = ('image',) # form 項目には画像を指定 , が無いとerror class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['id'] = 'username' self.fields['password'].widget.attrs['id'] = 'password' class SignUpForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' self.fields['username'].widget.attrs['id'] = 'username' self.fields['password1'].widget.attrs['id'] = 'password1' self.fields['password2'].widget.attrs['id'] = 'password2' class Meta: model = User fields = ('username', 'password1', 'password2')
import axios from "axios"; import { useEffect, useRef, useState } from "react"; import Modal from "./Modal"; import { MdFileOpen } from "react-icons/md"; import { toast, ToastContainer } from "react-toastify"; import 'react-toastify/dist/ReactToastify.css' function ListEmployeeComponent() { const [employees, setEmployees] = useState([]); const [addEmployee, setAddEmployee] = useState(false) const [isUpdate, setIsUpdate] = useState(false) const [img, setImg] = useState(null) const [ttlSalary, setTotalSalary] = useState(0) const [data, setData] = useState({ id: '', avatar: '', name: '', dob: '', phone: '', email: '', role: 'tester', baseSalary: 0, numOfOvtHours: 0, numOfErrors: 0 }) const formAdd = useRef(); const formEdit = useRef(); const [errInput, setErrInput] = useState({ file: '', name: '', phone: '', dob: '', email: '', baseSalary: '', role: '', numOfOvtHours: '', numOfErrors: '', isCheck: false }) const handleChange = (e) => { const { name, value } = e.target; setData({ ...data, [name]: value, }); }; useEffect(() => { (async () => await Load())(); }, []); async function Load() { const result = new Promise((resolve) => { const rs = axios.get( "http://localhost:8088/api/employees"); resolve(rs) }) result .then(result => { setEmployees(result.data.employees); return result.data.employees; }) .then((result) => { calculateTotal(result) }) } function calculateTotal(e) { var tt = 0 e.map((item) => tt += item.role === 'coder' ? (parseInt(item.baseSalary) + 200000 * parseInt(item.numOfOvtHours)) : (parseInt(item.baseSalary) + 50000 * parseInt(item.numOfErrors)) ) setTotalSalary(tt) } const handleImageChange = (e) => { const file = e.target.files[0]; setImg(file) if (file) { const reader = new FileReader(); reader.onloadend = () => { setData({ ...data, avatar: reader.result }); }; reader.readAsDataURL(file); } }; const handleRule = { 'required': (value) => { return value !== '' ? '' : "Please fill out this field!" }, 'imgRequired': () => { } } const handleAdd = async (e) => { e.preventDefault(); const nodeList = formAdd.current.querySelectorAll('input') const arrayFromNodeList = Array.from(nodeList); arrayFromNodeList.forEach(item => { const rules = item.getAttribute('rules') if (rules) { const ruleArr = rules.split('|'); for (var rule of ruleArr) { if (rule) { const ruleFunc = handleRule[rule] const rs = ruleFunc(item.getAttribute('value')) console.log(item.getAttribute('name'), rs) setErrInput(prev => { const obj = { ...prev }; obj[item.getAttribute('name')] = rs return obj }) } } } }) if (typeof (formAdd.current.file.files[0]) === 'undefined') { setErrInput(prev => { const obj = { ...prev }; obj.file = 'Avatar employee is required!' return obj }) } else { setErrInput(prev => { const obj = { ...prev }; obj.file = '' obj.isCheck = true return obj }) } if (errInput.name === '' && errInput.file === '' && errInput.dob === '' && errInput.phone === '' && errInput.email === '' && errInput.isCheck) { const formData = new FormData(); formData.append('file', img); formData.append('avatar', ""); formData.append('name', data.name); formData.append('dob', data.dob); formData.append('phone', data.phone); formData.append('email', data.email); formData.append('role', data.role); formData.append('baseSalary', data.baseSalary); formData.append('numOfOvtHours', data.numOfOvtHours); formData.append('numOfErrors', data.numOfErrors); console.log(data) console.log(formData) try { const response = await axios.post('http://localhost:8088/api/employees/create', formData, { headers: { 'Content-Type': 'multipart/form-data', 'charset': 'utf-8' }, }); console.log('Response:', response.data); toast(response.data.message) } catch (error) { console.error('Error:', error); } setAddEmployee(false) setErrInput({ file: '', name: '', phone: '', dob: '', email: '', baseSalary: '', role: '', numOfOvtHours: '', numOfErrors: '', isCheck: false }) setData({ avatar: '', name: '', dob: '', phone: '', email: '', role: 'tester', baseSalary: 0, numOfOvtHours: 0, numOfErrors: 0 }) setImg(null) Load(); } } const handleDelete = async (item) => { try { await axios.delete( "http://localhost:8088/api/employees/delete/" + item.employeeId); toast("Delete employee successfully.") Load() } catch (error) { console.error('Error:', error); } } const handleOpenEdit = (item) => { setData({ id: item.employeeId, avatar: item.avatar, name: item.name, dob: item.dob, phone: item.phone, email: item.email, role: item.role, baseSalary: item.baseSalary, numOfOvtHours: item.numOfOvtHours, numOfErrors: item.numOfErrors }) setIsUpdate(true) } const handleUpdate = async (e) => { e.preventDefault(); const err ={ file: '', name: '', phone: '', dob: '', email: '', baseSalary: '', role: '', numOfOvtHours: '', numOfErrors: '', isCheck: false } const nodeList = formEdit.current.querySelectorAll('input') const arrayFromNodeList = Array.from(nodeList); arrayFromNodeList.forEach(item => { const rules = item.getAttribute('rules') if (rules) { const ruleArr = rules.split('|'); for (var rule of ruleArr) { if (rule) { const ruleFunc = handleRule[rule] const rs = ruleFunc(item.getAttribute('value')) console.log(item.getAttribute('name'), rs) err[item.getAttribute('name')]=rs setErrInput(prev => { const obj = { ...prev }; obj[item.getAttribute('name')] = rs return obj }) } } } }) if (err.name === '' && err.file === '' && err.dob === '' && err.phone === '' && err.email === '' ) { const formData = new FormData(); console.log(img) formData.append('file', img); formData.append('avatar', data.avatar); formData.append('name', data.name); formData.append('dob', data.dob); formData.append('phone', data.phone); formData.append('email', data.email); formData.append('role', data.role); formData.append('baseSalary', data.baseSalary); formData.append('numOfOvtHours', data.numOfOvtHours); formData.append('numOfErrors', data.numOfErrors); console.log('http://localhost:8088/api/employees/update/' + data.id) try { const response = await axios.post('http://localhost:8088/api/employees/update/' + data.id, formData, { headers: { 'Content-Type': 'multipart/form-data', 'charset': 'utf-8' }, }); console.log('Response:', response.data); toast(response.data.message) } catch (error) { console.error('Error:', error); } setIsUpdate(false) setErrInput({ file: '', name: '', phone: '', dob: '', email: '', baseSalary: '', role: '', numOfOvtHours: '', numOfErrors: '', isCheck: false }) setData({ avatar: '', name: '', dob: '', phone: '', email: '', role: 'tester', baseSalary: 0, numOfOvtHours: 0, numOfErrors: 0 }) Load(); } } const handleDobToString = (dob) => { // Tạo đối tượng Date từ chuỗi const originalDate = new Date(dob); // Lấy ngày, tháng và năm const day = originalDate.getDate().toString().padStart(2, '0'); const month = (originalDate.getMonth() + 1).toString().padStart(2, '0'); // Tháng trong JavaScript bắt đầu từ 0 const year = originalDate.getFullYear(); // Tạo chuỗi định dạng mới const formattedDate = `${day}-${month}-${year}`; return formattedDate } const parseToVND = (salary) => { const formattedNumberString = Number(salary).toLocaleString(); return `${formattedNumberString} VND` } return ( <div> <h1 className="text-center mt-4 " style={{ fontSize: '49px' }}>Employee List</h1> <div className="d-flex" style={{ justifyContent: 'space-between' }}> <button className="btn btn-primary mt-4 mb-4" onClick={() => { setAddEmployee(true); setData({ avatar: '', name: '', dob: '', phone: '', email: '', role: 'tester', baseSalary: 0, numOfOvtHours: 0, numOfErrors: 0 }) }}>Add Employee</button> <div className="d-flex " style={{ alignItems: 'center' }} >Total Salary: <span>{parseToVND(ttlSalary)}</span></div> </div> <div className="row"> <table className="table table-bordered fw-normal" > <thead className="table-light"> <tr > <th>Id</th> <th >Name</th> <th>Role</th> <th>Email</th> <th>Base salary</th> <th>Over Times/ <br /> Errors Num</th> <th>Total salary</th> <th>Actions</th> </tr> </thead> <tbody className="fw-normal"> { employees.map((item, index) => { return ( <tr key={index} className="fw-normal"> <th className="fw-normal">NV{index + 1}</th> <th > <div className="d-flex"> <div style={{ marginRight: '10px' }}> <img src={`http://localhost:8088/api/employees/images/${item.avatar}`} alt="avt" style={{ width: '80px', height: '80px' }} /> </div> <div className="fw-normal"> <div><strong>Name:</strong> {item.name}</div> <div><strong>Dob:</strong> {handleDobToString(item.dob)}</div> <div><strong>Phone:</strong> {item.phone}</div> </div> </div> </th> <th className="fw-normal">{item.role === 'coder' ? 'Coder' : "Tester"}</th> <th className="fw-normal">{item.email}</th> <th className="fw-normal">{parseToVND(item.baseSalary)}</th> <th className="fw-normal">{item.role === 'coder' ? item.numOfOvtHours : item.numOfErrors}</th> <th className="fw-normal">{parseToVND(item.role === 'coder' ? (parseInt(item.baseSalary) + 200000 * parseInt(item.numOfOvtHours)).toString() : (parseInt(item.baseSalary) + 50000 * parseInt(item.numOfErrors)).toString())}</th> <th> <div className="d-flex mr-0"> <button className="btn btn-primary " onClick={() => handleOpenEdit(item)} style={{ marginRight: '12px' }} >Edit</button> <button className="btn btn-danger" onClick={() => handleDelete(item)} >Delete</button> </div> </th> </tr> ); }) } </tbody> </table> </div> <Modal visible={addEmployee} setModal={setAddEmployee}> <div className="container " style={{ width: '45vw', height: 'fit-content', backgroundColor: 'white', padding: '20px' }}> <h2 className="text-center">Add Employee </h2> <div className="container mt-4 " style={{ width: '100%' }}> <form ref={formAdd}> <div className="form-group d-flex " > <div style={{ width: '260px', height: '260px', border: '1px solid #ccc', marginRight: '16px' }}> <img src={data.avatar} alt="avt" style={{ width: '258px', height: '258px', border: '1px solid #ccc' }} /> {errInput.file && <p style={{ color: 'red', fontSize: '14px', marginTop:'2px' }}>{errInput.file}</p>} </div> <div style={{ display: 'flex', marginRight: '60px', marginLeft: '10px', flexDirection:'column-reverse' }}> <label htmlFor="file" style={{ backgroundColor: 'rgb(87, 243, 69)', height: '30px', width: '30px', borderRadius: '12px', color: 'black', alignContent: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center' }}><MdFileOpen /></label> <input type="file" style={{ display: 'none' }} rules='imgRequired' id="file" name="file" onChange={handleImageChange}></input> </div> <div className="form-group w-75 " > <label>Employee Name</label> <input type="text" name="name" className="form-control" value={data.name} rules="required" onChange={handleChange} /> {errInput.name && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.name}</p>} <label>Phone</label> <input type="text" name="phone" className="form-control" value={data.phone} rules="required" onChange={handleChange} /> {errInput.phone && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.phone}</p>} <label>Dob</label> <input type="datetime-local" name="dob" className="form-control" value={data.dob} rules="required" onChange={handleChange} /> {errInput.dob && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.dob}</p>} </div> </div> <div className="form-group d-flex mt-4"> <div className="w-50 " style={{ marginRight: '20px' }}> <label>Email</label> <input type="email" name="email" className="form-control" value={data.email} rules="required" onChange={handleChange} /> {errInput.email && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.email}</p>} </div> <div className="w-50"> <label>Base salary</label> <input type="number" name="baseSalary" className="form-control" value={data.baseSalary} rules="required" onChange={handleChange} /> {errInput.baseSalary && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.baseSalary}</p>} </div> </div> <div className="form-group d-flex mt-4"> <div className="w-50 " style={{ marginRight: '20px', display: 'flex', flexDirection: 'column' }}> <label>Role</label> <select value={data.role} className="form-select" name="role" onChange={handleChange} > <option value="tester" >Tester</option> <option value="coder">Coder</option> </select> </div> {data.role === 'coder' ? <div className="w-50"> <label>Over time hour</label> <input type="number" className="form-control" name="numOfOvtHours" value={data.numOfOvtHours} onChange={handleChange} /> </div> : <div className="w-50"> <label>Errors number</label> <input type="number" className="form-control" name="numOfErrors" value={data.numOfErrors} onChange={handleChange} /> </div>} </div> <div className="d-flex flex-row-reverse"> <button className="btn btn-primary mt-4" onClick={handleAdd}>Add</button> </div> </form> </div> </div> </Modal> <Modal visible={isUpdate} setModal={setIsUpdate}> <div className="container " style={{ width: '45vw', height: 'fit-content', backgroundColor: 'white', padding: '16px' }}> <h2 className="text-center">Edit Employee </h2> <div className="container mt-4 " style={{ width: '100%' }}> <form ref={formEdit}> <div className="form-group d-flex " > <div style={{ width: '260px', height: '260px', border: '1px solid #ccc', marginRight: '16px' }}> <img src={data.avatar.includes('data:image') ? data.avatar : `http://localhost:8088/api/employees/images/${data.avatar}`} alt="avt" style={{ width: '258px', height: '258px', border: '1px solid #ccc' }} /> {errInput.file && <p style={{ color: 'red', fontSize: '14px', marginTop:'2px' }}>{errInput.file}</p>} </div> <div style={{ display: 'flex', flexDirection: 'column-reverse', marginRight: '60px', marginLeft: '10px' }}> <label htmlFor="file" style={{ backgroundColor: 'rgb(87, 243, 69)', height: '30px', width: '30px', borderRadius: '12px', color: 'black', alignContent: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center' }}><MdFileOpen /></label> <input type="file" style={{ display: 'none' }} id="file" onChange={handleImageChange}></input> </div> <div className="form-group w-75" > <label>Employee Name</label> <input type="text" name="name" className="form-control" value={data.name} rules="required" onChange={handleChange} /> {errInput.name && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.name}</p>} <label>Phone</label> <input type="text" name="phone" className="form-control" value={data.phone} rules="required" onChange={handleChange} /> {errInput.phone && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.phone}</p>} <label>Dob</label> <input type="datetime-local" name="dob" className="form-control" value={data.dob} rules="required" onChange={handleChange} /> {errInput.dob && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.dob}</p>} </div> </div> <div className="form-group d-flex mt-4"> <div className="w-50 " style={{ marginRight: '20px' }}> <label>Email</label> <input type="email" name="email" className="form-control" value={data.email} rules="required" onChange={handleChange} /> {errInput.email && <p style={{ color: 'red', fontSize: '14px' }}>{errInput.email}</p>} </div> <div className="w-50"> <label>Base salary</label> <input type="number" name="baseSalary" className="form-control" value={data.baseSalary} rules="required" onChange={handleChange} /> </div> </div> <div className="form-group d-flex mt-4"> <div className="w-50 " style={{ marginRight: '20px', display: 'flex', flexDirection: 'column' }}> <label>Role</label> <select value={data.role} className="form-select" name="role" onChange={handleChange} > <option value="tester" >Tester</option> <option value="coder">Coder</option> </select> </div> {data.role === 'coder' ? <div className="w-50"> <label>Over time hour</label> <input type="number" className="form-control" name="numOfOvtHours" value={data.numOfOvtHours} onChange={handleChange} /> </div> : <div className="w-50"> <label>Errors number</label> <input type="number" className="form-control" name="numOfErrors" value={data.numOfErrors} onChange={handleChange} /> </div>} </div> <div className="d-flex flex-row-reverse"> <button className="btn btn-primary mt-4" onClick={(e) => handleUpdate(e)}>Update</button> </div> </form> </div> </div> </Modal> <ToastContainer position="top-right" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover /> </div> ); } export default ListEmployeeComponent;
<?php namespace App\Http\Controllers\admin; use App\Http\Controllers\Controller; use App\Models\Category; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Str; use Illuminate\Http\Request; class AdminCategoryController extends Controller { /** * Display a listing of the resource. */ public function index() { $categories = Category::latest()->get(); return view("admin.category.index", compact("categories")); } /** * Show the form for creating a new resource. */ /** * Store a newly created resource in storage. */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required|max:255', 'description' => 'required', ]); $request["slug"] = Str::slug($request["name"]); $validator->validate(); Category::create($request->all()); // Eğer product başarıyla oluşturulduysa, isteği uygun şekilde işleyebilirsiniz $notification = array( "message" => "kategori başarıyla oluşturuldu.", "alert-type" => "success" ); return redirect()->route('categories.index')->with($notification); } /** * Display the specified resource. */ // public function show(Category $category) // { // } /** * Show the form for editing the specified resource. */ public function edit(Category $category) { return view('admin.category.edit', compact('category')); } /** * Update the specified resource in storage. */ public function update(Request $request, Category $category) { $request->validate([ 'name' => 'required|string|max:255', "description" => 'required|string|max:255', ]); $category->update($request->all()); $notification = array( "message" => "Kategori başarıyla güncellendi.", "alert-type" => "success" ); return redirect()->route('categories.index')->with($notification); } /** * Remove the specified resource from storage. */ public function destroy(Category $category) { if (!$category) { return redirect()->route('categories.index') ->with('error', 'kategori bulunamadı'); } $category->delete(); $notification = array( "message" => "Kategori başarıyla silindi.", "alert-type" => "success" ); return redirect()->route('categories.index')->with($notification); } }
package com.springshortpath.app; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.neo4j.driver.Driver; import org.neo4j.driver.Record; import org.neo4j.driver.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.servlet.MockMvc; import org.testcontainers.containers.Neo4jContainer; import org.testcontainers.containers.Neo4jLabsPlugin; import java.util.List; import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @AutoConfigureWebTestClient public class ApplicationWebTests { static Neo4jContainer<?> container = new Neo4jContainer<>("neo4j:4.3-community").withLabsPlugins(Neo4jLabsPlugin.APOC); @Autowired private MockMvc mockMvc; @Autowired private WebTestClient webTestClient; @Autowired private Driver driver; private final UUID cityId1 = UUID.randomUUID(); private final UUID cityId2 = UUID.randomUUID(); private final UUID routeId = UUID.randomUUID(); @BeforeAll static void startContainer() { container.start(); } @DynamicPropertySource static void properties(DynamicPropertyRegistry registry) { registry.add("spring.neo4j.authentication.username", () -> "neo4j"); registry.add("spring.neo4j.authentication.password", () -> container.getAdminPassword()); registry.add("spring.neo4j.uri", () -> container.getBoltUrl()); } @BeforeEach void setupData() { try (Session session = driver.session()) { session.run("MATCH (n) detach delete n").consume(); session.run("CREATE (:City{id:$cityId1, name:'Istanbul'})" + "-[:ROUTES]->(:Route{id:$routeId,from:'Istanbul', destination:'Ankara', duration: 2}) " + "-[:ROUTES]->(:City{id:$cityId2, name:'Ankara'})", Map.of("cityId1", cityId1.toString(), "cityId2", cityId2.toString(), "routeId", routeId.toString())) .consume(); } } @Test void listCities() throws Exception { mockMvc.perform(get("/api/v1/city/cities").accept("application/json")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$[0]['name']").value("Istanbul")) .andExpect(jsonPath("$[1]['name']").value("Ankara")); } @Test void cityById() throws Exception { mockMvc.perform(get("/api/v1/city/id/" + cityId1).accept("application/json")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Istanbul")); // ensure optional match works and returns a city without a route relationship mockMvc.perform(get("/api/v1/city/id/" + cityId2).accept("application/json")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Ankara")); } @Test void cityByName() throws Exception { mockMvc.perform(get("/api/v1/city/name/Istanbul").accept("application/json")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("Istanbul")); } @Test void listRoutesByCity() throws Exception { mockMvc.perform(get("/api/v1/route/" + cityId1 + "/routes").accept("application/json")) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$[0]['from']").value("Istanbul")) .andExpect(jsonPath("$[0]['destination']").value("Ankara")); } @Test void addRoute() throws Exception { mockMvc.perform(post("/api/v1/route/" + cityId1 + "/" + cityId2 + "/create-route") .contentType("application/json") .content("{\"from\" : \"Istanbul\", \"destination\" : \"Ankara\", \"departureTime\" : \"9:00\", \"arriveTime\" : \"11:00\"}") .accept("application/json")) .andDo(print()) .andExpect(status().isCreated()) .andExpect(jsonPath("$.from").value("Istanbul")) .andExpect(jsonPath("$.destination").value("Ankara")); try (Session session = driver.session()) { List<Record> records = session.run("MATCH (c:City) return c.name as cityName").list(); assertThat(records).hasSize(2); assertThat(records).map(record -> record.get("cityName").asString()) .containsExactlyInAnyOrder("Ankara", "Istanbul"); } } @Test void deleteRoute() throws Exception { mockMvc.perform(delete("/api/v1/route/" + cityId1 + "/delete-route/" + routeId) .accept("application/json")) .andDo(print()) .andExpect(status().isOk()); try (Session session = driver.session()) { long routeCount = session.run("MATCH (r:ROUTE) return count(r) as routeCount").single().get("routeCount").asLong(); assertThat(routeCount).isEqualTo(0L); } } @Test void shortestPath() throws Exception { webTestClient.method(HttpMethod.GET).uri("/api/v1/shortestpath/shortest-path") .accept(MediaType.APPLICATION_JSON) .bodyValue("{\"from\":\"Istanbul\", \"destination\":\"Ankara\"}") .header("content-type", "application/json") .exchange() .expectStatus().isOk() .expectBody() .json("{\"departureCity\":\"Istanbul\",\"arrivalCity\":\"Ankara\",\"totalConnections\":1}"); } @Test void shortestPathInTime() throws Exception { webTestClient.method(HttpMethod.GET).uri("/api/v1/shortestpath/shortest-path-in-time") .accept(MediaType.APPLICATION_JSON) .bodyValue("{\"from\":\"Istanbul\", \"destination\":\"Ankara\"}") .header("content-type", "application/json") .exchange() .expectStatus().isOk() .expectBody() .json("{\"departureCity\":\"Istanbul\",\"arrivalCity\":\"Ankara\",\"totalInTime\":2}"); } @AfterAll static void tearDownContainer() { container.stop(); } }
import {Injectable} from "@angular/core"; import {environment} from "../../../environments/environment"; import {HttpClient} from "@angular/common/http"; import {User} from "../entity/user"; import {Observable} from "rxjs"; import {AuthenticationResponse} from "../entity/authentication-response"; import {ACCESS_TOKEN, LocalStorageManagerService} from "./local-storage-manager.service"; import {AuthRequest} from "../entity/auth-request"; import {RegisterRequest} from "../entity/register-request"; @Injectable({ providedIn: 'root' }) export class AuthService { private readonly URL: string = environment.apiUrl + '/auth' constructor(private http: HttpClient, private localStorageService: LocalStorageManagerService) { } authenticate(authRequest: AuthRequest): Observable<AuthenticationResponse> { return this.http.post<AuthenticationResponse>(this.URL + '/authenticate', authRequest) } register(registerRequest: RegisterRequest): Observable<AuthenticationResponse> { return this.http.post<AuthenticationResponse>(this.URL + '/register', registerRequest); } logout(): void { this.localStorageService.removeFromStorage(ACCESS_TOKEN) } get accessToken(): string { return this.localStorageService.getFromStorage(ACCESS_TOKEN) } set accessToken(accessToken: string) { this.localStorageService.addToStorage(ACCESS_TOKEN, accessToken) } }
import { defineStore } from "pinia"; import { cloneDeep } from "lodash"; import { getMongodbBase } from "qqlx-cdk"; import { PATH_BRAND_WAREHOUSE } from "qqlx-core"; import type { postWarehouseDto, postWarehouseRes, getWarehouseDto, getWarehouseRes, patchWarehouseDto, patchWarehouseRes, Warehouse } from "qqlx-core"; import { request } from "@/lib"; import { useNotifyStore } from "@/stores/quasar/notify"; const NotifyStore = useNotifyStore(); function getSchema(): Warehouse { return { corpId: "", name: "", address: "", isDisabled: false, ...getMongodbBase(), }; } export const useWarehouseStore = defineStore("Warehouse", { state: () => ({ picked: getSchema(), editor: getSchema(), list: [] as Warehouse[], }), actions: { async get() { const dto: getWarehouseDto = null; const res: getWarehouseRes = await request.get(PATH_BRAND_WAREHOUSE); this.list = res; }, /** @viewcatch */ async post() { try { const dto: postWarehouseDto = this.editor; const res: postWarehouseRes = await request.post(PATH_BRAND_WAREHOUSE, { dto }); await this.get(); NotifyStore.success("添加成功"); } catch (error) { NotifyStore.fail((error as Error).message); } }, /** @viewcatch */ async patch() { try { const dto: patchWarehouseDto = this.editor; const res: patchWarehouseRes = await request.patch(PATH_BRAND_WAREHOUSE, { dto }); await this.get(); NotifyStore.success("修改成功"); } catch (error) { NotifyStore.fail((error as Error).message); } }, pick(house?: Warehouse) { if (!house) return; this.picked = cloneDeep(house); NotifyStore.success(`正在使用 @${this.picked.name}`); }, getSchema() { const schema: Warehouse = getSchema(); return schema; }, setEditor(target?: Warehouse) { const schema = target ? cloneDeep(target) : this.getSchema(); this.editor = schema; }, }, });
import { all, call, put, takeLatest } from "typed-redux-saga/macro"; import { getLexicaArt } from "../../utils/lexica/lexica.utils"; import { fetchCategoriesFail, fetchCategoriesSuccess, } from "./categories.action"; import { CATEGORIES_ACTION_TYPES } from "./categories.types"; export function* fetchCategoriesAsync() { try { const categoriesArray = yield* call(getLexicaArt); yield* put(fetchCategoriesSuccess(categoriesArray)); } catch (error) { yield* put(fetchCategoriesFail(error as Error)); } } export function* onFetchCategories() { yield* takeLatest( CATEGORIES_ACTION_TYPES.FETCH_CATEGORIES_START, fetchCategoriesAsync ); } export function* categoriesSaga() { yield* all([call(onFetchCategories)]); }
PlayerMoveState = Class{__includes = EntityMoveState} function PlayerMoveState:init(player) self.entity = player -- render offset for spaced character sprite; negated in render function of state self.entity.offsetY = 0 self.entity.offsetX = 0 self.entity:changeAnimation('move-left') end function PlayerMoveState:update(dt) if love.keyboard.isDown('a') or love.keyboard.isDown('left') then self.entity:changeAnimation('move-left') self.entity.dx = -self.entity.moveSpeed elseif love.keyboard.isDown('d') or love.keyboard.isDown('right') then self.entity:changeAnimation('move-right') self.entity.dx = self.entity.moveSpeed elseif love.keyboard.isDown('w') or love.keyboard.isDown('up') then self.entity:changeAnimation('turn-up') self.entity.dy = -self.entity.moveSpeed elseif love.keyboard.isDown('s') or love.keyboard.isDown('down') then self.entity:changeAnimation('turn-down') self.entity.dy = self.entity.moveSpeed else self.entity:changeState('idle') self.entity.dy = 0 self.entity.dx = 0 end -- perform base collision detection against walls EntityMoveState.update(self, dt) if self.entity.dy < 0 then self.entity.y = math.max(-self.entity.offsetY, self.entity.y + self.entity.dy * dt) else self.entity.y = math.min(VIRTUAL_HEIGHT - self.entity.height + self.entity.offsetY, self.entity.y + self.entity.dy * dt) end if self.entity.dx < 0 then self.entity.x = math.max(-self.entity.offsetX, self.entity.x + self.entity.dx * dt) else self.entity.x = math.min(VIRTUAL_WIDTH - self.entity.width + self.entity.offsetX, self.entity.x + self.entity.dx * dt) end if self.entity.remove then self.entity:changeAnimation('destroy') end end function PlayerMoveState:render() local anim = self.entity.currentAnimation love.graphics.draw(gTextures[anim.texture], gFrames[anim.texture][anim:getCurrentFrame()], math.floor(self.entity.x - self.entity.offsetX), math.floor(self.entity.y - self.entity.offsetY), 0, 96 / 192, 96 / 192) end
<!doctype html> <html> <!-- v-model其實是一個語法糖,他的背後本質上是包含兩個操作:v-bind綁定一個value屬性 跟 v-on指令給當前元素綁定的input事件 (v-model參考影片: https://www.bilibili.com/video/BV15741177Eh?p=46&spm_id_from=pageDriver ) --> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/vue.js"></script> </head> <body> <div id="app"> <!-- 往後端提交的時後,都是以name屬性為key往後傳!!!可參下影片第三分鐘 https://www.bilibili.com/video/BV15741177Eh?p=47&spm_id_from=pageDriver --> <!-- 前端的value會傳值給下面data中的sex值,他們之間用v-model做關連,而name的sex則是送後端時的關連 --> <label for="male"> <input type="radio" id="male" name="sex" value="男" v-model="sex">男 </label> <label for="male"> <input type="radio" id="female" name="sex" value="女" v-model="sex">女 </label> <h2>選擇的性別是:{{sex}}</h2> </div> <!-- v-on 監聽,其實可以直接用 @ 取代…就是個語法糖--> <!-- v-bond 綁定,可以用: --> <script> const app = new Vue({ el: '#app', data: { message: '你好阿', sex:'' } }) </script> </body> </html>
/** * The MIT License (MIT) * * Copyright (C) 2022 Mauricio Ventura Pérez. * * 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 Foundation import SwiftyXMLParser class NibColorResourceEditor { let fm = FileManager.default var catalog: [String: String] = [:] var editedColors = 0 var editedFiles = 0 var errors = [String]() @discardableResult init(sourcePath: String, xibCatalogPath: String) { catalog = createCatalog(xibCatalogPath: xibCatalogPath) guard !catalog.isEmpty else { let error = "Couldn't create catalog from path: \(xibCatalogPath)" errors.append(error) print(error) return } iterateOverPath(sourcePath) print("\(editedColors) were updated in \(editedFiles) files") guard !errors.isEmpty else { print("No errors found") return } print("ERRORS:") errors.forEach { print($0) } } func createCatalog(xibCatalogPath: String) -> [String: String] { guard let data = fm.contents(atPath: xibCatalogPath) else { return [:] } let xml = XML.parse(data) var colorsCatalog = [String: String]() xml["document", "resources", "namedColor"].forEach { guard let colorName = $0.attributes["name"], let colorString = $0.colorString else { return } print("String for new color \(colorName) was created") colorsCatalog[colorName] = colorString } return colorsCatalog } func iterateOverPath(_ path: String) { let items = readContentsOfFolder(path) items.forEach { let currentPath = path + "/\($0)" if $0.contains(".storyboard") || $0.contains(".xib") { editXib(path: currentPath) } else if !$0.contains(".") { iterateOverPath(currentPath) } } } func readContentsOfFolder(_ folder: String) -> [String] { do { return try fm.contentsOfDirectory(atPath: folder) } catch { errors.append(error.localizedDescription) print(error) return [String]() } } func editXib(path: String) { let data = fm.contents(atPath: path)! var xibString = String(decoding: data, as: UTF8.self) let xml = XML.parse(data) let resources = xml["document", "resources"] var colorsCount = 0 resources["namedColor"].forEach { guard let colorName = $0.attributes["name"], let oldColorString = $0.colorString else { return } guard let catalogColor = catalog[colorName] else { let error = "Couldn't find \(colorName) in catalog" errors.append(error) print(error) return } xibString = xibString.replacingOccurrences(of: oldColorString, with: catalogColor) print(" Color \(colorName) was modified") colorsCount += 1 } do { try fm.removeItem(atPath: path) try xibString.write(toFile: path, atomically: false, encoding: .utf8) if colorsCount > 0 { editedColors += colorsCount editedFiles += 1 } } catch { errors.append(error.localizedDescription) print(error) } } }
class MoviesController < ApplicationController before_action :set_movie, only: [:show, :edit, :update] def index @movies = Movie.all end def show end def new @movie = Movie.new end def create @movie = Movie.new(movie_params) if @movie.save redirect_to movie_path(@movie), notice: 'Movie was successfully created.' else render :new end end def edit end def update if @movie.update(movie_params) redirect_to movie_path(@movie), notice: 'Movie was successfully updated.' else render :edit end end private def set_movie @movie = Movie.find(params[:id]) end def movie_params params.require(:movie).permit(:title, :overview, :poster_url, :rating) end end
package es.progcipfpbatoi.controlador; import javafx.event.Event; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.io.IOException; public class ChangeScene { /** * Cambia de escena a partir de un stage (una ventana ya existente) * @param stage * @param controller * @param path_to_view_file * @throws IOException */ public static void change(Stage stage, Initializable controller, String path_to_view_file) throws IOException{ FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(ChangeScene.class.getResource(path_to_view_file)); fxmlLoader.setController(controller); AnchorPane rootLayout = fxmlLoader.load(); Scene scene = new Scene(rootLayout); stage.setScene(scene); stage.setResizable(true); stage.show(); } /** * Cambia de escena a partir de un evento del cual se puede obtener el stage * @param event * @param controller * @param path_to_view_file * @throws IOException */ public static void change(Event event, Initializable controller, String path_to_view_file) throws IOException{ Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); change(stage, controller, path_to_view_file); } }
import React, { useCallback, useContext, useMemo } from "react" import { dataContext } from "../app/dataContext" import { ongletContext } from "../app/ongletContext" import { TrashBTN } from "../trashBTN/trashBTN" export const Onglet = function({value=undefined, index, children='', onClick=undefined}) { const [currentOnglet, setCurrentOnglet] = useContext(ongletContext) const [data, setData] = useContext(dataContext) currentClass = useMemo(() => {4 return !(index == currentOnglet) ? "hover:bg-gray-700" : "bg-violet-400 bg-opacity-60" }) const handleClicks = useCallback((event) => { onClick != undefined ? onClick(index) : null }) const handleDeletes = useCallback((event) => { const newData = [...data] newData.splice(index, 1) currentOnglet >= index ? setCurrentOnglet(index-1) : null setData(() => { return newData }) }) return ( <div className={` ${currentClass} cursor-pointer hoverspanspawn w-full flex justify-between rounded-md text-left overflow-hidden text-gray-300`}> <a onClick={handleClicks} className=" px-2 py-1 w-full whitespace-nowrap overflow-hidden overflow-ellipsis">{value == undefined ? children : value}</a> <span className=" opacity-0 hover:opacity-100"> <TrashBTN className="pr-2 w-full" onClick={handleDeletes}></TrashBTN> </span> </div> ) }
import 'dart:math'; import 'package:flutter/material.dart'; import '../../../Helper/Colors/custom_color.dart'; import '../../../Helper/TextController/BuildText/BuildText.dart'; import '../../StringDefine/StringDefine.dart'; class PateintListWidget extends StatefulWidget { PateintListWidget({super.key, required this.context, required this.firstName, required this.address, required this.middleName, required this.lastName, required this.dob, required this.onTap}); BuildContext? context; String? firstName; String? middleName; String? lastName; String? dob; String? address; VoidCallback? onTap; @override State<PateintListWidget> createState() => _PateintListWidgetState(); } class _PateintListWidgetState extends State<PateintListWidget> { @override Widget build(BuildContext context) { return InkWell( onTap: widget.onTap, child: Padding( padding: const EdgeInsets.only(top: 1, bottom: 0, left: 3, right: 3), child: Card( color: Colors.primaries[Random().nextInt(Colors.primaries.length)].shade100, child: Padding( padding: const EdgeInsets.all(8), child: Column( children: [ Padding( padding: const EdgeInsets.all(4), child: Row( children: [ BuildText.buildText(text: "$kName :", size: 14, color: AppColors.greyColor,), Flexible( child: RichText( text: TextSpan( style: TextStyle(fontSize: 14.0,color: AppColors.blackColor,), children: [ TextSpan(text: widget.firstName,style: const TextStyle(fontSize: 14,color: Colors.black),), TextSpan(text: widget.middleName,style: const TextStyle(fontSize: 14,color: Colors.black)), TextSpan(text: widget.lastName,style: const TextStyle(fontSize: 14,color: Colors.black)), ], ), ), ) ], ), ), Padding( padding: const EdgeInsets.all(4), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ BuildText.buildText( text: "$kAddress :", size: 14, color: AppColors.greyColor), Expanded( child: Row( children: [ Flexible( child: BuildText.buildText( text: widget.address!, textAlign: TextAlign.left), ), // if (list != null && list.isNotEmpty && list[index]['alt_address'] != null && list[index]['alt_address'] != "" && list[index]['alt_address'].toString() == "t") Image.asset( strIMG_AltAdd, height: 18, width: 18, ), ], ), ), ], ), ), Padding( padding: const EdgeInsets.all(4), child: Row( children: [ BuildText.buildText( text: kDOB, size: 14, color: AppColors.greyColor, ), BuildText.buildText( text: widget.dob!, size: 14, color: AppColors.blackColor, ), ], ), ), ], ), ), ), ), ); } }
:-['SentenceToListOfLettersOrWords.pl']. /*-------------------------------------------------------------- SPELL CHECKER HELP FILE --------------------------------------------------------------*/ /*-------------------------------------------------------------- spell_check/0 reads a sentence from the keyboard and transforms it into a list (words) of lists (letters for each word). --------------------------------------------------------------*/ spell_check(Sentence):- string_to_listofwords(Sentence,ListofWords), write(ListofWords),nl, check(ListofWords),!. /*-------------------------------------------------------------- check/1 calls check_word in order to check spelling for each word in a sentence. --------------------------------------------------------------*/ check([]). check([WordLetters|Rest]):- check_word(WordLetters), check(Rest). /*-------------------------------------------------------------- check_word/1 checks various types of errors in a word and prints out the appropriate message. --------------------------------------------------------------*/ check_word(WL):- missing_letter(WL,X), % as defined in Lab 6.6 wordtolist(W,WL), writelist([W,' has a missing letter ', X,nl]). /*-------------------------------------------------------------- Put the rest of the errors here --------------------------------------------------------------*/ % missing_letter(WL,X):- ... /*-------------------------------------------------------------- Converts a word (atom) to a list of letters and vice-versa. ?- wordtolist(prolog, WordLetters). WordLetters = [p,r,o,l,o,g] ?- wordtolist(Word, [p,r,o,l,o,g]). Word = prolog --------------------------------------------------------------*/ wordtolist(W,L):- var(W),!, ltow(W,L). wordtolist(W,L):- var(L),!, wtol(W,L). wtol(W,L):- name(W,ASCII),asciitoletter(ASCII,L). ltow(W,L):- asciitoletter(ASCII,L), name(W,ASCII). asciitoletter([],[]). asciitoletter([ASCIIH|ASCIIT],[H|T]):- name(H,[ASCIIH]),!, asciitoletter(ASCIIT,T).
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePaymentReceiptsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('payment_receipts', function (Blueprint $table) { $table->id(); $table->string('url'); $table->string('paymentReceiptStatus')->nullable(); $table->bigInteger('payment_id')->unsigned()->nullable(); $table->foreign('payment_id')->references('id')->on('payments')->onUpdate('cascade')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('payment_receipts'); } }
import {Component, ElementRef, EventEmitter, HostListener, OnInit, Output} from '@angular/core'; import {distinctUntilChanged, filter, map, pairwise, share, throttleTime} from 'rxjs/operators'; enum HeaderPosition { Top = 'Top', Sticky = 'Sticky' } export interface ScrollEvent { isReachingTop: boolean; originalEvent: Event; currentY: number; } const STICKY_TRIGGER_POSITION = 40; @Component({ selector: 'app-top-toolbar', templateUrl: './top-tool-bar.component.html', styleUrls: ['./top-tool-bar.component.scss'] }) export class TopToolBarComponent implements OnInit { @Output() onMenuIconClick: EventEmitter<any> = new EventEmitter<any>(); @Output() public onScroll = new EventEmitter<ScrollEvent>(); public headerFixed = false; public showBackToTop = false; constructor(private el: ElementRef) { } ngOnInit() { this.bindScrollEvent(); } // handle window scroll @HostListener('window:scroll') onWindowScroll($event: Event) { const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; (scrollTop > 300) ? this.showBackToTop = true : this.showBackToTop = false; const isReachingTop = scrollTop < this.el.nativeElement.offsetHeight; this.onScroll.emit({isReachingTop, originalEvent: $event, currentY: scrollTop}); } public sidenavToggle() { this.onMenuIconClick.emit(); } private bindScrollEvent() { // Capture scroll event const scroll$ = this.onScroll.pipe( throttleTime(10), map((event: ScrollEvent) => event.currentY), pairwise(), map(([y1, y2]): HeaderPosition => (y2 < STICKY_TRIGGER_POSITION ? HeaderPosition.Top : HeaderPosition.Sticky)), distinctUntilChanged(), share() ); const positionTop = scroll$.pipe( filter(direction => direction === HeaderPosition.Top) ); const positionSticky = scroll$.pipe( filter(direction => direction === HeaderPosition.Sticky) ); positionTop.subscribe(() => (this.headerFixed = false)); positionSticky.subscribe(() => (this.headerFixed = true)); } }
# Write-Up 404-CTF : De l'inversion __Catégorie :__ Algorithmique quantique - Difficile **Enoncé :** ![Enoncé](images/enonce.png) _Disclaimer_ : J'ai principalement résolu ce challenge à l'instinct et je m'excuse d'avance de ne pas pouvoir fournir une explication détaillée de pourquoi ça marche. Une solution plus détaillée devrait être disponible prochainement sur le [GitHub du club Hackademint](https://github.com/HackademINT/404CTF-2024). Je me permets néanmoins de vous présenter mon intuition. **Résolution :** Ce challenge a la même structure que le précédent. Nous devons compléter des circuits et envoyer les solutions au serveur pour obtenir le flag. **Etape 1 :** ![Image1](images/image1.png) Ma première idée est tout d'abord de créer un circuit faisant l'inverse du circuit qui nous est proposé, pour arriver à l'identité, et ensuite ajouter mes transformations pour arriver à l'état demandé. Cela colle bien avec un challenge intitulé "De l'inversion". Malheureusement, le circuit n'est que sur le second qubit, nous ne pouvons pas tout inverser. Je décide donc d'inverser au moins la première porte Rx pour voir ce que ça donne. ```python step_one = Circuit(2, "S1") step_one.add(0, RX(gamma)) ``` ![Image2](images/image2.png) Il semblerait que nous ayons annulé certaines choses en effet. L'état final est moins éparpillé entre différentes valeurs. Ma prochaine idée est de tester l'ajout d'une porte Rx(pi) sur le rail 1 puisqu'elle nous permet, dans un circuit composé uniquement de cette porte, de passer d'un état |1,0,1,0> (l'état initial) à l'état |1,0,0,1> (état désiré). ```python step_one = Circuit(2, "S1") step_one.add(0, RX(gamma)) step_one.add(0, RX(pi)) ``` ![Image3](images/image3.png) ... Bon ben ça a marché ! Au suivant ! **Etape 2 :** ![Image4](images/image4.png) Nous sommes positionné cette fois à la fin du circuit. Même approche qu'avant en tentant d'inverser les portes présentes au début du circuit, le second qubit. On voit deux portes, un Ry(theta) et un circuit HP qui s'avère être une porte d'Hadamard ainsi qu'un phase shifter de -pi/2. On va donc inverser l'effet de ces portes dans l'ordre inverse de leur apparition. ```python step_two = Circuit(2, "S2") step_two.add(0, RY(-theta)) step_two.add(0, PS(pi/2)) step_two.add(0, H) ``` ![Image5](images/image5.png) Et bien....... plutôt inattendu que ça marche aussi vite mais vraiment content, à croire que c'était la solution attendu 😀 **Flag :** `404CTF{It'S_4ll_JuPiT3r__alWaYs_H4s_bE3n}` ![Image6](images/image6.png)
import { Rule, Security } from "@/lib/types" export interface ProductRulesProps { rules: Rule[] securities: Security[] cancellationPolicy: string } const ProductRules: React.FC<ProductRulesProps> = ({ rules, securities, cancellationPolicy }) => { return ( <section className="pt-6 px-8 space-y-4"> <h3 className="text-xl font-bold border-b pb-2">Things to know</h3> <div className="flex w-full justify-between flex-wrap gap-6"> <div> <h5 className="font-semibold mb-3">House rules</h5> <ul className="text-sm space-y-2"> { rules.map(rule => ( <li key={rule.id}>{rule.description}</li> )) } </ul> </div> <div> <h5 className="font-semibold mb-3">Safety & property</h5> <ul className="text-sm space-y-2"> { securities.map(security => ( <li key={security.id}>{security.description}</li> )) } </ul> </div> <div> <h5 className="font-semibold mb-3">Cancellation policy</h5> <p className="text-sm">{cancellationPolicy}</p> </div> </div> </section> ) } export default ProductRules
//! use crate::node::NodeIdx; pub type Result<T> = std::result::Result<T, Error>; #[derive( Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde_derive::Deserialize, serde_derive::Serialize, displaydoc::Display, thiserror::Error, )] pub enum Error { /// I/O error: {0} Io(ioe::IoError), /// GraphViz generation error: {0} GraphvizParse(String), /// An error originating in a Gss instance: {0:?} GssError(#[from] crate::gss::Error), /// Detected a cycle: {path:?} CycleDetected { path: Vec<NodeIdx> }, /// Expected Node {0} to be a branch node ExpectedBranchNode(NodeIdx), /// Expected Node {0} to be a leaf node ExpectedLeafNode(NodeIdx), /// Expected Node {0} to be a root node ExpectedRootNode(NodeIdx), /// Expected `tree[node_idx]` to have `tree[parent_idx]` as a parent node ParentNotFound { node_idx: NodeIdx, parent_idx: Option<NodeIdx> }, /// Expected `tree[node_idx]` to have `tree[child_idx]` as a child node ChildNotFound { node_idx: NodeIdx, child_idx: NodeIdx }, /// No node found with NodeIdx `{0}` NodeNotFound(NodeIdx) } impl From<std::io::Error> for Error { fn from(err: std::io::Error) -> Self { Self::Io(ioe::IoError::from(err)) } }
#ifndef _STRUCTS_H_ #define _STRUCTS_H_ #define SIZEOF_FLOW_TABLE 30 /** 17 bytes * 30 = 510 bytes */ #define SIZEOF_ACTION_TABLE 20 /** 18 bytes * 20 = 360 bytes */ #define SIZEOF_SENSOR_TABLE 5 /** 10 bytes * 5 = 50 bytes */ #define SIZEOF_TIMER_TABLE 5 /** 15 bytes * 5 = 75 bytes */ #define SIZEOF_NEIGHBORS_TABLE 20 /** 2 bytes * 20 = 40 bytes */ /** total = 1015 bytes */ /******************* ** Who is SINK? *******************/ //uint16_t sink; /********************** ** Flow Tables **********************/ /** * @brief Flow Tables Entry for address filter * * */ struct flowAddressEntry { uint16_t sourceAddress; /**< */ uint16_t sourceMask; /**< Address's Mask. Need to make "and" with Address for to match. */ uint16_t destinationAddress; /**< */ uint16_t destinationMask; /**< */ }; /** 8 Bytes */ /** * @brief Values type in comparisons * * */ enum dataType_t { INT_8, /**< */ INT_8_2, /**< */ INT_16, /**< */ INT_16_2 /**< */ }; /** * @brief Operators type for comparisons * * */ enum operator_t{ NONE, /**< Unused comparisons */ E, /**< */ D, /**< */ GT, /**< */ GTOE, /**< */ LT, /**< */ LTOE, /**< */ GT_A_LT, /**< */ GTOE_A_LT, /**< */ GT_A_LTOE, /**< */ GTOE_A_LTOE /**< */ }; /** * @brief to access values in many ways * * */ struct value_t{ /** * @brief * * */ union{ /** * @brief * * */ struct { uint8_t valueInt8_1; /**< */ uint8_t valueInt8_2; /**< */ }; /** * @brief * * */ struct { uint16_t valueInt16_1; /**< */ uint16_t valueInt16_2; /**< */ }; }; }; /** 4 Bytes */ /** * @brief Flow Tables Entry for sensor measure values filter * * */ struct flowComparationEntry{ uint8_t dataType; /**< Data type to comparison */ uint8_t operatorC; /**< Operator (>, >=, <, <=, > e <, >= e <; >= e <=; > e <=;) */ struct value_t value; /**< Value for comparison */ }; /** 6 Bytes */ /** * @brief General Flow Table Entry * * */ struct flowEntry{ uint8_t flowID; /**< flow identification code */ uint8_t actionID; /**< Action to play for this flow */ unsigned int timeout; /**< When the flowEntry will be drop */ uint8_t counters; /**< Count times the flow was identified */ bool active; /**< Entry active or not */ /** * @brief For access flow entries in two ways. * * */ struct flowComparationEntry fc; /** 6 Bytes */ struct flowAddressEntry fa; /** 8 Bytes */ }; /** 17 Bytes */ //struct flowEntry flowTable[SIZEOF_FLOW_TABLE]; /************************ * * Actions Table * *********************/ /** * @brief Actions * * */ enum action_t{ A_DROP, /**> Discard the package */ A_RESEND_TO, /**> Resend the package to the destination address */ A_SEND_TO_SINK, /**> Send the package to the sink */ A_CHANGE_SINK, /**> Change the sensors sink */ A_ACTIVE_TIMER, /**> Activate a timer */ A_DEACTIVE_TIMER, /**> Deactivate a timer */ A_READ_SENSOR, /**> Read a sensor and send value to sink */ A_READ_SENSOR_AND_SEND_TO, /**> Read a sensor and send value to destination address */ A_SLEEP, /**> Make the sensor sleep */ A_WAKEUP, /**> Make the sensor wake up */ A_REPORT, /**> Send report mensage to controller */ A_RECEIVER_ON, /**> Activate radio receiver */ A_RECEIVER_OFF, /**> Deactivate radio receiver */ A_DISPLAY, /**> Display package Received (for debug)*/ /** Action for agregations fuctions */ A_STORE, /**> Store the value to flash memory */ A_RETRIEVE, /**> Retrieve the value from flash memory */ A_COMPARE, /**> Compare two values and perform action */ A_AVERAGE, /**> Calculates the average of store values */ A_MAX, /**> Find the highest stored value */ A_MIN /**> Find the lowest stored value */ }; /** * @brief Action Table Entry * * */ struct actionEntry{ uint8_t actionID; /**< action identification code */ uint8_t actionType; /**< Action's Type */ bool active; /**< Entry active or not */ uint8_t dataType; /**< Data Type */ uint8_t operatorC; /**< Operator (>, >=, <, <=, > e <, >= e <; >= e <=; > e <=;) */ struct value_t value1; /**< values depends of type of action */ struct value_t value2; struct value_t value3; }; /** 18 Bytes */ //struct actionEntry actionTable[SIZEOF_ACTION_TABLE]; /************************ ** Sensors Table ************************/ /** * @brief Sensor Type * * */ enum sensorType_t{ TEMPERATURE, HUMIDITY, PRESENCE, FLOW, LUMINANCE, HALL, FLAME, BATTERY }; /** * @brief Unit of measurement * * */ enum unit_t{ CELSIUS, PERCENT, ONOFF, GPM, /** for flow rate */ LUMENS, MVG, /** for HALL sensors */ VOLTS }; /** * @brief Interface Type between Arduino and Sensor * */ enum interfaceType_t{ DIGITAL, /**> Digital Interface (number 1 is interface ID) */ ANALOGIC, /**> Analogical Interface (number 1 is interface ID) */ SPI, /**> SPI Interface (number 1 and 2 is interface ID) */ I2C, /**> I2C Interface (number 1 and 2 is interface ID) */ SERIAL /**> Serial Interface (number 1 and 2 is interface ID) */ }; /** * @brief Sensors Table Entry * * */ struct sensorEntry{ uint8_t sensorID; /**< Sensor identification code */ uint8_t sensorType; /**< Sensor's Type */ uint8_t unit; /**< Unit of Measurement */ uint8_t dataType; /**< Data Type of measurement */ uint8_t interfaceType; /**< Interface Type */ uint8_t interfaceNumber1; /**< Interface Number 1*/ uint8_t interfaceNumber2; /**< Interface Number 1*/ bool active; /**< Entry active or not */ }; /** 10 Bytes */ //struct sensorEntry sensorTable[SIZEOF_SENSOR_TABLE]; /** * @brief Timers Table * * */ struct timerEntry{ uint8_t timerID; /**< Timer identification code */ uint8_t actionID; /**< action to execute */ double t0; /**< time zero */ double time; /**< time to execute action */ uint8_t repeat; /**< number of repetitions 255 indefinitely */ uint8_t multiply; /**< multiplication factor of time */ bool active; /**< Entry active or not */ }; //struct timerEntry timerTable[SIZEOF_TIMER_TABLE]; /** * @brief Neighbors Table * */ struct neighborsEntry { uint16_t address; }; /** 2 Bytes */ // struct neighborsEntry neighborsTable[SIZEOF_NEIGHBORS_TABLE]; #endif //_STRUCTS_H_
<div class="bodyBig"> <div class="wrapper"> <header> <div class="AdviceMeLogo"> <a id="logo" [routerLink]="['/']" fragment="home"><img src="/assets/Images/AdviceMe Logo.png" alt="Logo Image"></a> </div> <nav class="main-nav"> <a [routerLink]="['/']" fragment="home">Home</a> <a [routerLink]="['/']" fragment="action">Action</a> <a [routerLink]="['/']" fragment="adventure">Adventure</a> <a [routerLink]="['/']" fragment="animation">Animation</a> <a [routerLink]="['/']" fragment="comedy">Comedy</a> <a [routerLink]="['/']" fragment="drama">Drama</a> <a [routerLink]="['/']" fragment="horror">Horror</a> <a [routerLink]="['/']" fragment="scienceFiction">Science Fiction</a> </nav> <nav class="sub-nav"> <input [(ngModel)]="fieldText" type="text" name="query" placeholder="Search..."> <button (click)="update(fieldText)" [routerLink]="['/searchFilms', fieldText]"> <i class="fas fa-search sub-nav-logo"></i> </button> <a *ngIf="unregistered" [routerLink]="['/login']">Login</a> <a *ngIf="registered" [routerLink]="['/account']">Account</a> <a *ngIf="admin" [routerLink]="['/addFilm']">Post Film</a> <button *ngIf="admin" (click)="logout()" value="Sign out">Sign out</button> </nav> </header> <!-- MAIN CONTAINER --> <section class="main-container" > <h1 id="results">Results</h1> <div> <div class="box"> <a *ngFor="let film of films" [routerLink]="['/films', film.id]"><img [src]="filmImage(film)"></a> </div> <p *ngIf="films.length == 0">Nothing found...</p> <div *ngIf="films.length != 0"> <button (click)="loadMore()" id='btnSearch' class='btnSubmit'>More Films</button> <div *ngIf="loaderMore" class="lds-dual-ring overlay"></div> </div> </div> </section> </div> </div>
//Ejercicio 01 Else If import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); if (n % 2 == 1) { System.out.println("Weird"); } else { if (n >= 2 && n <= 5) { System.out.println("Not Weird"); } else if (n >= 6 && n <= 20) { System.out.println("Weird"); } else { System.out.println("Not Weird"); } } scanner.close(); } } //Ejercicio 02 Java Loops II import java.util.*; import java.io.*; class Solution{ public static void main(String []argh){ Scanner in = new Scanner(System.in); int t=in.nextInt(); for(int i = 0; i < t; i++){ int a = in.nextInt(); int b = in.nextInt(); int n = in.nextInt(); int sum = 0; for(int j = 0; j < n; j++){ sum += Math.pow(2, j) * b; System.out.printf("%d ", a + sum); } System.out.printf("%n"); } in.close(); } } //Ejercicio 03 Plus Minus import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; class Result { /* * Complete the 'plusMinus' function below. * * The function accepts INTEGER_ARRAY arr as parameter. */ public static void plusMinus(List<Integer> arr) { // Write your code here } } public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int positiveCount = 0; int negativeCount = 0; int zeroCount = 0; for (int i = 0; i < n; i++) { int num = in.nextInt(); if (num > 0) { positiveCount++; } else if (num < 0) { negativeCount++; } else { zeroCount++; } } System.out.printf("%.6f\n", (double) positiveCount / n); System.out.printf("%.6f\n", (double) negativeCount / n); System.out.printf("%.6f\n", (double) zeroCount / n); in.close(); } } //Prime Cheker 04 import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.lang.reflect.*; public class Solution { static class Prime { public void checkPrime(int... nums) { boolean isPrime; for (int num : nums) { if (num < 2) { continue; } isPrime = true; for (int i = 2; i * i <= num; i++) { if (num % i == 0) { isPrime = false; break; } } if (isPrime) { System.out.print(num + " "); } } System.out.println(); } } public static void main(String[] args) { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n1 = Integer.parseInt(br.readLine()); int n2 = Integer.parseInt(br.readLine()); int n3 = Integer.parseInt(br.readLine()); int n4 = Integer.parseInt(br.readLine()); int n5 = Integer.parseInt(br.readLine()); Prime ob = new Prime(); ob.checkPrime(n1); ob.checkPrime(n1, n2); ob.checkPrime(n1, n2, n3); ob.checkPrime(n1, n2, n3, n4, n5); Method[] methods = Prime.class.getDeclaredMethods(); Set<String> set = new HashSet<>(); boolean overload = false; for (int i = 0; i < methods.length; i++) { if (set.contains(methods[i].getName())) { overload = true; break; } set.add(methods[i].getName()); } if (overload) { throw new Exception("Overloading not allowed"); } } catch (Exception e) { System.out.println(e); } } } // Java Map 05 import java.util.*; import java.io.*; class Solution { public static void main(String[] argh) { Scanner in = new Scanner(System.in); int n = in.nextInt(); in.nextLine(); // Crear el mapa de nombres y números de teléfono Map<String, Integer> phoneBook = new HashMap<>(); for (int i = 0; i < n; i++) { String name = in.nextLine(); int phone = in.nextInt(); in.nextLine(); phoneBook.put(name, phone); } // Realizar consultas en el mapa de nombres y números de teléfono while (in.hasNext()) { String queryName = in.nextLine(); if (phoneBook.containsKey(queryName)) { int phone = phoneBook.get(queryName); System.out.println(queryName + "=" + phone); } else { System.out.println("Not found"); } } in.close(); } }
/******************************************************************************\ * Day4Handler.h * * * * Handles day 4. * * * * Written by Abed Na'ran December 2023 * * * \******************************************************************************/ #ifndef DAY_4_HANDLER #define DAY_4_HANDLER #include <iostream> #include "day.h" #include "day_4/day_4.h" #include <assert.h> #ifdef PART_1 #undef PART_1 #endif #ifdef PART_2 #undef PART_2 #endif #ifdef PATHS #undef PATHS #endif #ifdef INPUT #undef INPUT #endif #ifdef RESULTS1 #undef RESULTS1 #endif #ifdef RESULTS2 #undef RESULTS2 #endif #ifdef RESULTS2 #undef HAS_PART_2 #endif /* Only modify below. */ /* Enter the paths for the tests. */ static const char *Day4TestPaths[] = { "./tests/day_4/test1", }; /* Enter the expected results in the same order of the paths. */ static int Day4ResultsPart1[] = { 13, }, Day4ResultsPart2[] = { 30, }; /* Modify to the corresponding day. */ #define PART_1 Day4Part1 #define PART_2 Day4Part2 #define PATHS Day4TestPaths #define RESULTS1 Day4ResultsPart1 #define RESULTS2 Day4ResultsPart2 #define INPUT "./input/day_4.txt" #ifdef DAY_4_IMPLEMENTED_PART2 #define HAS_PART_2 #endif class Day4HandlerClass : public DayHandlerClass { public: ~Day4HandlerClass() = default; /* DO NOT MODIFY ANYTHING BELOW. */ void Run(int Part) const { int Output; if (Part == -1 || Part == 1) { Output = PART_1(INPUT); printf("Part 1: %d.\n", Output); } #ifdef HAS_PART_2 if (Part == -1 || Part == 2) { Output = PART_2(INPUT); printf("Part 2: %d.\n", Output); } #else (void)RESULTS2; /* Suprress warning. */ #endif /* DAY_4_IMPLEMENTED_PART2 */ } void Test(int Part) const { int Output; size_t i, NumTests = sizeof(PATHS) / sizeof(PATHS[0]); if (Part == -1 || Part == 1) { std::cout << "Testing part 1:" << std::endl; for (i = 0; i < NumTests; i++) { CurrentTestPath = PATHS[i]; Output = Day4Part1(CurrentTestPath); ASSERT_EQ(Output, RESULTS1[i]); } } #ifdef HAS_PART_2 if (Part == -1 || Part == 2) { std::cout << "Testing part 2:" << std::endl; for (i = 0; i < NumTests; i++) { CurrentTestPath = PATHS[i]; Output = Day4Part2(CurrentTestPath); ASSERT_EQ(Output, RESULTS2[i]); } } #endif /* HAS_PART_2 */ } }; #undef PART_1 #undef PART_2 #undef PATHS #undef INPUT #undef RESULTS1 #undef RESULTS2 #undef HAS_PART_2 #endif /* DAY_4_HANDLER */
import { type GetStaticPaths, Metadata, InferGetStaticPropsType } from "next"; import { getPostBySlug, getAllPosts, type Post } from "../../lib/blogApi"; import { remark } from "remark"; import html from "remark-html"; import { Box, Container, Heading, Link, Text } from "@chakra-ui/react"; import { parseISO, format } from "date-fns"; import { ptBR } from "date-fns/locale"; import markdownStyles from "./markdown-styles.module.css"; import Head from "next/head"; async function markdownToHtml(markdown: string) { const result = await remark().use(html).process(markdown); return result.toString(); } const DateFormatter = ({ dateString }: { dateString: string }) => { const date = parseISO(dateString); return ( <time dateTime={dateString}> {format(date, "LLLL d, yyyy", { locale: ptBR })} </time> ); }; export const getStaticPaths = (async () => { const posts = getAllPosts(); const staticPaths = { paths: posts.map((p) => ({ params: { slug: p.slug, }, })), // See the "paths" section below fallback: true, // false or "blocking" }; return staticPaths; }) satisfies GetStaticPaths; export async function getStaticProps({ params }: Params) { const slug = params.slug; const post = getPostBySlug(slug); const content = await markdownToHtml(post.content || ""); return { props: { post, content }, }; } export default function Post({ post, content, }: InferGetStaticPropsType<typeof getStaticProps>) { if(!post) return null return ( <Container> <Head> <title>{`${post.title} - Rodrigomaia.me`}</title> <meta name="description" content={post.excerpt} key="desc" /> <meta property="og:title" content={post.title} /> <meta property="og:description" content={post.excerpt} /> </Head> <article className="mb-32"> <Box> <Heading size="lg" color="pink" marginBlockEnd={"2px"}> {post.title} </Heading> <Text fontSize={"sm"} marginY={"10px"}> <DateFormatter dateString={post.date} /> </Text> </Box> <div className="max-w-2xl mx-auto"> <div className={markdownStyles["markdown"]} dangerouslySetInnerHTML={{ __html: content }} /> </div> </article> </Container> ); } type Params = { params: { slug: string; }; };
#pragma once #include "Tile.h" #include "TileIndex.h" #include "DeserialisedSceneData.h" #include "../../util/Uuid.h" #include "../asset/Model.h" #include "../asset/Renderable.h" #include "../asset/Material.h" #include "../asset/Animator.h" #include "../asset/Prefab.h" #include "../asset/Texture.h" #include "../asset/Light.h" #include "../animation/Skeleton.h" #include "../animation/Animation.h" #include "internal/SceneSerializer.h" #include <filesystem> #include <future> #include <memory> #include <vector> namespace render::scene { enum class SceneEventType { PrefabAdded, PrefabUpdated, PrefabRemoved, TextureAdded, TextureRemoved, ModelAdded, ModelRemoved, AnimationAdded, AnimationRemoved, AnimatorAdded, AnimatorUpdated, AnimatorRemoved, SkeletonAdded, SkeletonRemoved, MaterialAdded, MaterialUpdated, MaterialRemoved, RenderableAdded, RenderableUpdated, RenderableRemoved, LightAdded, LightUpdated, LightRemoved, DDGIAtlasAdded }; struct SceneEvent { SceneEventType _type; TileIndex _tileIdx; util::Uuid _id; }; struct SceneEventLog { std::vector<SceneEvent> _events; }; class Scene { public: Scene(); ~Scene(); Scene(Scene&&); Scene& operator=(Scene&&); // Copying is not allowed. Scene(const Scene&) = delete; Scene& operator=(const Scene&) = delete; // This will take a snapshot of the scene as it is at call time, // and then asynchronously serialize to path. void serializeAsync(const std::filesystem::path& path); std::future<DeserialisedSceneData> deserializeAsync(const std::filesystem::path& path); const SceneEventLog& getEvents() const; void resetEvents(); bool getTile(TileIndex idx, Tile** tileOut); const std::vector<asset::Material>& getMaterials() const { return _materials; } const std::vector<asset::Model>& getModels() const { return _models; } const std::vector<anim::Animation>& getAnimations() const { return _animations; } const std::vector<anim::Skeleton>& getSkeletons() const { return _skeletons; } const std::vector<asset::Animator>& getAnimators() const { return _animators; } const std::vector<asset::Prefab>& getPrefabs() const { return _prefabs; } const std::vector<asset::Texture>& getTextures() const { return _textures; } const std::vector<asset::Renderable>& getRenderables() const { return _renderables; } const std::vector<asset::Light>& getLights() const { return _lights; } util::Uuid addPrefab(asset::Prefab&& prefab); void updatePrefab(asset::Prefab prefab); void removePrefab(util::Uuid id); const asset::Prefab* getPrefab(util::Uuid id); util::Uuid addTexture(asset::Texture&& texture); void removeTexture(util::Uuid id); const asset::Texture* getTexture(util::Uuid id); util::Uuid addModel(asset::Model&& model); void removeModel(util::Uuid id); const asset::Model* getModel(util::Uuid id); util::Uuid addMaterial(asset::Material&& material); void updateMaterial(asset::Material material); void removeMaterial(util::Uuid id); const asset::Material* getMaterial(util::Uuid id); util::Uuid addAnimation(anim::Animation&& animation); void removeAnimation(util::Uuid id); const anim::Animation* getAnimation(util::Uuid id); util::Uuid addSkeleton(anim::Skeleton&& skeleton); void removeSkeleton(util::Uuid id); const anim::Skeleton* getSkeleton(util::Uuid id); util::Uuid addAnimator(asset::Animator&& animator); void updateAnimator(asset::Animator animator); void removeAnimator(util::Uuid id); const asset::Animator* getAnimator(util::Uuid id); util::Uuid addLight(asset::Light&& l); void updateLight(asset::Light l); void removeLight(util::Uuid id); const asset::Light* getLight(util::Uuid id); util::Uuid addRenderable(asset::Renderable&& renderable); void removeRenderable(util::Uuid id); const asset::Renderable* getRenderable(util::Uuid id); void setDDGIAtlas(util::Uuid texId, scene::TileIndex idx); // TODO: Decide if the Scene class really is the correct place to access/modify renderables. void setRenderableTint(util::Uuid id, const glm::vec3& tint); void setRenderableTransform(util::Uuid id, const glm::mat4& transform); void setRenderableName(util::Uuid id, std::string name); void setRenderableBoundingSphere(util::Uuid id, const glm::vec4& boundingSphere); void setRenderableVisible(util::Uuid id, bool val); struct TileInfo { TileIndex _idx; util::Uuid _ddgiAtlas; }; private: friend struct internal::SceneSerializer; std::unordered_map<TileIndex, Tile> _tiles; /* * TODO: In the future maybe these need to be tile - based aswell. * They may need to be streamed in on demand, but that should be decided using renderables * _using_ the assets. * Renderables aren't really assets... Maybe assets don't belong here, only renderables, lights, particle emitters etc. */ std::vector<asset::Model> _models; std::vector<asset::Material> _materials; std::vector<anim::Animation> _animations; std::vector<anim::Skeleton> _skeletons; std::vector<asset::Animator> _animators; std::vector<asset::Prefab> _prefabs; std::vector<asset::Texture> _textures; std::vector<asset::Renderable> _renderables; std::vector<asset::Light> _lights; std::vector<TileInfo> _tileInfos; SceneEventLog _eventLog; internal::SceneSerializer _serialiser; void addEvent(SceneEventType type, util::Uuid id, TileIndex tileIdx = TileIndex()); }; }
import os import stat import sys from datetime import datetime from pathlib import Path from typing import Dict, List, Optional, Tuple import click import dateutil.parser as dp import gql from gql.transport.exceptions import TransportQueryError from latch_sdk_gql.execute import JsonValue, execute import latch_cli.services.cp.upload as upl def upload_file(src: Path, dest: str): start = upl.start_upload(src, dest) if start is None: return parts: List[upl.CompletedPart] = [] for idx, url in enumerate(start.urls): parts.append( upl.upload_file_chunk( src, url, idx, start.part_size, ) ) upl.end_upload(dest, start.upload_id, parts) def check_src(p: Path, *, indent: str = "") -> Optional[Tuple[Path, os.stat_result]]: try: p_stat = os.stat(p) except FileNotFoundError: click.secho(indent + f"`{p}`: no such file or directory", fg="red", bold=True) return if not stat.S_ISREG(p_stat.st_mode) and not stat.S_ISDIR(p_stat.st_mode): click.secho(indent + f"`{p}`: not a regular file", fg="red", bold=True) return return (p, p_stat) def sync_rec( srcs: Dict[str, Tuple[Path, os.stat_result]], dest: str, *, delete: bool, level: int = 0, ): # rsync never deletes from the top level destination delete_effective = delete and level > 0 indent = " " * level try: query = """ query LatchCLISync($argPath: String! ${name_filter_arg}) { ldataResolvePathData(argPath: $argPath) { finalLinkTarget { type childLdataTreeEdges( filter: { child: { removed: {equalTo: false}, pending: {equalTo: false}, copiedFrom: {isNull: true} ${name_filter} } } ) { nodes { child { id name finalLinkTarget { type ldataNodeEvents( condition: {type: INGRESS}, orderBy: TIME_DESC, first: 1 ) { nodes { time } } } } } } } } } """ args: JsonValue = {"argPath": dest, "nameFilter": []} if not delete_effective: query = query.replace("${name_filter_arg}", ", $nameFilter: [String!]") query = query.replace("${name_filter}", ", name: {in: $nameFilter}") args["nameFilter"] = list(srcs.keys()) else: query = query.replace("${name_filter_arg}", "") query = query.replace("${name_filter}", "") resolve_data = execute( gql.gql(query), args, )["ldataResolvePathData"] dest_data = None if resolve_data is not None: dest_data = resolve_data["finalLinkTarget"] except TransportQueryError as e: if e.errors is None or len(e.errors) == 0: raise msg: str = e.errors[0]["message"] raise if len(srcs) == 0: if dest_data is not None: if dest_data["type"] != "DIR": click.secho( indent + f"`{dest}` is in the way of a directory", fg="red", ) return click.secho(indent + "Empty directory", dim=True) return if not dest[-1] == "/": dest += "/" click.secho(indent + "Creating empty directory", fg="bright_blue") execute( gql.gql(""" mutation LatchCLISyncMkdir($argPath: String!) { ldataMkdirp(input: {argPath: $argPath}) { clientMutationId } } """), {"argPath": dest}, ) return if ( (len(srcs) > 1 or stat.S_ISDIR(list(srcs.values())[0][1].st_mode)) and dest_data is not None and dest_data["type"] not in {"DIR", "ACCOUNT_ROOT"} ): click.secho(f"`{dest}` is not a directory", fg="red", bold=True) click.secho("\nOnly a single file can be synced with a file", fg="red") sys.exit(1) if dest_data is not None and dest_data["type"] not in {"DIR", "ACCOUNT_ROOT"}: # todo(maximsmol): implement click.secho( "Syncing single files is currently not supported", bold=True, fg="red" ) sys.exit(1) dest_children_by_name = ( { x["name"]: x for x in (raw["child"] for raw in dest_data["childLdataTreeEdges"]["nodes"]) } if dest_data is not None else {} ) for name, (p, p_stat) in srcs.items(): is_dir = stat.S_ISDIR(p_stat.st_mode) child = dest_children_by_name.get(name) child_dest = f"{dest}/{name}" skip = False verb = "Uploading" reason = "new" if child is not None: flt = child["finalLinkTarget"] if flt["type"] == "DIR" and not is_dir: # todo(maximsmol): confirm? pre-check? click.secho( indent + f"`{dest}` is in the way of a file", fg="red", ) continue if flt["type"] != "DIR" and is_dir: # todo(maximsmol): confirm? pre-check? click.secho( indent + f"`{dest}` is in the way of a directory", fg="red", ) continue if flt["type"] == "OBJ": remote_mtime = dp.isoparse(flt["ldataNodeEvents"]["nodes"][0]["time"]) local_mtime = datetime.fromtimestamp(p_stat.st_mtime).astimezone() if remote_mtime == local_mtime: verb = "Skipping" reason = "unmodified" skip = True elif remote_mtime > local_mtime: verb = "Skipping" reason = "older" skip = True else: verb = "Uploading" reason = "updated" else: reason = "existing" if verb == "Uploading" and is_dir: verb = "Syncing" fg = "bright_blue" dim = None if verb == "Skipping": fg = None dim = True click.echo( click.style( indent + verb + " ", fg=fg, dim=dim, ) + click.style( reason, underline=True, fg=fg, dim=dim, ) + click.style( ": ", fg=fg, dim=dim, ) + click.style( str(p) + ("" if not is_dir else "/") + ("" if skip else click.style(" -> ", dim=True) + child_dest), dim=dim, ) ) if skip: continue if is_dir: sub_srcs: Dict[str, Tuple[Path, os.stat_result]] = {} for x in p.iterdir(): res = check_src(x, indent=indent + " ") if res is None: # todo(maximsmol): pre-check or confirm? continue sub_srcs[x.name] = res sync_rec(sub_srcs, child_dest, delete=delete, level=level + 1) continue # todo(maximsmol): upload in parallel? upload_file(p, child_dest) if delete_effective: for name, child in dest_children_by_name.items(): child_dest = f"{dest}/{name}" if name in srcs: continue click.echo( indent + click.style("Removing extraneous: ", fg="yellow") + child_dest ) execute( gql.gql(""" mutation LatchCLISyncRemove($argNodeId: BigInt!) { ldataRmr(input: {argNodeId: $argNodeId}) { clientMutationId } } """), {"argNodeId": child["id"]}, ) def sync( srcs_raw: List[str], dest: str, *, delete: bool, ignore_unsyncable: bool, ): srcs: Dict[str, Tuple[Path, os.stat_result]] = {} have_errors = False for x in srcs_raw: p = Path(x) res = check_src(p) if res is None: have_errors = True continue srcs[p.name] = res if len(srcs) == 0: click.secho( "\nAll source paths were skipped due to errors", fg="red", bold=True ) sys.exit(1) if have_errors: # todo(maximsmol): do we want to precheck recursively? click.secho("\nSome source paths will be skipped due to errors", fg="red") if not ignore_unsyncable: if not click.confirm(click.style(f"Proceed?", fg="red")): sys.exit(1) else: click.secho( "Proceeding due to " + click.style("`--ignore-unsyncable`", bold=True), fg="yellow", ) click.echo() sync_rec(srcs, dest, delete=delete)
# -*- coding: utf-8 -*- """ Created on Wed Mar 8 14:45:14 2023 @author: SWW-Bc20 """ import sys # Add Koala remote librairies to Path sys.path.append(r'C:\Program Files\LynceeTec\Koala\Remote\Remote Libraries\x64') import os from pyKoalaRemote import client import skimage.restoration as skir import numpy.ma as ma import numpy as np import numpy.typing as npt import subprocess import time import pyautogui import cv2 import psutil import skimage.transform as trans from scipy import ndimage from skimage.registration import phase_cross_correlation from PyQt5.QtWidgets import QFileDialog from typing import Tuple, List sys.path.append("..") import config as cfg Image = npt.NDArray[np.float32] Matrix = np.ndarray def connect_to_remote_koala(ConfigNumber): # Define KoalaRemoteClient host host = client.pyKoalaRemoteClient() #Ask IP address IP = 'localhost' # Log on Koala - default to admin/admin combo host.Connect(IP) host.Login('admin') # Open config host.OpenConfig(ConfigNumber) host.OpenPhaseWin() host.OpenIntensityWin() host.OpenHoloWin() return host def crop_image(image_array, crop_coords): # Extract the crop coordinates ymin, ymax = crop_coords[0][0], crop_coords[0][1] xmin, xmax = crop_coords[1][0], crop_coords[1][1] return image_array[ymin:ymax, xmin:xmax] def evaluate_phase_shift_error(image1: Image, image2: Image, rotation: float, zoomlevel: float) -> float: im = trans.rotate(image2, rotation, mode="edge") im = zoom(im, zoomlevel) try: shift_measured, error, phasediff = phase_cross_correlation(image1, im, upsample_factor=10, normalization=None) except: shift_measured, error, phasediff = phase_cross_correlation(image1, im, upsample_factor=10) return error def Open_Directory(directory, message): fname = QFileDialog.getExistingDirectory(None, message, directory, QFileDialog.ShowDirsOnly) return fname def get_result_unwrap(phase, mask=None): ph_m = ma.array(phase, mask=mask) return np.array(skir.unwrap_phase(ph_m)) def get_masks_corners(mask): non_zero_indices = np.nonzero(mask) ymin, ymax = int(np.min(non_zero_indices[0])), int(np.max(non_zero_indices[0])+1) xmin, xmax = int(np.min(non_zero_indices[1])), int(np.max(non_zero_indices[1])+1) return ((ymin, ymax), (xmin, xmax)) def is_koala_running(): for proc in psutil.process_iter(['name', 'exe']): if proc.info['name'] == 'Koala.exe' and proc.info['exe'] == r'C:\Program Files\LynceeTec\Koala\Koala.exe': return True return False def logout_login_koala(): cfg.KOALA_HOST.Logout() time.sleep(0.1) cfg.KOALA_HOST.Connect('localhost') cfg.KOALA_HOST.Login('admin') cfg.KOALA_HOST.OpenConfig(cfg.koala_config_nr) cfg.KOALA_HOST.OpenPhaseWin() cfg.KOALA_HOST.OpenIntensityWin() cfg.KOALA_HOST.OpenHoloWin() def open_koala(): wd = os.getcwd() os.chdir(r"C:\Program Files\LynceeTec\Koala") subprocess.Popen(r"C:\Program Files\LynceeTec\Koala\Koala") time.sleep(4) pyautogui.typewrite('admin') pyautogui.press('tab') pyautogui.typewrite('admin') pyautogui.press('enter') time.sleep(4) os.chdir(wd) screenshot = pyautogui.screenshot() remote_log = cv2.imread(r'spatial_averaging/images/remote_log_icon.png') remote_log_pos = find_image_position(screenshot, remote_log) pyautogui.click(remote_log_pos) def find_image_position(screenshot, image, threshold=0.95): """ Finds the position of a given image in a given screenshot using template matching. Args: screenshot: A PIL Image object of the screenshot. image: A PIL Image object of the image to be located in the screenshot. threshold: A float indicating the threshold above which the match is considered valid (default: 0.95). Returns: A tuple of two integers representing the (x, y) coordinates of the center of the image in the screenshot. If the image is not found, returns None. """ screenshot_array = np.array(screenshot) image_array = np.array(image) h, w = image_array.shape[:2] match = cv2.matchTemplate(screenshot_array, image_array, cv2.TM_CCOEFF_NORMED) # Find the position of the best match in the match matrix min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(match) if max_val<=threshold: return None # Get the center coordinates of the best match center_x = int(max_loc[0] + w/2) center_y = int(max_loc[1] + h/2) return center_x, center_y def gradient_squared(image: Image) -> Image: grad_x = ndimage.sobel(image, axis=0) grad_y = ndimage.sobel(image, axis=1) return (grad_x**2+grad_y**2) def grid_search_2d( image1: Image, image2: Image, x_mid: float, y_mid: float, x_length: float, y_length: float, local_searches: int) -> (float, float): # Initialize the initial grid boundaries. x_start, x_end = x_mid - x_length/2, x_mid + x_length/2 y_start, y_end = y_mid - y_length/2, y_mid + y_length/2 count = 0 while count in range(local_searches): # Create a grid based on the current boundaries. x_values = np.linspace(x_start, x_end, 5) y_values = np.linspace(y_start, y_end, 5) # Initialize variables to track the minimum and its location. min_value = float('inf') min_x, min_y = None, None # Evaluate the function at each point in the grid. for i,x in enumerate(x_values): for j,y in enumerate(y_values): if (i+j)%2==0: value = evaluate_phase_shift_error(image1, image2, x, y) if value < min_value: min_value = value min_x, min_y = x, y # Check if the minimum is at the edge or in the middle. if ( min_x == x_start or min_x == x_end or min_y == y_start or min_y == y_end ): # If the minimum is at the edge, expand the search space. x_start, x_end = min_x - x_length/2, min_x + x_length/2 y_start, y_end = min_y - y_length/2, min_y + y_length/2 else: count += 1 # If the minimum is in the middle, reduce the grid size. x_length /= 3 y_length /= 3 x_start, x_end = min_x - x_length/2, min_x + x_length/2 y_start, y_end = min_y - y_length/2, min_y + y_length/2 return min_x, min_y def shut_down_restart_koala(): cfg.KOALA_HOST.KoalaShutDown() time.sleep(1) open_koala() cfg.KOALA_HOST = connect_to_remote_koala(cfg.koala_config_nr) def start_koala(): # Open Koala and load Configurations if not is_koala_running(): open_koala() try: cfg.KOALA_HOST.OpenPhaseWin() except: cfg.KOALA_HOST = None if cfg.KOALA_HOST is None: cfg.KOALA_HOST = client.pyKoalaRemoteClient() cfg.KOALA_HOST.Connect('localhost') cfg.KOALA_HOST.Login('admin') cfg.KOALA_HOST.OpenConfig(cfg.koala_config_nr) cfg.KOALA_HOST.OpenPhaseWin() cfg.KOALA_HOST.OpenIntensityWin() cfg.KOALA_HOST.OpenHoloWin() def zoom(I: Image, zoomlevel: float) -> Image: oldshape = I.shape I_zoomed = np.zeros_like(I) I = trans.rescale(I, zoomlevel, mode="edge") if zoomlevel<1: i0 = ( round(oldshape[0]/2 - I.shape[0]/2), round(oldshape[1]/2 - I.shape[1]/2), ) I_zoomed[i0[0]:i0[0]+I.shape[0], i0[1]:i0[1]+I.shape[1]] = I return I_zoomed else: I = trans.rescale(I, zoomlevel, mode="edge") i0 = ( round(I.shape[0] / 2 - oldshape[0] / 2), round(I.shape[1] / 2 - oldshape[1] / 2), ) I = I[i0[0] : (i0[0] + oldshape[0]), i0[1] : (i0[1] + oldshape[1])] return I class PolynomialPlaneSubtractor: _image_shape = None _polynomial_degree = None _X = None _X_pseudoinverse = None @classmethod def get_X(cls, image_shape: Tuple[int, int], polynomial_degree: int) -> Matrix: """ Get the design matrix X, calculating it if not already calculated. Args: image_shape (Tuple[int, int]): The shape of the image. polynomial_degree (int): The degree of the polynomial expansion. Returns: Matrix: The design matrix X. """ # Input checks assert isinstance(image_shape, tuple) and len(image_shape) == 2, "image_shape must be a tuple of two integers" assert all(isinstance(dim, int) and dim >= 0 for dim in image_shape), "image_shape elements must be non-negative integers" assert isinstance(polynomial_degree, int) and polynomial_degree >= 0, "polynomial_degree must be a non-negative integer" if cls._X is None: cls._calculate_X(image_shape, polynomial_degree) cls._image_shape = image_shape return cls._X @classmethod def get_X_pseudoinverse(cls) -> Matrix: """ Get the Moore-Penrose pseudoinverse of the design matrix X. Returns: Matrix: The Moore-Penrose pseudoinverse of X. """ if cls._X_pseudoinverse is None: raise ValueError("X_pseudoinverse has not been calculated yet") return cls._X_pseudoinverse @classmethod def subtract_plane(cls, image: Image, polynomial_degree: int) -> Image: """ Subtract a polynomial plane from the input image using the least squares method. Args: image (Image): The input 2D surface. polynomial_degree (int): The degree of the polynomial expansion. Returns: Image: The input image with the estimated polynomial plane subtracted. """ # Input checks assert isinstance(image, np.ndarray), "image must be a numpy.ndarray" assert isinstance(polynomial_degree, int) and polynomial_degree >= 0, "polynomial_degree must be a non-negative integer" if cls._X is None or cls._X_pseudoinverse is None or cls._polynomial_degree != polynomial_degree: cls._calculate_X(image.shape, polynomial_degree) theta = np.dot(cls._X_pseudoinverse, image.ravel()) plane = np.dot(cls._X, theta).reshape(image.shape) return image - plane @classmethod def _calculate_X(cls, image_shape: Tuple[int, int], polynomial_degree: int) -> None: x_coordinates, y_coordinates = np.mgrid[:image_shape[0], :image_shape[1]] X = np.column_stack((x_coordinates.ravel(), y_coordinates.ravel())) X = PolynomialFeatures(degree=polynomial_degree, include_bias=True).fit_transform(X) cls._image_shape = image_shape cls._polynomial_degree = polynomial_degree cls._X = X cls._X_pseudoinverse = np.dot(np.linalg.inv(np.dot(X.transpose(), X)), X.transpose())
const {encrypt, compare} = require("../utils/handlePassword"); const { tokenSign } = require("../utils/handleJwt"); // const { usersModel } = require("../models"); // const { handleHttpError } = require("../utils/handleError"); const client = require("../config/mongo.js") const registerUser = async (req, res) => { try { const {body} = req await client.connect(); const db = client.db("e-commerce_vue_express"); const password = await encrypt(body.password); const bodyParser = { ...body, password, cartItems: [], role: ["user"], createdAt: new Date() }; const {insertedId} = await db.collection("users").insertOne(bodyParser) const dataUser = await db.collection("users").findOne({_id: insertedId}) delete dataUser.password; const data = { token: await tokenSign(dataUser), user: dataUser, }; res.status(200).json(data) await client.close(); } catch (err) { return res.status(404).json({"error": "Error registering"}); } }; const loginUser = async (req, res) => { try { await client.connect(); const db = client.db("e-commerce_vue_express"); const {body} = req; const user = await db.collection("users").findOne({username: body.username}) // await usersModel.findOne({email: body.email}).select("password name email age") if (!user) { return res.status(404).json({"error": "User doesn't exist"}); } const hashPassword = user.password const check = await compare(body.password, hashPassword) if (!check) { return res.status(401).json({"error": "Password incorrect"}); } delete user.password const data = { token: await tokenSign(user), user } res.status(200).json(data) await client.close(); } catch (err) { res.status(404).json({"error": "Error login"}); } }; module.exports = { registerUser, loginUser }
import 'package:autohub/components/CustomPrimaryButton.dart'; import 'package:autohub/components/EllipsisText.dart'; import 'package:autohub/data/ServicesData.dart'; import 'package:autohub/data/UserProfileData.dart'; import 'package:autohub/data_notifier/CategoryNotifier.dart'; import 'package:autohub/db_references/NotifierType.dart'; import 'package:autohub/operation/CategoryOperation.dart'; import 'package:autohub/operation/ServicesOperation.dart'; import 'package:autohub/pages/EditServicePage.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:smooth_page_indicator/smooth_page_indicator.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:widget_state_notifier/widget_state_notifier.dart'; import '../components/CustomCircularButton.dart'; import '../components/CustomOnClickContainer.dart'; import '../components/CustomProject.dart'; import '../components/ExpandedPageView.dart'; import '../data/MediaData.dart'; import '../data_notifier/UserProfileNotifier.dart'; import '../handler/MediaHandler.dart'; import '../operation/AuthenticationOperation.dart'; import 'CheckPostMediaPage.dart'; class ServiceExtendedPage extends StatefulWidget { final ServicesData servicesData; final UserProfileNotifier? userAddedProfileNotifier; final UserProfileNotifier? userEditedProfileNotifier; const ServiceExtendedPage( {super.key, required this.servicesData, required this.userAddedProfileNotifier, required this.userEditedProfileNotifier}); @override State<ServiceExtendedPage> createState() => _ServiceExtendedPageState(); } class _ServiceExtendedPageState extends State<ServiceExtendedPage> { PageController controller = PageController(); void performBackPressed() { Navigator.pop(context); } void tappedOnMediaAt(int index) { Navigator.push( context, MaterialPageRoute( builder: (context) => CheckPostMediaPage( media: widget.servicesData.servicesMedia, startAt: index, ))); } void onTapMessage(UserProfileData data) { String? countryCodeText = data.phoneCode; String? numberText = data.phone; String messageBody = """ I am looking to avail of this service - *${widget.servicesData.servicesIdentity}* for a specific purpose or project. I believe it will greatly benefit me. Could you please discuss more on this? Total amount: ${widget.servicesData.servicesCurrency} ${widget.servicesData.servicesPrice} Thank you! """; if (countryCodeText != null && numberText != null) { var whatsappUrl = Uri.parse("whatsapp://send?phone=${countryCodeText + numberText}" "&text=${Uri.encodeComponent(messageBody)}"); try { launchUrl(whatsappUrl); } catch (e) { debugPrint(e.toString()); } } else { showToastMobile(msg: "An error has occurred"); } } void goToEditPage() { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => EditServicePage(servicesData: widget.servicesData))); } void deleteServices() { openDialog( context, color: Colors.grey.shade200, const Text( "Service Deletion", style: TextStyle(color: Colors.red, fontSize: 17), ), Text( "Are you sure you want to delete ${widget.servicesData.servicesIdentity} service?"), [ TextButton( onPressed: () { Navigator.pop(context); }, child: const Text("Cancel", style: TextStyle( fontSize: 15, color: Colors.black, fontWeight: FontWeight.bold))), TextButton( onPressed: () { Navigator.pop(context); onConfirmDelete(); }, child: const Text("Yes", style: TextStyle( fontSize: 15, color: Colors.black, fontWeight: FontWeight.bold))), ], ); } void onConfirmDelete() { showCustomProgressBar(context); final mediaDeletion = widget.servicesData.servicesMedia .asMap() .map((key, value) { return MapEntry( key, CategoryOperation().deletePostMedia( widget.servicesData.servicesId, CategoryOperation().getMediaIndex(value.mediaData), value.mediaType == MediaType.image ? "image" : "video")); }) .values .toList(); final deleteOperation = Future.wait(mediaDeletion); final serviceDeletion = ServicesOperation().deleteAService(widget.servicesData.servicesId); final operation = Future.wait<dynamic>([deleteOperation, serviceDeletion]); operation.then((value) { CategoryNotifier() .getServicesNotifier( widget.servicesData.servicesCategoryId, NotifierType.normal) ?.deleteTheServices(widget.servicesData.servicesId); closeCustomProgressBar(context); Navigator.pop(context); showToastMobile(msg: "Deleted the service"); }).onError((error, stackTrace) { closeCustomProgressBar(context); showDebug(msg: "$error $stackTrace"); showToastMobile(msg: "An error occurred"); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SafeArea( child: Column( children: [ // Back Button const SizedBox(height: 20), Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: Row(children: [ CustomCircularButton( imagePath: null, iconColor: Colors.black, onPressed: performBackPressed, icon: Icons.arrow_back, width: 40, height: 40, iconSize: 30, mainAlignment: Alignment.center, defaultBackgroundColor: Colors.transparent, clickedBackgroundColor: Colors.white, ), const SizedBox( width: 8, ), const Expanded( child: Text( "Service Details", textScaleFactor: 1, overflow: TextOverflow.ellipsis, style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold), ), ), if (AuthenticationOperation().thisUser != null) Row( children: [ CustomCircularButton( imagePath: null, iconColor: Colors.red, onPressed: deleteServices, icon: Icons.delete, width: 40, height: 40, iconSize: 30, mainAlignment: Alignment.center, defaultBackgroundColor: Colors.transparent, clickedBackgroundColor: Colors.white, ), const SizedBox( width: 8, ), CustomCircularButton( imagePath: null, iconColor: Colors.green, onPressed: goToEditPage, icon: Icons.edit, width: 40, height: 40, iconSize: 30, mainAlignment: Alignment.center, defaultBackgroundColor: Colors.transparent, clickedBackgroundColor: Colors.white, ), ], ) ]), ), const SizedBox( height: 8, ), Expanded( child: Stack( children: [ Positioned.fill( child: SingleChildScrollView( child: Column( children: [ widget.servicesData.servicesMedia.isNotEmpty ? ExpandablePageView( autoScroll: true, autoScrollDelay: const Duration(seconds: 5), pageController: controller, epViews: [ for (int index = 0; index < widget.servicesData.servicesMedia .length; index++) EPView( crossDimension: EPDimension.match, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 16), child: CustomOnClickContainer( defaultColor: Colors.transparent, clickedColor: Colors.transparent, clipBehavior: Clip.antiAlias, borderRadius: BorderRadius.circular(16), child: SizedBox( height: getScreenWidth(context) - (16 * 2), child: Column( children: [ Expanded( child: Row( children: [ Expanded( child: MediaHandler( media: widget.servicesData.servicesMedia[ index], clicked: () { tappedOnMediaAt( index); })), ], ), ), ], ), ), ), )) ]) : SizedBox( height: getScreenWidth(context) - (16 * 2), child: Center( child: Icon( Icons.shopping_cart, size: 180, color: Colors.black.withOpacity(0.5), ), ), ), if (widget.servicesData.servicesMedia.isNotEmpty) Padding( padding: const EdgeInsets.only(top: 16), child: SmoothPageIndicator( controller: controller, count: widget.servicesData.servicesMedia.length), ), const SizedBox( height: 16, ), // Identity Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: Row( children: [ Expanded( child: Text( widget.servicesData.servicesIdentity, style: GoogleFonts.anton( color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold, ), ), ), ], ), ), // Description Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: Row( children: [ Expanded( child: EllipsisText( text: widget.servicesData.servicesDescription, textStyle: TextStyle( fontSize: 16, color: Colors.grey[600]), maxLength: 100, ), ), ], ), ), // Added By const SizedBox( height: 24, ), WidgetStateConsumer( widgetStateNotifier: widget.userAddedProfileNotifier?.state ?? WidgetStateNotifier(currentValue: null), widgetStateBuilder: (context, data) { if (data == null) return const SizedBox(); return Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: Row( children: [ Container( decoration: BoxDecoration( color: Colors.black.withOpacity(0.7), borderRadius: BorderRadius.circular(5)), child: Padding( padding: const EdgeInsets.symmetric( vertical: 4, horizontal: 6), child: Text( data.fullName, style: const TextStyle( color: Colors.white, fontSize: 15, ), ), ), ), ], ), ); }), // Currency and Price Padding( padding: const EdgeInsets.symmetric( horizontal: 16, ), child: Row( children: [ Expanded( child: Text( "${widget.servicesData.servicesCurrency} ${CategoryOperation().formatNumber(double.parse(widget.servicesData.servicesPrice))}", style: const TextStyle( color: Colors.green, fontSize: 32, fontWeight: FontWeight.bold, ), ), ), ], ), ), SizedBox( height: 200, ) ], ), ), ), Positioned( bottom: 0, left: 0, right: 0, child: WidgetStateConsumer( widgetStateNotifier: widget.userAddedProfileNotifier?.state ?? WidgetStateNotifier(), widgetStateBuilder: (context, data) { if (data == null) return const SizedBox(); return Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 16), child: Container( color: Colors.white, child: Row( children: [ Expanded( child: CustomPrimaryButton( buttonText: "Message", onTap: () { onTapMessage(data); }), ) ], ), ), ); })) ], ), ) ], ), ), ); } }
# Amazon S3 access control lists - ACL is disabled by default - ACL enables you to manage access to buckets and objects when enabled - Each bucket and object has an ACL attached to it as a subresource - It defines which AWS accounts or groups are granted access and the type of access - When a request is received against a resource, Amazon S3 checks the corresponding ACL to verify that the requester has the necessary access permissions # ACL Object Ownership - It is an Amazon S3 bucket-level setting that you can use to both control ownership of the objects that are uploaded to your bucket and to disable or enable ACLs - By default, it is set to the bucket owner enforced setting, and all ACLs are disabled - When ACLs are disabled, the bucket owner owns all the objects in the bucket and manages access to them exclusively by using access-management policies - A majority of modern use cases in Amazon S3 no longer require the use of ACLs - We recommend that you keep ACLs disabled, except in unusual circumstances where you need to control access for each object individually - With ACLs disabled, you can use policies to control access to all objects in your bucket, regardless of who uploaded the objects to your bucket - If your bucket uses the bucket owner enforced setting for S3 Object Ownership, you must use policies to grant access to your bucket and the objects in it - With the bucket owner enforced setting enabled, requests to set access control lists (ACLs) or update ACLs fail and return the AccessControlListNotSupported error code. Requests to read ACLs are still supported
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Show extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('show', function (Blueprint $table) { $table->increments('id'); $table->string('title', 50); $table->string('alias', 50); $table->string('genreid', 2); $table->text('description'); $table->string('catid', 5); $table->string('image', 50); $table->string('publish', 2); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('show'); } }
import { useState, useEffect } from "react"; import { SearchPlaces } from "../searchPlaces/SearchPlaces.component"; import "./Location.styles.scss"; type Props = { currentTime: number | string | any[] | any; className?: string; setLocation: Function; setSelectedAPI: Function; location: stateData; selectedAPI: API; }; interface stateData { name?: string; accuracy?: number; latitude: number; longitude: number; } interface API { URL: string; title: string; } interface APIs { [key: number]: API; } export const Location = (props: Props): JSX.Element => { const [state, setState] = useState<stateData>(); useEffect(() => { const options = { enableHighAccuracy: true, timeout: 5000, maximumAge: 0, }; function success(pos: any) { setState(() => ({ ...pos.coords, accuracy: pos.coords.accuracy, latitude: pos.coords.latitude, longitude: pos.coords.longitude, })); console.log(pos.coords); if (state?.latitude !== undefined && state.longitude !== undefined) { console.log("Your current location is:"); console.log(`Latitude : ${state?.latitude}`); console.log(`Longitude: ${state?.longitude}`); console.log(`More or less ${state?.accuracy} meters.`); } } function error(err: any) { console.warn(`ERROR(${err.code}): ${err.message}`); } navigator.geolocation.getCurrentPosition(success, error, options); }, [state?.latitude, state?.longitude, state?.accuracy]); const listOfAPIs: APIs = [ { title: "open-meteo.com", URL: `https://api.open-meteo.com/v1/forecast?latitude=${state?.latitude}&longitude=${state?.longitude}&hourly=temperature_2m,relativehumidity_2m,dewpoint_2m,apparent_temperature,precipitation,rain,showers,snowfall,snow_depth,freezinglevel_height,weathercode,pressure_msl,surface_pressure,cloudcover,cloudcover_low,cloudcover_mid,cloudcover_high,evapotranspiration,et0_fao_evapotranspiration,vapor_pressure_deficit,windspeed_10m,windspeed_80m,windspeed_120m,windspeed_180m,winddirection_10m,winddirection_80m,winddirection_120m,winddirection_180m,windgusts_10m,temperature_80m,temperature_120m,temperature_180m,soil_temperature_0cm,soil_temperature_6cm,soil_temperature_18cm,soil_temperature_54cm,soil_moisture_0_1cm,soil_moisture_1_3cm,soil_moisture_3_9cm,soil_moisture_9_27cm,soil_moisture_27_81cm,shortwave_radiation,direct_radiation,diffuse_radiation,direct_normal_irradiance,terrestrial_radiation,shortwave_radiation_instant,direct_radiation_instant,diffuse_radiation_instant,direct_normal_irradiance_instant,terrestrial_radiation_instant,temperature_1000hPa,temperature_975hPa,temperature_950hPa,temperature_925hPa,temperature_900hPa,dewpoint_1000hPa,dewpoint_975hPa,dewpoint_950hPa,dewpoint_925hPa,dewpoint_900hPa,relativehumidity_1000hPa,relativehumidity_975hPa,relativehumidity_950hPa,relativehumidity_925hPa,relativehumidity_900hPa,cloudcover_1000hPa,cloudcover_975hPa,cloudcover_950hPa,cloudcover_925hPa,cloudcover_900hPa,windspeed_1000hPa,windspeed_975hPa,windspeed_950hPa,windspeed_925hPa,windspeed_900hPa,winddirection_1000hPa,winddirection_975hPa,winddirection_950hPa,winddirection_925hPa,winddirection_900hPa,geopotential_height_1000hPa,geopotential_height_975hPa,geopotential_height_950hPa,geopotential_height_925hPa,geopotential_height_900hPa&daily=weathercode,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,sunrise,sunset,precipitation_sum,rain_sum,showers_sum,snowfall_sum,precipitation_hours,windspeed_10m_max,windgusts_10m_max,winddirection_10m_dominant,shortwave_radiation_sum,et0_fao_evapotranspiration&timezone=auto`, }, { title: "7timer", URL: `http://www.7timer.info/bin/api.pl?lon=${state?.longitude}&lat=${state?.latitude}&product=civil&output=json `, }, ]; if ( props.selectedAPI.URL === "" && state?.latitude !== undefined && state?.longitude !== undefined ) props.setSelectedAPI(listOfAPIs[0]); return ( <div className={props.className}> <h2> Location <br /> {props.location.name} </h2> <div> <SearchPlaces /> </div> </div> ); };
package csci2110.ass05; /* Student name: Yongteng Li Student id: B00940715 Course: csci2110 Project: assignment 5 */ import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class Huffman { //global variable that validates the input static boolean valid = true; public static void main(String[] args) throws FileNotFoundException, InterruptedException { Scanner keyIn = new Scanner(System.in); //prompt to input the file name System.out.printf("Huffman Coding\nEnter the name of the file with letters and probability: "); String fileName = keyIn.nextLine(); //store the characters and their probabilities in a linked list Scanner fileIn = new Scanner(new File(fileName)); LinkedList<BinaryTree<Pair>> pairList = new LinkedList<>(); //read the data from the file and store it in a linked list of binary tree while(fileIn.hasNext()){ Pair pair = new Pair(fileIn.next().charAt(0), Double.parseDouble(fileIn.next())); BinaryTree<Pair> t = new BinaryTree<>(); t.makeRoot(pair); pairList.add(t); } //build the Huffman tree using the list containing the data BinaryTree<Pair> tree = buildHuffman(pairList); String[] huffmanEncode = new String[26]; //just a message presented to show the process is being done System.out.print("Building the Huffman tree"); for(int i = 0; i < 3; i++) { Thread.sleep(500); //show the process in a more natural way System.out.print("."); } //generate the Huffman encode for all the character from the tree generateCode(tree, huffmanEncode, ""); System.out.printf("\nHuffman coding completed.\n"); //prompt to enter a line System.out.println("Enter a line(upper case letters only): "); String line = keyIn.nextLine(); String code = ""; //array that stores the code by character String[] lineCode = new String[line.length()]; //generate the code for the line, and store the code in the array code = getCode(huffmanEncode, line, code, lineCode); //stop the program if the input is not valid if(!valid) return; System.out.println("Here's the encoded line: " + code); //decode the string, using Huffman code array and the code of the characters String decode = decode(huffmanEncode, lineCode); System.out.println("The decoded line is: " + decode); fileIn.close(); keyIn.close(); } /** * Builds a Huffman tree from a list of binary trees representing individual characters. * @param list The list of binary trees representing characters and their frequencies. * @return The Huffman tree representing the optimal encoding. */ public static BinaryTree<Pair> buildHuffman(LinkedList<BinaryTree<Pair>> list){ //take the first two nodes and create a parent node of them BinaryTree<Pair> t1 = list.removeFirst(); BinaryTree<Pair> t2 = list.removeFirst(); //make a new node Pair p3 = new Pair('$', t1.getData().getP() + t2.getData().getP()); //turn the node into a tree BinaryTree<Pair> t3 = new BinaryTree<>(); t3.makeRoot(p3); //attach them together t3.attachLeft(t1); t3.attachRight(t2); //check the list, stop recursion when the list is empty if(list.size() == 0) return t3; //add the new node into the list in a sorted manner list.addLast(t3); list.sort(Comparator.comparing(e -> e.getData().getP())); return buildHuffman(list); } /** * Recursively generates Huffman codes for each character in the Huffman tree. * @param t The current node in the Huffman tree. * @param codes An array to store the generated Huffman codes for each character. * @param code The current Huffman code being constructed. */ public static void generateCode(BinaryTree<Pair> t, String[] codes, String code){ //stop the recursion when the leaf node is reached if(t.getLeft() == null && t.getRight() == null){ codes[t.getData().getChar() - 65] = code; } //get to every leaf node recursively else{ generateCode(t.getLeft(), codes, code + "0"); generateCode(t.getRight(), codes, code + "1"); } } /** * Encodes a given line of characters using the provided Huffman encoding. * @param huffmanEncode The array of Huffman codes for each character. * @param line The input line to be encoded. * @param code The encoded representation of the input line. * @param lineCode An array to store individual Huffman codes for each character in the line. * @return The encoded representation of the input line. */ private static String getCode(String[] huffmanEncode, String line, String code, String[] lineCode) { for(int i = 0; i < line.length(); i++){ //if there is a space, just store a space if(line.charAt(i) == ' ') { code += " "; lineCode[i] = " "; } //validate the input else if(line.charAt(i) < 65 || line.charAt(i) > 90){ System.out.println("Your input is not valid!"); valid = false; return ""; } //not a space, store the Huffman code according to ascii value else{ code += huffmanEncode[line.charAt(i) - 65]; lineCode[i] = huffmanEncode[line.charAt(i) - 65]; } } return code; } /** * Decodes an encoded message using the provided Huffman encoding. * @param huffman The array of Huffman codes for each character. * @param code The encoded message to be decoded. * @return The decoded message. */ public static String decode(String[] huffman, String[] code){ String word = ""; for(int i = 0; i < code.length; i++){ //if the encoding is a space, means no encoding, just a space if(code[i] == " ") word += " "; else{ //if not a space, find the match in the Huffman list and get the character for(int j = 0; j < 26; j++){ if(huffman[j].equals(code[i])){ word += (char)(65 + j); break; } } } } return word; } }
import knexConnection from "../database/database"; import ModelService from "../provider/model.service" import { users, accounts } from './test-data' import { v4 } from "uuid"; const userServices = new ModelService("users") const accountServices = new ModelService("accounts") beforeAll(async () => { try { await knexConnection.migrate.latest({ directory: "migrations" }); console.log("Migration successful"); } catch (error) { console.log("Migration Failed"); } }); afterAll(async () => { try { await knexConnection.migrate.rollback({ directory: "migrations" }); knexConnection.destroy(); } catch (error) { console.log(error); } }); describe("Authentication", () => { it("sign-up a user successfully", async () => { const id = v4(); const userData: UserType = users[0] userData.id = id; await userServices.create(userData) const [ user ] = await userServices.findOne({ email: userData.email }) expect(user.id).toBe(id); expect(user.email).toBe(userData.email) }); it("sign-up only unique email address", async () => { const id = v4(); const userData: UserType = users[2] userData.id = id; const [ user ] = await userServices.findOne({ email: userData.email }) if (!user) await userServices.create(userData) expect(user.id).not.toBe(id); expect(user.email).toBe(userData.email) }); }); describe("Accounts", () => { let userID: string; const funds = 5000 it("should create an account", async () => { const randomAccountNo = accounts[0] const userData: UserType = users[1] userData.id = v4(); userID = userData.id await userServices.create(userData) await accountServices.create({ user_id: userData.id, account_number: randomAccountNo, balance: 0 }) const [user] = await accountServices.findOne({user_id: userID}) expect(user.id).toBe(1); expect(user.user_id).toBe(userID) expect(user.balance).toBe(0) }); it("should return all registered account", async () => { const accounts = await accountServices.find() expect(accounts).toBeTruthy() expect(accounts.length).toBeGreaterThanOrEqual(1) }); it("should update user account balance", async () => { await accountServices.update({ user_id: userID }, { balance: funds }) const [account] = await accountServices.findOne({ user_id: userID }) expect(account).toBeTruthy() expect(account.balance).toEqual(funds) expect(account.user_id).toBe(userID) }); });
package com.ktran.shopping_cart; import com.ktran.shopping_cart.model.Product; import com.ktran.shopping_cart.service.ProductService; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ServletComponentScan @EnableCaching public class ShoppingCartApplication { public static void main(String[] args) { SpringApplication.run(ShoppingCartApplication.class, args); } @Bean CommandLineRunner runner(ProductService productService) { return args -> { productService.save(new Product(1L, "TV Set", 300.00, "http://placehold.it/200x100")); productService.save(new Product(2L, "Game Console", 200.00, "http://placehold.it/200x100")); productService.save(new Product(3L, "Sofa", 100.00, "http://placehold.it/200x100")); productService.save(new Product(4L, "Icecream", 5.00, "http://placehold.it/200x100")); productService.save(new Product(5L, "Beer", 3.00, "http://placehold.it/200x100")); productService.save(new Product(6L, "Phone", 500.00, "http://placehold.it/200x100")); productService.save(new Product(7L, "Watch", 30.00, "http://placehold.it/200x100")); }; } }
import Avatar from "@mui/material/Avatar"; import DateFormatter from "./DateFormatter"; // import CoverImage from "./CoverImage"; import PostTitle from "./PostTitle"; type Props = { title: string; publishedAt: string; updatedAt?: string; }; const AUTHOR_NAME = "Jacob Fredericksen"; const IMAGE = "/images/profile.jpg"; const PostHeader = ({ title, publishedAt }: Props) => { return ( <> <PostTitle>{title}</PostTitle> <div className="hidden md:block md:mb-12"> <Avatar alt={AUTHOR_NAME} src={IMAGE} /> </div> {/* <div className="mb-8 md:mb-16 sm:mx-0"> <CoverImage title={title} src={coverImage} /> </div> */} <div className="max-w-2xl mx-auto"> <div className="block md:hidden mb-6"> <Avatar alt={AUTHOR_NAME} src={IMAGE} /> </div> <div className="mb-6 text-lg"> <DateFormatter dateString={publishedAt} /> </div> </div> </> ); }; export default PostHeader;
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/styles.css"> <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=Montserrat:wght@400;700&family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet"> <title>WebStudio</title> </head> <body> <!-- Шапкpа страницы --> <header> <nav> <a href="./index.html" class="logo-blue link">Web<span class="logo-black link">Studio</span></a> <ul> <li><a class="site-navigation link" href="./index.html">Студия</a></li> <li><a class="site-navigation link" href="./portfolio.html">Портфолио</a></li> <li><a class="site-navigation link" href="">Контакты</a></li> </ul> </nav> <ul> <li><a class="auth-navigation link" href="mail:[email protected]">[email protected]</a></li> <li><a class="auth-navigation link" href="tel:+380961111111">+38 096 111 11 11</a></li> </ul> </header> <!-- Уникальный контент страницы --> <main> <!-- Герой --> <section class="hero"> <h1 class="hero-title">Эффективные решения <br />для вашего бизнеса</h1> <button class="hero-btn">Заказать услугу</button> </section> <section class="block"> <h2 class="visually-hidden">Наши особенности</h2> <ul> <li> <h3 class="block-title-text">Внимание к деталям</h3> <p>Идейные соображения, а также начало повседневной работы по формированию позиции.</p> </li> <li> <h3 class="block-title-text">Пунктуальность</h3> <p>Задача организации, в особенности же рамки и место обучения кадров влечет за собой.</p> </li> <li> <h3 class="block-title-text">Планирование</h3> <p>Равным образом консультация с широким активом в значительной степени обуславливает.</p> </li> <li> <h3 class="block-title-text">Современные технологии</h3> <p>Значимость этих проблем настолько очевидна, что реализация плановых заданий.</p> </li> </ul> </section> <section class="block"> <h2 class="block-title">Чем мы занимаемся</h2> <ul> <li><img src="./images/services-img-1.jpg" alt="Ноутбук" width="370" height="294"> </li> <li><img src="./images/services-img-2.jpg" alt="Андроид" width="370" height="294"> </li> <li><img src="./images/services-img-3.jpg" alt="Планшет" width="370" height="294"> </li> </ul> </section> <section class="block-our-team"> <h2 class="block-title">Наша команда</h2> <ul class="feature-list"> <li><img src="./images/our-team-img-1.jpg" alt="Дизайнер" width="270" height="260"> <h3 class="title">Игорь Демьяненко</h3> <p class="text" lang="en">Product Designer</p> </li> <li><img src="./images/our-team-img-2.jpg" alt="Разработчик" width="270" height="260"> <h3 class="title">Ольга Репина</h3> <p class="text" lang="en">Frontend Developer</p> </li> <li><img src="./images/our-team-img-3.jpg" alt="Маркетолог" width="270" height="260"> <h3 class="title">Николай Тарасов</h3> <p class="text" lang="en">Marketing</p> </li> <li><img src="./images/our-team-img-4.jpg" alt="Дизайнер интерфейсов" width="270" height="260"> <h3 class="title">Михаил Ермаков</h3> <p class="text" lang="en">UI Designer</p> </li> </ul> </section> </main> <!-- Подвал страницы --> <footer> <a href="./index.html" class="logo-blue link">Web<span class="logo-white link">Studio</span></a> <address class="location"> <p class="location-text">г. Киев, пр-т Леси Украинки, 26</p> <ul> <li><a class="location-list link" href="mail:[email protected]">[email protected]</a></li> <li><a class="location-list link" href="tel:+380961111111">+38 096 111 11 11</a></li> </ul> </address> </footer> </body> </html>
import { useState } from "react"; import { useNavigate } from "react-router-dom"; import { Button, TextField, Box, Container, Typography, Stack, } from "@mui/material"; import { saveArchivos, uploaFiles } from "../services/firebase"; import swal from "sweetalert"; export default function Register() { const [file, setFile] = useState(null); const [urlImg, seturlImg] = useState(""); const [isLoading, setIsLoading] = useState(false); const navigate = useNavigate(); const handleSubmit = async (e) => { const formData = new FormData(e.target); setIsLoading(true); e.preventDefault(); const result = await uploaFiles(file); seturlImg(result); // obtener los datos del formulario const nombre = formData.get("name"); const apellido = formData.get("lastName"); const cedula = formData.get("id"); const nMadre = formData.get("name_madre"); const nPadre = formData.get("name_padre"); const idPadre = formData.get("idPadre"); const idMadre = formData.get("idMadre"); const img = result; // guardar datos en un objeto const newObj = { nombre, apellido, cedula, nMadre, nPadre, idPadre, idMadre, img, }; await saveArchivos(newObj) .then( swal( "Registro Exitoso", "Gracias por registrarte, Espera nuestro llamado", "success" ) ) .then(() => { setIsLoading(false); // establecer el estado de carga en falso cuando se completa la operación navigate("/Students"); }); }; return ( <> <Box sx={{ p: 3 }}> <Container maxWidth="sm" sx={{ bgcolor: "#fff", p: 3 }}> <Typography variant="h4" align="center" mb={3}> Registro de estudiante </Typography> </Container> <Box component="form" onSubmit={handleSubmit} sx={{ mt: 2 }}> <TextField fullWidth label="Nombre completo del estudiante" name="name" id="name" mb={2} required sx={{ my: 1 }} /> <TextField fullWidth label="Apellido" name="lastName" id="lastName" mb={2} required sx={{ my: 1 }} /> <TextField fullWidth label="Documento de identidad del estudiante (opcional)" name="id" id="id" mb={2} sx={{ my: 1 }} /> <TextField fullWidth label="Nombre completo de la madre" name="name_madre" id="name_madre" mb={2} required sx={{ my: 1 }} /> <TextField fullWidth label="Nombre completo del padre" name="name_padre" id="name_padre" mb={2} required sx={{ my: 1 }} /> <TextField fullWidth label="Documento de identidad del padre" name="idPadre" id="idPadre" mb={2} required sx={{ my: 1 }} /> <TextField fullWidth label="Documento de identidad de la madre" name="idMadre" id="idMadre" mb={2} required sx={{ my: 1 }} /> <TextField fullWidth type="file" name="file" id="file" mb={2} required onChange={(e) => setFile(e.target.files[0])} sx={{ my: 1 }} InputLabelProps={{ shrink: true, sx: { mr: 0, my: 0 }, }} label="imagen del estudiante" /> {isLoading ? ( <Typography variant="body1" align="center" mt={2}> Cargando... </Typography> ) : null} <Stack> <Button variant="contained" type="submit"> Enviar </Button> </Stack> </Box> </Box> </> ); }
import React, { useState} from 'react'; export default function StudentForm (props){ const [showAlert, setShowAlert] = useState(false); const Card = () =>{ return ( <div> {showAlert && ( <div className="alert alert-warning" role="alert"> All fields are required... </div> )} </div> ); } const [formData, setFormData] = useState({ name: '', class: '', section: '', fee: '', joiningDate: '' }); const [students, setStudents] = useState([]); const handleInputChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; const handleSave = () => { if(formData.name.trim() === '' | formData.class.trim() === '' || formData.section.trim() === '' || formData.fee.trim() === '' || formData.joiningDate.trim() === '') { setShowAlert(true); setTimeout(() => { setShowAlert(false); }, 1500); } else{ setShowAlert(false); const newStudent = { ...formData }; setStudents([...students, newStudent]); setFormData({ name: '', class: '', section: '', fee: '', joiningDate: '' }); } }; return( <> <Card/> <div className='container'> <h2>Student Information</h2> <div> <label>Name:</label> <input type="text" name="name" value={formData.name} onChange={handleInputChange} /> </div> <div> <label>Class:</label> <input type="text" name="class" value={formData.class} onChange={handleInputChange} /> </div> <div> <label>Section:</label> <input type="text" name="section" value={formData.section} onChange={handleInputChange} /> </div> <div> <label>Fee:</label> <input type="number" name="fee" value={formData.fee} onChange={handleInputChange} /> </div> <div> <label>Joining Date:</label> <input type="date" name="joiningDate" value={formData.joiningDate} onChange={handleInputChange} /> </div> <button onClick={handleSave}>Save</button> {/* Displaying entered data */} <div> <h2>Students Information</h2> <ul> {students.map((student, index) => ( <li key={index}> {`Name: ${student.name}, Class: ${student.class}, Section: ${student.section}, Fee: ${student.fee}, Joining Date: ${student.joiningDate}`} </li> ))} </ul> </div> </div> </> ); }
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Arbitre } from '../model/arbitre'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class ArbitreService { private static URL: string = 'http://localhost:8080/projetbasket/api/arbitre'; constructor(private httpClient: HttpClient) {} public getArbitres(): Observable<Arbitre[]> { let options = undefined; if (sessionStorage.getItem('token')) { options = { headers: new HttpHeaders({ Authorization: sessionStorage.getItem('token')!, }), }; } return this.httpClient.get<Arbitre[]>(ArbitreService.URL, options); } public deleteById(id: number): Observable<void> { return this.httpClient.delete<void>(`${ArbitreService.URL}/${id}`); } public create(arbitre: Arbitre): Observable<Arbitre> { return this.httpClient.post<Arbitre>(ArbitreService.URL, arbitre); } public getById(id: number): Observable<Arbitre> { return this.httpClient.get<Arbitre>(`${ArbitreService.URL}/${id}`); } public update(arbitre: Arbitre): Observable<Arbitre> { return this.httpClient.put<Arbitre>( `${ArbitreService.URL}/${arbitre.id}`, arbitre ); } }
import { PrismaClient } from '@prisma/client'; const prisma = new PrismaClient(); type EventReferentialCreation = ({ title: string; day: string; month: string; country: string; type: "HOLIDAY"; } | { title: string; day: string; month: string; country: string; type: "BIRTHDAY"; })[]; function birthdaysES(): EventReferentialCreation { return [ { title: 'Santo de los Pacos', day: '04', month: '10', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños del tío Fernando', day: '11', month: '10', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de las Pilis', day: '12', month: '10', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Eduardos', day: '13', month: '10', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Paco Eloy', day: '21', month: '10', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Marga', day: '24', month: '10', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Mamen y de Pepe Infierno.', day: '08', month: '11', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de María', day: '11', month: '11', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de la prima Mari Mar', day: '14', month: '11', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de las Cecis', day: '22', month: '11', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Eli y Tavio', day: '25', month: '11', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de la tía Carmen', day: '30', month: '11', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de las Elis', day: '02', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Javis', day: '03', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Susana y Teresa', day: '04', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Aniversario de Luis y Carmen (papa y mama)', day: '07', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Concha.', day: '08', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños Tía Pilar', day: '13', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Elisa (facultad).', day: '18', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Perico', day: '20', month: '12', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Eduardo (padre)', day: '02', month: '01', country: 'FR', type: 'HOLIDAY' }, { title: 'Nuevo Cumpleaños de Eduardo (padre)', day: '02', month: '01', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños del tio Pablo.', day: '04', month: '01', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de ELVIS', day: '08', month: '01', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Javi', day: '28', month: '01', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños del tio Jose', day: '03', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Feni', day: '08', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños y santo del primo Raúl', day: '14', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Pablo (de Andrea)', day: '16', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños del primo Fernando', day: '17', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Lara', day: '18', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de la prima Ceci', day: '23', month: '02', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Joses', day: '19', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Día del Padre', day: '19', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Andrea', day: '21', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Isi', day: '21', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Lola (Toral)', day: '23', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Rocio', day: '23', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo y cumpleaños de la Agüelina', day: '31', month: '03', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños del primo Jorge', day: '07', month: '04', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de mamá Eli', day: '10', month: '04', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Zapa', day: '09', month: '05', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños del primo Jose Pablo', day: '10', month: '05', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Santiago (de Andrea)', day: '24', month: '05', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Fernandos', day: '30', month: '05', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de papá Luis', day: '04', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Cristi', day: '10', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de la Infierna', day: '11', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Gala', day: '15', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Luises', day: '21', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Pedros', day: '29', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de los Pablos', day: '29', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Albertito ', day: '29', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de las Carmenes', day: '16', month: '07', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Luisete', day: '03', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Edu (Jr.)', day: '08', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Mari Jose.', day: '15', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de Jesu', day: '29', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de la Chata', day: '31', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Santo de María', day: '12', month: '09', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños de la tía Ceci', day: '18', month: '09', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños tía Pili (T)', day: '29', month: '09', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumple Esther', day: '29', month: '09', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumpleaños Manuel', day: '19', month: '06', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumple María M.', day: '17', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumple Carlos', day: '21', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumple Inés', day: '23', month: '08', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumple Tijana', day: '16', month: '09', country: 'FR', type: 'HOLIDAY' }, { title: 'Cumple Tomé', day: '16', month: '09', country: 'FR', type: 'HOLIDAY' }, ] } function holidaysES(): EventReferentialCreation { return [ { title: 'Año nuevo', day: '01', month: '01', country: 'ES', type: 'HOLIDAY', } ] } function holidaysFR(): EventReferentialCreation { return [ { title: "Jour de l'an", day: '01', month: '01', country: 'FR', type: 'HOLIDAY', } ] } async function main() { await prisma.eventReferential.createMany({ data: [ ...birthdaysES() ], }); } main() .then(async () => { await prisma.$disconnect(); }) .catch(async (e) => { console.error(e); await prisma.$disconnect(); process.exit(1); });
<?php namespace App\Http\Livewire\Employee\Attendance; use App\Http\Livewire\Basic\BasicTable; use App\Models\Attendance; use App\Models\Employee\Employee; use App\Models\Hr\Branch; use App\Models\Hr\Management; use App\Models\Hr\Department; use Carbon\Carbon; use Carbon\CarbonPeriod; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class Table extends BasicTable { public $branches = []; public $managements = []; public $departments = []; public $employees = []; public $emps = []; public $timezone = "Africa/Cairo"; public $branchId, $managementId, $departmentId, $employeeId, $fromDate, $toDate; public $ids = [], $empId; public function mount(Request $request) { $this->branches = Branch::pluck('name', 'id')->toArray(); // $this->attendances = Attendance::whereDate('created_at', now())->get(); $this->fromDate = date("Y-m-d"); $this->toDate = date("Y-m-d"); $this->searchEmployees(); $timezone = timezone($request->ip()); if ($timezone != "") { $this->timezone = $timezone; } } public function render() { $employeesGroups = $this->searchEmployees(); return view('livewire.employee.attendance.table',compact('employeesGroups')); } public function updatedBranchId($data) { $this->managements = Management::where('branch_id', $data)->pluck('name', 'id')->toArray(); // $this->searchEmployees(); } public function updatedManagementId($data) { $this->departments = Department::where('management_id', $data)->pluck('name', 'id')->toArray(); // $this->searchEmployees(); } public function updatedDepartmentId($data) { // $this->searchEmployees(); } public function updatedFromDate($data) { if (Carbon::hasFormat($data, 'Y-m-d') && Carbon::createFromFormat('Y-m-d', $data)->isValid()) { // if ( Carbon::parse($this->fromDate)->format('Y') !== Carbon::parse(now()->format('Y'))) { // $this->fromDate = Carbon::create(Carbon::now()->year, 1, 1)->format('Y-m-d'); // }else{ $this->fromDate = $data ; // } }else{ $this->fromDate = date("Y-m-d") ; } } public function updatedToDate($data) { if (Carbon::hasFormat($data, 'Y-m-d') && Carbon::createFromFormat('Y-m-d', $data)->isValid()) { // if ( Carbon::parse($this->toDate)->format('Y') !== Carbon::parse(now()->format('Y'))) { // $this->toDate = Carbon::create(Carbon::now()->year, 12, 31)->format('Y-m-d'); // }else{ $this->toDate = $data ; // } }else{ $this->toDate = date("Y-m-d") ; } } public function updatedEmployeeId($data) { $this->empId = $data; } public function searchEmployees() { $query = Employee::query()->draft(0); if ($this->employeeId) { $query->where('id', $this->employeeId); }else{ if (!empty($this->departmentId)) { $query->whereHas("workAt", fn($q) => $q->where('workable_id', $this->departmentId)->where('workable_type', 'departments')); } elseif (!empty($this->managementId)) { $query->whereHas("workAt", fn($q) => $q->where('workable_id', $this->managementId)->where('workable_type', 'managements')); $departmentIds = Department::where('management_id',$this->managementId)->pluck('id')->toArray(); $query->orWhereHas("workAt", fn($q) => $q->whereIn('workable_id', $departmentIds)->where('workable_type', 'departments')); } elseif (!empty($this->branchId)) { $query->whereHas("workAt", fn($q) => $q->where('workable_id', $this->branchId)->where('workable_type', 'branches')); $managementIds = Management::where('branch_id',$this->branchId)->pluck('id')->toArray(); $query->orWhereHas("workAt", fn($q) => $q->whereIn('workable_id', $managementIds)->where('workable_type', 'managements')); $departmentIds = Department::whereIn('management_id',$managementIds)->pluck('id')->toArray(); $query->orWhereHas("workAt", fn($q) => $q->whereIn('workable_id', $departmentIds)->where('workable_type', 'departments')); } } $this->emps = $query->with(['workAt'])->latest()->get() ; $ranges = CarbonPeriod::create($this->fromDate, $this->toDate); $list = collect(); foreach ($ranges as $rangeDate){ $query->with(['reports'=>fn($q) => $q->whereDate('created_at', $rangeDate->format('Y-m-d')) ,'shift'=>fn($q)=>$q->whereHas('days',fn($q)=>$q->where('day_name',$rangeDate->format('D'))), 'workAt'=>fn($q)=>$q->with(['workable'])]); $empsdata= $query->latest()->get(); $list[$rangeDate->format('Y-m-d')] = $empsdata ; } return $list; } public function confirmDelete($id) { Attendance::findOrFail($id)->delete(); $this->dispatchBrowserEvent('toastr', ['type' => 'success', 'message' => __('message.deleted', ['model' => __('names.attend-in')])]); } }
const { model, Schema } = require('mongoose'); const cartSchema = new Schema({ id: Number, products: [ { productId: Number, quantity: Number } ] }); const CartModel = model('Cart', cartSchema); class CartsManager { constructor() { } async readCarts() { try { const carts = await CartModel.find(); return carts; } catch (error) { console.error('Error reading carts from MongoDB:', error); return []; } } async getCartById(cid) { try { console.log(cid); // <-- Aquí deberías imprimir cid, no id const cart = await CartModel.findOne({ _id: cid }); if (!cart) { return 'No se encuentra el carrito'; } return cart; } catch (error) { console.error('Error getting cart by ID from MongoDB:', error); return 'Error obteniendo carrito por ID'; } } async createCart() { try { const carts = await this.readCarts(); let newCart; if (carts.length === 0) { newCart = { products: [] }; // Eliminamos el campo 'id' aquí } else { newCart = { products: [] }; // Eliminamos el campo 'id' aquí también } // Generamos el ID compuesto utilizando la función generaIdcompuesto newCart.id = this.generaIdcompuesto(carts.length); const createdCart = await CartModel.create(newCart); return createdCart; } catch (error) { console.error('Error creating cart in MongoDB:', error); return 'Error creando carrito'; } } async addProductToCart(cid, pid) { try { const cart = await CartModel.findOne({ id: cid }); if (!cart) { return 'No se encuentra el carrito'; } const productIndex = cart.products.findIndex((product) => product.productId === pid); if (productIndex !== -1) { cart.products[productIndex].quantity += 1; } else { cart.products.push({ productId: pid, quantity: 1 }); } const updatedCart = await cart.save(); return updatedCart; } catch (error) { console.error('Error adding product to cart in MongoDB:', error); return 'Error añadiendo producto al carrito'; } } getCarts() { return this.readCarts(); } generaIdcompuesto(largo) { const now = new Date(); const year = now.getFullYear(); const month = now.getMonth() + 1; const day = now.getDate(); const idCorrelative = largo + 1; const combinedId = year * 1000000 + month * 10000 + day * 100 + idCorrelative; return combinedId; } } module.exports = CartsManager;
import requests from bs4 import BeautifulSoup import os import request_page def remove_invalid_characters(url_link): """ removes all invalid characters of the invalid_char_list in the url_link and returns it """ invalid_char_list = ["www.", 'https://', '#', '%', '&', '{', '}', '\\', '*', '?', '/', ' ', '$', "\'", '\"', ':', '@', '+', "`", '|', '='] cleaned_string = url_link for char in invalid_char_list: # replace() "returns" an altered string cleaned_string = cleaned_string.replace(char, "#") return cleaned_string def sanitize_url(url): """ makes an url ready to be saved by removing invalid characters """ sanitized_url = remove_invalid_characters(url) sanitized_url = url.replace("https://", "").replace("/", "_").replace("www.", "") return sanitized_url def get_correct_file_path_to_save(url_link, file_path): """ input: url_link = link that is going to be accessed file_path = location to be saved on output: complete_path = a combination of url_ink and file_path, for the cached file to be saved on """ sanitized_file_name_to_save = sanitize_url(url_link) if isinstance(file_path, str): complete_path = f"{file_path}{sanitized_file_name_to_save}.html" if file_path[-1] == '\\' else f"{file_path}/{sanitized_file_name_to_save}.html" return complete_path elif file_path is None: complete_path = f"{sanitized_file_name_to_save}.html" return complete_path else: if file_path is not None: raise Exception("you specified a wrong type!") def get_cached_file(complete_path): try: with open(complete_path, "r") as cached_file: original_url = cached_file.readline().strip() # Read the first line to get the original url html = cached_file.read() # Read the rest of the file to get the HTML return original_url, html except Exception as e: raise Exception(f"something went wrong: {str(e)}") def save_cached_file(complete_path, original_url, html_file): with open(complete_path, "w") as cached_file: cached_file.write(original_url + "\n") # Write the original url on the first line cached_file.write(str(html_file)) # Write the HTML after the url def get_or_save_cached_file_in_soup_format(url_link, file_path=None): """ input: url_link: link to get access file_path: the folder that you want to access to get/save the output_file output: output: beautiful_soup object in html.parser """ complete_path = get_correct_file_path_to_save(url_link=url_link, file_path=file_path) if os.path.isfile(complete_path): original_url, html = get_cached_file(complete_path) if url_link == original_url: webpage_soup = BeautifulSoup(html, "html.parser") return original_url, webpage_soup #default actions, happen only if the file_path doesn't exist or the original_url not the same as requested webpage_soup = request_page.request_webpage_random_user_agent(url_link) save_cached_file(complete_path=complete_path, original_url=url_link, html_file=webpage_soup) return url_link, webpage_soup if __name__ == "__main__": url_link = "https://www.artificialintelligence-news.com/2023/06/14/european-parliament-adopts-ai-act-position/" #url_link = "https://www.google.nl" url_link = "https://www.unidis.nl" link, webpage = get_or_save_cached_file_in_soup_format(url_link, "cached_files") print(link) print('hi')
SUBROUTINE KPG1_FFTF<T>( M, N, IN, WORK, OUT, STATUS ) *+ * Name: * KPG1_FFTFx * Purpose: * Takes the forward FFT of a real image. * Language: * Starlink Fortran 77 * Invocation: * CALL KPG1_FFTFx( M, N, IN, WORK, OUT, STATUS ) * Description: * The Fourier transform of the input (purely real) image is taken * and returned in OUT. The returned FT is stored in Hermitian * format, in which the real and imaginary parts of the FT are * combined into a single array. The FT can be inverted using * KPG1_FFTBx, and two Hermitian FTs can be multipled together * using routine KPG1_HMLTx. * Arguments: * M = INTEGER (Given) * Number of columns in the input image. * N = INTEGER (Given) * Number of rows in the input image. * IN( M, N ) = ? (Given) * The input image. * WORK( * ) = ? (Given) * Work space. This must be at least ( 3*MAX( M, N ) + 15 ) * elements long. * OUT( M, N ) = ? (Returned) * The FFT in Hermitian form. Note, the same array can be used * for both input and output, in which case the supplied values * will be over-written. * STATUS = INTEGER (Given and Returned) * The global status. * Notes: * - There is a routine for the data types real or double precision: * replace "x" in the routine name by R or D respectively, as * appropriate. The input and output data arrays plus a work space * must have the data type specified. * Copyright: * Copyright (C) 1995, 2003, 2004 Central Laboratory of the Research * Councils. * Copyright (C) 2005 Particle Physics & Astronomy Research * Council. * All Rights Reserved. * Licence: * This programme is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either Version 2 of * the License, or (at your option) any later version. * * This programme 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 programme; if not, write to the Free Software * Foundation, Inc., 51, Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * Authors: * DSB: David Berry (STARLINK) * MJC: Malcolm J. Currie (STARLINK) * TIMJ: Tim Jenness (JAC, Hawaii) * {enter_new_authors_here} * History: * 14-FEB-1995 (DSB): * Original version. Written to replace KPG1_RLFFT which * used NAG routines. * 1995 March 27 (MJC): * Removed long lines and minor documentation revisions. Used * modern-style variable declarations. * 1995 September 7 (MJC): * Used PDA_ prefix for FFTPACK routines. * 13-DEC-2003 (DSB): * Use KPG1_<T>2NAG in stead of PDA_<T>2NAG. KPG1_<T>2NAG uses * workspace to achieve greater speed. * 2004 September 1 (TIMJ): * Use CNF_PVAL. * 2005 September 17 (TIMJ): * Generic-ify. * 2006 April 20 (MJC): * Added Notes and removed RETURN. * {enter_further_changes_here} * Implementation Status: * Some of the generated code looks a bit odd because the names of * the PDA subroutines do not match the standard type naming * conventions required by GENERIC. Explicit IF statements are * included but since these compare constants (after generic is run) * the compiler will optimize the checks out of the final runtime. * The real fix is to fix the names of the PDA routines (and * associated KPG routine). * Bugs: * {note_any_bugs_here} *- * Type Definitions: IMPLICIT NONE ! No implicit typing * Global Constants: INCLUDE 'SAE_PAR' ! Standard SAE constants INCLUDE 'CNF_PAR' ! For CNF_PVAL function * Arguments Given: INTEGER M INTEGER N <TYPE> IN( M, N ) <TYPE> WORK( * ) * Arguments Returned: <TYPE> OUT( M, N ) * Status: INTEGER STATUS ! Global status * Local Variables: INTEGER I ! Column counter INTEGER IPW ! Pointer to work space INTEGER IW ! Index into work array INTEGER J ! Row counter *. * Check the inherited global status. IF ( STATUS .NE. SAI__OK ) RETURN IF ( '<HTYPE>' .NE. '_REAL' .AND. '<HTYPE>' .NE. '_DOUBLE') THEN STATUS = SAI__ERROR CALL ERR_REP( 'KPG1_FFTF<T>', : 'Routine only supports _REAL or _DOUBLE not <HTYPE>', : STATUS ) GOTO 999 END IF * Allocate work space for use in KPG1_R2NAG. Abort if failure. CALL PSX_CALLOC( MAX( M, N ), '<HTYPE>', IPW, STATUS ) IF ( STATUS .NE. SAI__OK ) RETURN * Copy the input array to the output array. DO J = 1, N DO I = 1, M OUT( I, J ) = IN( I, J ) END DO END DO * Initialise an array holding trig. functions used to form the FFT * of the input image rows. IF ( '<TYPE>' .EQ. 'REAL' ) THEN CALL PDA_RFFTI( M, WORK ) ELSE CALL PDA_DRFFTI( M, WORK ) END IF * Transform each row of the output array, and convert each array into * the equivalent NAG format. IF ( '<TYPE>' .EQ. 'REAL' ) THEN DO J = 1, N CALL PDA_RFFTF( M, OUT( 1, J ), WORK ) CALL KPG1_R2NAG( M, OUT( 1, J ), %VAL( CNF_PVAL( IPW ) ) ) END DO ELSE DO J = 1, N CALL PDA_DRFFTF( M, OUT( 1, J ), WORK ) CALL KPG1_DR2NAG( M, OUT( 1, J ), %VAL( CNF_PVAL( IPW ) ) ) END DO END IF * Re-initialise the work array to hold trig. functions used to form * the FFT of the image columns. IF ( '<TYPE>' .EQ. 'REAL' ) THEN CALL PDA_RFFTI( N, WORK ) ELSE CALL PDA_DRFFTI( N, WORK ) END IF * Store the index of the last-used element in the work array. IW = 2 * N + 15 * Transform each column of the current output array. DO I = 1, M * Copy this column to the end of the work array, beyond the part used * to store trig. functions. DO J = 1, N WORK( IW + J ) = OUT( I, J ) END DO * Transform the copy of this column. * The compiler should be able to optimize out the IF that is * always true IF ( '<TYPE>' .EQ. 'REAL' ) THEN CALL PDA_RFFTF( N, WORK( IW + 1 ), WORK ) CALL KPG1_R2NAG( N, WORK( IW + 1 ), : %VAL( CNF_PVAL( IPW ) ) ) ELSE CALL PDA_DRFFTF( N, WORK( IW + 1 ), WORK ) CALL KPG1_DR2NAG( N, WORK( IW + 1 ), : %VAL( CNF_PVAL( IPW ) ) ) END IF * Copy the transformed column back to the output array. DO J = 1, N OUT( I, J ) = WORK( IW + J ) END DO END DO * Free the work space. CALL PSX_FREE( IPW, STATUS ) 999 CONTINUE END
// 재귀함수 이용 func binarySearch(array: [Int], target: Int, start: Int, end: Int) -> Int? { if start > end { return nil } let mid = (start + end) / 2 if array[mid] == target { return mid } else if array[mid] > target { return binarySearch(array: array, target: target, start: start, end: mid - 1) } else { return binarySearch(array: array, target: target, start: mid + 1, end: end) } } let inputs = readLine()!.split(separator: " ").map { return Int($0)! } let n = inputs[0], target = inputs[1] let array = readLine()!.split(separator: " ").map { return Int($0)! } if let result = binarySearch(array: array, target: target, start: 0, end: n - 1) { print(result + 1) } else { print("원소가 존재하지 않습니다") }
import random word_associations = { 'Dog': ['pet', 'bark', 'loyal', 'paw', 'tail'], 'Sun': ['shine', 'day', 'bright', 'warm', 'sky'], 'Music': ['melody', 'rhythm', 'song', 'notes', 'instrument'], 'Tree': ['leaves', 'trunk', 'branch', 'shade', 'nature'], 'Cake': ['sweet', 'dessert', 'celebration', 'birthday', 'delicious'], 'Sleep': ['rest', 'dreams', 'night', 'bed', 'relax'], 'Water': ['drink', 'thirst', 'hydrate', 'wet', 'refreshing'], 'Flower': ['bloom', 'fragrance', 'garden', 'petal', 'colorful'], 'Game': ['play', 'fun', 'competition', 'win', 'entertainment'], 'Phone': ['call', 'text', 'communication', 'device', 'mobile'], 'Rain': ['wet', 'umbrella', 'drops', 'weather', 'storm'], 'Dance': ['movement', 'music', 'rhythm', 'expression', 'joy'], 'Beach': ['sand', 'ocean', 'sun', 'waves', 'relaxation'], 'Moon': ['night', 'lunar', 'orbit', 'crescent', 'astronomy'], 'Car': ['drive', 'road', 'vehicle', 'transportation', 'engine'], 'Raincoat': ['wet', 'protect', 'umbrella', 'waterproof', 'weather'], 'Smile': ['happy', 'joy', 'expression', 'cheerful', 'laugh'], 'Book': ['reading', 'story', 'pages', 'novel', 'literature'], 'Soccer': ['sports', 'ball', 'goal', 'team', 'kick'], 'Bird': ['feather', 'wings', 'fly', 'beak', 'song'], 'Pizza': ['cheese', 'delicious', 'tomato', 'slice', 'topping'], 'Garden': ['flowers', 'plants', 'green', 'grow', 'nature'], 'Moonlight': ['night', 'lunar', 'glow', 'romantic', 'calm'], 'Bicycle': ['ride', 'pedal', 'wheels', 'cycle', 'transportation'], 'Mountain': ['peak', 'hiking', 'scenic', 'summit', 'elevation'], 'Ocean': ['blue', 'waves', 'beach', 'marine', 'tide'], 'Rainbow': ['colors', 'sky', 'arc', 'rain', 'spectrum'], 'Family': ['love', 'relatives', 'caring', 'supportive', 'home'], 'Chocolate': ['sweet', 'indulgence', 'cocoa', 'treat', 'delicious'], 'Star': ['sky', 'shining', 'celestial', 'twinkle', 'astronomy'], 'Camera': ['photography', 'lens', 'shutter', 'capture', 'memories'], 'Summer': ['hot', 'sun', 'vacation', 'season', 'swim'], 'Friend': ['companion', 'bond', 'trust', 'supportive', 'relationship'], 'Coffee': ['caffeine', 'aroma', 'mornings', 'espresso', 'beverage'], 'Adventure': ['explore', 'journey', 'travel', 'excitement', 'thrilling'], 'Cat': ['meow', 'whiskers', 'purr', 'feline', 'pet'], 'River': ['water', 'flow', 'bank', 'current', 'nature'], 'Art': ['creativity', 'expression', 'painting', 'sculpture', 'imagination'], 'Friendship': ['caring', 'trust', 'companionship', 'bond', 'support'], 'Spring': ['flowers', 'renewal', 'growth', 'blossom', 'season'], 'Hat': ['head', 'wear', 'brim', 'fashion', 'sun'], 'Chair': ['sit', 'furniture', 'seat', 'backrest', 'comfort'], 'Ball': ['round', 'sports', 'play', 'bounce', 'kick'], 'Lamp': ['light', 'illuminate', 'bulb', 'table', 'shade'], 'Apple': ['fruit', 'red', 'bite', 'juicy', 'healthy'], 'Boat': ['water', 'sail', 'oar', 'float', 'navigate'], 'Clock': ['time', 'ticking', 'hour', 'minute', 'second'], 'Shirt': ['clothing', 'wear', 'fabric', 'sleeves', 'button'], 'Spoon': ['utensil', 'eat', 'stir', 'soup', 'handle'], 'Window': ['glass', 'view', 'open', 'shut', 'frame'], 'Candle': ['light', 'wax', 'flame', 'burn', 'decorative'], 'Banana': ['fruit', 'yellow', 'peel', 'tropical', 'healthy'], 'Chair': ['sit', 'furniture', 'seat', 'backrest', 'comfort'], 'Pillow': ['sleep', 'rest', 'cushion', 'bed', 'soft'], 'Butterfly': ['insect', 'wings', 'fly', 'colorful', 'garden'], 'Key': ['lock', 'door', 'metal', 'unlock', 'access'], 'Cloud': ['sky', 'white', 'fluffy', 'rain', 'weather'], 'Bridge': ['cross', 'river', 'structure', 'connect', 'path'], 'Guitar': ['music', 'strings', 'play', 'instrument', 'melody'], 'Moonlight': ['night', 'lunar', 'glow', 'romantic', 'calm'], 'Orange': ['fruit', 'citrus', 'juice', 'round', 'zest'], 'Camera': ['photography', 'lens', 'shutter', 'capture', 'memories'], 'Dolphin': ['ocean', 'mammal', 'swim', 'marine', 'intelligent'], 'Ice Cream': ['dessert', 'sweet', 'cold', 'flavor', 'scoop'], 'Flowerpot': ['plant', 'soil', 'garden', 'decorate', 'clay'], 'Backpack': ['carry', 'school', 'travel', 'straps', 'pockets'], 'Telescope': ['stars', 'observe', 'astronomy', 'lens', 'sky'], 'Fireworks': ['celebration', 'explosion', 'night', 'sparkle', 'display'], 'Puzzle': ['pieces', 'solve', 'challenge', 'game', 'assemble'], 'Television': ['watch', 'shows', 'entertainment', 'screen', 'remote'], 'Rainbow': ['colors', 'sky', 'arc', 'rain', 'spectrum'], 'Pizza': ['cheese', 'delicious', 'tomato', 'slice', 'topping'], 'River': ['water', 'flow', 'bank', 'current', 'nature'], 'Moonlight': ['night', 'lunar', 'glow', 'romantic', 'calm'], 'Music': ['melody', 'rhythm', 'song', 'notes', 'instrument'], 'Soccer': ['sports', 'ball', 'goal', 'team', 'kick'], 'Dolphin': ['ocean', 'mammal', 'swim', 'marine', 'intelligent'], 'Lemon': ['fruit', 'yellow', 'sour', 'juice', 'citrus'], 'Guitar': ['music', 'strings', 'play', 'instrument', 'melody'], 'Winter': ['cold', 'snow', 'season', 'cozy', 'holiday'], 'Forest': ['trees', 'nature', 'green', 'wildlife', 'peaceful'], 'Penguin': ['bird', 'waddle', 'snow', 'flightless', 'Antarctica'], 'Camera': ['photography', 'lens', 'shutter', 'capture', 'memories'], 'Summer': ['hot', 'sun', 'vacation', 'season', 'swim'] } def get_user_name(): return input("Greetings, adventurer! What's your name? ") def display_word_association(word): print(f"\nWord: {word}") #def play_again(): #return input("\nDo you want to embark on another journey? (yes/no) ").lower().startswith('y') def show_outro(user_name, score): print(f"\nFarewell, {user_name}!") print(f"Your quest has come to an end. You achieved a score of {score}.") print("May your adventures continue in the realms of knowledge and fun!\n") def main(): print("\nWelcome to the Word Association Game!") print("# Disclaimer: The association words are limited to the game master.\n") user_name = get_user_name() score = 0 while True: word = random.choice(list(word_associations.keys())) display_word_association(word) user_input = input("\nWhat word is associated with the given word? Your answer: ") if user_input in (word_associations[word]): score += 1 print(f"Correct! Your current score is: {score}\n") else: print(f"Alas! That was not the right word.") break #if not play_again(): #break show_outro(user_name, score) if __name__ == "__main__": main()
const router = require('express').Router(); const { celebrate, Joi } = require('celebrate'); const { getUserById, getUsers, updateUser, updateAvatar, getCurrentUser, } = require('../controllers/users'); router.get('/', getUsers); router.get('/me', getCurrentUser); router.get( '/:userId', celebrate({ params: Joi.object().keys({ userId: Joi.string().required().hex().length(24), }), }), getUserById, ); router.patch('/me', celebrate({ body: Joi.object().keys({ name: Joi.string().required().min(2).max(30), about: Joi.string().required().min(2).max(30), }), }), updateUser); router.patch('/me/avatar', celebrate({ body: Joi.object().keys({ avatar: Joi.string().required().pattern(/https?:\/\/(www\.)?[-a-z0-9-._~:/?#@!$&'()*+,;=_]#?/), }), }), updateAvatar); module.exports = router;
import { collection, getDoc, getDocs, limit, orderBy, query, where } from "firebase/firestore"; import { useEffect } from "react"; import { useState } from "react"; import { Link } from "react-router-dom"; import ListingItem from "../components/ListingItem"; import { db } from "../firebase"; import Footer from "../components/Footer"; import { useLocation } from "react-router-dom"; export default function AllListigs() { // Offers const [offerListings, setOfferListings] = useState(null); useEffect(() => { async function fetchListings() { try { // get reference const listingsRef = collection(db, "listings"); // create the query const q = query(listingsRef, where("offer", "==", true), orderBy("timestamp", "desc"), limit(4)); // execute the query const querySnap = await getDocs(q); const listings = []; querySnap.forEach((doc) => { return listings.push({ id: doc.id, data: doc.data(), }); }); setOfferListings(listings); } catch (error) { console.log(error); } } fetchListings(); }, []); // Places for rent const [rentListings, setRentListings] = useState(null); useEffect(() => { async function fetchListings() { try { // get reference const listingsRef = collection(db, "listings"); // create the query const q = query(listingsRef, where("type", "==", "rent"), orderBy("timestamp", "desc"), limit(4)); // execute the query const querySnap = await getDocs(q); const listings = []; querySnap.forEach((doc) => { return listings.push({ id: doc.id, data: doc.data(), }); }); setRentListings(listings); } catch (error) { console.log(error); } } fetchListings(); }, []); // Places for rent const [saleListings, setSaleListings] = useState(null); useEffect(() => { async function fetchListings() { try { // get reference const listingsRef = collection(db, "listings"); // create the query const q = query(listingsRef, where("type", "==", "sale"), orderBy("timestamp", "desc"), limit(4)); // execute the query const querySnap = await getDocs(q); const listings = []; querySnap.forEach((doc) => { return listings.push({ id: doc.id, data: doc.data(), }); }); setSaleListings(listings); } catch (error) { console.log(error); } } fetchListings(); }, []); const location = useLocation(); useEffect(() => { if (location.hash === "#rentalHouses") { setTimeout(() => { const rentalHousesElement = document.getElementById("rentalHouses"); if (rentalHousesElement) { rentalHousesElement.scrollIntoView({ behavior: "smooth" }); } }, 4000); } }, [location]); return ( <div> {/* <Slider /> */} <div className="max-w-8xl mx-auto pt-4 space-y-6 px-6"> {offerListings && offerListings.length > 0 && ( <div className="m-2 mb-6"> <h2 className="px-3 text-2xl mt-6 font-semibold">Recent offers</h2> <Link to="/offers"> <p className="px-3 text-sm text-blue-600 hover:text-blue-800 transition duration-150 ease-in-out">Show more offers</p> </Link> <ul className="sm:grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 "> {offerListings.map((listing) => ( <ListingItem key={listing.id} listing={listing.data} id={listing.id} /> ))} </ul> </div> )} {rentListings && rentListings.length > 0 && ( <div className="m-2 mb-6" id="rentalHouses"> <h2 className="px-3 text-2xl mt-6 font-semibold">Places for rent</h2> <Link to="/category/rent"> <p className="px-3 text-sm text-blue-600 hover:text-blue-800 transition duration-150 ease-in-out">Show more places for rent</p> </Link> <ul className="sm:grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 "> {rentListings.map((listing) => ( <ListingItem key={listing.id} listing={listing.data} id={listing.id} /> ))} </ul> </div> )} {saleListings && saleListings.length > 0 && ( <div className="m-2 mb-6"> <h2 className="px-3 text-2xl mt-6 font-semibold">Places for sale</h2> <Link to="/category/sale"> <p className="px-3 text-sm text-blue-600 hover:text-blue-800 transition duration-150 ease-in-out">Show more places for sale</p> </Link> <ul className="sm:grid sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 "> {saleListings.map((listing) => ( <ListingItem key={listing.id} listing={listing.data} id={listing.id} /> ))} </ul> </div> )} </div> <Footer /> </div> ); }
import { Component, Inject, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { ApiService } from '../services/api.service'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; @Component({ selector: 'app-dialog', templateUrl: './dialog.component.html', styleUrls: ['./dialog.component.scss'] }) export class DialogComponent implements OnInit { activityList = ["Project", "Presentation", "Class Work"] studentForm !: FormGroup; actionBtn : string = "Save" constructor(private formBuilder : FormBuilder, private api : ApiService, @Inject(MAT_DIALOG_DATA) public editData : any, private dialogRef : MatDialogRef<DialogComponent>) { } ngOnInit(): void { this.studentForm = this.formBuilder.group({ studentName : ['',Validators.required], gender : ['',Validators.required], activitytype : ['',Validators.required], grade : ['',Validators.required], comment : ['',Validators.required], date : ['',Validators.required], }); if(this.editData){ this.actionBtn = "Update" this.studentForm.controls['studentName'].setValue(this.editData.studentName); this.studentForm.controls['gender'].setValue(this.editData.gender); this.studentForm.controls['activitytype'].setValue(this.editData.activitytype); this.studentForm.controls['grade'].setValue(this.editData.grade); this.studentForm.controls['comment'].setValue(this.editData.comment); this.studentForm.controls['date'].setValue(this.editData.date); } } addStudent(){ if(!this.editData){ if(this.studentForm.valid){ this.api.postStudent(this.studentForm.value) .subscribe({ next:(res)=>{ alert("Student Was Added Sucessfully") this.studentForm.reset(); this.dialogRef.close('save'); }, error:(err)=>{ alert("Error While Adding The Student!!") } }) } }else{ this.updateStudent() } } updateStudent(){ this.api.putStudent(this.studentForm.value,this.editData.id) .subscribe({ next:(res)=>{ alert("Student Info Updated Successfully"); this.studentForm.reset(); this.dialogRef.close('update'); }, error:()=>{ alert("Error While Updating Student Info!!"); } }) } }
import { DOTS, usePagination } from "../hooks/usePagination.jsx"; const classnames = () => { return ""; }; const Pagination = (props) => { const { onPageChange, totalCount, siblingCount = 1, currentPage, pageSize, className, } = props; const paginationRange = usePagination({ currentPage, totalCount, siblingCount, pageSize, }); if (currentPage === 0 || paginationRange.length < 2) { return null; } const onNext = () => { onPageChange(currentPage + 1); }; const onPrevious = () => { onPageChange(currentPage - 1); }; let lastPage = paginationRange[paginationRange.length - 1]; return ( <div className="flex"> <ul className="s-pagination"> {paginationRange.map((pageNumber, index) => { if (pageNumber === DOTS) { return ( <li key={index} className="dots"> &#8230; </li> ); } return ( <li key={index} className={pageNumber === currentPage ? "selected" : ""} onClick={ pageNumber === currentPage ? () => {} : () => onPageChange(pageNumber) } > {pageNumber} </li> ); })} </ul> </div> ); }; export default Pagination;
<!DOCTYPE html> <html lang="ru"> <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>First home task</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.0.0/modern-normalize.min.css" /> <link rel="stylesheet" href="./css/styles.css" /> <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=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap" rel="stylesheet" /> </head> <body class="page"> <header class="page-header"> <nav> <a class="logo primary" href="./index.html" lang="en" >Web<span class="logo secondary">Studio</span></a > <ul class="site-nav list"> <li><a class="link current" href="./index.html">Студия</a></li> <li><a class="link" href="./portfolio.html">Портфолио</a></li> <li><a class="link" href="">Контакты</a></li> </ul> </nav> <ul class="contacts list"> <li> <a class="info" href="mailto:[email protected]" >[email protected]</a > </li> <li> <a class="info" href="tel:+380961111111">+38 096 111 11 11</a> </li> </ul> </header> <main class="unique"> <!-- Герой --> <section class="hero"> <h1 class="hero-title"> Эффективные решения <br /> для вашего бизнеса </h1> <button name="order_button" value="primary" type="button" class="button" > Заказать услугу </button> </section> <!-- Преимущества --> <section class="section"> <!-- <h2 class="hidden">Чем мы лучше</h2> --> <ul class="features list"> <li> <h3 class="title">Внимание к деталям</h3> <p class="passage"> Идейные соображения, а также начало повседневной работы по формированию позиции. </p> </li> <li> <h3 class="title">Пунктуальность</h3> <p class="passage"> Задача организации, в особенности же рамки и место обучения кадров влечет за собой. </p> </li> <li> <h3 class="title">Планирование</h3> <p class="passage"> Равным образом консультация с широким активом в значительной степени обуславливает. </p> </li> <li> <h3 class="title">Современные технологии</h3> <p class="passage"> Значимость этих проблем настолько очевидна, что реализация плановых заданий. </p> </li> </ul> </section> <section class="section"> <h2 class="section-title">Чем мы занимаемся</h2> <ul class="section-list"> <li> <img src="./images/box1.jpg" alt="Программист печатает код" width="370" height="294" /> </li> <li> <img src="./images/box2.jpg" alt="Программист делает адаптацию для телефонов" width="370" height="294" /> </li> <li> <img src="./images/box3.jpg" alt="Программист изучает палитру цветов" width="370" height="294" /> </li> </ul> </section> <section class="section team"> <h2 class="section-title">Наша команда</h2> <ul class="teamlist"> <li class="teammates"> <img class="userpic" src="./images/img.jpg" alt="дизайнер продукта" width="270" /> <h3 class="team-member">Игорь Демьяненко</h3> <p class="position" lang="en">Product Designer</p> </li> <li class="teammates"> <img class="userpic" src="./images/img1.jpg" alt="фронт-энд разработчик" width="270" /> <h3 class="team-member">Ольга Репина</h3> <p class="position" lang="en">Frontend Developer</p> </li> <li class="teammates"> <img class="userpic" src="./images/img2.jpg" alt="маркетинг" width="270" /> <h3 class="team-member">Николай Тарасов</h3> <p class="position" lang="en">Marketing</p> </li> <li class="teammates"> <img class="userpic" src="./images/img3.jpg" alt="дизайнер" width="270" /> <h3 class="team-member">Михаил Ермаков</h3> <p class="position" lang="en">UI Designer</p> </li> </ul> </section> </main> <footer class="footer"> <a class="logo primary" href="./index.html" lang="en" >Web<span class="logo secondary">Studio</span></a > <address class="address"> г. Киев, пр-т Леси Украинки, 26 <br /> <a class="contact-info" href="mailto:[email protected]" >[email protected]</a > <br /> <a class="contact-info" href="tel:+380961111111">+38 099 111 11 11</a> </address> </footer> </body> </html>
package com.hidden.artify.ui.edit import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.hidden.artify.core.common.Resource import com.hidden.artify.core.viewmodel.BaseViewModel import com.hidden.artify.data.model.EditResponse import com.hidden.artify.data.repository.ImageRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import java.io.File import javax.inject.Inject @HiltViewModel class EditPhotoViewModel @Inject constructor( private val repository: ImageRepository ) : BaseViewModel() { private val _editedImageResponse = MutableLiveData<Resource<EditResponse>>() val editedImageResponse: LiveData<Resource<EditResponse>> = _editedImageResponse fun uploadImage(file: File, mask: File, prompt: String, n: Int, size: String) = viewModelScope.launch { _editedImageResponse.value = Resource.loading(null) viewModelScope.launch { val response = repository.loadImage(file, mask, prompt, n, size) _editedImageResponse.postValue(response) } } }
// See the 'COPYING' file in the project root for licensing information. /* * Adaptive Framework memory pool internal header. * * Copyright (c) 2010-2023 Clemson University * */ #ifndef __AFW_POOL_INTERNAL_H__ #define __AFW_POOL_INTERNAL_H__ #include "afw_interface.h" /** * @defgroup afw_pool_internal Pool * @ingroup afw_c_api_internal * * Pool internal API * * @{ */ /** * @file afw_pool.h * @brief Adaptive Framework memory pool internal header. */ AFW_BEGIN_DECLARES typedef struct afw_pool_internal_multithreaded_self_s afw_pool_internal_multithreaded_self_t; struct afw_pool_internal_multithreaded_self_s { afw_pool_t pub; /** @brief Associated apr pool or NULL if it has not been created. */ apr_pool_t *apr_p; /** @brief Optional pool name. */ const afw_utf8_t *name; /** @brief Parent pool of this pool. */ afw_pool_internal_multithreaded_self_t *parent; /* @brief First subpool of this pool. */ afw_pool_internal_multithreaded_self_t * AFW_ATOMIC first_child; /* @brief Next sibling of this pool. */ afw_pool_internal_multithreaded_self_t * AFW_ATOMIC next_sibling; /** * @brief Pools reference count. * * This starts at 1 on create and is incremented and decremented * by afw_pool_add_reference() and afw_pool_release(). */ AFW_ATOMIC afw_integer_t reference_count; /** @brief First cleanup function. */ afw_pool_cleanup_t *first_cleanup; /** @brief Bytes allocated via afw_pool_malloc()/afw_pool_calloc(). */ AFW_ATOMIC afw_size_t bytes_allocated; /** @brief Unique number for pool. */ afw_integer_t pool_number; }; typedef struct afw_pool_internal_singlethreaded_self_s afw_pool_internal_singlethreaded_self_t; struct afw_pool_internal_singlethreaded_self_s { afw_pool_t pub; /** @brief Associated apr pool or NULL if it has not been created. */ apr_pool_t *apr_p; /** @brief Optional pool name. */ const afw_utf8_t *name; /** @brief Parent pool of this pool. */ afw_pool_internal_singlethreaded_self_t *parent; /* @brief First subpool of this pool. */ afw_pool_internal_singlethreaded_self_t *first_child; /* @brief Next sibling of this pool. */ afw_pool_internal_singlethreaded_self_t *next_sibling; /** * @brief Pools reference count. * * This starts at 1 on create and is incremented and decremented * by afw_pool_add_reference() and afw_pool_release(). */ afw_integer_t reference_count; /** * @brief Thread associated with a thread specific pool. * * If this is not NULL, this pool is thread specific and can only be * accessed by this thread. */ const afw_thread_t *thread; /** @brief First cleanup function. */ afw_pool_cleanup_t *first_cleanup; /** @brief Bytes allocated via afw_pool_malloc()/afw_pool_calloc(). */ afw_size_t bytes_allocated; /** @brief Unique number for pool. */ afw_integer_t pool_number; }; /** * @internal * @brief Allocate base pool. * @return Pointer to base pool or NULL if there is an error. * * This should only be used in afw_environment_create(). */ AFW_DECLARE(const afw_pool_t *) afw_pool_internal_create_base_pool(); /** * @internal * @brief Create thread struct in new thread specific pool with p set. * @param size of thread struct or -1 if sizeof(afw_thread_t) should be used. * @param xctx of caller. * @return new thread struct with p set. * * This should only be called from afw_thread_create(). */ AFW_DECLARE(afw_thread_t *) afw_pool_internal_create_thread( afw_size_t size, afw_xctx_t *xctx); /** * @internal * @brief Debug version of create thread struct in new thread specific pool * with p set. * @param size of thread struct or -1 if sizeof(afw_thread_t) should be used. * @param xctx of caller. * @param source_z file:line where function called. * @return new thread struct with p set. * * This should only be called from afw_thread_create(). */ AFW_DECLARE(afw_thread_t *) afw_pool_internal_create_thread_debug( afw_size_t size, afw_xctx_t *xctx, const afw_utf8_z_t *source_z); #ifdef AFW_POOL_DEBUG #define afw_pool_internal_create_thread(size,xctx) \ afw_pool_internal_create_thread_debug(size, xctx, AFW__FILE_LINE__) #endif AFW_END_DECLARES /** @} */ #endif /* __AFW_POOL_INTERNAL_H__ */
import { createTable, createRender } from 'svelte-headless-table'; import { addSortBy, addTableFilter, addSelectedRows, addHiddenColumns, addDataExport } from 'svelte-headless-table/plugins'; import SelectCell from './selectCell.svelte'; import ImageCell from './imageCell.svelte'; export class SuperTable { cols = []; rowNumber = 0; constructor(data, colArray, options) { this.defaultPlugins = { sort: addSortBy({ disableMultiSort: false }), tableFilter: addTableFilter(), select: addSelectedRows(), hidden: addHiddenColumns(), export: addDataExport() }; this.defaultOptions = { order: true, sort: true, tableFilter: true, select: true, hidden: true, export: true, rowSelector: false }; this.runFilterOption = this.filterOption(this.defaultOptions, this.defaultPlugins, options); this.table = createTable(data, this.defaultPlugins); this.plugins = { sort: { invert: true }, tableFilter: { exclude: false } }; this.createColsArray(colArray, this.plugins); this.init = this.table.createViewModel(this.table.createColumns(this.cols)); this.plugin = this.init.pluginStates; } filterOption = (defaultOptions, defaultPlugins, input) => { Object.keys(input).forEach((key) => { if (input[key] === false) { delete defaultOptions[key]; delete defaultPlugins[key]; } }); }; createColsArray = (colArray, plugin) => { /** * define select column and it's plugin */ const ColSelect = { id: 'selected', header: ({ row }, { pluginStates }) => { const { allRowsSelected } = pluginStates.select; return createRender(SelectCell, { isSelected: allRowsSelected }); }, cell: ({ row }, { pluginStates }) => { const { isSelected } = pluginStates.select.getRowState(row); return createRender(SelectCell, { isSelected }); }, plugins: { export: { exclude: true } } }; /** * define order column, i'm sure there's feature to do this * but i cant find it so i only knew this way (the sort plugin works). */ const ColOrder = { id: 'order', header: 'No', cell: ({ row }) => { return parseInt(row.id) + 1; }, accessor: () => { return (this.rowNumber += 1); }, plugins: { sort: Object.keys(this.defaultOptions).includes('sort') ? { invert: true } : undefined } }; /** * check if there's image to display * so we add costum createRender with ImageCell components */ colArray = colArray.map((v, index) => { if (v.isImage === true) { v.cell = ({ row }) => { let column = v.accessor; return createRender(ImageCell, { row, column }); }; return v; } return v; }); /** * recreate the array to include the plugin * then creating table.column() * only data that work with table.column */ colArray.forEach((v, index) => { v = { ...v, plugins: plugin }; this.cols[index] = this.table.column(v); }); /** * add the select column and order column with unshift * so the array will insert to the first index */ if (Object.keys(this.defaultOptions).includes('order')) { this.cols.unshift(this.table.column(ColOrder)); } if (Object.keys(this.defaultOptions).includes('rowSelector')) { // if (this?.options?.rowSelector === true) { this.cols.unshift(this.table.display(ColSelect)); } this.rowNumber = 0; }; }
import { FC, PropsWithChildren, ReactNode } from "react"; import * as RadixDialog from "@radix-ui/react-dialog"; import { Track } from ".."; import "./Modal.scss"; type ModalProps = { title: string | null; footer?: ReactNode; onClose: () => void; }; const Modal: FC<PropsWithChildren<ModalProps>> = ({ title, footer, onClose, children }) => { return ( <RadixDialog.Root defaultOpen={true} onOpenChange={onClose}> <RadixDialog.Portal> <RadixDialog.Overlay className="modal__overlay" /> <RadixDialog.Content className="modal"> {title && ( <div className="modal__header"> <RadixDialog.Title className="h3 modal__title">{title}</RadixDialog.Title> </div> )} <div className="modal__body">{children}</div> {footer && ( <Track className="modal__footer" gap={16} justify="end"> {footer} </Track> )} </RadixDialog.Content> </RadixDialog.Portal> </RadixDialog.Root> ); }; export default Modal;
import numpy as np import scipy.stats as stats import scipy from math import comb, factorial, pi, exp, sqrt std_of_geometric_dist = lambda p : sqrt(1 - p) / p def std_of_disc_rand_var(X, p): X = np.array(X) p = np.array(p) E = np.dot(X, p) var = np.dot(p, (X - E)**2) std = np.sqrt(var) return std def binom_mean_std(p, n): """ https://www.khanacademy.org/math/ap-statistics/random-variables-ap/binomial-mean-standard-deviation/v/variance-of-binomial-variable X = Number of succ from n trials where P(succ) = p for each independent trial Y Y: P(Y = 1) = p P(Y = 0) = q = 1 - p E(Y) = p * 1 + q * 0 = p Var(Y) = E[(Y - E(Y))^2] = p * (1 - p)^2 + q * (0 - p)^2 = p * (1 - 2p + p^2) + q * p^2 = p * (1 - 2p + p^2) + (1 - p) * (p^2) = p - 2p^2 + p^3 + p^2 - p^3 = p - p^2 = p * (1- p) = p * q E(X)= n * E(Y) = n * p Var(Y) = n * Var(X) = n * p * q """ q = 1 - p mean = n * p var = n * p * q std = sqrt(var) return mean, std binom_std = lambda p, n=1: sqrt(n * p * (1 - p)) def geometric_mean_std(prob): """ Returns the mean and standard deviation for a given probability. """ mean = 1 / prob std = ((1 - prob) ** 0.5) / prob return mean, std def integral(f, a, b, h=0.001): x_values = np.arange(a, b, h) y_values = f(x_values) area = np.sum(y_values) * h return area def unit_norm(x): num = exp(-0.5 * x**2) den = (2 * pi)**0.5 return num / den def custom_norm(mean, std): return lambda x: (unit_norm(x) * std) + mean def clip(n, min_val=-4, max_val=4): if n < min_val: return min_val elif n > max_val: return max_val else: return n z_score_to_cdf = lambda z_score : stats.norm.cdf(z_score) cdf_to_z_score = lambda cdf : scipy.stats.norm.ppf(cdf) def z_star_to_conf_level(z_star): p = z_score_to_cdf(z_star) q = 1 -p conf = 1 - 2 * q return conf def conf_level_to_z_star(conf_level): q = 1 - conf_level cdf = 1 - q/2 return cdf_to_z_score(cdf) anti_log10 = lambda x: 10**x anti_ln = lambda x: np.e**x nCr = lambda n, r: comb(n, r) fac = lambda x: factorial(x)
%w[book classroom nameable person rental student teacher].each { |file| require_relative file } class App def initialize() @all_students = [] @all_teachers = [] @all_books = [] @all_rentals = [] end def list_all_books if @all_books.empty? puts 'No books available' else banner('All available books') @all_books.each do |book| puts "Title: #{book.title}, Author: #{book.author}" end end end def list_all_people banner('All available people') if @all_students.length.positive? || @all_teachers.length.positive? @all_students.each do |student| puts "[student] Name: #{student.name}, ID: #{student.id} ,Age: #{student.age}" end @all_teachers.each do |teacher| puts "[Teacher] Name: #{teacher.name}, ID: #{teacher.id}, Age: #{teacher.age}" end else puts 'No person to display' end end def create_person banner('Create a person') print 'Do you want to create a student (1) or a teacher (2)? [input the number] >> ' choice = gets.chomp.to_i case choice when 1 create_student when 2 create_teacher else puts 'Invalid input' end end def create_student puts 'Create a student' print 'Age: ' age = gets.chomp.to_i print 'Name: ' name = gets.chomp print 'Has parent permission? [y/n]' gets.chomp classroom = Classroom.new('Class A') student = Student.new(age, name, classroom.label) @all_students.push(student) puts 'Person created successfully' end def create_teacher puts 'Create a teacher' print 'Age: ' age = gets.chomp.to_i print 'Name: ' name = gets.chomp print 'Specialization: ' spec = gets.chomp teacher = Teacher.new(age, name, spec) @all_teachers.push(teacher) puts 'Person created successfully' end def create_book banner('Create a book') print 'Title: ' title = gets.chomp print 'Author: ' author = gets.chomp book = Book.new(title, author) puts book @all_books.push(book) puts 'Book created successfully' end def create_rental banner('Create a rental') if @all_books.empty? puts 'No books to display' else puts 'Select a book from the following list by number ' @all_books.each_with_index { |book, i| puts "#{i}) Title: #{book.title}, Author: #{book.author} \n" } book_choice = gets.chomp.to_i selected_book = @all_books[book_choice] puts 'Select a person from the following list by number (not id)' persons = @all_students + @all_teachers persons.each_with_index { |person, i| puts "#{i}) Name: #{person.name}, ID: #{person.id}, Age: #{person.age}" } person_choice = gets.chomp.to_i selected_person = persons[person_choice] print 'Date: ' date = gets.chomp rental = Rental.new(date, selected_book, selected_person) @all_rentals.push(rental) puts 'Rental created successfully' end end def list_all_rentals banner('All available rentals') if @all_rentals.empty? puts 'No rentals available' else print 'ID of the person: ' person_id = gets.chomp.to_i puts 'Rentals: ' @all_rentals.each do |rental| if rental.person.id == person_id puts "Date: #{rental.date}, Book: #{rental.book.title} by #{rental.book.author}" end end end end def header banner('Welcome to SCHOOL LIBRARY App') puts 'Please choose an option by entering a number:' puts '1 - List all books ' puts '2 - List all people ' puts '3 - Create a person ' puts '4 - Create a book ' puts '5 - Create a rental ' puts '6 - List all rentals for a given person id ' puts '7 - Exit ' end def banner(title) puts ''.center(50, '*') puts '**' << ''.center(46) << '**' puts '**' << title.center(46) << '**' puts '**' << ''.center(46) << '**' puts ''.center(50, '*') end end
import React, { Component } from 'react' import ReactDOM from 'react-dom' import LunarCalendar from 'lunar-calendar' import '../style/calendar.less' import '../images/calendar.png' // 如果是节日,显示节日 // 如果不是节日但是是节气,显示节气 // 如果不是节日和节气但是是每月农历初一,显示农历月份 // 否则显示农历日 function lunarFestivalFilter (value) { switch (value) { case '龙抬头节': case '妈祖生辰': case '下元节': return '' case '七夕情人节': return '七夕节' default: return value } } function getAlmanac (yyyymm) { let arr = [] let lunar = LunarCalendar.calendar(yyyymm.substr(0, 4), yyyymm.substr(4, 2), false).monthData // 生肖年 节气 干支年 干支月 干支日 农历月 农历日 公历节日 农历节日 // let keys = ['zodiac', 'term', 'GanZhiYear', 'GanZhiMonth', 'GanZhiDay', 'lunarMonthName', 'lunarDayName', 'solarFestival', 'lunarFestival'] for (let i = 0; i < lunar.length; i++) { let lu = lunar[i] lu.lunarFestival = lunarFestivalFilter(lu.lunarFestival) lu.lunarValue = lu.lunarFestival || lu.term || (lu.lunarDayName === '初一' ? lu.lunarMonthName : lu.lunarDayName) arr.push(lu) } return arr } class Calendar extends Component { constructor () { super() this.state = { date: new Date(), lunar: {}, holiday: {} } } render () { let oDate = this.state.date let year = oDate.getFullYear() let month = oDate.getMonth() let date = oDate.getDate() let days = this.getMonthDays(year, month, date) let rows = [] let cells = [] for (let i = 0; i < days.length; i++) { let classList = ['cell'] if (days[i].inactive) { classList.push('inactive') } else if (days[i].date === date) { classList.push('current') } cells.push( <div className={classList.join(' ')} key={i}> {(days[i].holiday && days[i].holiday.status) && (days[i].holiday.status === '1' ? <div className='rest'>休</div> : <div className='work'>班</div>)} <p>{days[i].date}</p> {(days[i].holiday && days[i].holiday.name) ? <p>{days[i].holiday.name}</p> : <p>{days[i].lunar.lunarValue}</p>} </div> ) } for (let i = 0; i < Math.ceil(cells.length / 7); i++) { rows.push( <div className='row' key={i}> {cells.slice(i * 7, (i + 1) * 7)} </div> ) } return ( <div className='calendar'> <div className='ctrl'> <div className='year'> <select onChange={this.yearChange.bind(this)} value={year}> <option value={year - 2}>{year - 2}年</option> <option value={year - 1}>{year - 1}年</option> <option value={year}>{year}年</option> <option value={year + 1}>{year + 1}年</option> <option value={year + 2}>{year + 2}年</option> <option value={year + 3}>{year + 3}年</option> </select> </div> <div className='month'> <a href='javascript:;' className='btn-prev' onClick={this.prevHandler.bind(this)}>&lt;</a> <select onChange={this.monthChange.bind(this)} value={month}> {(function () { let arr = [] for (let i = 0; i < 12; i++) { arr.push(<option value={i} key={i}>{i + 1}月</option>) } return arr })()} </select> <a href='javascript:;' className='btn-next' onClick={this.nextHandler.bind(this)}>&gt;</a> </div> <div className='today'> <a href='javascript:;' onClick={this.todayHandler.bind(this)}>返回今天</a> </div> </div> <div className='table' onClick={this.dateChange.bind(this)}> <div className='row'> <div className='cell'><p>一</p></div> <div className='cell'><p>二</p></div> <div className='cell'><p>三</p></div> <div className='cell'><p>四</p></div> <div className='cell'><p>五</p></div> <div className='cell'><p>六</p></div> <div className='cell'><p>日</p></div> </div> {rows} </div> </div> ) } componentWillMount () { // 节气 ['小寒', '大寒', '立春', '雨水', '惊蛰', '春分', '清明', '谷雨', '立夏', '小满', '芒种', '夏至', '小暑', '大暑', '立秋', '处暑', '白露', '秋分', '寒露', '霜降', '立冬', '小雪', '大雪', '冬至'] // 天干 ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'] // 地址 ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'] // 生效 ['鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪'] let oDate = this.state.date let yyyymms = this.getYYYYMMs(oDate.getFullYear(), oDate.getMonth()) this.getAlmanacInfo(yyyymms) this.getHolidayInfo(yyyymms) } shouldComponentUpdate (nextProps, nextState) { let oDate = nextState.date let lunar = nextState.lunar let holiday = nextState.holiday let bool = true let yyyymms = this.getYYYYMMs(oDate.getFullYear(), oDate.getMonth()) yyyymms.forEach(item => { if (bool === true) { if (!lunar[item]) { bool = false } if (holiday[item] === undefined) { bool = false } } }) return bool } getYYYYMMs (year, month) { return [ month === 0 ? (year - 1) + '12' : year + ('0' + month).substr(-2, 2), year + ('0' + (month + 1)).substr(-2, 2), month === 11 ? (year + 1) + '01' : year + ('0' + (month + 2)).substr(-2, 2) ] } getMonthDays (year, month, date) { let lunar = this.state.lunar let holiday = this.state.holiday let [prev, now, next] = this.getYYYYMMs(year, month) let dateStr = year + '-' + ('0' + (month + 1)).substr(-2, 2) + '-' + ('0' + date).substr(-2, 2) let firstDay = this.getFirstDay(dateStr) || 7 // 本月第一天星期几, 星期一是1, 星期日是0, 用7表示 let days = this.getDayCountByMonth(dateStr) // 本月一共多少天 // 上个月一共多少天 let lastMonthDays = this.getDayCountByMonth(month === 0 ? (year - 1) + '-12' : year + '-' + ('0' + month).substr(-2, 2)) let arr = [] // 需要显示的上个月日期 for (let i = lastMonthDays - (firstDay - 1) + 1; i <= lastMonthDays; i++) { arr.push({ date: i, lunar: lunar[prev][i - 1], holiday: (holiday && holiday[prev]) ? holiday[prev][i] : {}, inactive: true }) } for (let i = 1; i <= days; i++) { arr.push({ date: i, lunar: lunar[now][i - 1], holiday: (holiday && holiday[now]) ? holiday[now][i] : {} }) } if (arr.length % 7 !== 0) { arr = arr.concat([1, 2, 3, 4, 5, 6, 7].slice(0, 7 - arr.length % 7).map(i => { return { date: i, lunar: lunar[next][i - 1], holiday: (holiday && holiday[next]) ? holiday[next][i] : {}, inactive: true } })) } return arr } getAlmanacInfo (arr) { let state = {} for (let i = 0; i < arr.length; i++) { state[arr[i]] = getAlmanac(arr[i]) } this.setState({ lunar: state }) } getHolidayInfo (arr) { let state = {} let temp = [] let data = JSON.parse(window.localStorage.getItem('holiday') || '{}') arr.map(yyyymm => { if (data && data[yyyymm] && Object.keys(data[yyyymm]).length !== 0) { state[yyyymm] = data[yyyymm] } else { state[yyyymm] = {} temp.push(yyyymm) } }) if (temp.length > 0 && navigator.onLine) { this.fetchHolidayInfo(temp).then(holiday => { for (let name in holiday) { data[name] = holiday[name] state[name] = holiday[name] } this.setState({ holiday: state }) window.localStorage.setItem('holiday', JSON.stringify(data)) }, err => { throw err }) } else { this.setState({ holiday: state }) } } fetchHolidayInfo (range) { return new Promise((resolve, reject) => { let xhr = new window.XMLHttpRequest() xhr.responseType = 'json' xhr.open('POST', window.location.protocol + '//hunter.im-flower.com/holiday') xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send('yyyymms=' + range.join('|')) xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { resolve(xhr.response) } else { reject(new Error('fetch holiday info error')) } } } }) } setDate (oDate) { this.setState({ date: oDate }) let yyyymms = this.getYYYYMMs(oDate.getFullYear(), oDate.getMonth()) this.getAlmanacInfo(yyyymms) this.getHolidayInfo(yyyymms) } yearChange (e) { let value = Number(e.nativeEvent.target.value) let oDate = this.state.date oDate.setFullYear(value) this.setDate(oDate) } monthChange (e) { let value = Number(e.nativeEvent.target.value) let oDate = this.state.date oDate.setMonth(value) this.setDate(oDate) } dateChange (e) { let oDate = this.state.date let year = oDate.getFullYear() let month = oDate.getMonth() // let date = oDate.getDate() let target = e.nativeEvent.target target.tagName.toLowerCase() === 'p' && (target = target.parentNode) let inactive = target.className.indexOf('inactive') !== -1 let value = target.innerText // 点到 一二三 if (value.match(/\d+/g) === null || target.className.indexOf('cell') === -1) { return } value = Number(value.match(/\d+/g)[0]) oDate.setDate(value) if (inactive) { // 上个月 if (value > 20) { month-- if (month === -1) { oDate.setFullYear(year - 1) oDate.setMonth(11) } else { oDate.setMonth(month) } } // 下个月 if (value < 7) { month++ if (month === 12) { oDate.setFullYear(year + 1) oDate.setMonth(0) } else { oDate.setMonth(month) } } } this.setDate(oDate) } prevHandler () { let oDate = this.state.date let year = oDate.getFullYear() let month = oDate.getMonth() if (this.state.month === 0) { oDate.setFullYear(year - 1) oDate.setMonth(11) } else { oDate.setMonth(month - 1) } this.setDate(oDate) } nextHandler () { let oDate = this.state.date let year = oDate.getFullYear() let month = oDate.getMonth() if (month === 11) { oDate.setFullYear(year + 1) oDate.setMonth(0) } else { oDate.setMonth(month + 1) } this.setDate(oDate) } todayHandler () { this.setDate(new Date()) } // 求出本月有多少天? // 先把日期调到1号(避免5.31号的下个月6月没有31号),月份再调到下个月,最后日期调到0。 getDayCountByMonth (date) { let oDate = new Date('' + date) oDate.setDate(1) oDate.setMonth(oDate.getMonth() + 1) oDate.setDate(0) return oDate.getDate() } // 求出本月第一天是周几? getFirstDay (date) { let oDate = new Date('' + date) oDate.setDate(1) return oDate.getDay() } } ReactDOM.render(<Calendar />, document.getElementById('app'))
import { responses } from "../../config/strings"; import constants from "../../config/constants"; import LessonModel, { Lesson } from "../../models/Lesson"; import CourseModel from "../../models/Course"; import { Group } from "@courselit/common-models"; import mongoose from "mongoose"; const { text, audio, video, pdf, embed } = constants; export const lessonValidator = (lessonData: Lesson) => { if ([text, embed].includes(lessonData.type) && !lessonData.content) { throw new Error(responses.content_cannot_be_null); } if ( (lessonData.type === audio || lessonData.type === video || lessonData.type === pdf) && !(lessonData.media && lessonData.media.mediaId) ) { throw new Error(responses.media_id_cannot_be_null); } }; type GroupLessonItem = Pick<Lesson, "lessonId" | "groupId" | "groupRank">; export const getGroupedLessons = async ( courseId: string, domainId: mongoose.Types.ObjectId ): Promise<GroupLessonItem[]> => { const course = await CourseModel.findOne({ courseId: courseId, domain: domainId, }); const allLessons = await LessonModel.find<GroupLessonItem>( { lessonId: { $in: [...course.lessons], }, domain: domainId, }, { lessonId: 1, groupRank: 1, groupId: 1, } ); const lessonsInSequentialOrder = []; for (let group of course.groups.sort( (a: Group, b: Group) => a.rank - b.rank )) { lessonsInSequentialOrder.push( ...allLessons .filter( (lesson: GroupLessonItem) => lesson.groupId === group.id ) .sort( (a: GroupLessonItem, b: GroupLessonItem) => a.groupRank - b.groupRank ) ); } return lessonsInSequentialOrder; }; export const getPrevNextCursor = async ( courseId: string, domainId: mongoose.Types.ObjectId, lessonId?: string ) => { const lessonsInSequentialOrder = await getGroupedLessons( courseId, domainId ); const indexOfCurrentLesson = lessonId ? lessonsInSequentialOrder.findIndex( (item) => item.lessonId === lessonId ) : -1; return { prevLesson: indexOfCurrentLesson - 1 < 0 ? "" : lessonsInSequentialOrder[indexOfCurrentLesson - 1].lessonId, nextLesson: indexOfCurrentLesson + 1 > lessonsInSequentialOrder.length - 1 ? "" : lessonsInSequentialOrder[indexOfCurrentLesson + 1].lessonId, }; };
import {css, CSSResult, html, HTMLTemplateResult, LitElement} from "lit"; import {customElement, property, query, state} from "lit/decorators.js"; import {YoutubeControllerService} from "../Services/YoutubeController.service"; import {dialogStyles} from "./dialog-styles.css"; import {Song} from "../DataTypes/Song"; import "@material/mwc-linear-progress"; @customElement("youtube-video-selector-dialog") export class YoutubeVideoSelectorDialog extends LitElement { @query("mwc-dialog") private dialog; @property() public youtubeControllerService?: YoutubeControllerService; @state() private isLoading: boolean; @state() private songs: Array<Song>; @state() private loadingError?: Error; @state() private isOpen: boolean; private searchQuery: string; private dialogResolver?: {resolve: (id: string) => void; reject: (error: Error) => void}; public constructor() { super(); this.isOpen = false; this.isLoading = true; this.songs = []; this.loadingError = undefined; this.searchQuery = ""; } public async selectVideo(query: string): Promise<string> { return new Promise((resolve, reject) => { if (this.dialogResolver) { this.dialogResolver.reject(new Error("The previous dialog was not resolved")); } this.dialogResolver = {resolve, reject}; this.loadingError = undefined; this.songs = []; this.openDialog(); this.loadData(query); }); } public render(): HTMLTemplateResult { return html` <mwc-dialog title="Vyber video" heading="Vyber video" scrimClickAction="undefined" escapeKeyAction="undefined" ?open="${this.isOpen}" @closed="${this.onClosed}" > <div role="alertdialog" aria-modal="true" aria-labelledby="my-dialog-title" aria-describedby="my-dialog-content"> <div class="mdc-dialog__content" id="my-dialog-content"> <mwc-linear-progress indeterminate ?closed="${!this.isLoading}"> </mwc-linear-progress> <div class="loading-error ${this.loadingError ? "" : " hidden"}"> <p>An error happened during fetching search results from youtube!</p> <p>${this.loadingError?.message}</p> <button @click="${() => this.loadData(this.searchQuery)}">Try again</button> </div> <ul class="mdc-list mdc-list--avatar-list"> ${this.renderVideoList()} </ul> </div> </div> </mwc-dialog> `; } private renderVideoList(): Array<HTMLTemplateResult> { return this.songs.map((song) => this.buildItem(song)); } private buildItem(song: Song): HTMLTemplateResult { const thumbnail = song.thumbnails.sort((thumbnail1: any, thumbnail2: any) => (thumbnail1.width > thumbnail2.width ? 1 : -1))[0]?.url; return html` <li class="mdc-list-item" tabindex="0" dialogAction="${song.id}"> <span class="mdc-list-item__graphic"> <img src="${thumbnail}" /> </span> <span class="mdc-list-item__text">${song.title}</span> </li> `; } private onClosed(event): void { if (event.detail.action === "undefined") { this.dialogResolver?.reject(new Error("Dialog was canceled")); } else { this.dialogResolver?.resolve(event.detail.action); } this.dialogResolver = undefined; this.isOpen = false; } private openDialog(): void { this.isOpen = true; this.centerDialog(); } private centerDialog(): void { const surfaceElement = this.dialog.shadowRoot.querySelector(".mdc-dialog__surface"); if (surfaceElement) { const gap = (window.innerHeight - window.innerHeight * 0.9) / 2; surfaceElement.style.top = `${window.scrollY + gap}px`; surfaceElement.style.position = "absolute"; } } private async loadData(query: string): Promise<void> { this.searchQuery = query; try { this.loadingError = undefined; this.isLoading = true; const response = await this.youtubeControllerService?.getSearchResults(query); this.isLoading = false; this.songs = response?.results as Array<Song>; } catch (error: any) { console.error(`Could not fetch data for the dialog because of ${error.message}`); this.isLoading = false; this.loadingError = error; } } static get styles(): Array<CSSResult> { return [ css` .hidden { display: none; } .loading-error { color: red; } mwc-linear-progress { --mdc-theme-primary: red; } `, dialogStyles, ]; } }
@mixin anim($time, $delay) { -webkit-transition: all $time ease $delay; -moz-transition: all $time ease $delay; -ms-transition: all $time ease $delay; -o-transition: all $time ease $delay; transition: all $time ease $delay; } @mixin anim_cubic($time, $delay) { -webkit-transition: all $time cubic-bezier(0.68, -0.55, 0.265, 1.55) $delay; -moz-transition: all $time cubic-bezier(0.68, -0.55, 0.265, 1.55) $delay; -ms-transition: all $time cubic-bezier(0.68, -0.55, 0.265, 1.55) $delay; -o-transition: all $time cubic-bezier(0.68, -0.55, 0.265, 1.55) $delay; transition: all $time cubic-bezier(0.68, -0.55, 0.265, 1.55) $delay; } @mixin rotate($deg) { -moz-transform: rotate($deg); -ms-transform: rotate($deg); -webkit-transform: rotate($deg); -o-transform: rotate($deg); transform: rotate($deg); } @mixin scale($num) { -moz-transform: scale($num); -ms-transform: scale($num); -webkit-transform: scale($num); -o-transform: scale($num); transform: scale($num); } @mixin skew($num) { -webkit-transform: skewX($num); -moz-transform: skewX($num); -ms-transform: skewX($num); -o-transform: skewX($num); transform: skewX($num); } @mixin cnt($h) { display: flex; flex-direction: column; height: $h; text-align: center; align-items: stretch; justify-content: center; } @mixin tr($x, $y, $z) { transform: translate3d($x, $y, $z); } @mixin flexbox() { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; /* font-size: 0; */ } @mixin flexorder($val) { -webkit-box-ordinal-group: $val; -moz-box-ordinal-group: $val; -ms-flex-order: $val; -webkit-order: $val; order: $val; } $maxWidth: 1920; $maxWidthContainer: 1140; @mixin adaptiv-value($property, $startSize, $minSize, $type) { $addSize: $startSize - $minSize; @if $type==1 { // Только если меньше контейнера #{$property}: $startSize + px; @media (max-width: #{$maxWidthContainer + px}) { #{$property}: calc(#{$minSize + px} + #{$addSize} * ((100vw - 320px) / #{$maxWidthContainer - 320})); } } @else if $type==2 { // Только если больше контейнера #{$property}: $startSize + px; @media (min-width: #{$maxWidthContainer + px}) { #{$property}: calc(#{$minSize + px} #{$addSize} * ((100vw - 320px) / #{$maxWidth - 320})); } } @else { // Всегда #{$property}: calc(#{$minSize + px} + #{$addSize} * ((100vw - 320px) / #{$maxWidth - 320})); } } @mixin adaptiv-font($pcSize, $mobSize) { $addSize: $pcSize - $mobSize; $maxWidth: $maxWidth - 320; font-size: calc(#{$mobSize + px} + #{$addSize} * ((100vw - 320px) / #{$maxWidth})); } @font-face { font-family: "GothamPro"; src: url(../fonts/GothamPro.woff) format("woff"), url(../fonts/GothamPro.woff2) format("woff2"); } @font-face { font-family: "GothamPro"; src: url(../fonts/GothamPro-Bold.woff) format("woff"), url(../fonts/GothamPro-Bold.woff2) format("woff2"); } @font-face { font-family: "GothamPro"; src: url(../fonts/GothamPro-Medium.woff) format("woff"), url(../fonts/GothamPro-Medium.woff2) format("woff2"); } $fontfamily: GothamPro; $fontSize: 16px; $minwidth: 320px; $mw: 1140; $md1: $mw + 12px; $md2: 991.98px; $md3: 767.98px; $md4: 479.98px; $mainColor: #3a3a3a; $orangeColor: #e89f71; $grayColor: #898989; $darkGrayColor: #616161; $maxWidth: 1920; $maxWidthContainer: 1270; * { padding: 0px; margin: 0px; border: 0px; } *, *:before, *:after { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } :focus, :active { outline: none; } a:focus, a:active { outline: none; } aside, nav, footer, header, section { display: block; } html, body { height: 100%; margin: 0; padding: 0; min-width: $minwidth; position: relative; width: 100%; color: $mainColor; background-color: #fff; } body { font-size: 100%; line-height: 1; font-size: $fontSize; font-weight: 500; font-family: $fontfamily; -ms-text-size-adjust: 100%; -moz-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; background-color: #fff; /* background-color: #fafafa; */ &.lock { overflow: hidden; /* @media (max-width: $md3) { width: 100%; position: fixed; overflow: hidden; } */ } } input, button, textarea { font-family: $fontfamily; } input::-ms-clear { display: none; } button { cursor: pointer; } button::-moz-focus-inner { padding: 0; border: 0; } a, a:hover, a:focus, a:active, a:visited { text-decoration: none; color: inherit; } ul li { list-style: none; } h1, h2, h3, h4, h5, h6 { font-weight: inherit; font-size: inherit; } .wrapper { width: 100%; min-height: 100%; overflow: hidden; @include flexbox(); flex-direction: column; } .container { max-width: $mw + px; padding: 0 15px; margin: 0 auto; @media (max-width: 767px) { padding: 0 10px; } } @import "popup.scss"; @import "header.scss"; @import "footer.scss"; .page { flex: 1 1 auto; } .first { // .main__screen &__screen { position: relative; @include flexbox(); justify-content: center; align-items: center; // .main__screen_content &_content { flex: 1 1 auto; position: relative; z-index: 2; @include adaptiv-value("padding-top", 120, 30, 1); @include adaptiv-value("padding-bottom", 150, 50, 1); /* max-width:570px; */ @include adaptiv-font(20, 10); line-height: 1.75; text-align: left; color: #fff; font-weight: 400; } // .main__screen_slogan &_slogan { max-width: 570px; @media (max-width: 1150px) { max-width: 300px; } @media (max-width: 650px) { max-width: 220px; } @media (max-width: 480px) { max-width: 170px; } } // .main__screen_logo &_logo { @include adaptiv-value("padding-top", 50, 20, 1); @include adaptiv-value("padding-bottom", 50, 20, 1); } // .main__screen_logo-image &_logo-image { img { @media (max-width: 1150px) { height: 50%; width: 40%; } } } // .main__screen_logo-text &_logo-text { @include adaptiv-font(27, 12); font-weight: 500; line-height: 1.3; color: #e84a0d; @media (max-width: 1150px) { max-width: 300px; } @media (max-width: 650px) { max-width: 350px; } } // .main__screen_about &_about { max-width: 570px; @media (max-width: 1150px) { max-width: 400px; } @media (max-width: 650px) { max-width: 250px; } } // .main__screen_bg &_bg { position: absolute; width: 100%; height: 100%; top: 0; left: 0; } &_car { position: absolute; width: 40%; height: 90%; top: 7%; right: 0; @media (max-width: 1250px) { top: 10%; width: 40%; height: 75%; } @media (max-width: 950px) { top: 20%; width: 40%; height: 67%; } @media (max-width: 700px) { top: 10%; width: 40%; } @media (max-width: 480px) { top: 5%; width: 50%; height: 63%; } @media (max-width: 400px) { top: 0%; } } } } .cars { padding: 40px 0px 50px 0px; // .cars__container &__container { } // .cars__top &__top { &_item { @include flexbox(); justify-content: space-between; @media (max-width: 900px) { flex-direction: column; text-align: center; align-items: center; } } // .cars__top_column &_column { } // .cars__top_column-left &_column-left { } // .cars__top_title &_title { @include adaptiv-font(50, 30); font-weight: bold; text-align: left; color: #771975; @media (max-width: 900px) { text-align: center; align-items: center; } } // .cars__top_subtitle &_subtitle { padding: 20px 0px 0px 0px; max-width: 640px; @include adaptiv-font(20, 14); line-height: 1.75; text-align: left; color: #000; @media (max-width: 900px) { text-align: center; align-items: center; } } // .cars__top_column-right &_column-right { } // .cars__top_image &_image { padding: 20px 0px 0px 0px; } &_button { text-align: right; @media (max-width: 900px) { margin: 20px 0px 0px 0px; text-align: center; align-items: center; } &-link { color: #fff; @include adaptiv-font(16, 12); position: relative; padding: 14px 23px 14px 20px; &-img { } } button { background-image: linear-gradient(to right, #ea4106 0%, #761976 100%); padding: 14px 33px 14px 20px; border-radius: 50px; background-image: linear-gradient(to right, #ea4106 0%, #761976 100%); } } } // .cars__bottom &__bottom { text-align: right; // .cars__bottom_spoiler &_spoiler { } &_desktop { position: relative; .swiper-wrapper { width: 100%; height: 100%; z-index: 1; transition-property: transform; box-sizing: content-box; justify-content: space-between; display: flex; } .swiper-slide { min-width: 0; transition: opacity 200ms ease-in-out, visibility 200ms ease-in-out; } .swiper-slide-active { opacity: 1; visibility: visible; } .swiper-horizontal > .swiper-pagination-bullets, .swiper-pagination-bullets.swiper-pagination-horizontal, .swiper-pagination-custom, .swiper-pagination-fraction { bottom: -5%; left: 0; width: 100%; } .swiper-pagination-bullet-active { background: #000; } } &_slider { } // .cars__bottom_body &_body { overflow: hidden; padding: 0px 0px 60px 0px; .swiper-slide { } } // .cars__bottom_column &_column { min-width: 0; } // .cars__bottom_item &_item { text-align: left; &:not(:last-child) { @media (min-width: 1150px) { padding: 0px 0px 60px 0px; } } @media (max-width: 1150px) { text-align: center; align-items: center; } } // .cars__bottom_item-image &_item-image { } // .cars__bottom_item-title &_item-title { padding: 0px 0px 20px 0px; @include adaptiv-font(25, 16); font-weight: bold; color: #771975; } // .cars__bottom_item-subtitle &_item-subtitle { @include adaptiv-font(20, 14); line-height: 1.5; color: #000; } } // .cars__block &__block { } } .btn__img { position: absolute; right: 4%; } .btn__text { padding: 0px 13px 0px 0px; } .cars { // .cars__top &__top { // .cars__top_button &_button { button { background-image: linear-gradient(to right, #ea4106 0%, #761976 100%); padding: 14px 20px; border-radius: 50px; background-image: linear-gradient(to right, #ea4106 0%, #761976 100%); animation: pulse 1s ease-in-out infinite; z-index: 50; } } // .cars__top_button-link &_button-link { color: #fff; @include adaptiv-font(16, 12); } } } @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.03); } 100% { transform: scale(1); } } .advantages { background: url("../img/advantages/bg.webp"); padding: 50px 0px 50px 0px; // .advantages__container &__container { } // .advantages__top &__top { // .advantages__top_title position: relative; &_body { @include flexbox(); justify-content: space-between; @media (min-width: 767px) { flex-direction: column; } @media (max-width: 767px) { } } &_column { &-item { @include flexbox(); width: 50%; @media (max-width: 1050px) { flex-direction: column; text-align: center; align-items: center; width: 100%; } &-bottom { @media (max-width: 767px) { flex-direction: row; width: 100%; } @media (min-width: 767px) { width: 100%; } } } @include flexbox(); color: inherit; cursor: pointer; } &_title { } // .advantages__top_card &_card { @media (max-width: 1050px) { min-width: 255px; } @media (max-width: 630px) { min-width: 60%; } } // .advantages__top_card-front } // .advantages__title &__title { width: 100%; margin-left: 1rem; font-weight: 900; font-size: 1.618rem; text-transform: uppercase; letter-spacing: 0.1ch; line-height: 1; padding-bottom: 0.5em; margin-bottom: 1rem; position: relative; color: #fff; } // .advantages__bottom &__bottom { @media (max-width: 767px) { padding: 70px 0px 0px 0px; } position: relative; // .advantages__bottom_title &_body { @media (min-width: 767px) { @include flexbox(); flex-direction: row; overflow: hidden; } .swiper-slide { @media (min-width: 767px) { width: 50%; } } } &_slider { text-align: center; align-items: center; justify-content: center; align-items: center; margin: 0px auto; min-width: 0; @media (max-width: 767px) { text-align: center; align-items: center; justify-content: center; align-items: center; margin: 0px auto; } .swiper-wrapper { @include flexbox(); margin: 0 auto; min-width: 0; width: 100%; height: 100%; z-index: 1; display: flex; @media (min-width: 767px) { } @media (max-width: 800px) { } } .swiper-slide { min-width: 0; color: inherit; cursor: pointer; margin: 1rem; position: relative; border: solid 1px #9a2e9d; width: calc(25% - 2rem); height: 235px; min-height: 235px; @media (max-width: 800px) { max-width: 255px; min-width: 255px; } @media (max-width: 500px) { } } } &_title { } // .advantages__bottom_card &_card { @media (max-width: 767px) { text-align: center; align-items: center; justify-content: center; align-items: center; min-width: 40%; } } // .advantages__bottom_card-front } } .swiper_01, .swiper_02 { .swiper-horizontal > .swiper-pagination-bullets, .swiper-pagination-bullets.swiper-pagination-horizontal, .swiper-pagination-custom, .swiper-pagination-fraction { bottom: -5%; left: 0; width: 100%; } } .swiper_01{ .swiper-pagination{ @media (min-width:767px){ display: none; } } } @media (max-width: 767px) { .swiper-slide { opacity: 0; visibility: hidden; transition: opacity 200ms ease-in-out, visibility 200ms ease-in-out; } .swiper-slide-active { opacity: 1; visibility: visible; } } .swiper_02 { @media (max-width: 767px) { text-align: center; align-items: center; justify-content: center; align-items: center; margin: 0px auto; } } .front { padding: 30px 0px 40px 0px; @include flexbox(); flex-direction: column; justify-content: space-between; // .front__iamge &__iamge { img{ @media (max-width:767px){ width: 85%; height: 85%; } } } // .front__title &__title { @include adaptiv-font(20, 12); font-weight: 500; line-height: 1.25; text-align: center; color: #fff; } } .back { // .back__title &__title { padding: 0px 0px 10px 0px; @include adaptiv-font(20, 10); font-weight: 500; text-align: center; color: #8c1e8e; } // .back__text &__text { @include adaptiv-font(12, 8.5); font-weight: normal; font-style: normal; line-height: 1.5; text-align: left; color: #000; } } .card { margin: 1rem; position: relative; border: solid 1px #9a2e9d; /* height: 295px; */ min-height: 245px; width: calc(50% - 2rem); @media (max-width: 767px) { height: 195px; min-height: 195px; } } @media screen and (max-width: 800px) { .card { width: calc(50% - 2rem); } } @media screen and (max-width: 767px) { .card { width: 90%; } } .advantages__bottom_card{ width: calc(25% - 2rem); @media (max-width:767px){ width: 90%; } } .front, .back { display: flex; border-radius: 6px; background-position: center; background-size: cover; text-align: center; justify-content: center; align-items: center; position: absolute; height: 100%; width: 100%; -webkit-backface-visibility: hidden; backface-visibility: hidden; transform-style: preserve-3d; transition: ease-in-out 600ms; } .front { background-size: cover; padding: 2rem; font-size: 1.618rem; font-weight: 600; color: #fff; overflow: hidden; font-family: Poppins, sans-serif; } .front:before { position: absolute; display: block; content: ""; top: 0; left: 0; right: 0; bottom: 0; opacity: 0.25; z-index: -1; } .card:hover .front { transform: rotateY(180deg); } .card:nth-child(even):hover .front { transform: rotateY(-180deg); } .back { background: #fff; transform: rotateY(-180deg); padding: 0 1em; box-shadow: 0 0 10px 10px rgba(26, 87, 230, 0.25); } .card:hover .back { transform: rotateY(0deg); } .card:nth-child(even) .back { transform: rotateY(180deg); } .card:nth-child(even):hover .back { transform: rotateY(0deg); } .mission { position: relative; @include flexbox(); justify-content: center; align-items: center; // .mission__content &__content { flex: 1 1 auto; position: relative; z-index: 2; @include adaptiv-value("padding-top", 100, 30, 1); @include adaptiv-value("padding-bottom", 130, 50, 1); /* max-width:570px; */ @include adaptiv-font(20, 10); line-height: 1.75; text-align: left; color: #fff; font-weight: 400; } // .mission__slogan &__slogan { @include adaptiv-font(20, 14); } // .mission__title &__title { @include adaptiv-font(50, 20); max-width: 640px; @media (max-width: 600px) { max-width: 400px; } } // .mission__screen &__screen { position: absolute; width: 100%; height: 100%; top: 0; left: 0; } } .contacts { padding: 50px 0px 50px 0px; // .contacts__container &__container { } // .contacts__title &__title { @include adaptiv-font(50, 24); font-weight: bold; color: #771975; padding: 0px 0px 30px 0px; @media (max-width: 670px) { text-align: center; align-items: center; } } // .contacts__content &__content { @include flexbox(); justify-content: space-between; text-align: left; @media (max-width: 670px) { flex-direction: column; justify-content: center; align-items: center; text-align: center; } // .contacts__content_column &_column { @media (max-width: 670px) { } } // .contacts__content_location &_location { @include adaptiv-font(20, 14); line-height: 1.75; font-style: italic; color: #000; } // .contacts__content_location-adress &_location-adress { @include adaptiv-font(25, 18); font-weight: 500; line-height: 1.6; color: #000; } // .contacts__content_service &_service { @include adaptiv-font(20, 14); line-height: 1.75; font-style: italic; color: #000; } // .contacts__content_service-phone &_service-phone { @include adaptiv-font(25, 18); font-weight: 500; line-height: 1.6; color: #000; } // .contacts__content_service-email &_service-email { @include adaptiv-font(25, 18); font-weight: 500; line-height: 1.6; color: #771975; } // .contacts__content_director &_director { @include adaptiv-font(20, 14); line-height: 1.75; font-style: italic; color: #000; } // .contacts__content_director-name &_director-name { @include adaptiv-font(25, 18); font-weight: 500; line-height: 1.6; color: #000; } // .contacts__content_director-phone &_director-phone { @include adaptiv-font(25, 18); font-weight: 500; line-height: 1.6; color: #000; } // .contacts__content_director-email &_director-email { @include adaptiv-font(25, 18); font-weight: 500; line-height: 1.6; color: #771975; } } } /* @media (min-width:767px){ .swiper-slide{ display: none; } } */ @import "forms.scss"; @import "ui.scss";
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { StoreModule } from '@ngrx/store'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { PurrComponent } from './purr/purr.component'; import { featureKey, purrReducer } from './purr/store/purr.reducer'; import { PurringListComponent } from './purr/components/purring-list/purring-list.component'; import { PurringComponent } from './purr/components/purring/purring.component'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatIconModule } from '@angular/material/icon'; import { PurringCreationComponent } from './purr/components/purring-creation/purring-creation.component'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatCardModule } from '@angular/material/card'; import { MatInputModule } from '@angular/material/input'; import { MatButtonModule } from '@angular/material/button'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { StoreDevtoolsModule } from '@ngrx/store-devtools'; @NgModule({ declarations: [ AppComponent, PurrComponent, PurringComponent, PurringListComponent, PurringCreationComponent ], imports: [ BrowserModule, AppRoutingModule, StoreModule.forRoot({ purr: purrReducer }), StoreModule.forFeature(featureKey, purrReducer), BrowserAnimationsModule, FormsModule, ReactiveFormsModule, MatToolbarModule, MatIconModule, MatFormFieldModule, MatCardModule, MatInputModule, MatButtonModule, StoreDevtoolsModule.instrument({ maxAge: 25, logOnly: false, autoPause: true }) ], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
import { describe, expect, it, vi } from 'vitest'; import { EventPublisher } from './event-publisher'; import { BaseEvent } from './base-event'; class TestEvent extends BaseEvent { constructor(aggregateId: string, public readonly delay: number) { super(aggregateId); } }; class TestEventPublisher extends EventPublisher<TestEvent> { publish(event: TestEvent): Promise<void> { throw new Error('Method not implemented.'); } } describe('EventPublisher', () => { it('should call publish for every event in sequential manner', async () => { /** * Idea is to call publishAll with two Events. * First event with version 1, and execution timeout 2 * Second - with version 2, and exection timeout 1 * * So, we test that event publish method executed sequentially we would like * to test that second publish executed exactly after first execution finished */ const tep = new TestEventPublisher(); let executionOrder = ''; const publishSpy = vi.spyOn(tep, 'publish').mockImplementation(async (event: TestEvent) => { await new Promise<void>((resolve) => { setTimeout(() => { executionOrder += event.meta.version; // once we finish event processing we will add its version to executionOrder string resolve(); }, event.delay); }) }) const event1 = new TestEvent('agg1', 2); event1.meta.version = 1; const event2 = new TestEvent('agg1', 1); event2.meta.version = 2; await tep.publishAll([event1, event2]); expect(publishSpy).toHaveBeenNthCalledWith(1, event1); expect(publishSpy).toHaveBeenNthCalledWith(2, event2); // expect that we finished processing of event 1 before event 2, even delay (processing time) for the first event is bigger expect(executionOrder).toBe('12'); }) });
package com.polar.bookService.controllers; import com.polar.bookService.data.Inventory; import com.polar.bookService.service.InventoryService; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/inventory") @Slf4j @RequiredArgsConstructor public class InventoryController { private final InventoryService inventoryService; @GetMapping("/serialNumber") Inventory getInventoryBySerialNumber(@RequestParam("serialNumber") String serialNumber) { return inventoryService.getInventoryBySerialNumber(serialNumber); } @PostMapping @ResponseStatus(HttpStatus.CREATED) Inventory registerInventory(@Valid @RequestBody Inventory inventory) { return inventoryService.registerInventory(inventory); } @PutMapping @ResponseStatus(HttpStatus.OK) Inventory updateInventory(@Valid @RequestBody Inventory inventory){ return inventoryService.updateInventory(inventory); } @DeleteMapping @ResponseStatus(HttpStatus.NO_CONTENT) void deleteInventory(@RequestParam("serialNumber") String serialNumber){ inventoryService.deleteInventory(serialNumber); } }
import {NgModule} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {EffectsModule} from '@ngrx/effects'; import {Store, StoreModule} from '@ngrx/store'; import {NxModule} from '@nrwl/angular'; import {readFirst} from '@nrwl/angular/testing'; import * as UsersActions from './users.actions'; import {UsersEffects} from './users.effects'; import {UsersFacade} from './users.facade'; import {UsersEntity} from './users.models'; import {reducer, State, USERS_FEATURE_KEY} from './users.reducer'; interface TestSchema { users: State; } describe('UsersFacade', () => { let facade: UsersFacade; let store: Store<TestSchema>; const createUsersEntity = (id: string, name = ''): UsersEntity => ({ id, name: name || `name-${id}` }); describe('used in NgModule', () => { beforeEach(() => { @NgModule({ imports: [StoreModule.forFeature(USERS_FEATURE_KEY, reducer), EffectsModule.forFeature([UsersEffects])], providers: [UsersFacade] }) class CustomFeatureModule {} @NgModule({ imports: [NxModule.forRoot(), StoreModule.forRoot({}), EffectsModule.forRoot([]), CustomFeatureModule] }) class RootModule {} TestBed.configureTestingModule({ imports: [RootModule] }); store = TestBed.inject(Store); facade = TestBed.inject(UsersFacade); }); /** * The initially generated facade::loadAll() returns empty array */ it('loadAll() should return empty list with loaded == true', async () => { let list = await readFirst(facade.allUsers$); let isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(0); expect(isLoaded).toBe(false); facade.init(); list = await readFirst(facade.allUsers$); isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(0); expect(isLoaded).toBe(true); }); /** * Use `loadUsersSuccess` to manually update list */ it('allUsers$ should return the loaded list; and loaded flag == true', async () => { let list = await readFirst(facade.allUsers$); let isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(0); expect(isLoaded).toBe(false); store.dispatch( UsersActions.loadUsersSuccess({ users: [createUsersEntity('AAA'), createUsersEntity('BBB')] }) ); list = await readFirst(facade.allUsers$); isLoaded = await readFirst(facade.loaded$); expect(list.length).toBe(2); expect(isLoaded).toBe(true); }); }); });
import { createEmitter, ReadOnlyEmitter } from "@lib/emitter"; import { delay, Task } from "@lib/async/task"; import { shallow } from "@lib/compare"; export type MeterStatus<T> = { states: T[]; idx: number; mode: "playing" | "paused" | "idle"; }; export type Meter<T> = { emitter: ReadOnlyEmitter<MeterStatus<T>>; pushStates: (...states: T[]) => void; setIdx: (idx: number | ((idx: number, length: number) => number)) => void; setPlay: (toggle: boolean | ((status: boolean) => boolean)) => void; waitFor: (task?: Task<any> | number) => void; }; export const createMeter = <T>(initial: T): Meter<T> => { let states = [initial]; let idx = 0; let waitingFor: Task<any>[] = []; let playing = true; let clearing = false; function getMode() { if (!playing) return "paused"; if (waitingFor.length > 0 || idx < states.length - 1) return "playing"; return "idle"; } function getStatus() { return { states, idx, mode: getMode() } as const; } const { subscribe, get, next } = createEmitter(getStatus(), { isEqual: shallow, }); function emit() { next(getStatus()); } function updateState(nextIdx: number) { if (nextIdx > states.length - 1 || nextIdx < 0) { emit(); return; } idx = nextIdx; /** * if (!history) { states = states.slice(idx); idx = 0; } */ emit(); // client receives -- sets waitFors onChange(); } function onChange() { if (waitingFor.length > 0 || !playing) { emit(); return; } updateState(idx + 1); } function clearWaiting() { clearing = true; waitingFor.forEach((task) => { task.finish(); }); clearing = false; waitingFor = []; } return { emitter: { subscribe, get }, pushStates: (...incoming) => { states = [...states, ...incoming]; onChange(); }, setIdx: (input) => { const nextIdx = typeof input === "function" ? input(idx, states.length) : input; playing = false; clearWaiting(); updateState(nextIdx); }, setPlay: (toggle) => { typeof toggle === "function" ? (playing = toggle(playing)) : (playing = toggle); onChange(); }, waitFor: (task) => { if (!task) return; const realTask = typeof task === "number" ? delay(task) : task; realTask.finished.then(() => { if (clearing) return; waitingFor = waitingFor.filter((x) => x !== realTask); onChange(); }); waitingFor = [...waitingFor, realTask]; onChange(); }, }; }; export default createMeter;